List of usage examples for java.util Scanner nextLine
public String nextLine()
From source file:Main.java
public static void main(String[] args) { String s = "java2s.com 1 + 1 = 2.0"; Scanner scanner = new Scanner(s); // find a pattern of 2 letters before com, with horizon of 5 System.out.println(scanner.findWithinHorizon(Pattern.compile("..com"), 5)); // find a pattern of 2 letters before com, with horizon of 10 System.out.println(scanner.findWithinHorizon(Pattern.compile("..com"), 10)); // print the rest of the string System.out.println(scanner.nextLine()); scanner.close();// www . j av a 2 s. co m }
From source file:com.git.ifly6.components.Census.java
public static void main(String[] args) { Scanner scan = new Scanner(System.in); try {// www . j av a2 s . co m region = new NSRegion(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("Please input the name of your region: \t"); region = new NSRegion(scan.nextLine()); } try { HashMap<String, Integer> endoMap = new HashMap<String, Integer>(); String[] waMembers = region.getWAMembers(); int[] valueCount = new int[waMembers.length]; System.out.println( "[INFO] This census will take: " + time((int) Math.round(waitTime * waMembers.length))); for (int i = 0; i < waMembers.length; i++) { NSNation nation = new NSNation(waMembers[i]); valueCount[i] = nation.getEndoCount(); endoMap.put(waMembers[i], new Integer(valueCount[i])); System.out.println("[LOG] Fetched information for: " + waMembers[i] + ", " + (i + 1) + " of " + waMembers.length); } TreeMap<String, Integer> sortedMap = sortByValue(endoMap); int current = 0; int previous = sortedMap.firstEntry().getValue(); System.out.printf("%-35s %12s %12s%n", "Nations", "Endorsements", "Difference"); System.out.println("-------------------------------------------------------------"); for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) { String nationName = StringUtils.capitalize(entry.getKey().replace('_', ' ')); current = entry.getValue(); if ((previous - current) != 0) { System.out.printf("%-35s %12s %12s%n", nationName, entry.getValue(), (previous - current)); } else { System.out.printf("%-35s %12s %12s%n", nationName, entry.getValue(), "-"); } previous = entry.getValue(); } System.out.println("-------------------------------------------------------------"); System.out.printf("%-35s %12s %12s%n", "Delegate", "Endorsements", "Proportion"); System.out.printf("%-35s %12s %12s%n", StringUtils.capitalize(sortedMap.firstEntry().getKey().replace('_', ' ')), sortedMap.firstEntry().getValue(), (double) (sortedMap.firstEntry().getValue() / waMembers.length)); } catch (IOException e) { printError("Failed to fetch WA members or get endorsements in this region. " + "Check your internet connection or the state of the API."); } scan.close(); }
From source file:com.github.rnewson.couchdb.lucene.Index.java
public static void main(String[] args) throws Exception { Utils.LOG.info("indexer started."); final Indexer indexer = new Indexer(FSDirectory.getDirectory(Config.INDEX_DIR)); final Thread thread = new Thread(indexer, "index"); thread.setDaemon(true);//from w w w . ja v a 2 s .com thread.start(); final Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { final String line = scanner.nextLine(); final JSONObject obj = JSONObject.fromObject(line); if (obj.has("type") && obj.has("db")) { indexer.setStale(true); } } Utils.LOG.info("indexer stopped."); }
From source file:com.joliciel.talismane.terminology.TalismaneTermExtractorMain.java
public static void main(String[] args) throws Exception { String termFilePath = null;//from w w w .j a va 2 s .com String outFilePath = null; Command command = Command.extract; int depth = -1; String databasePropertiesPath = null; String projectCode = null; String terminologyPropertiesPath = null; Map<String, String> argMap = StringUtils.convertArgs(args); String logConfigPath = argMap.get("logConfigFile"); if (logConfigPath != null) { argMap.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } Map<String, String> innerArgs = new HashMap<String, String>(); for (Entry<String, String> argEntry : argMap.entrySet()) { String argName = argEntry.getKey(); String argValue = argEntry.getValue(); if (argName.equals("command")) command = Command.valueOf(argValue); else if (argName.equals("termFile")) termFilePath = argValue; else if (argName.equals("outFile")) outFilePath = argValue; else if (argName.equals("depth")) depth = Integer.parseInt(argValue); else if (argName.equals("databaseProperties")) databasePropertiesPath = argValue; else if (argName.equals("terminologyProperties")) terminologyPropertiesPath = argValue; else if (argName.equals("projectCode")) projectCode = argValue; else innerArgs.put(argName, argValue); } if (termFilePath == null && databasePropertiesPath == null) throw new TalismaneException("Required argument: termFile or databasePropertiesPath"); if (termFilePath != null) { String currentDirPath = System.getProperty("user.dir"); File termFileDir = new File(currentDirPath); if (termFilePath.lastIndexOf("/") >= 0) { String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/")); termFileDir = new File(termFileDirPath); termFileDir.mkdirs(); } } long startTime = new Date().getTime(); try { if (command.equals(Command.analyse)) { innerArgs.put("command", "analyse"); } else { innerArgs.put("command", "process"); } String sessionId = ""; TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId); TalismaneService talismaneService = locator.getTalismaneService(); TalismaneConfig config = talismaneService.getTalismaneConfig(innerArgs, sessionId); TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(locator); TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService(); TerminologyBase terminologyBase = null; if (projectCode == null) throw new TalismaneException("Required argument: projectCode"); File file = new File(databasePropertiesPath); FileInputStream fis = new FileInputStream(file); Properties dataSourceProperties = new Properties(); dataSourceProperties.load(fis); terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties); TalismaneSession talismaneSession = talismaneService.getTalismaneSession(); if (command.equals(Command.analyse) || command.equals(Command.extract)) { Locale locale = talismaneSession.getLocale(); Map<TerminologyProperty, String> terminologyProperties = new HashMap<TerminologyProperty, String>(); if (terminologyPropertiesPath != null) { Map<String, String> terminologyPropertiesStr = StringUtils.getArgMap(terminologyPropertiesPath); for (String key : terminologyPropertiesStr.keySet()) { try { TerminologyProperty property = TerminologyProperty.valueOf(key); terminologyProperties.put(property, terminologyPropertiesStr.get(key)); } catch (IllegalArgumentException e) { throw new TalismaneException("Unknown terminology property: " + key); } } } else { terminologyProperties = getDefaultTerminologyProperties(locale); } if (depth <= 0 && !terminologyProperties.containsKey(TerminologyProperty.maxDepth)) throw new TalismaneException("Required argument: depth"); InputStream regexInputStream = getInputStreamFromResource( "parser_conll_with_location_input_regex.txt"); Scanner regexScanner = new Scanner(regexInputStream, "UTF-8"); String inputRegex = regexScanner.nextLine(); regexScanner.close(); config.setInputRegex(inputRegex); Charset outputCharset = config.getOutputCharset(); TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase, terminologyProperties); if (depth > 0) termExtractor.setMaxDepth(depth); termExtractor.setOutFilePath(termFilePath); if (outFilePath != null) { if (outFilePath.lastIndexOf("/") >= 0) { String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/")); File outFileDir = new File(outFileDirPath); outFileDir.mkdirs(); } File outFile = new File(outFilePath); outFile.delete(); outFile.createNewFile(); Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset)); TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer); termExtractor.addTermObserver(termAnalysisWriter); } Talismane talismane = config.getTalismane(); talismane.setParseConfigurationProcessor(termExtractor); talismane.process(); } else if (command.equals(Command.list)) { List<Term> terms = terminologyBase.findTerms(2, null, 0, null, null); for (Term term : terms) { LOG.debug("Term: " + term.getText()); LOG.debug("Frequency: " + term.getFrequency()); LOG.debug("Heads: " + term.getHeads()); LOG.debug("Expansions: " + term.getExpansions()); LOG.debug("Contexts: " + term.getContexts()); } } } finally { long endTime = new Date().getTime(); long totalTime = endTime - startTime; LOG.info("Total time: " + totalTime); } }
From source file:net.sfr.tv.mom.mgt.HornetqConsole.java
/** * @param args the command line arguments *///w w w . ja v a 2 s . co m public static void main(String[] args) { try { String jmxHost = "127.0.0.1"; String jmxPort = "6001"; // Process command line arguments String arg; for (int i = 0; i < args.length; i++) { arg = args[i]; switch (arg) { case "-h": jmxHost = args[++i]; break; case "-p": jmxPort = args[++i]; break; default: break; } } // Check for arguments consistency if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) { LOGGER.info("Usage : "); LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n"); System.exit(1); } System.out.println( SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN))); final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':') .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort) .append("/jmxrmi"); final String jmxServiceUrl = _url.toString(); JMXConnector jmxc = null; final CommandRouter router = new CommandRouter(); try { jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null); assert jmxc != null; // jmxc must be not null } catch (final MalformedURLException e) { System.out.println(SystemUtils.LINE_SEPARATOR .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED))); } catch (Throwable t) { System.out.println(SystemUtils.LINE_SEPARATOR.concat( Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED))); System.out.print(SystemUtils.LINE_SEPARATOR.concat( Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA))); System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format( "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?", Color.MAGENTA))); System.exit(-1); } System.out.println("\n".concat(Ansi .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW))); final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); // PRINT SERVER STATUS REPORT System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null)); System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null)); System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null)); printHelp(router); // START COMMAND LINE Scanner scanner = new Scanner(System.in); System.out.print("> "); String input; while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) { String[] cliArgs = input.split("\\ "); CommandHandler handler; if (cliArgs.length < 1) { System.out.print("> "); continue; } Command cmd = Command.fromString(cliArgs[0]); if (cmd == null) { System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n")); cmd = Command.HELP; } switch (cmd) { case STATUS: case LIST: case DROP: Set<Option> options = router.get(cmd); for (Option opt : options) { if (cliArgs[1].equals(opt.toString())) { handler = router.get(cmd, opt); String[] cmdOpts = null; if (cliArgs.length > 2) { cmdOpts = new String[cliArgs.length - 2]; for (int i = 0; i < cmdOpts.length; i++) { cmdOpts[i] = cliArgs[2 + i]; } } Object result = handler.execute(mbsc, cmdOpts); if (result != null && String.class.isAssignableFrom(result.getClass())) { System.out.print((String) result); } System.out.print("> "); } } break; case FORK: // EXECUTE SYSTEM COMMAND ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length)); pb.inheritIO(); pb.start(); break; case HELP: printHelp(router); break; } } } catch (MalformedURLException ex) { LOGGER.log(Level.SEVERE, null, ex); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN))); }
From source file:net.airvantage.sample.AirVantageExampleFlow2.java
public static void main(String[] args) { String apiUrl = "https://na.airvantage.net/api"; // Replace these with your own api key and secret String apiKey = "your_app_id"; String apiSecret = "your_api_secret"; String login = null;//from w w w . j av a 2 s. c o m String password = null; String access_token = null; Scanner in = new Scanner(System.in); System.out.println("=== AirVantage's OAuth Workflow ==="); System.out.println(); // Obtain User/Password System.out.println("Enter your login:"); System.out.print(">>"); login = in.nextLine(); System.out.println(); System.out.println("...and your password:"); System.out.print(">>"); password = in.nextLine(); System.out.println(); // Get the Access Token System.out.println("Getting the Access Token..."); System.out.println(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password + "&client_id=" + apiKey + "&client_secret=" + apiSecret); try { access_token = Request .Get(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password + "&client_id=" + apiKey + "&client_secret=" + apiSecret) .execute().handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } try { String content = IOUtils.toString(entity.getContent()); JSONObject result = new JSONObject(content); return result.getString("access_token"); } catch (JSONException e) { throw new ClientProtocolException("Malformed JSON", e); } } }); System.out.println("Got the Access Token!"); System.out.println("(if you're curious it looks like this: " + access_token + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to get info about the current user..."); JSONObject result = Request.Get(apiUrl + "/v1/users/current?access_token=" + access_token).execute() .handleResponse(new ResponseHandler<JSONObject>() { public JSONObject handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } try { String content = IOUtils.toString(entity.getContent()); return new JSONObject(content); } catch (JSONException e) { throw new ClientProtocolException("Malformed JSON", e); } } }); System.out.println("Got it! Let's see what we found..."); System.out.println(); System.out.println(result.toString()); System.out.println(); System.out.println("That's it man! Go and build something awesome with AirVantage! :)"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:bankconsoleapp.console.Main.java
/** * @param args the command line arguments *///w w w.j a va 2 s. c o m public static void main(String[] args) { //Injecting applicationContext to main ApplicationContext context = new ClassPathXmlApplicationContext("bankconsoleapp/applicationContext.xml"); EmployeeService eS = context.getBean("EmployeeService", EmployeeService.class); CustomerService cS = context.getBean("CustomerService", CustomerService.class); SavingService sS = context.getBean("SavingService", SavingService.class); String userName, pass; Scanner in = new Scanner(System.in); boolean user = false; boolean savingRedo = false; do { System.out.println("Enter Employee ID:"); userName = in.nextLine(); for (Employee emp : eS.getAllEmp()) { if (userName.equals(emp.geteID())) { System.out.println("Password:"); pass = in.nextLine(); for (Employee em : eS.getAllEmp()) { if (pass.equals(em.getPassword())) { user = true; } } } } } while (!user); long start = System.currentTimeMillis(); long end = start + 60 * 1000; // 60 seconds * 1000 ms/sec int operation = 0; int userChoice; boolean quit = false; do { System.out.println("ACME Bank Saving System:"); System.out.println("------------------------"); System.out.println("1. Create Customer & Saving Account"); System.out.println("2. Deposit Money"); System.out.println("3. Withdraw Money"); System.out.println("4. View Balance"); System.out.println("5. Quit"); System.out.print("Operation count: " + operation + "(Shut down at 5)"); userChoice = in.nextInt(); switch (userChoice) { case 1: //create customer, then saving account regard to existing customer( maximum 2 SA per Customer) System.out.println("Create Customer :"); String FirstN, LastN, DoB, accNum, answer; Scanner sc = new Scanner(System.in); Customer c = new Customer(); int saID = 0; System.out.println("Enter First Name:"); FirstN = sc.nextLine(); c.setFname(FirstN); System.out.println("Enter Last Name:"); LastN = sc.nextLine(); c.setLname(LastN); System.out.println("Enter Date of Birth:"); DoB = sc.nextLine(); c.setDoB(DoB); do { System.out.println("Creating saving acount, Enter Account Number:"); accNum = sc.nextLine(); c.setSA(accNum); c.setSavingAccounts(c.getSA()); saID++; System.out.println("Create another SA? Y/N?"); answer = sc.nextLine(); if (answer.equals("n")) { savingRedo = true; } if (saID == 2) { System.out.println("Maximum Saving account reached!"); } } while (!savingRedo && saID != 2); cS.createCustomer(c); operation++; break; case 2: // deposit String acNum; int amt; Scanner sc1 = new Scanner(System.in); System.out.println("Enter Saving Account number u wish to do deposit."); acNum = sc1.nextLine(); System.out.println("Enter amount :"); amt = sc1.nextInt(); sS.deposit(acNum, amt); operation++; break; case 3: String acNums; int amts; Scanner sc2 = new Scanner(System.in); System.out.println("Enter Saving Account number u wish to do withdraw."); acNums = sc2.nextLine(); System.out.println("Enter amount :"); amts = sc2.nextInt(); sS.withdraw(acNums, amts); operation++; break; case 4: // view System.out.println("Saving Account Balance:"); System.out.println(sS.getAllSA()); operation++; break; case 5: quit = true; break; default: System.out.println("Wrong choice."); break; } System.out.println(); if (operation == 5) { System.out.println("5 operation reached, System shutdown."); } if (System.currentTimeMillis() > end) { System.out.println("Session Expired."); } } while (!quit && operation != 5 && System.currentTimeMillis() < end); System.out.println("Bye!"); }
From source file:br.usp.poli.lta.cereda.spa2run.Main.java
public static void main(String[] args) { Utils.printBanner();//from w ww . j a va 2 s. c o m CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(Utils.getOptions(), args); List<Spec> specs = Utils.fromFilesToSpecs(line.getArgs()); List<Metric> metrics = Utils.fromFilesToMetrics(line); Utils.setMetrics(metrics); Utils.resetCalculations(); AdaptiveAutomaton automaton = Utils.getAutomatonFromSpecs(specs); System.out.println("SPA generated successfully:"); System.out.println("- " + specs.size() + " submachine(s) found."); if (!Utils.detectEpsilon(automaton)) { System.out.println("- No empty transitions."); } if (!metrics.isEmpty()) { System.out.println("- " + metrics.size() + " metric(s) found."); } System.out.println("\nStarting shell, please wait...\n" + "(press CTRL+C or type `:quit'\n" + "to exit the application)\n"); String query = ""; Scanner scanner = new Scanner(System.in); String prompt = "[%d] query> "; String result = "[%d] result> "; int counter = 1; do { try { String term = String.format(prompt, counter); System.out.print(term); query = scanner.nextLine().trim(); if (!query.equals(":quit")) { boolean accept = automaton.recognize(Utils.toSymbols(query)); String type = automaton.getRecognitionPaths().size() == 1 ? " (deterministic)" : " (nondeterministic)"; System.out.println(String.format(result, counter) + accept + type); if (!metrics.isEmpty()) { System.out.println(StringUtils.repeat(" ", String.format("[%d] ", counter).length()) + Utils.prettyPrintMetrics()); } System.out.println(); } } catch (Exception exception) { System.out.println(); Utils.printException(exception); System.out.println(); } counter++; Utils.resetCalculations(); } while (!query.equals(":quit")); System.out.println("That's all folks!"); } catch (ParseException nothandled) { Utils.printHelp(); } catch (Exception exception) { Utils.printException(exception); } }
From source file:carmen.demo.LocationResolverDemo.java
public static void main(String[] args) throws ParseException, FileNotFoundException, IOException, ClassNotFoundException { // Parse the command line. String[] manditory_args = { "input_file" }; createCommandLineOptions();/* w ww. j a v a 2 s . c o m*/ CommandLineUtilities.initCommandLineParameters(args, LocationResolverDemo.options, manditory_args); // Get options String inputFile = CommandLineUtilities.getOptionValue("input_file"); String outputFile = null; if (CommandLineUtilities.hasArg("output_file")) { outputFile = CommandLineUtilities.getOptionValue("output_file"); } logger.info("Creating LocationResolver."); LocationResolver resolver = LocationResolver.getLocationResolver(); Scanner scanner = Utils.createScanner(inputFile); Writer writer = null; if (outputFile != null) { writer = Utils.createWriter(outputFile); logger.info("Saving geolocated tweets to: " + outputFile); } ObjectMapper mapper = new ObjectMapper(); int numResolved = 0; int total = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); @SuppressWarnings("unchecked") HashMap<String, Object> tweet = (HashMap<String, Object>) mapper.readValue(line, Map.class); total++; Location location = resolver.resolveLocationFromTweet(tweet); if (location != null) { logger.debug("Found location: " + location.toString()); numResolved++; } if (writer != null) { if (location != null) { tweet.put("location", Location.createJsonFromLocation(location)); } mapper.writeValue(writer, tweet); writer.write("\n"); } } scanner.close(); if (writer != null) writer.close(); logger.info("Resolved locations for " + numResolved + " of " + total + " tweets."); }
From source file:com.thinkbiganalytics.kerberos.TestKerberosKinit.java
public static void main(String[] args) throws Exception { final TestKerberosKinit testKerberosKinit = new TestKerberosKinit(); Scanner scanner = new Scanner(System.in); System.out.println(" "); System.out.print("Which environment are you in? Enter 1 for HDP or 2 for Cloudera: "); String environmentCode = scanner.nextLine(); if (StringUtils.isEmpty(environmentCode)) { environmentCode = "1"; }//from w ww .j a v a 2 s . co m String environment; switch (environmentCode) { case "1": environment = ENVIRONMENT_HDP; break; case "2": environment = ENVIRONMENT_CLOUDERA; break; default: throw new Exception("Invalid environment code"); } System.out.println(" "); System.out.println( "Hit enter to default to: /etc/hadoop/conf/core-site.xml,/etc/hadoop/conf/hdfs-site.xml,/usr/hdp/current/hive-client/conf/hive-site.xml"); System.out.print("Please enter the list of configuration resources: "); String configResources = scanner.nextLine(); if (StringUtils.isEmpty(configResources)) { configResources = "/etc/hadoop/conf/core-site.xml,/etc/hadoop/conf/hdfs-site.xml,/usr/hdp/current/hive-client/conf/hive-site.xml"; } System.out.println(" "); System.out.println("Hit enter to default to: /etc/security/keytabs/hive-thinkbig.headless.keytab"); System.out.print("Please enter the keytab file location: "); String keytab = scanner.nextLine(); if (StringUtils.isEmpty(keytab)) { keytab = "/etc/security/keytabs/hive-thinkbig.headless.keytab"; } System.out.println(" "); System.out.println("Hit enter to default to: hive/sandbox.hortonworks.com@sandbox.hortonworks.com"); System.out.print("Please enter the real user principal name: "); String realUserPrincipal = scanner.nextLine(); if (StringUtils.isEmpty(realUserPrincipal)) { realUserPrincipal = "hive/sandbox.hortonworks.com@sandbox.hortonworks.com"; } System.out.println(" "); System.out.println("Please enter Y/N (default is N)"); System.out.print("Do you want to test with a proxy user: "); String proxyUser = scanner.nextLine(); if (StringUtils.isEmpty(realUserPrincipal)) { proxyUser = "N"; } System.out.println(" "); System.out.println("Hit enter to default to: hdfs://sandbox.hortonworks.com:8020"); System.out.print("Please enter the HDFS URL: "); String hdfsUrl = scanner.nextLine(); if (StringUtils.isEmpty(hdfsUrl)) { hdfsUrl = "hdfs://sandbox.hortonworks.com:8020"; } System.out.println(" "); System.out.println("Hit enter to default to: jdbc:hive2://localhost:10000/default"); System.out.print("Please enter the Hive base connection string: "); String hiveHost = scanner.nextLine(); if (StringUtils.isEmpty(hiveHost)) { hiveHost = "jdbc:hive2://localhost:10000/default"; } String proxyUserName = null; if ("Y".equalsIgnoreCase(proxyUser)) { System.out.println(" "); System.out.print("Please enter the proxy user: "); proxyUserName = scanner.next(); } System.out.println(" "); System.out.println("Executing Kinit to generate a kerberos ticket"); if ("Y".equalsIgnoreCase(proxyUser)) { System.out.println("Testing with the proxy user: " + proxyUserName); testKerberosKinit.testHdfsWithUserImpersonation(configResources, keytab, realUserPrincipal, proxyUserName, environment, hdfsUrl); //testKerberosKinit.testHiveJdbcConnectionWithUserImpersonation(configResources, keytab, realUserPrincipal, proxyUserName); testKerberosKinit.testHiveJdbcConnection(configResources, keytab, realUserPrincipal, proxyUserName, hiveHost); } else { System.out.println("No Proxy User"); testKerberosKinit.testHdfsAsKerberosUser(configResources, keytab, realUserPrincipal, environment, hdfsUrl); testKerberosKinit.testHiveJdbcConnection(configResources, keytab, realUserPrincipal, null, hiveHost); } }