You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ranger.apache.org by ma...@apache.org on 2014/12/12 02:30:20 UTC
[37/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java
----------------------------------------------------------------------
diff --git a/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java b/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java
deleted file mode 100644
index 946ef4f..0000000
--- a/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java
+++ /dev/null
@@ -1,494 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
- package com.xasecure.utils.install;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Properties;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.apache.commons.cli.BasicParser;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.OptionBuilder;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-public class XmlConfigChanger {
-
- private static final String EMPTY_TOKEN = "%EMPTY%" ;
- private static final String EMPTY_TOKEN_VALUE = "" ;
-
- public static final String ROOT_NODE_NAME = "configuration" ;
- public static final String NAME_NODE_NAME = "name" ;
- public static final String PROPERTY_NODE_NAME = "property" ;
- public static final String VALUE_NODE_NAME = "value" ;
-
- private File inpFile ;
- private File outFile ;
- private File confFile ;
- private File propFile ;
-
- private Document doc ;
-
-
-
- public static void main(String[] args) {
- XmlConfigChanger xmlConfigChanger = new XmlConfigChanger() ;
- xmlConfigChanger.parseConfig(args);
- try {
- xmlConfigChanger.run();
- }
- catch(Throwable t) {
- System.err.println("*************************************************************************") ;
- System.err.println("******* ERROR: unable to process xml configuration changes due to error:" + t.getMessage()) ;
- t.printStackTrace();
- System.err.println("*************************************************************************") ;
- System.exit(1);
- }
- }
-
-
-
-
- @SuppressWarnings("static-access")
- public void parseConfig(String[] args) {
-
-
- Options options = new Options();
-
- Option inputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("input").withDescription("Input xml file name").create('i');
- options.addOption(inputOption);
-
- Option outputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("output").withDescription("Output xml file name").create('o');
- options.addOption(outputOption);
-
- Option configOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("config").withDescription("Config file name").create('c');
- options.addOption(configOption);
-
- Option installPropOption = OptionBuilder.hasArgs(1).isRequired(false).withLongOpt("installprop").withDescription("install.properties").create('p');
- options.addOption(installPropOption);
-
- CommandLineParser parser = new BasicParser();
- CommandLine cmd = null ;
- try {
- cmd = parser.parse(options, args);
- } catch (ParseException e) {
- String header = "ERROR: " + e ;
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String inputFileName = cmd.getOptionValue('i') ;
- this.inpFile = new File(inputFileName) ;
- if (! this.inpFile.canRead()) {
- String header = "ERROR: Input file [" + this.inpFile.getAbsolutePath() + "] can not be read.";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String outputFileName = cmd.getOptionValue('o') ;
- this.outFile = new File(outputFileName) ;
- if (this.outFile.exists()) {
- String header = "ERROR: Output file [" + this.outFile.getAbsolutePath() + "] already exists. Specify a filepath for creating new output file for the input [" + this.inpFile.getAbsolutePath() + "]";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String configFileName = cmd.getOptionValue('c') ;
- this.confFile = new File(configFileName) ;
- if (! this.confFile.canRead()) {
- String header = "ERROR: Config file [" + this.confFile.getAbsolutePath() + "] can not be read.";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String installPropFileName = (cmd.hasOption('p') ? cmd.getOptionValue('p') : null ) ;
- if (installPropFileName != null) {
- this.propFile = new File(installPropFileName) ;
- if (! this.propFile.canRead()) {
- String header = "ERROR: Install Property file [" + this.propFile.getAbsolutePath() + "] can not be read.";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
- }
-
- }
-
-
-
-
- public void run() throws ParserConfigurationException, SAXException, IOException, TransformerException {
-
-
- loadInstallProperties() ;
-
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
- DocumentBuilder builder = factory.newDocumentBuilder() ;
- doc = builder.parse(inpFile) ;
-
- BufferedReader reader = null ;
- try {
- reader = new BufferedReader(new FileReader(confFile)) ;
-
- String line = null ;
-
- @SuppressWarnings("unused")
- int lineNo = 0 ;
-
- while ((line = reader.readLine()) != null) {
-
- lineNo++ ;
-
- line = line.trim() ;
-
- if (line.isEmpty() )
- continue ;
- if (line.startsWith("#")) {
- continue ;
- }
-
- if (line.contains("#")) {
- int len = line.indexOf("#") ;
- line = line.substring(0,len) ;
- }
-
- String[] tokens = line.split("\\s+") ;
-
- String propName = tokens[0] ;
-
- String propValue = null ;
-
- try {
- propValue = replaceProp(tokens[1],installProperties) ;
- } catch (ValidationException e) {
- // throw new RuntimeException("Unable to replace tokens in the line: \n[" + line + "]\n in file [" + confFile.getAbsolutePath() + "] line number:[" + lineNo + "]" ) ;
- throw new RuntimeException(e) ;
- }
-
-
-
- String actionType = tokens[2] ;
- String options = (tokens.length > 3 ? tokens[3] : null) ;
- boolean createIfNotExists = (options != null && options.contains("create-if-not-exists")) ;
-
-
- if ("add".equals(actionType)) {
- addProperty(propName, propValue);
- }
- else if ("mod".equals(actionType)) {
- modProperty(propName, propValue,createIfNotExists);
- }
- else if ("del".equals(actionType)) {
- delProperty(propName);
- }
- else if ("append".equals(actionType)) {
- String curVal = getProperty(propName) ;
- if (curVal == null) {
- if (createIfNotExists) {
- addProperty(propName, propValue);
- }
- }
- else {
- String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
- if (! curVal.contains(propValue)) {
- String newVal = null ;
- if (curVal.length() == 0) {
- newVal = propValue ;
- }
- else {
- newVal = curVal + appendDelimitor + propValue ;
- }
- modProperty(propName, newVal,createIfNotExists) ;
- }
- }
- }
- else if ("delval".equals(actionType)) {
- String curVal = getProperty(propName) ;
- if (curVal != null) {
- String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
- if (curVal.contains(propValue)) {
- String[] valTokens = curVal.split(appendDelimitor) ;
- StringBuilder sb = new StringBuilder() ;
- for(String v : valTokens) {
- if (! v.equals(propValue)) {
- if (sb.length() > 0) {
- sb.append(appendDelimitor) ;
- }
- sb.append(v);
- }
- }
- String newVal = sb.toString() ;
- modProperty(propName, newVal,createIfNotExists) ;
- }
- }
- }
- else {
- throw new RuntimeException("Unknown Command Found: [" + actionType + "], Supported Types: add modify del append") ;
- }
-
- }
-
- TransformerFactory tfactory = TransformerFactory.newInstance() ;
- Transformer transformer = tfactory.newTransformer() ;
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
-
- DOMSource source = new DOMSource(doc) ;
- FileOutputStream out = new FileOutputStream(outFile) ;
- StreamResult result = new StreamResult(out) ;
- transformer.transform(source, result);
- out.close();
-
- }
- finally {
- if (reader != null) {
- reader.close();
- }
- }
-
- }
-
-
- private void addProperty(String propName, String val) {
- NodeList nl = doc.getElementsByTagName(ROOT_NODE_NAME) ;
- Node rootConfig = nl.item(0) ;
- rootConfig.appendChild(createNewElement(propName,val)) ;
- }
-
- private void modProperty(String propName, String val, boolean createIfNotExists) {
- Node node = findProperty(propName) ;
- if (node != null) {
- NodeList cnl = node.getChildNodes() ;
- for (int j = 0 ; j < cnl.getLength() ; j++) {
- String nodeName = cnl.item(j).getNodeName() ;
- if (nodeName.equals(VALUE_NODE_NAME)) {
- if (cnl.item(j).hasChildNodes()) {
- cnl.item(j).getChildNodes().item(0).setNodeValue(val);
- }
- else {
- Node propValueNode = cnl.item(j) ;
- Node txtNode = doc.createTextNode(val) ;
- propValueNode.appendChild(txtNode) ;
- txtNode.setNodeValue(val);
- }
- return ;
- }
- }
- }
- if (createIfNotExists) {
- addProperty(propName, val);
- }
- }
-
- private String getProperty(String propName) {
- String ret = null;
- try {
- Node node = findProperty(propName) ;
- if (node != null) {
- NodeList cnl = node.getChildNodes() ;
- for (int j = 0 ; j < cnl.getLength() ; j++) {
- String nodeName = cnl.item(j).getNodeName() ;
- if (nodeName.equals(VALUE_NODE_NAME)) {
- Node valueNode = null ;
- if (cnl.item(j).hasChildNodes()) {
- valueNode = cnl.item(j).getChildNodes().item(0) ;
- }
- if (valueNode == null) { // Value Node is defined with
- ret = "" ;
- }
- else {
- ret = valueNode.getNodeValue() ;
- }
- break ;
- }
- }
- }
- }
- catch(Throwable t) {
- throw new RuntimeException("getProperty(" + propName + ") failed.", t) ;
- }
- return ret ;
- }
-
-
- private void delProperty(String propName) {
- Node node = findProperty(propName) ;
- if (node != null) {
- node.getParentNode().removeChild(node) ;
- }
- }
-
-
- private Node findProperty(String propName) {
- Node ret = null;
- try {
- NodeList nl = doc.getElementsByTagName(PROPERTY_NODE_NAME) ;
-
- for(int i = 0 ; i < nl.getLength() ; i++) {
- NodeList cnl = nl.item(i).getChildNodes();
- boolean found = false ;
- for (int j = 0 ; j < cnl.getLength() ; j++) {
- String nodeName = cnl.item(j).getNodeName() ;
- if (nodeName.equals(NAME_NODE_NAME)) {
- String pName = cnl.item(j).getChildNodes().item(0).getNodeValue() ;
- found = pName.equals(propName) ;
- if (found)
- break ;
- }
- }
- if (found) {
- ret = nl.item(i) ;
- break;
- }
- }
- }
- catch(Throwable t) {
- throw new RuntimeException("findProperty(" + propName + ") failed.", t) ;
- }
- return ret ;
- }
-
-
- private Element createNewElement(String propName, String val) {
- Element ret = null ;
-
- try {
- if (doc != null) {
- ret = doc.createElement(PROPERTY_NODE_NAME) ;
- Node propNameNode = doc.createElement(NAME_NODE_NAME) ;
- Node txtNode = doc.createTextNode(propName) ;
- propNameNode.appendChild(txtNode) ;
- propNameNode.setNodeValue(propName);
- ret.appendChild(propNameNode);
-
- Node propValueNode = doc.createElement(VALUE_NODE_NAME) ;
- txtNode = doc.createTextNode(val) ;
- propValueNode.appendChild(txtNode) ;
- propValueNode.setNodeValue(propName);
- ret.appendChild(propValueNode);
- }
- }
- catch(Throwable t) {
- throw new RuntimeException("createNewElement(" + propName + ") with value [" + val + "] failed.", t) ;
- }
-
-
- return ret ;
- }
-
-
- Properties installProperties = new Properties() ;
-
- private void loadInstallProperties() throws IOException {
- if (propFile != null) {
- FileInputStream in = new FileInputStream(propFile) ;
- installProperties.load(in);
- }
- // To support environment variable, we will add all environment variables to the Properties
- installProperties.putAll(System.getenv());
- }
-
-
- private String replaceProp(String propValue, Properties prop) throws ValidationException {
-
- StringBuilder tokensb = new StringBuilder() ;
- StringBuilder retsb = new StringBuilder() ;
- boolean isToken = false ;
-
- for(char c : propValue.toCharArray()) {
- if (c == '%') {
- if (isToken) {
- String token = tokensb.toString();
- String tokenValue = (token.length() == 0 ? "%" : prop.getProperty(token) ) ;
- if (tokenValue == null || tokenValue.trim().isEmpty()) {
- throw new ValidationException("ERROR: configuration token [" + token + "] is not defined in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
- }
- else {
- if (EMPTY_TOKEN.equals(tokenValue)) {
- retsb.append(EMPTY_TOKEN_VALUE) ;
- }
- else {
- retsb.append(tokenValue) ;
- }
- }
- isToken = false;
- }
- else {
- isToken = true ;
- tokensb.setLength(0);
- }
- }
- else if (isToken) {
- tokensb.append(String.valueOf(c)) ;
- }
- else {
- retsb.append(String.valueOf(c)) ;
- }
- }
-
- if (isToken) {
- throw new ValidationException("ERROR: configuration has a token defined without end-token [" + propValue + "] in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
- }
-
- return retsb.toString();
- }
-
-
- @SuppressWarnings("serial")
- class ValidationException extends Exception {
-
- public ValidationException(String msg) {
- super(msg);
- }
-
- public ValidationException(Throwable cause) {
- super(cause);
- }
-
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java
----------------------------------------------------------------------
diff --git a/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java b/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java
new file mode 100644
index 0000000..3632c1a
--- /dev/null
+++ b/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ranger.utils.install;
+
+import java.util.ArrayList;
+import java.util.Random;
+
+public class PasswordGenerator {
+
+
+ private int minimumPasswordLength = 8 ;
+
+ private int maximumPasswordLength = 12 ;
+
+ private boolean isExpectedNumberic = true ;
+
+ private boolean isExpectedBothCase = true ;
+
+ private static final ArrayList<Character> alphaLetters = new ArrayList<Character>() ;
+
+ private static final ArrayList<Character> alphaUpperLetters = new ArrayList<Character>() ;
+
+ private static final ArrayList<Character> numericLetters = new ArrayList<Character>() ;
+
+
+ static {
+ for(int x = 'a' ; x <= 'z' ; x++) {
+ char v = (char)x ;
+ alphaLetters.add(Character.toLowerCase(v)) ;
+ alphaUpperLetters.add(Character.toUpperCase(v)) ;
+ }
+ for(int i = 0 ; i < 10 ; i++) {
+ numericLetters.add(Character.forDigit(i,10)) ;
+ }
+ }
+
+
+
+ public static void main(String[] args) {
+ PasswordGenerator pg = new PasswordGenerator() ;
+ System.out.println(pg.generatorPassword()) ;
+ }
+
+
+ private int getPasswordLength() {
+ int ret = 0;
+
+ if (minimumPasswordLength == maximumPasswordLength) {
+ ret = minimumPasswordLength ;
+ }
+ else {
+
+ int diff = Math.abs(maximumPasswordLength - minimumPasswordLength) + 1 ;
+ ret = minimumPasswordLength + new Random().nextInt(diff) ;
+ }
+ return (ret) ;
+ }
+
+
+ public String generatorPassword() {
+
+ String password = null ;
+
+ ArrayList<Character> all = new ArrayList<Character>() ;
+
+ all.addAll(alphaLetters) ;
+ all.addAll(alphaUpperLetters) ;
+ all.addAll(numericLetters) ;
+
+ int len = getPasswordLength() ;
+
+ Random random = new Random() ;
+
+ int setSz = all.size();
+
+ do
+ {
+ StringBuilder sb = new StringBuilder();
+
+ for(int i = 0 ; i < len ; i++) {
+ int index = random.nextInt(setSz) ;
+ Character c = all.get(index) ;
+ while ((i == 0) && Character.isDigit(c)) {
+ index = random.nextInt(setSz) ;
+ c = all.get(index) ;
+ }
+ sb.append(all.get(index)) ;
+ }
+ password = sb.toString() ;
+ } while (! isValidPassword(password)) ;
+
+
+ return password ;
+
+ }
+
+ private boolean isValidPassword(String pass) {
+ boolean ret = true ;
+
+ if (isExpectedNumberic || isExpectedBothCase) {
+ boolean lowerCaseFound = false ;
+ boolean digitFound = false ;
+ boolean upperCaseFound = false ;
+ for(char c : pass.toCharArray()) {
+ if (!digitFound && Character.isDigit(c)) {
+ digitFound = true ;
+ }
+ else if (!lowerCaseFound && Character.isLowerCase(c)) {
+ lowerCaseFound = true ;
+ }
+ else if (!upperCaseFound && Character.isUpperCase(c) ) {
+ upperCaseFound = true ;
+ }
+ }
+
+ if (isExpectedNumberic && !digitFound) {
+ ret = false ;
+ }
+
+ if (isExpectedBothCase && (!lowerCaseFound || !upperCaseFound)) {
+ ret = false ;
+ }
+ }
+
+ return ret ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java
----------------------------------------------------------------------
diff --git a/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java b/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java
new file mode 100644
index 0000000..9c5fb6f
--- /dev/null
+++ b/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java
@@ -0,0 +1,494 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+ package org.apache.ranger.utils.install;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Properties;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.apache.commons.cli.BasicParser;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+public class XmlConfigChanger {
+
+ private static final String EMPTY_TOKEN = "%EMPTY%" ;
+ private static final String EMPTY_TOKEN_VALUE = "" ;
+
+ public static final String ROOT_NODE_NAME = "configuration" ;
+ public static final String NAME_NODE_NAME = "name" ;
+ public static final String PROPERTY_NODE_NAME = "property" ;
+ public static final String VALUE_NODE_NAME = "value" ;
+
+ private File inpFile ;
+ private File outFile ;
+ private File confFile ;
+ private File propFile ;
+
+ private Document doc ;
+
+
+
+ public static void main(String[] args) {
+ XmlConfigChanger xmlConfigChanger = new XmlConfigChanger() ;
+ xmlConfigChanger.parseConfig(args);
+ try {
+ xmlConfigChanger.run();
+ }
+ catch(Throwable t) {
+ System.err.println("*************************************************************************") ;
+ System.err.println("******* ERROR: unable to process xml configuration changes due to error:" + t.getMessage()) ;
+ t.printStackTrace();
+ System.err.println("*************************************************************************") ;
+ System.exit(1);
+ }
+ }
+
+
+
+
+ @SuppressWarnings("static-access")
+ public void parseConfig(String[] args) {
+
+
+ Options options = new Options();
+
+ Option inputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("input").withDescription("Input xml file name").create('i');
+ options.addOption(inputOption);
+
+ Option outputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("output").withDescription("Output xml file name").create('o');
+ options.addOption(outputOption);
+
+ Option configOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("config").withDescription("Config file name").create('c');
+ options.addOption(configOption);
+
+ Option installPropOption = OptionBuilder.hasArgs(1).isRequired(false).withLongOpt("installprop").withDescription("install.properties").create('p');
+ options.addOption(installPropOption);
+
+ CommandLineParser parser = new BasicParser();
+ CommandLine cmd = null ;
+ try {
+ cmd = parser.parse(options, args);
+ } catch (ParseException e) {
+ String header = "ERROR: " + e ;
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String inputFileName = cmd.getOptionValue('i') ;
+ this.inpFile = new File(inputFileName) ;
+ if (! this.inpFile.canRead()) {
+ String header = "ERROR: Input file [" + this.inpFile.getAbsolutePath() + "] can not be read.";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String outputFileName = cmd.getOptionValue('o') ;
+ this.outFile = new File(outputFileName) ;
+ if (this.outFile.exists()) {
+ String header = "ERROR: Output file [" + this.outFile.getAbsolutePath() + "] already exists. Specify a filepath for creating new output file for the input [" + this.inpFile.getAbsolutePath() + "]";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String configFileName = cmd.getOptionValue('c') ;
+ this.confFile = new File(configFileName) ;
+ if (! this.confFile.canRead()) {
+ String header = "ERROR: Config file [" + this.confFile.getAbsolutePath() + "] can not be read.";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String installPropFileName = (cmd.hasOption('p') ? cmd.getOptionValue('p') : null ) ;
+ if (installPropFileName != null) {
+ this.propFile = new File(installPropFileName) ;
+ if (! this.propFile.canRead()) {
+ String header = "ERROR: Install Property file [" + this.propFile.getAbsolutePath() + "] can not be read.";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+ }
+
+ }
+
+
+
+
+ public void run() throws ParserConfigurationException, SAXException, IOException, TransformerException {
+
+
+ loadInstallProperties() ;
+
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
+ DocumentBuilder builder = factory.newDocumentBuilder() ;
+ doc = builder.parse(inpFile) ;
+
+ BufferedReader reader = null ;
+ try {
+ reader = new BufferedReader(new FileReader(confFile)) ;
+
+ String line = null ;
+
+ @SuppressWarnings("unused")
+ int lineNo = 0 ;
+
+ while ((line = reader.readLine()) != null) {
+
+ lineNo++ ;
+
+ line = line.trim() ;
+
+ if (line.isEmpty() )
+ continue ;
+ if (line.startsWith("#")) {
+ continue ;
+ }
+
+ if (line.contains("#")) {
+ int len = line.indexOf("#") ;
+ line = line.substring(0,len) ;
+ }
+
+ String[] tokens = line.split("\\s+") ;
+
+ String propName = tokens[0] ;
+
+ String propValue = null ;
+
+ try {
+ propValue = replaceProp(tokens[1],installProperties) ;
+ } catch (ValidationException e) {
+ // throw new RuntimeException("Unable to replace tokens in the line: \n[" + line + "]\n in file [" + confFile.getAbsolutePath() + "] line number:[" + lineNo + "]" ) ;
+ throw new RuntimeException(e) ;
+ }
+
+
+
+ String actionType = tokens[2] ;
+ String options = (tokens.length > 3 ? tokens[3] : null) ;
+ boolean createIfNotExists = (options != null && options.contains("create-if-not-exists")) ;
+
+
+ if ("add".equals(actionType)) {
+ addProperty(propName, propValue);
+ }
+ else if ("mod".equals(actionType)) {
+ modProperty(propName, propValue,createIfNotExists);
+ }
+ else if ("del".equals(actionType)) {
+ delProperty(propName);
+ }
+ else if ("append".equals(actionType)) {
+ String curVal = getProperty(propName) ;
+ if (curVal == null) {
+ if (createIfNotExists) {
+ addProperty(propName, propValue);
+ }
+ }
+ else {
+ String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
+ if (! curVal.contains(propValue)) {
+ String newVal = null ;
+ if (curVal.length() == 0) {
+ newVal = propValue ;
+ }
+ else {
+ newVal = curVal + appendDelimitor + propValue ;
+ }
+ modProperty(propName, newVal,createIfNotExists) ;
+ }
+ }
+ }
+ else if ("delval".equals(actionType)) {
+ String curVal = getProperty(propName) ;
+ if (curVal != null) {
+ String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
+ if (curVal.contains(propValue)) {
+ String[] valTokens = curVal.split(appendDelimitor) ;
+ StringBuilder sb = new StringBuilder() ;
+ for(String v : valTokens) {
+ if (! v.equals(propValue)) {
+ if (sb.length() > 0) {
+ sb.append(appendDelimitor) ;
+ }
+ sb.append(v);
+ }
+ }
+ String newVal = sb.toString() ;
+ modProperty(propName, newVal,createIfNotExists) ;
+ }
+ }
+ }
+ else {
+ throw new RuntimeException("Unknown Command Found: [" + actionType + "], Supported Types: add modify del append") ;
+ }
+
+ }
+
+ TransformerFactory tfactory = TransformerFactory.newInstance() ;
+ Transformer transformer = tfactory.newTransformer() ;
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
+
+ DOMSource source = new DOMSource(doc) ;
+ FileOutputStream out = new FileOutputStream(outFile) ;
+ StreamResult result = new StreamResult(out) ;
+ transformer.transform(source, result);
+ out.close();
+
+ }
+ finally {
+ if (reader != null) {
+ reader.close();
+ }
+ }
+
+ }
+
+
+ private void addProperty(String propName, String val) {
+ NodeList nl = doc.getElementsByTagName(ROOT_NODE_NAME) ;
+ Node rootConfig = nl.item(0) ;
+ rootConfig.appendChild(createNewElement(propName,val)) ;
+ }
+
+ private void modProperty(String propName, String val, boolean createIfNotExists) {
+ Node node = findProperty(propName) ;
+ if (node != null) {
+ NodeList cnl = node.getChildNodes() ;
+ for (int j = 0 ; j < cnl.getLength() ; j++) {
+ String nodeName = cnl.item(j).getNodeName() ;
+ if (nodeName.equals(VALUE_NODE_NAME)) {
+ if (cnl.item(j).hasChildNodes()) {
+ cnl.item(j).getChildNodes().item(0).setNodeValue(val);
+ }
+ else {
+ Node propValueNode = cnl.item(j) ;
+ Node txtNode = doc.createTextNode(val) ;
+ propValueNode.appendChild(txtNode) ;
+ txtNode.setNodeValue(val);
+ }
+ return ;
+ }
+ }
+ }
+ if (createIfNotExists) {
+ addProperty(propName, val);
+ }
+ }
+
+ private String getProperty(String propName) {
+ String ret = null;
+ try {
+ Node node = findProperty(propName) ;
+ if (node != null) {
+ NodeList cnl = node.getChildNodes() ;
+ for (int j = 0 ; j < cnl.getLength() ; j++) {
+ String nodeName = cnl.item(j).getNodeName() ;
+ if (nodeName.equals(VALUE_NODE_NAME)) {
+ Node valueNode = null ;
+ if (cnl.item(j).hasChildNodes()) {
+ valueNode = cnl.item(j).getChildNodes().item(0) ;
+ }
+ if (valueNode == null) { // Value Node is defined with
+ ret = "" ;
+ }
+ else {
+ ret = valueNode.getNodeValue() ;
+ }
+ break ;
+ }
+ }
+ }
+ }
+ catch(Throwable t) {
+ throw new RuntimeException("getProperty(" + propName + ") failed.", t) ;
+ }
+ return ret ;
+ }
+
+
+ private void delProperty(String propName) {
+ Node node = findProperty(propName) ;
+ if (node != null) {
+ node.getParentNode().removeChild(node) ;
+ }
+ }
+
+
+ private Node findProperty(String propName) {
+ Node ret = null;
+ try {
+ NodeList nl = doc.getElementsByTagName(PROPERTY_NODE_NAME) ;
+
+ for(int i = 0 ; i < nl.getLength() ; i++) {
+ NodeList cnl = nl.item(i).getChildNodes();
+ boolean found = false ;
+ for (int j = 0 ; j < cnl.getLength() ; j++) {
+ String nodeName = cnl.item(j).getNodeName() ;
+ if (nodeName.equals(NAME_NODE_NAME)) {
+ String pName = cnl.item(j).getChildNodes().item(0).getNodeValue() ;
+ found = pName.equals(propName) ;
+ if (found)
+ break ;
+ }
+ }
+ if (found) {
+ ret = nl.item(i) ;
+ break;
+ }
+ }
+ }
+ catch(Throwable t) {
+ throw new RuntimeException("findProperty(" + propName + ") failed.", t) ;
+ }
+ return ret ;
+ }
+
+
+ private Element createNewElement(String propName, String val) {
+ Element ret = null ;
+
+ try {
+ if (doc != null) {
+ ret = doc.createElement(PROPERTY_NODE_NAME) ;
+ Node propNameNode = doc.createElement(NAME_NODE_NAME) ;
+ Node txtNode = doc.createTextNode(propName) ;
+ propNameNode.appendChild(txtNode) ;
+ propNameNode.setNodeValue(propName);
+ ret.appendChild(propNameNode);
+
+ Node propValueNode = doc.createElement(VALUE_NODE_NAME) ;
+ txtNode = doc.createTextNode(val) ;
+ propValueNode.appendChild(txtNode) ;
+ propValueNode.setNodeValue(propName);
+ ret.appendChild(propValueNode);
+ }
+ }
+ catch(Throwable t) {
+ throw new RuntimeException("createNewElement(" + propName + ") with value [" + val + "] failed.", t) ;
+ }
+
+
+ return ret ;
+ }
+
+
+ Properties installProperties = new Properties() ;
+
+ private void loadInstallProperties() throws IOException {
+ if (propFile != null) {
+ FileInputStream in = new FileInputStream(propFile) ;
+ installProperties.load(in);
+ }
+ // To support environment variable, we will add all environment variables to the Properties
+ installProperties.putAll(System.getenv());
+ }
+
+
+ private String replaceProp(String propValue, Properties prop) throws ValidationException {
+
+ StringBuilder tokensb = new StringBuilder() ;
+ StringBuilder retsb = new StringBuilder() ;
+ boolean isToken = false ;
+
+ for(char c : propValue.toCharArray()) {
+ if (c == '%') {
+ if (isToken) {
+ String token = tokensb.toString();
+ String tokenValue = (token.length() == 0 ? "%" : prop.getProperty(token) ) ;
+ if (tokenValue == null || tokenValue.trim().isEmpty()) {
+ throw new ValidationException("ERROR: configuration token [" + token + "] is not defined in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
+ }
+ else {
+ if (EMPTY_TOKEN.equals(tokenValue)) {
+ retsb.append(EMPTY_TOKEN_VALUE) ;
+ }
+ else {
+ retsb.append(tokenValue) ;
+ }
+ }
+ isToken = false;
+ }
+ else {
+ isToken = true ;
+ tokensb.setLength(0);
+ }
+ }
+ else if (isToken) {
+ tokensb.append(String.valueOf(c)) ;
+ }
+ else {
+ retsb.append(String.valueOf(c)) ;
+ }
+ }
+
+ if (isToken) {
+ throw new ValidationException("ERROR: configuration has a token defined without end-token [" + propValue + "] in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
+ }
+
+ return retsb.toString();
+ }
+
+
+ @SuppressWarnings("serial")
+ class ValidationException extends Exception {
+
+ public ValidationException(String msg) {
+ super(msg);
+ }
+
+ public ValidationException(Throwable cause) {
+ super(cause);
+ }
+
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/.gitignore
----------------------------------------------------------------------
diff --git a/credentialbuilder/.gitignore b/credentialbuilder/.gitignore
index 0f63015..de3a426 100644
--- a/credentialbuilder/.gitignore
+++ b/credentialbuilder/.gitignore
@@ -1,2 +1,3 @@
/target/
/bin/
+/bin/
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java b/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java
deleted file mode 100644
index f0627ae..0000000
--- a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
- package com.hortonworks.credentialapi;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.alias.CredentialProvider;
-import org.apache.hadoop.security.alias.CredentialProviderFactory;
-import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
-
-public class CredentialReader {
-
- public static String getDecryptedString(String CrendentialProviderPath,String alias) {
- String credential=null;
- try{
- if(CrendentialProviderPath==null || alias==null){
- return null;
- }
- char[] pass = null;
- Configuration conf = new Configuration();
- String crendentialProviderPrefix=JavaKeyStoreProvider.SCHEME_NAME + "://file";
- crendentialProviderPrefix=crendentialProviderPrefix.toLowerCase();
- CrendentialProviderPath=CrendentialProviderPath.trim();
- alias=alias.trim();
- if(CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefix)){
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- CrendentialProviderPath);
- }else{
- if(CrendentialProviderPath.startsWith("/")){
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- JavaKeyStoreProvider.SCHEME_NAME + "://file" + CrendentialProviderPath);
- }else{
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- JavaKeyStoreProvider.SCHEME_NAME + "://file/" + CrendentialProviderPath);
- }
- }
- List<CredentialProvider> providers = CredentialProviderFactory.getProviders(conf);
- List<String> aliasesList=new ArrayList<String>();
- CredentialProvider.CredentialEntry credEntry=null;
- for(CredentialProvider provider: providers) {
- //System.out.println("Credential Provider :" + provider);
- aliasesList=provider.getAliases();
- if(aliasesList!=null && aliasesList.contains(alias.toLowerCase())){
- credEntry=null;
- credEntry= provider.getCredentialEntry(alias);
- pass = credEntry.getCredential();
- if(pass!=null && pass.length>0){
- credential=String.valueOf(pass);
- break;
- }
- }
- }
- }catch(Exception ex){
- ex.printStackTrace();
- credential=null;
- }
- return credential;
- }
-
- /*
- public static void main(String args[]) throws Exception{
- String keystoreFile =new String("/tmp/mykey3.jceks");
- String password=CredentialReader.getDecryptedString(keystoreFile, "mykey3");
- System.out.println(password);
- }*/
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java b/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java
deleted file mode 100644
index 717fba2..0000000
--- a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java
+++ /dev/null
@@ -1,433 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
- package com.hortonworks.credentialapi;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.alias.CredentialShell;
-import org.apache.hadoop.util.GenericOptionsParser;
-
-public class buildks {
- public static void main(String[] args) {
- buildks buildksOBJ=new buildks();
- String command=null;
- try{
- if(args!=null && args.length>=3){
- command=args[0];
- if(command!=null && !command.trim().isEmpty()){
- if(command.equalsIgnoreCase("create")){
- buildksOBJ.createCredential(args);
- }else if(command.equalsIgnoreCase("list")){
- buildksOBJ.listCredential(args);
- }else if(command.equalsIgnoreCase("get")){
- String credential=buildksOBJ.getCredential(args);
- if(credential!=null){
- System.out.println(credential);
- System.exit(0);
- }else{
- System.exit(1);
- }
- }else{
- System.out.println(command +" is not supported in current version of CredentialBuilder API.");
- System.exit(1);
- }
- }
- }else{
- System.out.println("Invalid Command line argument.");
- System.exit(1);
- }
- }catch(Exception ex){
- ex.printStackTrace();
- System.exit(1);
- }
- }
-
- public int createCredential(String args[]){
- int returnCode=-1;
- String command=null;
- String alias=null;
- String valueOption=null;
- String credential=null;
- String providerOption=null;
- String providerPath=null;
- String tempCredential=null;
- try{
- if(args!=null && args.length==6)
- {
- command=args[0];
- alias=args[1];
- valueOption=args[2];
- credential=args[3];
- providerOption=args[4];
- providerPath=args[5];
- if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
- return returnCode;
- }
- tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
- }else{
- return returnCode;
- }
-
- if(tempCredential==null){
- returnCode=createKeyStore(args);
- }else{
- try{
- System.out.println("Alias already exist!! will try to delete first.");
- String argsDelete[]=new String[4];
- argsDelete[0]="delete";
- argsDelete[1]=alias;
- argsDelete[2]=providerOption;
- argsDelete[3]=providerPath;
- returnCode=deleteCredential(argsDelete);
- if(returnCode==0){
- returnCode=createKeyStore(args);
- }
- }catch(Exception ex){
- returnCode=-1;
- }
- }
- }catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public int createKeyStore(String args[]){
- int returnCode=-1;
- try{
- String command=null;
- String alias=null;
- String valueOption=null;
- String credential=null;
- String providerOption=null;
- String providerPath=null;
- if(args!=null && args.length==6)
- {
- command=args[0];
- alias=args[1];
- valueOption=args[2];
- credential=args[3];
- providerOption=args[4];
- providerPath=args[5];
- if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
- return returnCode;
- }
- displayCommand(args);
- }else{
- return returnCode;
- }
-
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- // int i = 0 ;
- // for(String s : toolArgs) {
- // System.out.println("TooArgs [" + i + "] = [" + s + "]") ;
- // i++ ;
- // }
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
- public int createCredentialFromUserInput(){
- int returnCode=-1;
- try{
- String[] args=null;
- String command=null;
- String alias=null;
- String valueOption=null;
- String credential=null;
- String providerOption=null;
- String providerPath=null;
- //below code can ask user to input if command line input fails
- System.out.println("Enter Alias Name:");
- BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
- alias = bufferRead.readLine();
- System.out.println("Enter password:");
- credential = bufferRead.readLine();
- System.out.println("Enter .jceks output file name with path:");
- providerPath = bufferRead.readLine();
- if(providerPath!=null && !providerPath.trim().isEmpty() && !providerPath.startsWith("jceks://file"))
- {
- if(providerPath.startsWith("/")){
- providerPath="jceks://file"+providerPath;
- }else{
- providerPath="jceks://file/"+providerPath;
- }
- }
- command="create";
- valueOption="-value";
- providerOption="-provider";
- if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
- return returnCode;
- }
- args=new String[6];
- args[0]=command;
- args[1]=alias;
- args[2]=valueOption;
- args[3]=credential;
- args[4]=providerOption;
- args[5]=providerPath;
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public int listCredential(String args[]){
- int returnCode=-1;
- try{
- if(args!=null && args.length==3)
- {
- //display command which need to be executed or entered
- displayCommand(args);
- }else{
- return returnCode;
- }
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public int deleteCredential(String args[]){
- int returnCode=-1;
- try{
- if(args!=null && args.length==4)
- {
- //display command which need to be executed or entered
- displayCommand(args);
- }else{
- return returnCode;
- }
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public static boolean isValidCreateCommand(String command,String alias,String valueOption,String credential,String providerOption,String providerPath)
- {
- boolean isValid=true;
- try{
- if(command==null || !"create".equalsIgnoreCase(command.trim()))
- {
- System.out.println("Invalid create phrase in credential creation command!!");
- System.out.println("Expected:'create' Found:'"+command+"'");
- displaySyntax("create");
- return false;
- }
- if(alias==null || "".equalsIgnoreCase(alias.trim()))
- {
- System.out.println("Invalid alias name phrase in credential creation command!!");
- System.out.println("Found:'"+alias+"'");
- displaySyntax("create");
- return false;
- }
- if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
- {
- System.out.println("Invalid value option switch in credential creation command!!");
- System.out.println("Expected:'-value' Found:'"+valueOption+"'");
- displaySyntax("create");
- return false;
- }
- if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
- {
- System.out.println("Invalid value option in credential creation command!!");
- System.out.println("Expected:'-value' Found:'"+valueOption+"'");
- displaySyntax("create");
- return false;
- }
- if(credential==null)
- {
- System.out.println("Invalid credential value in credential creation command!!");
- System.out.println("Found:"+credential);
- displaySyntax("create");
- return false;
- }
- if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
- {
- System.out.println("Invalid provider option in credential creation command!!");
- System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
- displaySyntax("create");
- return false;
- }
- if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
- {
- System.out.println("Invalid provider option in credential creation command!!");
- System.out.println("Found:'"+providerPath+"'");
- displaySyntax("create");
- return false;
- }
- }catch(Exception ex){
- System.out.println("Invalid input or runtime error! Please try again.");
- System.out.println("Input:"+command+" "+alias+" "+valueOption+" "+credential+" "+providerOption+" "+providerPath);
- displaySyntax("create");
- ex.printStackTrace();
- return false;
- }
- return isValid;
- }
-
- public static void displayCommand(String args[])
- {
- String debugOption = System.getProperty("debug") ;
- if (debugOption != null && "TRUE".equalsIgnoreCase(debugOption)) {
- StringBuffer tempBuffer=new StringBuffer("");
- if(args!=null && args.length>0){
- for(int index=0;index<args.length;index++){
- tempBuffer.append(args[index]+" ");
- }
- System.out.println("Command to execute:["+tempBuffer+"]");
- }
- }
- }
-
- public static void displaySyntax(String command){
- if(command!=null && command.trim().equalsIgnoreCase("create")){
- System.out.println("Correct syntax is:create <aliasname> -value <password> -provider <jceks://file/filepath>");
- System.out.println("sample command is:create myalias -value password123 -provider jceks://file/tmp/ks/myks.jceks");
- }
- }
- public String getCredential(String args[]){
- String command=null;
- String alias=null;
- String providerOption=null;
- String providerPath=null;
- String tempCredential=null;
- try{
- if(args!=null && args.length==4){
- command=args[0];
- alias=args[1];
- providerOption=args[2];
- providerPath=args[3];
- if(!isValidGetCommand(command,alias,providerOption,providerPath)){
- displaySyntax("get");
- }else{
- tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
- }
- }else{
- displaySyntax("get");
- }
- if(tempCredential==null){
- System.out.println("Alias "+ alias +" does not exist!!");
- }
- }catch(Exception ex){
- ex.printStackTrace();
- }
- return tempCredential;
- }
-
- public static boolean isValidGetCommand(String command,String alias,String providerOption,String providerPath){
- boolean isValid=true;
- try{
- if(command==null || !"get".equalsIgnoreCase(command.trim())){
- System.out.println("Invalid get phrase in credential get command!!");
- System.out.println("Expected:'get' Found:'"+command+"'");
- displaySyntax("get");
- return false;
- }
- if(alias==null || "".equalsIgnoreCase(alias.trim()))
- {
- System.out.println("Invalid alias name phrase in credential get command!!");
- System.out.println("Found:'"+alias+"'");
- displaySyntax("get");
- return false;
- }
- if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
- {
- System.out.println("Invalid provider option in credential get command!!");
- System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
- displaySyntax("get");
- return false;
- }
- if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
- {
- System.out.println("Invalid provider option in credential get command!!");
- System.out.println("Found:'"+providerPath+"'");
- displaySyntax("get");
- return false;
- }
- }catch(Exception ex){
- System.out.println("Invalid input or runtime error! Please try again.");
- System.out.println("Input:"+command+" "+alias+" "+providerOption+" "+providerPath);
- displaySyntax("get");
- ex.printStackTrace();
- return false;
- }
- return isValid;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
new file mode 100644
index 0000000..0b4a71a
--- /dev/null
+++ b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+ package org.apache.ranger.credentialapi;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.alias.CredentialProvider;
+import org.apache.hadoop.security.alias.CredentialProviderFactory;
+import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
+
+public class CredentialReader {
+
+ public static String getDecryptedString(String CrendentialProviderPath,String alias) {
+ String credential=null;
+ try{
+ if(CrendentialProviderPath==null || alias==null){
+ return null;
+ }
+ char[] pass = null;
+ Configuration conf = new Configuration();
+ String crendentialProviderPrefix=JavaKeyStoreProvider.SCHEME_NAME + "://file";
+ crendentialProviderPrefix=crendentialProviderPrefix.toLowerCase();
+ CrendentialProviderPath=CrendentialProviderPath.trim();
+ alias=alias.trim();
+ if(CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefix)){
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ CrendentialProviderPath);
+ }else{
+ if(CrendentialProviderPath.startsWith("/")){
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ JavaKeyStoreProvider.SCHEME_NAME + "://file" + CrendentialProviderPath);
+ }else{
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ JavaKeyStoreProvider.SCHEME_NAME + "://file/" + CrendentialProviderPath);
+ }
+ }
+ List<CredentialProvider> providers = CredentialProviderFactory.getProviders(conf);
+ List<String> aliasesList=new ArrayList<String>();
+ CredentialProvider.CredentialEntry credEntry=null;
+ for(CredentialProvider provider: providers) {
+ //System.out.println("Credential Provider :" + provider);
+ aliasesList=provider.getAliases();
+ if(aliasesList!=null && aliasesList.contains(alias.toLowerCase())){
+ credEntry=null;
+ credEntry= provider.getCredentialEntry(alias);
+ pass = credEntry.getCredential();
+ if(pass!=null && pass.length>0){
+ credential=String.valueOf(pass);
+ break;
+ }
+ }
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ credential=null;
+ }
+ return credential;
+ }
+
+ /*
+ public static void main(String args[]) throws Exception{
+ String keystoreFile =new String("/tmp/mykey3.jceks");
+ String password=CredentialReader.getDecryptedString(keystoreFile, "mykey3");
+ System.out.println(password);
+ }*/
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java
new file mode 100644
index 0000000..25be1d6
--- /dev/null
+++ b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java
@@ -0,0 +1,433 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+ package org.apache.ranger.credentialapi;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.alias.CredentialShell;
+import org.apache.hadoop.util.GenericOptionsParser;
+
+public class buildks {
+ public static void main(String[] args) {
+ buildks buildksOBJ=new buildks();
+ String command=null;
+ try{
+ if(args!=null && args.length>=3){
+ command=args[0];
+ if(command!=null && !command.trim().isEmpty()){
+ if(command.equalsIgnoreCase("create")){
+ buildksOBJ.createCredential(args);
+ }else if(command.equalsIgnoreCase("list")){
+ buildksOBJ.listCredential(args);
+ }else if(command.equalsIgnoreCase("get")){
+ String credential=buildksOBJ.getCredential(args);
+ if(credential!=null){
+ System.out.println(credential);
+ System.exit(0);
+ }else{
+ System.exit(1);
+ }
+ }else{
+ System.out.println(command +" is not supported in current version of CredentialBuilder API.");
+ System.exit(1);
+ }
+ }
+ }else{
+ System.out.println("Invalid Command line argument.");
+ System.exit(1);
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ public int createCredential(String args[]){
+ int returnCode=-1;
+ String command=null;
+ String alias=null;
+ String valueOption=null;
+ String credential=null;
+ String providerOption=null;
+ String providerPath=null;
+ String tempCredential=null;
+ try{
+ if(args!=null && args.length==6)
+ {
+ command=args[0];
+ alias=args[1];
+ valueOption=args[2];
+ credential=args[3];
+ providerOption=args[4];
+ providerPath=args[5];
+ if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
+ return returnCode;
+ }
+ tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
+ }else{
+ return returnCode;
+ }
+
+ if(tempCredential==null){
+ returnCode=createKeyStore(args);
+ }else{
+ try{
+ System.out.println("Alias already exist!! will try to delete first.");
+ String argsDelete[]=new String[4];
+ argsDelete[0]="delete";
+ argsDelete[1]=alias;
+ argsDelete[2]=providerOption;
+ argsDelete[3]=providerPath;
+ returnCode=deleteCredential(argsDelete);
+ if(returnCode==0){
+ returnCode=createKeyStore(args);
+ }
+ }catch(Exception ex){
+ returnCode=-1;
+ }
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public int createKeyStore(String args[]){
+ int returnCode=-1;
+ try{
+ String command=null;
+ String alias=null;
+ String valueOption=null;
+ String credential=null;
+ String providerOption=null;
+ String providerPath=null;
+ if(args!=null && args.length==6)
+ {
+ command=args[0];
+ alias=args[1];
+ valueOption=args[2];
+ credential=args[3];
+ providerOption=args[4];
+ providerPath=args[5];
+ if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
+ return returnCode;
+ }
+ displayCommand(args);
+ }else{
+ return returnCode;
+ }
+
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ // int i = 0 ;
+ // for(String s : toolArgs) {
+ // System.out.println("TooArgs [" + i + "] = [" + s + "]") ;
+ // i++ ;
+ // }
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+ public int createCredentialFromUserInput(){
+ int returnCode=-1;
+ try{
+ String[] args=null;
+ String command=null;
+ String alias=null;
+ String valueOption=null;
+ String credential=null;
+ String providerOption=null;
+ String providerPath=null;
+ //below code can ask user to input if command line input fails
+ System.out.println("Enter Alias Name:");
+ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
+ alias = bufferRead.readLine();
+ System.out.println("Enter password:");
+ credential = bufferRead.readLine();
+ System.out.println("Enter .jceks output file name with path:");
+ providerPath = bufferRead.readLine();
+ if(providerPath!=null && !providerPath.trim().isEmpty() && !providerPath.startsWith("jceks://file"))
+ {
+ if(providerPath.startsWith("/")){
+ providerPath="jceks://file"+providerPath;
+ }else{
+ providerPath="jceks://file/"+providerPath;
+ }
+ }
+ command="create";
+ valueOption="-value";
+ providerOption="-provider";
+ if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
+ return returnCode;
+ }
+ args=new String[6];
+ args[0]=command;
+ args[1]=alias;
+ args[2]=valueOption;
+ args[3]=credential;
+ args[4]=providerOption;
+ args[5]=providerPath;
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public int listCredential(String args[]){
+ int returnCode=-1;
+ try{
+ if(args!=null && args.length==3)
+ {
+ //display command which need to be executed or entered
+ displayCommand(args);
+ }else{
+ return returnCode;
+ }
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public int deleteCredential(String args[]){
+ int returnCode=-1;
+ try{
+ if(args!=null && args.length==4)
+ {
+ //display command which need to be executed or entered
+ displayCommand(args);
+ }else{
+ return returnCode;
+ }
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public static boolean isValidCreateCommand(String command,String alias,String valueOption,String credential,String providerOption,String providerPath)
+ {
+ boolean isValid=true;
+ try{
+ if(command==null || !"create".equalsIgnoreCase(command.trim()))
+ {
+ System.out.println("Invalid create phrase in credential creation command!!");
+ System.out.println("Expected:'create' Found:'"+command+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(alias==null || "".equalsIgnoreCase(alias.trim()))
+ {
+ System.out.println("Invalid alias name phrase in credential creation command!!");
+ System.out.println("Found:'"+alias+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
+ {
+ System.out.println("Invalid value option switch in credential creation command!!");
+ System.out.println("Expected:'-value' Found:'"+valueOption+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
+ {
+ System.out.println("Invalid value option in credential creation command!!");
+ System.out.println("Expected:'-value' Found:'"+valueOption+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(credential==null)
+ {
+ System.out.println("Invalid credential value in credential creation command!!");
+ System.out.println("Found:"+credential);
+ displaySyntax("create");
+ return false;
+ }
+ if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
+ {
+ System.out.println("Invalid provider option in credential creation command!!");
+ System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
+ {
+ System.out.println("Invalid provider option in credential creation command!!");
+ System.out.println("Found:'"+providerPath+"'");
+ displaySyntax("create");
+ return false;
+ }
+ }catch(Exception ex){
+ System.out.println("Invalid input or runtime error! Please try again.");
+ System.out.println("Input:"+command+" "+alias+" "+valueOption+" "+credential+" "+providerOption+" "+providerPath);
+ displaySyntax("create");
+ ex.printStackTrace();
+ return false;
+ }
+ return isValid;
+ }
+
+ public static void displayCommand(String args[])
+ {
+ String debugOption = System.getProperty("debug") ;
+ if (debugOption != null && "TRUE".equalsIgnoreCase(debugOption)) {
+ StringBuffer tempBuffer=new StringBuffer("");
+ if(args!=null && args.length>0){
+ for(int index=0;index<args.length;index++){
+ tempBuffer.append(args[index]+" ");
+ }
+ System.out.println("Command to execute:["+tempBuffer+"]");
+ }
+ }
+ }
+
+ public static void displaySyntax(String command){
+ if(command!=null && command.trim().equalsIgnoreCase("create")){
+ System.out.println("Correct syntax is:create <aliasname> -value <password> -provider <jceks://file/filepath>");
+ System.out.println("sample command is:create myalias -value password123 -provider jceks://file/tmp/ks/myks.jceks");
+ }
+ }
+ public String getCredential(String args[]){
+ String command=null;
+ String alias=null;
+ String providerOption=null;
+ String providerPath=null;
+ String tempCredential=null;
+ try{
+ if(args!=null && args.length==4){
+ command=args[0];
+ alias=args[1];
+ providerOption=args[2];
+ providerPath=args[3];
+ if(!isValidGetCommand(command,alias,providerOption,providerPath)){
+ displaySyntax("get");
+ }else{
+ tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
+ }
+ }else{
+ displaySyntax("get");
+ }
+ if(tempCredential==null){
+ System.out.println("Alias "+ alias +" does not exist!!");
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return tempCredential;
+ }
+
+ public static boolean isValidGetCommand(String command,String alias,String providerOption,String providerPath){
+ boolean isValid=true;
+ try{
+ if(command==null || !"get".equalsIgnoreCase(command.trim())){
+ System.out.println("Invalid get phrase in credential get command!!");
+ System.out.println("Expected:'get' Found:'"+command+"'");
+ displaySyntax("get");
+ return false;
+ }
+ if(alias==null || "".equalsIgnoreCase(alias.trim()))
+ {
+ System.out.println("Invalid alias name phrase in credential get command!!");
+ System.out.println("Found:'"+alias+"'");
+ displaySyntax("get");
+ return false;
+ }
+ if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
+ {
+ System.out.println("Invalid provider option in credential get command!!");
+ System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
+ displaySyntax("get");
+ return false;
+ }
+ if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
+ {
+ System.out.println("Invalid provider option in credential get command!!");
+ System.out.println("Found:'"+providerPath+"'");
+ displaySyntax("get");
+ return false;
+ }
+ }catch(Exception ex){
+ System.out.println("Invalid input or runtime error! Please try again.");
+ System.out.println("Input:"+command+" "+alias+" "+providerOption+" "+providerPath);
+ displaySyntax("get");
+ ex.printStackTrace();
+ return false;
+ }
+ return isValid;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java b/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java
deleted file mode 100644
index 8becce8..0000000
--- a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.hortonworks.credentialapi;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class TestCredentialReader {
- private final String keystoreFile =System.getProperty("user.home")+"/testkeystore.jceks";
- @Before
- public void setup() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"create", "TestCredential2", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
- int rc2=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals( 0, rc2);
- assertTrue(rc2==0);
- }
-
- @Test
- public void testPassword() throws Exception {
- String password=CredentialReader.getDecryptedString(keystoreFile, "TestCredential2");
- assertEquals( "PassworD123", password);
- assertTrue(password,"PassworD123".equals(password));
- //delete after use
- String[] argsdeleteCommand = {"delete", "TestCredential2", "-provider", "jceks://file" + keystoreFile};
- buildks buildksOBJ=new buildks();
- buildksOBJ.deleteCredential(argsdeleteCommand);
-
- }
-
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java b/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java
deleted file mode 100644
index e4acf89..0000000
--- a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.hortonworks.credentialapi;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-public class Testbuildks {
- private final String keystoreFile =System.getProperty("user.home")+"/testkeystore.jceks";
- @Test
- public void testBuildKSsuccess() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"create", "TestCredential1", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
- int rc1=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals( 0, rc1);
- assertTrue(rc1==0);
-
- String[] argsListCommand = {"list", "-provider","jceks://file" + keystoreFile};
- int rc2=buildksOBJ.listCredential(argsListCommand);
- assertEquals(0, rc2);
- assertTrue(rc2==0);
-
- String[] argsGetCommand = {"get", "TestCredential1", "-provider", "jceks://file" +keystoreFile };
- String pw=buildksOBJ.getCredential(argsGetCommand);
- assertEquals("PassworD123", pw);
- assertTrue(pw.equals("PassworD123"));
- boolean getCredentialPassed = pw.equals("PassworD123");
-
- String[] argsDeleteCommand = {"delete", "TestCredential1", "-provider", "jceks://file" +keystoreFile };
- int rc3=buildksOBJ.deleteCredential(argsDeleteCommand);
- assertEquals(0, rc3);
- assertTrue(rc3==0);
-
- if(rc1==rc2 && rc2==rc3 && rc3==0 && getCredentialPassed){
- System.out.println("Test Case has been completed successfully..");
- }
- }
-
- @Test
- public void testInvalidProvider() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"create", "TestCredential1", "-value", "PassworD123", "-provider", "jksp://file"+keystoreFile};
- int rc1=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals(-1, rc1);
- assertTrue(rc1==-1);
- }
-
- @Test
- public void testInvalidCommand() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"creat", "TestCredential1", "-value", "PassworD123", "-provider", "jksp://file"+keystoreFile};
- int rc1=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals(-1, rc1);
- assertTrue(rc1==-1);
- }
- /*public static void main(String args[]) throws Exception{
- Testbuildks tTestbuildks=new Testbuildks();
- tTestbuildks.testBuildKSsuccess();
- }*/
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java b/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java
new file mode 100644
index 0000000..f3e1ca8
--- /dev/null
+++ b/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ranger.credentialapi;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.ranger.credentialapi.CredentialReader;
+import org.apache.ranger.credentialapi.buildks;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestCredentialReader {
+ private final String keystoreFile =System.getProperty("user.home")+"/testkeystore.jceks";
+ @Before
+ public void setup() throws Exception {
+ buildks buildksOBJ=new buildks();
+ String[] argsCreateCommand = {"create", "TestCredential2", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
+ int rc2=buildksOBJ.createCredential(argsCreateCommand);
+ assertEquals( 0, rc2);
+ assertTrue(rc2==0);
+ }
+
+ @Test
+ public void testPassword() throws Exception {
+ String password=CredentialReader.getDecryptedString(keystoreFile, "TestCredential2");
+ assertEquals( "PassworD123", password);
+ assertTrue(password,"PassworD123".equals(password));
+ //delete after use
+ String[] argsdeleteCommand = {"delete", "TestCredential2", "-provider", "jceks://file" + keystoreFile};
+ buildks buildksOBJ=new buildks();
+ buildksOBJ.deleteCredential(argsdeleteCommand);
+
+ }
+
+
+
+
+}