List of usage examples for java.lang System console
public static Console console()
From source file:org.apache.sqoop.SqoopOptions.java
/** * Allow the user to enter his password on the console without printing * characters.//from ww w.j ava 2 s .c om * @return the password as a string */ private String securePasswordEntry() { try { return new String(System.console().readPassword("Enter password: ")); } catch (NullPointerException e) { LOG.error("It seems that you have launched a Sqoop metastore job via"); LOG.error("Oozie with sqoop.metastore.client.record.password disabled."); LOG.error("But this configuration is not supported because Sqoop can't"); LOG.error("prompt the user to enter the password while being executed"); LOG.error("as Oozie tasks. Please enable sqoop.metastore.client.record"); LOG.error(".password in sqoop-site.xml, or provide the password"); LOG.error("explictly using --password in the command tag of the Oozie"); LOG.error("workflow file."); return null; } }
From source file:com.datatorrent.stram.cli.DTCli.java
public void preImpersonationInit(String[] args) throws IOException { Signal.handle(new Signal("INT"), new SignalHandler() { @Override/*from ww w .ja v a 2 s . c om*/ public void handle(Signal sig) { System.out.println("^C"); if (commandThread != null) { commandThread.interrupt(); mainThread.interrupt(); } else { System.out.print(prompt); System.out.flush(); } } }); consolePresent = (System.console() != null); Options options = new Options(); options.addOption("e", true, "Commands are read from the argument"); options.addOption("v", false, "Verbose mode level 1"); options.addOption("vv", false, "Verbose mode level 2"); options.addOption("vvv", false, "Verbose mode level 3"); options.addOption("vvvv", false, "Verbose mode level 4"); options.addOption("r", false, "JSON Raw mode"); options.addOption("p", true, "JSONP padding function"); options.addOption("h", false, "Print this help"); options.addOption("f", true, "Use the specified prompt at all time"); options.addOption("kp", true, "Use the specified kerberos principal"); options.addOption("kt", true, "Use the specified kerberos keytab"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("v")) { verboseLevel = 1; } if (cmd.hasOption("vv")) { verboseLevel = 2; } if (cmd.hasOption("vvv")) { verboseLevel = 3; } if (cmd.hasOption("vvvv")) { verboseLevel = 4; } if (cmd.hasOption("r")) { raw = true; } if (cmd.hasOption("e")) { commandsToExecute = cmd.getOptionValues("e"); consolePresent = false; } if (cmd.hasOption("p")) { jsonp = cmd.getOptionValue("p"); } if (cmd.hasOption("f")) { forcePrompt = cmd.getOptionValue("f"); } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(DTCli.class.getSimpleName(), options); System.exit(0); } if (cmd.hasOption("kp")) { kerberosPrincipal = cmd.getOptionValue("kp"); } if (cmd.hasOption("kt")) { kerberosKeyTab = cmd.getOptionValue("kt"); } } catch (ParseException ex) { System.err.println("Invalid argument: " + ex); System.exit(1); } if (kerberosPrincipal == null && kerberosKeyTab != null) { System.err.println( "Kerberos key tab is specified but not the kerberos principal. Please specify it using the -kp option."); System.exit(1); } if (kerberosPrincipal != null && kerberosKeyTab == null) { System.err.println( "Kerberos principal is specified but not the kerberos key tab. Please specify it using the -kt option."); System.exit(1); } Level logLevel; switch (verboseLevel) { case 0: logLevel = Level.OFF; break; case 1: logLevel = Level.ERROR; break; case 2: logLevel = Level.WARN; break; case 3: logLevel = Level.INFO; break; default: logLevel = Level.DEBUG; break; } for (org.apache.log4j.Logger logger : new org.apache.log4j.Logger[] { org.apache.log4j.Logger.getRootLogger(), org.apache.log4j.Logger.getLogger(DTCli.class) }) { @SuppressWarnings("unchecked") Enumeration<Appender> allAppenders = logger.getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender appender = allAppenders.nextElement(); if (appender instanceof ConsoleAppender) { ((ConsoleAppender) appender).setThreshold(logLevel); } } } if (commandsToExecute != null) { for (String command : commandsToExecute) { LOG.debug("Command to be executed: {}", command); } } if (kerberosPrincipal != null && kerberosKeyTab != null) { StramUserLogin.authenticate(kerberosPrincipal, kerberosKeyTab); } else { Configuration config = new YarnConfiguration(); StramClientUtils.addDTLocalResources(config); StramUserLogin.attemptAuthentication(config); } }
From source file:org.quickserver.net.server.QuickServer.java
/** * Sets the console log handler level.//ww w . j av a 2s . c om * @since 1.2 */ public void setConsoleLoggingLevel(Level level) { Logger rlogger = Logger.getLogger(""); Handler[] handlers = rlogger.getHandlers(); boolean isConsole = true; try { if (System.console() == null) { isConsole = false; } } catch (Throwable e) { //ignore } for (int index = 0; index < handlers.length; index++) { if (ConsoleHandler.class.isInstance(handlers[index])) { if (isConsole == false && level != Level.OFF) { System.out.println("QuickServer: You do not have a console.. so turning console logger off.."); level = Level.OFF; } if (level == Level.OFF) { logger.info("QuickServer: Removing console handler.. "); rlogger.removeHandler(handlers[index]); handlers[index].setLevel(level); handlers[index].close(); } else { handlers[index].setLevel(level); } } } if (level == Level.SEVERE) consoleLoggingLevel = "SEVERE"; else if (level == Level.WARNING) consoleLoggingLevel = "WARNING"; else if (level == Level.INFO) consoleLoggingLevel = "INFO"; else if (level == Level.CONFIG) consoleLoggingLevel = "CONFIG"; else if (level == Level.FINE) consoleLoggingLevel = "FINE"; else if (level == Level.FINER) consoleLoggingLevel = "FINER"; else if (level == Level.FINEST) consoleLoggingLevel = "FINEST"; else if (level == Level.OFF) consoleLoggingLevel = "OFF"; else consoleLoggingLevel = "UNKNOWN"; logger.log(Level.FINE, "Set to {0}", level); }
From source file:com.clark.func.Functions.java
public static Console console() { return System.console(); }
From source file:com.datatorrent.stram.cli.ApexCli.java
public void preImpersonationInit(String[] args) throws IOException { Signal.handle(new Signal("INT"), new SignalHandler() { @Override//from w w w. j a va 2 s . co m public void handle(Signal sig) { System.out.println("^C"); if (commandThread != null) { commandThread.interrupt(); mainThread.interrupt(); } else { System.out.print(prompt); System.out.flush(); } } }); consolePresent = (System.console() != null); Options options = new Options(); options.addOption("e", true, "Commands are read from the argument"); options.addOption("v", false, "Verbose mode level 1"); options.addOption("vv", false, "Verbose mode level 2"); options.addOption("vvv", false, "Verbose mode level 3"); options.addOption("vvvv", false, "Verbose mode level 4"); options.addOption("r", false, "JSON Raw mode"); options.addOption("p", true, "JSONP padding function"); options.addOption("h", false, "Print this help"); options.addOption("f", true, "Use the specified prompt at all time"); options.addOption("kp", true, "Use the specified kerberos principal"); options.addOption("kt", true, "Use the specified kerberos keytab"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("v")) { verboseLevel = 1; } if (cmd.hasOption("vv")) { verboseLevel = 2; } if (cmd.hasOption("vvv")) { verboseLevel = 3; } if (cmd.hasOption("vvvv")) { verboseLevel = 4; } if (cmd.hasOption("r")) { raw = true; } if (cmd.hasOption("e")) { commandsToExecute = cmd.getOptionValues("e"); consolePresent = false; } if (cmd.hasOption("p")) { jsonp = cmd.getOptionValue("p"); } if (cmd.hasOption("f")) { forcePrompt = cmd.getOptionValue("f"); } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ApexCli.class.getSimpleName(), options); System.exit(0); } if (cmd.hasOption("kp")) { kerberosPrincipal = cmd.getOptionValue("kp"); } if (cmd.hasOption("kt")) { kerberosKeyTab = cmd.getOptionValue("kt"); } } catch (ParseException ex) { System.err.println("Invalid argument: " + ex); System.exit(1); } if (kerberosPrincipal == null && kerberosKeyTab != null) { System.err.println( "Kerberos key tab is specified but not the kerberos principal. Please specify it using the -kp option."); System.exit(1); } if (kerberosPrincipal != null && kerberosKeyTab == null) { System.err.println( "Kerberos principal is specified but not the kerberos key tab. Please specify it using the -kt option."); System.exit(1); } Level logLevel; switch (verboseLevel) { case 0: logLevel = Level.OFF; break; case 1: logLevel = Level.ERROR; break; case 2: logLevel = Level.WARN; break; case 3: logLevel = Level.INFO; break; default: logLevel = Level.DEBUG; break; } for (org.apache.log4j.Logger logger : new org.apache.log4j.Logger[] { org.apache.log4j.Logger.getRootLogger(), org.apache.log4j.Logger.getLogger(ApexCli.class) }) { /* * Override logLevel specified by user, the same logLevel would be inherited by all * appenders related to logger. */ logger.setLevel(logLevel); @SuppressWarnings("unchecked") Enumeration<Appender> allAppenders = logger.getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender appender = allAppenders.nextElement(); if (appender instanceof ConsoleAppender) { ((ConsoleAppender) appender).setThreshold(logLevel); } } } if (commandsToExecute != null) { for (String command : commandsToExecute) { LOG.debug("Command to be executed: {}", command); } } if (kerberosPrincipal != null && kerberosKeyTab != null) { StramUserLogin.authenticate(kerberosPrincipal, kerberosKeyTab); } else { Configuration config = new YarnConfiguration(); StramClientUtils.addDTLocalResources(config); StramUserLogin.attemptAuthentication(config); } }
From source file:me.gloriouseggroll.quorrabot.Quorrabot.java
public static void main(String[] args) throws IOException { String user = ""; String oauth = ""; String apioauth = ""; String channelName = ""; String webauth = ""; String webauthro = ""; String clientid = ""; String owner = ""; String hostname = ""; int baseport = 25300; InetAddress ip = InetAddress.getByName("127.0.0.1"); int port = 0; double msglimit30 = 18.75; String datastore = ""; String datastoreconfig = ""; String youtubekey = ""; String gamewispauth = ""; String gamewisprefresh = ""; String twitchalertstoken = ""; String lastfmuser = ""; String tpetoken = ""; String twittertoken = ""; String twittertokensecret = ""; String streamtiptoken = ""; String streamtipid = ""; boolean webenable = true; boolean musicenable = true; boolean usehttps = false; String keystorepath = ""; String keystorepassword = ""; String timeZone = ""; String mySqlConn = ""; String mySqlHost = ""; String mySqlPort = ""; String mySqlName = ""; String mySqlUser = ""; String mySqlPass = ""; FollowersCache followersCache;/*ww w . j a v a 2s. co m*/ ChannelUsersCache channelUsersCache; ChannelHostCache hostCache; SubscribersCache subscribersCache; String discordToken = ""; String discordMainChannel = ""; boolean changed = false; try { if (new File("./botlogin.txt").exists()) { String data = FileUtils.readFileToString(new File("./botlogin.txt")); String[] lines = data.replaceAll("\\r", "").split("\\n"); for (String line : lines) { if (line.startsWith("logtimezone=") && line.length() >= 15) { timeZone = line.substring(12); } if (line.startsWith("websocketircab")) { Quorrabot.webSocketIRCAB = true; } if (line.startsWith("user=") && line.length() > 8) { user = line.substring(5); } if (line.startsWith("oauth=") && line.length() > 9) { oauth = line.substring(6); } if (line.startsWith("apioauth=") && line.length() > 12) { apioauth = line.substring(9); } if (line.startsWith("clientid=") && line.length() > 12) { clientid = line.substring(9); } if (line.startsWith("channel=") && line.length() > 11) { channelName = line.substring(8); } if (line.startsWith("owner=") && line.length() > 9) { owner = line.substring(6); } if (line.startsWith("baseport=") && line.length() > 10) { baseport = Integer.parseInt(line.substring(9)); } if (line.startsWith("ip=") && line.length() > 4) { ip = InetAddress.getByName(line.substring(3)); } if (line.startsWith("hostname=") && line.length() > 10) { hostname = line.substring(9); } if (line.startsWith("port=") && line.length() > 6) { port = Integer.parseInt(line.substring(5)); } if (line.startsWith("msglimit30=") && line.length() > 12) { msglimit30 = Double.parseDouble(line.substring(11)); } if (line.startsWith("datastore=") && line.length() > 11) { datastore = line.substring(10); } if (line.startsWith("youtubekey=") && line.length() > 12) { youtubekey = line.substring(11); } if (line.startsWith("gamewispauth=") && line.length() > 14) { gamewispauth = line.substring(13); } if (line.startsWith("gamewisprefresh=") && line.length() > 17) { gamewisprefresh = line.substring(16); } if (line.startsWith("twitchalertstoken=") && line.length() > 19) { twitchalertstoken = line.substring(18); } if (line.startsWith("lastfmuser=") && line.length() > 12) { lastfmuser = line.substring(11); } if (line.startsWith("tpetoken=") && line.length() > 10) { tpetoken = line.substring(9); } if (line.startsWith("twittertoken=") && line.length() > 14) { twittertoken = line.substring(13); } if (line.startsWith("twittertokensecret=") && line.length() > 20) { twittertokensecret = line.substring(19); } if (line.startsWith("streamtiptoken=") && line.length() > 16) { streamtiptoken = line.substring(15); } if (line.startsWith("streamtipid=") && line.length() > 13) { streamtipid = line.substring(12); } if (line.startsWith("webenable=") && line.length() > 11) { webenable = Boolean.valueOf(line.substring(10)); } if (line.startsWith("musicenable=") && line.length() > 13) { musicenable = Boolean.valueOf(line.substring(12)); } if (line.startsWith("usehttps=") && line.length() > 10) { usehttps = Boolean.valueOf(line.substring(9)); } if (line.startsWith("mysqlhost=") && line.length() > 11) { mySqlHost = line.substring(10); } if (line.startsWith("mysqlport=") && line.length() > 11) { mySqlPort = line.substring(10); } if (line.startsWith("mysqlname=") && line.length() > 11) { mySqlName = line.substring(10); } if (line.startsWith("mysqluser=") && line.length() > 11) { mySqlUser = line.substring(10); } if (line.startsWith("mysqlpass=") && line.length() > 11) { mySqlPass = line.substring(10); } if (line.startsWith("keystorepath=") && line.length() > 14) { keystorepath = line.substring(13); } if (line.startsWith("keystorepassword=") && line.length() > 18) { keystorepassword = line.substring(17); } if (line.startsWith("webauth=") && line.length() > 9) { webauth = line.substring(8); } if (line.startsWith("webauthro=") && line.length() > 11) { webauthro = line.substring(10); } if (line.startsWith("discordtoken=") && line.length() >= 14) { discordToken = line.substring(13); } if (line.startsWith("discordmainchannel=") && line.length() >= 20) { discordMainChannel = line.substring(19); } } } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /** * Check to see if there's a soundboardauth set */ if (webauth.isEmpty()) { webauth = generateWebAuth(); com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt"); changed = true; } /** * Check to see if there's a soundboardauthread set */ if (webauthro.isEmpty()) { webauthro = generateWebAuth(); com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt"); changed = true; } try { if (user.isEmpty()) { com.gmt2001.Console.out.print("Please enter the bot's twitch username: "); user = System.console().readLine().trim().toLowerCase(); changed = true; } if (oauth.isEmpty()) { com.gmt2001.Console.out.println( "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below."); com.gmt2001.Console.out .println("IMPORTANT: This MUST be done while logged in as the BOT account!" + "\n"); com.gmt2001.Console.out.println("Please enter the bot's tmi oauth token: "); oauth = System.console().readLine().trim(); changed = true; } if (channelName.isEmpty()) { com.gmt2001.Console.out.print( "Please enter the name of the twitch channel the bot should join (not the url, just the name): "); channelName = System.console().readLine().trim().toLowerCase(); changed = true; } if (apioauth.isEmpty()) { com.gmt2001.Console.out.println( "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below."); com.gmt2001.Console.out.println( "IMPORTANT: This MUST be done while logged in on the CHANNEL OWNER account!" + "\n"); com.gmt2001.Console.out.println("Please enter the channel owner's tmi oauth token: "); apioauth = System.console().readLine().trim(); changed = true; } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } if (owner.isEmpty()) { owner = channelName; changed = true; } if (args.length > 0) { for (String arg : args) { if (arg.equalsIgnoreCase("printlogin")) { com.gmt2001.Console.out.println("user='" + user + "'"); com.gmt2001.Console.out.println("oauth='" + oauth + "'"); com.gmt2001.Console.out.println("apioauth='" + apioauth + "'"); com.gmt2001.Console.out.println("clientid='" + clientid + "'"); com.gmt2001.Console.out.println("channel='" + channelName + "'"); com.gmt2001.Console.out.println("owner='" + owner + "'"); com.gmt2001.Console.out.println("baseport='" + baseport + "'"); com.gmt2001.Console.out.println("ip='" + ip.getHostAddress() + "'"); com.gmt2001.Console.out.println("hostname='" + hostname + "'"); com.gmt2001.Console.out.println("port='" + port + "'"); com.gmt2001.Console.out.println("msglimit30='" + msglimit30 + "'"); com.gmt2001.Console.out.println("datastore='" + datastore + "'"); com.gmt2001.Console.out.println("youtubekey='" + youtubekey + "'"); com.gmt2001.Console.out.println("gamewispauth=" + gamewispauth + "'"); com.gmt2001.Console.out.println("gamewisprefresh=" + gamewisprefresh + "'"); com.gmt2001.Console.out.println("twitchalertstoken='" + twitchalertstoken + "'"); com.gmt2001.Console.out.println("lastfmuser='" + lastfmuser + "'"); com.gmt2001.Console.out.println("tpetoken='" + tpetoken + "'"); com.gmt2001.Console.out.println("twittertoken='" + twittertoken + "'"); com.gmt2001.Console.out.println("twittertokensecret='" + twittertokensecret + "'"); com.gmt2001.Console.out.println("streamtiptoken='" + streamtiptoken + "'"); com.gmt2001.Console.out.println("streamtipid='" + streamtipid + "'"); com.gmt2001.Console.out.println("webenable=" + webenable); com.gmt2001.Console.out.println("musicenable=" + musicenable); com.gmt2001.Console.out.println("usehttps=" + usehttps); com.gmt2001.Console.out.println("keystorepath='" + keystorepath + "'"); com.gmt2001.Console.out.println("keystorepassword='" + keystorepassword + "'"); com.gmt2001.Console.out.println("discordtoken='" + discordToken + "'"); com.gmt2001.Console.out.println("discordmainchannel='" + discordMainChannel + "'"); } if (arg.equalsIgnoreCase("debugon")) { Quorrabot.enableDebugging = true; } if (arg.equalsIgnoreCase("ini2sqlite")) { com.gmt2001.Console.out.println("Converting default IniStore to default SqliteStore..."); ini2sqlite(false); com.gmt2001.Console.out.println("Operation complete. The bot will now exit"); System.exit(0); return; } if (arg.toLowerCase().startsWith("user=") && arg.length() > 8) { if (!user.equals(arg.substring(5))) { user = arg.substring(5).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("oauth=") && arg.length() > 9) { if (!oauth.equals(arg.substring(6))) { oauth = arg.substring(6); changed = true; } } if (arg.toLowerCase().startsWith("apioauth=") && arg.length() > 12) { if (!apioauth.equals(arg.substring(9))) { apioauth = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("mysqlhost=") && arg.length() > 11) { if (!mySqlHost.equals(arg.substring(10))) { mySqlHost = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlport=") && arg.length() > 11) { if (!mySqlPort.equals(arg.substring(10))) { mySqlPort = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlname=") && arg.length() > 11) { if (!mySqlName.equals(arg.substring(10))) { mySqlName = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqluser=") && arg.length() > 11) { if (!mySqlUser.equals(arg.substring(14))) { mySqlUser = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlpass=") && arg.length() > 11) { if (!mySqlPass.equals(arg.substring(10))) { mySqlPass = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("clientid=") && arg.length() > 12) { if (!clientid.equals(arg.substring(9))) { clientid = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("channel=") && arg.length() > 11) { if (!channelName.equals(arg.substring(8))) { channelName = arg.substring(8).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("owner=") && arg.length() > 9) { if (!owner.equals(arg.substring(6))) { owner = arg.substring(6).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("baseport=") && arg.length() > 10) { if (baseport != Integer.parseInt(arg.substring(9))) { baseport = Integer.parseInt(arg.substring(9)); changed = true; } } if (arg.toLowerCase().startsWith("ip=") && arg.length() > 4) { if (ip != InetAddress.getByName(arg.substring(3))) { ip = InetAddress.getByName(arg.substring(3)); changed = true; } } if (arg.toLowerCase().startsWith("hostname=") && arg.length() > 10) { if (!hostname.equals(arg.substring(9))) { hostname = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("port=") && arg.length() > 6) { if (port != Integer.parseInt(arg.substring(5))) { port = Integer.parseInt(arg.substring(5)); changed = true; } } if (arg.toLowerCase().startsWith("msglimit30=") && arg.length() > 12) { if (msglimit30 != Double.parseDouble(arg.substring(11))) { msglimit30 = Double.parseDouble(arg.substring(11)); changed = true; } } if (arg.toLowerCase().startsWith("datastore=") && arg.length() > 11) { if (!datastore.equals(arg.substring(10))) { datastore = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("datastoreconfig=") && arg.length() > 17) { datastoreconfig = arg.substring(16); } if (arg.toLowerCase().startsWith("youtubekey=") && arg.length() > 12) { if (!youtubekey.equals(arg.substring(11))) { youtubekey = arg.substring(11); changed = true; } } if (arg.toLowerCase().startsWith("gamewispauth=") && arg.length() > 14) { if (!gamewispauth.equals(arg.substring(13))) { gamewispauth = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("gamewisprefresh=") && arg.length() > 17) { if (!gamewisprefresh.equals(arg.substring(16))) { gamewisprefresh = arg.substring(16); changed = true; } } if (arg.toLowerCase().startsWith("twitchalertstoken=") && arg.length() > 19) { if (!twitchalertstoken.equals(arg.substring(18))) { twitchalertstoken = arg.substring(18); changed = true; } } if (arg.toLowerCase().startsWith("lastfmuser=") && arg.length() > 12) { if (!lastfmuser.equals(arg.substring(11))) { lastfmuser = arg.substring(11); changed = true; } } if (arg.toLowerCase().startsWith("tpetoken=") && arg.length() > 10) { if (!tpetoken.equals(arg.substring(9))) { tpetoken = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("twittertoken=") && arg.length() > 14) { if (!twittertoken.equals(arg.substring(13))) { twittertoken = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("twittertokensecret=") && arg.length() > 20) { if (!twittertokensecret.equals(arg.substring(19))) { twittertokensecret = arg.substring(19); changed = true; } } if (arg.toLowerCase().startsWith("streamtiptoken=") && arg.length() > 16) { if (!streamtiptoken.equals(arg.substring(15))) { streamtiptoken = arg.substring(15); changed = true; } } if (arg.toLowerCase().startsWith("streamtipid=") && arg.length() > 13) { if (!streamtipid.equals(arg.substring(12))) { streamtipid = arg.substring(12); changed = true; } } if (arg.toLowerCase().startsWith("webenable=") && arg.length() > 11) { if (webenable != Boolean.valueOf(arg.substring(10))) { webenable = Boolean.valueOf(arg.substring(10)); changed = true; } } if (arg.toLowerCase().startsWith("musicenable=") && arg.length() > 13) { if (musicenable != Boolean.valueOf(arg.substring(12))) { musicenable = Boolean.valueOf(arg.substring(12)); changed = true; } } if (arg.toLowerCase().startsWith("usehttps=") && arg.length() > 10) { if (usehttps != Boolean.valueOf(arg.substring(9))) { usehttps = Boolean.valueOf(arg.substring(9)); changed = true; } } if (arg.toLowerCase().startsWith("keystorepath=") && arg.length() > 14) { if (!keystorepath.equals(arg.substring(13))) { keystorepath = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("keystorepassword=") && arg.length() > 18) { if (!keystorepassword.equals(arg.substring(17))) { keystorepassword = arg.substring(17); changed = true; } } if (arg.equalsIgnoreCase("help") || arg.equalsIgnoreCase("--help") || arg.equalsIgnoreCase("-h") || arg.equalsIgnoreCase("-?")) { com.gmt2001.Console.out.println( "Usage: java -Dfile.encoding=UTF-8 -jar QuorraBot.jar [printlogin] [user=<bot username>] " + "[oauth=<bot irc oauth>] [apioauth=<editor oauth>] [clientid=<oauth clientid>] [channel=<channel to join>] " + "[owner=<bot owner username>] [baseport=<bot webserver port, music server will be +1>] [ip=<IP address (optional) to bind to>] [hostname=<custom irc server>] " + "[port=<custom irc port>] [msglimit30=<message limit per 30 seconds>] " + "[datastore=<DataStore type, for a list, run java -jar QuorraBot.jar storetypes>] " + "[datastoreconfig=<Optional DataStore config option, different for each DataStore type>] " + "[youtubekey=<youtube api key>] [webenable=<true | false>] [musicenable=<true | false>] " + "[gamewispauth=<gamewisp oauth>] " + "[gamewisprefresh=<gamewisp refresh key>] " + "[twitchalertstoken=<TwitchAlerts access token>] " + "[lastfmuser=<Last.FM username>] " + "[tpetoken=<Tipeeestream access token>] " + "[streamtiptoken=<StreamTip access token>] " + "[streamtipid=<StreamTip Client ID>] " + "[twittertoken=<Twitter access token>] " + "[twittertokensecret=<Twitter access token secret>]"); return; } if (arg.equalsIgnoreCase("storetypes")) { com.gmt2001.Console.out.println( "DataStore types: IniStore (datastoreconfig parameter is folder name, stores in .ini files), " + "TempStore (Stores in memory, lost on shutdown), " + "SqliteStore (Default, Stores in a SQLite3 database, datastoreconfig parameter is a config file"); return; } } } if (changed) { String data = ""; data += "user=" + user + "\r\n"; data += "oauth=" + oauth + "\r\n"; data += "apioauth=" + apioauth + "\r\n"; data += "clientid=" + clientid + "\r\n"; data += "webauth=" + webauth + "\r\n"; data += "webauthro=" + webauthro + "\r\n"; data += "channel=" + channelName + "\r\n"; data += "owner=" + owner + "\r\n"; data += "baseport=" + baseport + "\r\n"; data += "ip=" + ip.getHostAddress() + "\r\n"; data += "hostname=" + hostname + "\r\n"; data += "port=" + port + "\r\n"; data += "msglimit30=" + msglimit30 + "\r\n"; data += "datastore=" + datastore + "\r\n"; data += "youtubekey=" + youtubekey + "\r\n"; data += "gamewispauth=" + gamewispauth + "\r\n"; data += "gamewisprefresh=" + gamewisprefresh + "\r\n"; data += "twitchalertstoken=" + twitchalertstoken + "\r\n"; data += "lastfmuser=" + lastfmuser + "\r\n"; data += "tpetoken=" + tpetoken + "\r\n"; data += "twittertoken=" + twittertoken + "\r\n"; data += "twittertokensecret=" + twittertokensecret + "\r\n"; data += "streamtiptoken=" + streamtiptoken + "\r\n"; data += "streamtipid=" + streamtipid + "\r\n"; data += "webenable=" + webenable + "\r\n"; data += "musicenable=" + musicenable + "\r\n"; data += "usehttps=" + usehttps + "\r\n"; data += "logtimezone=" + timeZone + "\r\n"; data += "mysqlhost=" + mySqlHost + "\r\n"; data += "mysqlport=" + mySqlPort + "\r\n"; data += "mysqlname=" + mySqlName + "\r\n"; data += "mysqluser=" + mySqlUser + "\r\n"; data += "mysqlpass=" + mySqlPass + "\r\n"; data += "keystorepath=" + keystorepath + "\r\n"; data += "keystorepassword=" + keystorepassword + "\r\n"; data += "discordtoken=" + discordToken + "\r\n"; data += "discordmainchannel=" + discordMainChannel; Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } channelUsersCache = ChannelUsersCache.instance(owner); followersCache = FollowersCache.instance(owner); hostCache = ChannelHostCache.instance(owner); subscribersCache = SubscribersCache.instance(owner); Quorrabot.instance = new Quorrabot(user, oauth, apioauth, clientid, channelName, owner, baseport, ip, hostname, port, msglimit30, datastore, datastoreconfig, youtubekey, gamewispauth, gamewisprefresh, twitchalertstoken, lastfmuser, tpetoken, twittertoken, twittertokensecret, streamtiptoken, streamtipid, webenable, webauth, webauthro, musicenable, usehttps, timeZone, mySqlHost, mySqlPort, mySqlConn, mySqlPass, mySqlUser, mySqlName, keystorepath, followersCache, hostCache, channelUsersCache, subscribersCache, discordToken, discordMainChannel); }
From source file:me.mast3rplan.phantombot.PhantomBot.java
@Subscribe public void consoleInput(ConsoleInputEvent event) { String message = event.getMsg(); Boolean changed = false;//from ww w. j a v a 2 s . c om Boolean reset = false; String arguments; String[] argument = null; /* Check to see if the message is null or has nothing in it */ if (message == null || message.isEmpty()) { return; } /* Check for arguments */ if (message.contains(" ")) { String messageString = message; message = messageString.substring(0, messageString.indexOf(" ")); arguments = messageString.substring(messageString.indexOf(" ") + 1); argument = arguments.split(" "); } if (message.equalsIgnoreCase("ankhtophantombot")) { print("Not all of AnkhBot's data will be compatible with PhantomBot."); print("This process will take a long time."); print("Are you sure you want to convert AnkhBot's data to PhantomBot? [y/n]"); String check = System.console().readLine().trim(); if (check.equals("y")) { AnkhConverter.instance(); } else { print("No changes were made."); return; } } if (message.equalsIgnoreCase("backupdb")) { SimpleDateFormat datefmt = new SimpleDateFormat("ddMMyyyy.hhmmss"); datefmt.setTimeZone(TimeZone.getTimeZone(timeZone)); String timestamp = datefmt.format(new Date()); dataStore.backupSQLite3("phantombot.manual.backup." + timestamp + ".db"); return; } /* Update the followed (followers) table. */ if (message.equalsIgnoreCase("fixfollowedtable")) { TwitchAPIv3.instance().FixFollowedTable(channelName, dataStore, false); return; } /* Update the followed (followers) table - forced. */ if (message.equalsIgnoreCase("fixfollowedtable-force")) { TwitchAPIv3.instance().FixFollowedTable(channelName, dataStore, true); return; } if (message.equalsIgnoreCase("jointest")) { for (int i = 0; i < 30; i++) { EventBus.instance() .postAsync(new IrcChannelJoinEvent(this.session, this.channel, generateRandomString(8))); } } /* tests a follow event */ if (message.equalsIgnoreCase("followertest")) { String randomUser = generateRandomString(10); print("[CONSOLE] Executing followertest (User: " + randomUser + ")"); EventBus.instance() .postAsync(new TwitchFollowEvent(randomUser, PhantomBot.getChannel(this.channelName))); return; } /* tests multiple follows */ if (message.equalsIgnoreCase("followerstest")) { String randomUser = generateRandomString(10); int followCount = 5; if (argument != null) { followCount = Integer.parseInt(argument[0]); } print("[CONSOLE] Executing followerstest (Count: " + followCount + ", User: " + randomUser + ")"); for (int i = 0; i < followCount; i++) { EventBus.instance().postAsync( new TwitchFollowEvent(randomUser + "_" + i, PhantomBot.getChannel(this.channelName))); } return; } /* Test a subscriber event */ if (message.equalsIgnoreCase("subscribertest")) { String randomUser = generateRandomString(10); print("[CONSOLE] Executing subscribertest (User: " + randomUser + ")"); EventBus.instance().postAsync(new NewSubscriberEvent(PhantomBot.getSession(this.channelName), PhantomBot.getChannel(this.channelName), randomUser)); return; } /* Test a prime subscriber event */ if (message.equalsIgnoreCase("primesubscribertest")) { String randomUser = generateRandomString(10); print("[CONSOLE] Executing primesubscribertest (User: " + randomUser + ")"); EventBus.instance().postAsync(new NewPrimeSubscriberEvent(PhantomBot.getSession(this.channelName), PhantomBot.getChannel(this.channelName), randomUser)); return; } /* Test a resubscriber event */ if (message.equalsIgnoreCase("resubscribertest")) { String randomUser = generateRandomString(10); print("[CONSOLE] Executing resubscribertest (User: " + randomUser + ")"); EventBus.instance().postAsync(new NewReSubscriberEvent(PhantomBot.getSession(this.channelName), PhantomBot.getChannel(this.channelName), randomUser, "10")); return; } /* Test the online event */ if (message.equalsIgnoreCase("onlinetest")) { print("[CONSOLE] Executing onlinetest"); EventBus.instance().postAsync(new TwitchOnlineEvent(PhantomBot.getChannel(this.channelName))); return; } /* Test the offline event */ if (message.equalsIgnoreCase("offlinetest")) { print("[CONSOLE] Executing offlinetest"); EventBus.instance().postAsync(new TwitchOfflineEvent(PhantomBot.getChannel(this.channelName))); return; } /* Test the host event */ if (message.equalsIgnoreCase("hosttest")) { print("[CONSOLE] Executing hosttest"); EventBus.instance() .postAsync(new TwitchHostedEvent(this.botName, PhantomBot.getChannel(this.channelName))); return; } /* test the gamewisp subscriber event */ if (message.equalsIgnoreCase("gamewispsubscribertest")) { print("[CONSOLE] Executing gamewispsubscribertest"); EventBus.instance().postAsync(new GameWispSubscribeEvent(this.botName, 1)); return; } /* test the gamewisp resubscriber event */ if (message.equalsIgnoreCase("gamewispresubscribertest")) { print("[CONSOLE] Executing gamewispresubscribertest"); EventBus.instance().postAsync(new GameWispAnniversaryEvent(this.botName, 2)); return; } /* test the bits event */ if (message.equalsIgnoreCase("bitstest")) { print("[CONSOLE] Executing bitstest"); EventBus.instance().postAsync(new BitsEvent(PhantomBot.getSession(this.channelName), PhantomBot.getChannel(this.channelName), this.botName, "100")); return; } /* enables debug mode */ if (message.equalsIgnoreCase("debugon")) { print("[CONSOLE] Executing debugon: Enable Debug Mode"); PhantomBot.setDebugging(true); return; } /* disables debug mode - note that setDebuggingLogOnly() completely disables all debugging */ if (message.equalsIgnoreCase("debugoff")) { print("[CONSOLE] Executing debugoff: Disable Debug Mode"); PhantomBot.setDebuggingLogOnly(false); return; } /* enables debug mode - log only */ if (message.equalsIgnoreCase("debuglog")) { print("[CONSOLE] Executing debuglog: Enable Debug Mode - Log Only"); PhantomBot.setDebuggingLogOnly(true); return; } /* Reset the bot login */ if (message.equalsIgnoreCase("reset")) { print("Are you sure you want to reset the bot login? [y/n]"); String check = System.console().readLine().trim(); if (check.equals("y")) { reset = true; changed = true; } else { print("No changes were made."); return; } } /* Change the apiOAuth token */ if (message.equalsIgnoreCase("apioauth")) { System.out.print( "Please enter you're oauth token that you generated from https://phantombot.tv/oauth while logged as the caster: "); apiOAuth = System.console().readLine().trim(); pbProperties.setProperty("apioauth", apiOAuth); changed = true; } /* Setup for MySql */ if (message.equalsIgnoreCase("mysqlsetup")) { try { print(""); print("PhantomBot MySQL setup."); print(""); com.gmt2001.Console.out.print("Please enter your MySQL host name: "); mySqlHost = System.console().readLine().trim(); pbProperties.setProperty("mysqlhost", mySqlHost); com.gmt2001.Console.out.print("Please enter your MySQL port: "); mySqlPort = System.console().readLine().trim(); pbProperties.setProperty("mysqlport", mySqlPort); com.gmt2001.Console.out.print("Please enter your MySQL db name: "); mySqlName = System.console().readLine().trim(); pbProperties.setProperty("mysqlname", mySqlName); com.gmt2001.Console.out.print("Please enter a username for MySQL: "); mySqlUser = System.console().readLine().trim(); pbProperties.setProperty("mysqluser", mySqlUser); com.gmt2001.Console.out.print("Please enter a password for MySQL: "); mySqlPass = System.console().readLine().trim(); pbProperties.setProperty("mysqlpass", mySqlPass); dataStoreType = "MySQLStore"; pbProperties.setProperty("datastore", dataStoreType); print("PhantomBot MySQL setup done, PhantomBot will exit."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Setup for GameWisp */ if (message.equalsIgnoreCase("gamewispsetup")) { try { print(""); print("PhantomBot GameWisp setup."); print(""); com.gmt2001.Console.out.print("Please enter your GameWisp OAuth key: "); gameWispOAuth = System.console().readLine().trim(); pbProperties.setProperty("gamewispauth", gameWispOAuth); com.gmt2001.Console.out.print("Please enter your GameWisp refresh key: "); gameWispRefresh = System.console().readLine().trim(); pbProperties.setProperty("gamewisprefresh", gameWispRefresh); print("PhantomBot GameWisp setup done, PhantomBot will exit."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Setup for StreamLabs (TwitchAlerts) */ if (message.equalsIgnoreCase("streamlabssetup")) { try { print(""); print("PhantomBot StreamLabs setup."); print(""); com.gmt2001.Console.out.print("Please enter your StreamLabs OAuth key: "); twitchAlertsKey = System.console().readLine().trim(); pbProperties.setProperty("twitchalertskey", twitchAlertsKey); print("PhantomBot StreamLabs setup done, PhantomBot will exit."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Setup for StreamTip */ if (message.equalsIgnoreCase("streamtipsetup")) { try { print(""); print("PhantomBot StreamTip setup."); print(""); com.gmt2001.Console.out.print("Please enter your StreamTip Api OAuth: "); streamTipOAuth = System.console().readLine().trim(); pbProperties.setProperty("streamtipkey", streamTipOAuth); com.gmt2001.Console.out.print("Please enter your StreamTip Client Id: "); streamTipClientId = System.console().readLine().trim(); pbProperties.setProperty("streamtipid", streamTipClientId); print("PhantomBot StreamTip setup done, PhantomBot will exit."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Setup for TipeeeStream */ if (message.equalsIgnoreCase("tipeeestreamsetup")) { try { print(""); print("PhantomBot TipeeeStream setup."); print(""); com.gmt2001.Console.out.print("Please enter your TipeeeStream Api OAuth: "); tipeeeStreamOAuth = System.console().readLine().trim(); pbProperties.setProperty("tipeeestreamkey", tipeeeStreamOAuth); print("PhantomBot TipeeeStream setup done, PhantomBot will exit."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Setup the web panel login info */ if (message.equalsIgnoreCase("panelsetup")) { try { print(""); print("PhantomBot Web Panel setup."); print("Note: Do not use any ascii characters in your username of password."); print(""); com.gmt2001.Console.out.print("Please enter a username of your choice: "); panelUsername = System.console().readLine().trim(); pbProperties.setProperty("paneluser", panelUsername); com.gmt2001.Console.out.print("Please enter a password of your choice: "); panelPassword = System.console().readLine().trim(); pbProperties.setProperty("panelpassword", panelPassword); print("PhantomBot Web Panel setup done, PhantomBot will exit."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Setup for Twitter */ if (message.equalsIgnoreCase("twittersetup")) { try { print(""); print("PhantomBot Twitter setup."); print(""); com.gmt2001.Console.out.print("Please enter your Twitter username: "); twitterUsername = System.console().readLine().trim(); pbProperties.setProperty("twitterUser", twitterUsername); com.gmt2001.Console.out.print("Please enter your consumer key: "); twitterConsumerToken = System.console().readLine().trim(); pbProperties.setProperty("twitter_consumer_key", twitterConsumerToken); com.gmt2001.Console.out.print("Please enter your consumer secret: "); twitterConsumerSecret = System.console().readLine().trim(); pbProperties.setProperty("twitter_consumer_secret", twitterConsumerSecret); com.gmt2001.Console.out.print("Please enter your access token: "); twitterAccessToken = System.console().readLine().trim(); pbProperties.setProperty("twitter_access_token", twitterAccessToken); com.gmt2001.Console.out.print("Please enter your access token secret: "); twitterSecretToken = System.console().readLine().trim(); pbProperties.setProperty("twitter_secret_token", twitterSecretToken); /* Delete the old Twitter file if it exists */ try { File f = new File("./twitter.txt"); f.delete(); } catch (NullPointerException ex) { com.gmt2001.Console.debug.println(ex); } print("PhantomBot Twitter setup done, PhantomBot will exit."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Check to see if any settings have been changed */ if (changed && !reset) { Properties outputProperties = new Properties() { @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(new TreeSet<>(super.keySet())); } }; try { try (FileOutputStream outputStream = new FileOutputStream("botlogin.txt")) { outputProperties.putAll(pbProperties); outputProperties.store(outputStream, "PhantomBot Configuration File"); } dataStore.SaveAll(true); print(""); print("Changes have been saved, now exiting PhantomBot."); print(""); System.exit(0); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } return; } /* Save everything */ if (message.equalsIgnoreCase("save")) { print("[CONSOLE] Executing save"); dataStore.SaveAll(true); return; } /* Exit phantombot */ if (message.equalsIgnoreCase("exit")) { print("[CONSOLE] Executing exit"); System.exit(0); return; } /* handle any other commands */ handleCommand(botName, event.getMsg(), PhantomBot.getChannel(this.channelName)); // Need to support channel here. command (channel) argument[1] /* Handle dev commands */ if (event.getMsg().startsWith("!debug !dev")) { devDebugCommands(event.getMsg(), "no_id", botName, true); } }
From source file:tv.phantombot.PhantomBot.java
public static void main(String[] args) throws IOException { // Move user files. moveUserConfig();/*from w w w . j a v a 2s .c o m*/ /* List of properties that must exist. */ String requiredProperties[] = new String[] { "oauth", "channel", "owner", "user" }; String requiredPropertiesErrorMessage = ""; if (Float.valueOf(System.getProperty("java.specification.version")) < (float) 1.8 || Float.valueOf(System.getProperty("java.specification.version")) >= (float) 1.9) { System.out.println("Detected Java " + System.getProperty("java.version") + ". " + "PhantomBot requires Java 8. Java 9 and above will NOT work."); System.exit(1); } /* Properties configuration */ Properties startProperties = new Properties(); /* Indicates that the botlogin.txt file should be overwritten/created. */ Boolean changed = false; /* Print the user dir */ com.gmt2001.Console.out.println("The working directory is: " + System.getProperty("user.dir")); com.gmt2001.Console.out.println("Detected Java " + System.getProperty("java.version") + " running on " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")"); /* If prompted, now that the version has been reported, exit. */ if (args.length > 0) { if (args[0].equals("--version") || args[0].equals("-v")) { com.gmt2001.Console.out.println("PhantomBot Version: " + RepoVersion.getPhantomBotVersion() + " (" + RepoVersion.getRepoVersion() + ")"); System.exit(1); } } /* Load up the bot info from the bot login file */ try { if (new File("./config/botlogin.txt").exists()) { FileInputStream inputStream = new FileInputStream("./config/botlogin.txt"); startProperties.load(inputStream); inputStream.close(); } else { /* Fill in the Properties object with some default values. Note that some values are left * unset to be caught in the upcoming logic to enforce settings. */ startProperties.setProperty("baseport", "25000"); startProperties.setProperty("usehttps", "false"); startProperties.setProperty("webenable", "true"); startProperties.setProperty("msglimit30", "19.0"); startProperties.setProperty("musicenable", "true"); startProperties.setProperty("whisperlimit60", "60.0"); } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } catch (Exception ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Load up the bot info from the environment */ for (Entry<String, String> v : System.getenv().entrySet()) { String Prefix = "PHANTOMBOT_"; String Key = v.getKey().toUpperCase(); String Value = v.getValue(); if (Key.startsWith(Prefix) && Prefix.length() < Key.length()) { Key = Key.substring(Prefix.length()).toLowerCase(); startProperties.setProperty(Key, Value); } } /* Check to enable debug mode */ if (startProperties.getProperty("debugon", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Mode Enabled"); PhantomBot.enableDebugging = true; } /* Check to enable debug to File */ if (startProperties.getProperty("debuglog", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Log Only Mode Enabled"); PhantomBot.enableDebugging = true; PhantomBot.enableDebuggingLogOnly = true; } /* Check to enable Script Reloading */ if (startProperties.getProperty("reloadscripts", "false").equals("true")) { com.gmt2001.Console.out.println("Enabling Script Reloading"); PhantomBot.reloadScripts = true; } /* Check to enable Rhino Debugger */ if (startProperties.getProperty("rhinodebugger", "false").equals("true")) { com.gmt2001.Console.out.println("Rhino Debugger will be launched if system supports it."); PhantomBot.enableRhinoDebugger = true; } /* Check to see if there's a webOauth set */ if (startProperties.getProperty("webauth") == null) { startProperties.setProperty("webauth", generateWebAuth()); com.gmt2001.Console.debug.println("New webauth key has been generated for ./config/botlogin.txt"); changed = true; } /* Check to see if there's a webOAuthRO set */ if (startProperties.getProperty("webauthro") == null) { startProperties.setProperty("webauthro", generateWebAuth()); com.gmt2001.Console.debug .println("New webauth read-only key has been generated for ./config/botlogin.txt"); changed = true; } /* Check to see if there's a panelUsername set */ if (startProperties.getProperty("paneluser") == null) { com.gmt2001.Console.debug.println( "No Panel Username, using default value of 'panel' for Control Panel and YouTube Player"); startProperties.setProperty("paneluser", "panel"); changed = true; } /* Check to see if there's a panelPassword set */ if (startProperties.getProperty("panelpassword") == null) { com.gmt2001.Console.debug.println( "No Panel Password, using default value of 'panel' for Control Panel and YouTube Player"); startProperties.setProperty("panelpassword", "panel"); changed = true; } /* Check to see if there's a youtubeOAuth set */ if (startProperties.getProperty("ytauth") == null) { startProperties.setProperty("ytauth", generateWebAuth()); com.gmt2001.Console.debug .println("New YouTube websocket key has been generated for ./config/botlogin.txt"); changed = true; } /* Check to see if there's a youtubeOAuthThro set */ if (startProperties.getProperty("ytauthro") == null) { startProperties.setProperty("ytauthro", generateWebAuth()); com.gmt2001.Console.debug .println("New YouTube read-only websocket key has been generated for ./config/botlogin.txt"); changed = true; } /* Make a new botlogin with the botName, oauth or channel is not found */ if (startProperties.getProperty("user") == null || startProperties.getProperty("oauth") == null || startProperties.getProperty("channel") == null) { try { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("Welcome to the PhantomBot setup process!\r\n"); com.gmt2001.Console.out.print( "If you have any issues please report them on our forum, Tweet at us, or join our Discord!\r\n"); com.gmt2001.Console.out.print("Forum: https://community.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("Documentation: https://docs.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("Twitter: https://twitter.com/PhantomBot/\r\n"); com.gmt2001.Console.out.print("Discord: https://discord.gg/rkPqDuK/\r\n"); com.gmt2001.Console.out.print("Support PhantomBot on Patreon: https://phantombot.tv/support/\r\n"); com.gmt2001.Console.out.print("\r\n"); final String os = System.getProperty("os.name").toLowerCase(); // Detect Windows, MacOS, Linux or any other operating system. if (os.startsWith("win")) { com.gmt2001.Console.out .print("PhantomBot has detected that your device is running Windows.\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for Windows: https://community.phantombot.tv/t/windows-setup-guide/"); } else if (os.startsWith("mac")) { com.gmt2001.Console.out.print("PhantomBot has detected that your device is running macOS.\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for macOS: https://community.phantombot.tv/t/macos-setup-guide/"); } else { com.gmt2001.Console.out.print("PhantomBot has detected that your device is running Linux.\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for Ubuntu: https://community.phantombot.tv/t/ubuntu-16-04-lts-setup-guide/\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for CentOS: https://community.phantombot.tv/t/centos-7-setup-guide/"); } com.gmt2001.Console.out.print("\r\n\r\n\r\n"); // Bot name. do { com.gmt2001.Console.out.print("1. Please enter the bot's Twitch username: "); startProperties.setProperty("user", System.console().readLine().trim().toLowerCase()); } while (startProperties.getProperty("user", "").length() <= 0); // Twitch oauth. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out .print("2. You will now need a OAuth token for the bot to be able to chat.\r\n"); com.gmt2001.Console.out.print( "Please note, this OAuth token needs to be generated while you're logged in into the bot's Twitch account.\r\n"); com.gmt2001.Console.out.print( "If you're not logged in as the bot, please go to https://twitch.tv/ and login as the bot.\r\n"); com.gmt2001.Console.out .print("Get the bot's OAuth token here: https://twitchapps.com/tmi/\r\n"); com.gmt2001.Console.out.print("Please enter the bot's OAuth token: "); startProperties.setProperty("oauth", System.console().readLine().trim()); } while (startProperties.getProperty("oauth", "").length() <= 0); // api oauth. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print( "3. You will now need your channel OAuth token for the bot to be able to change your title and game.\r\n"); com.gmt2001.Console.out.print( "Please note, this OAuth token needs to be generated while you're logged in into your caster account.\r\n"); com.gmt2001.Console.out.print( "If you're not logged in as the caster, please go to https://twitch.tv/ and login as the caster.\r\n"); com.gmt2001.Console.out .print("Get the your OAuth token here: https://phantombot.tv/oauth/\r\n"); com.gmt2001.Console.out.print("Please enter your OAuth token: "); startProperties.setProperty("apioauth", System.console().readLine().trim()); } while (startProperties.getProperty("apioauth", "").length() <= 0); // Channel name. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out .print("4. Please enter the name of the Twitch channel the bot should join: "); startProperties.setProperty("channel", System.console().readLine().trim()); } while (startProperties.getProperty("channel", "").length() <= 0); // Panel username. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("5. Please enter a custom username for the web panel: "); startProperties.setProperty("paneluser", System.console().readLine().trim()); } while (startProperties.getProperty("paneluser", "").length() <= 0); // Panel password. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("6. Please enter a custom password for the web panel: "); startProperties.setProperty("panelpassword", System.console().readLine().trim()); } while (startProperties.getProperty("panelpassword", "").length() <= 0); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("PhantomBot will launch in 10 seconds.\r\n"); com.gmt2001.Console.out.print( "If you're hosting the bot locally you can access the control panel here: http://localhost:25000/panel \r\n"); com.gmt2001.Console.out.print( "If you're running the bot on a server, make sure to open the following ports: \r\n"); com.gmt2001.Console.out.print( "25000, 25003, and 25004. You have to change 'localhost' to your server ip to access the panel. \r\n"); try { Thread.sleep(10000); } catch (InterruptedException ex) { com.gmt2001.Console.debug.println("Failed to sleep in setup: " + ex.getMessage()); } changed = true; newSetup = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); com.gmt2001.Console.out.println("[ERROR] Failed to setup PhantomBot. Now exiting..."); System.exit(0); } } /* Make sure the oauth has been set correctly */ if (startProperties.getProperty("oauth") != null) { if (!startProperties.getProperty("oauth").startsWith("oauth") && !startProperties.getProperty("oauth").isEmpty()) { startProperties.setProperty("oauth", "oauth:" + startProperties.getProperty("oauth")); changed = true; } } /* Make sure the apiOAuth has been set correctly */ if (startProperties.getProperty("apioauth") != null) { if (!startProperties.getProperty("apioauth").startsWith("oauth") && !startProperties.getProperty("apioauth").isEmpty()) { startProperties.setProperty("apioauth", "oauth:" + startProperties.getProperty("apioauth")); changed = true; } } /* Make sure the channelName does not have a # */ if (startProperties.getProperty("channel").startsWith("#")) { startProperties.setProperty("channel", startProperties.getProperty("channel").substring(1)); changed = true; } else if (startProperties.getProperty("channel").contains(".tv")) { startProperties.setProperty("channel", startProperties.getProperty("channel") .substring(startProperties.getProperty("channel").indexOf(".tv/") + 4).replaceAll("/", "")); changed = true; } /* Check for the owner after the channel check is done. */ if (startProperties.getProperty("owner") == null) { if (startProperties.getProperty("channel") != null) { if (!startProperties.getProperty("channel").isEmpty()) { startProperties.setProperty("owner", startProperties.getProperty("channel")); changed = true; } } } /* Iterate the properties and delete entries for anything that does not have a * value. */ for (String propertyKey : startProperties.stringPropertyNames()) { if (startProperties.getProperty(propertyKey).isEmpty()) { changed = true; startProperties.remove(propertyKey); } } /* * Check for required settings. */ for (String requiredProperty : requiredProperties) { if (startProperties.getProperty(requiredProperty) == null) { requiredPropertiesErrorMessage += requiredProperty + " "; } } if (!requiredPropertiesErrorMessage.isEmpty()) { com.gmt2001.Console.err.println(); com.gmt2001.Console.err.println("Missing Required Properties: " + requiredPropertiesErrorMessage); com.gmt2001.Console.err.println("Exiting PhantomBot"); System.exit(0); } /* Check to see if anything changed */ if (changed) { Properties outputProperties = new Properties() { @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(new TreeSet<>(super.keySet())); } }; try { try (FileOutputStream outputStream = new FileOutputStream("./config/botlogin.txt")) { outputProperties.putAll(startProperties); outputProperties.store(outputStream, "PhantomBot Configuration File"); } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Start PhantomBot */ PhantomBot.instance = new PhantomBot(startProperties); }
From source file:org.nuxeo.launcher.connect.ConnectBroker.java
/** * Prompt user for yes/no answer/* w w w. ja va2s .c om*/ * * @param message The message to display * @param defaultValue The default answer if there's no console or if "Enter" key is pressed. * @param objects Parameters to use in the message (like in {@link String#format(String, Object...)}) * @return {@code "true"} if answer is in {@link #POSITIVE_ANSWERS}, else return {@code "false"} */ protected String readConsole(String message, String defaultValue, Object... objects) { String answer; Console console = System.console(); if (console == null || StringUtils.isEmpty(answer = console.readLine(message, objects))) { answer = defaultValue; } answer = answer.trim().toLowerCase(); return parseAnswer(answer); }
From source file:com.okta.tools.awscli.java
private static String oktaAuthentication() throws ClientProtocolException, JSONException, IOException { String strSessionToken = ""; AuthResult authResult = null;// ww w .ja va 2 s.c o m int requestStatus = 0; String strAuthStatus = ""; //Redo sequence if response from AWS doesn't return 200 Status while (!strAuthStatus.equalsIgnoreCase("SUCCESS") && !strAuthStatus.equalsIgnoreCase("MFA_REQUIRED")) { // Prompt for user credentials System.out.print("Username: "); //Scanner scanner = new Scanner(System.in); String oktaUsername = null; //scanner.next(); Console console = System.console(); String oktaPassword = null; if (console != null) { oktaPassword = new String(console.readPassword("Password: ")); } else { // hack to be able to debug in an IDE System.out.print("Password: "); } try { authResult = authenticateCredentials(oktaUsername, oktaPassword); strAuthStatus = authResult.getStatus(); if (strAuthStatus.equalsIgnoreCase("MFA_REQUIRED")) { if (userClient != null) { LinkedHashMap<String, Object> user = (LinkedHashMap<String, Object>) (authResult .getEmbedded().get("user")); userId = (String) user.get("id"); //userId = user.getId(); /*User user = userClient.getUser(oktaUsername); if(user!=null) userId = user.getId();*/ } } } catch (ApiException apiException) { String strEx = apiException.getMessage(); switch (apiException.getStatusCode()) { case 400: case 401: System.out.println("You provided invalid credentials, please try again."); break; case 500: System.out.println("\nUnable to establish connection with: " + oktaOrg + " \nPlease verify that your Okta org url is correct and try again"); System.exit(0); break; default: throw new RuntimeException("Failed : HTTP error code : " + apiException.getStatusCode() + " Error code: " + apiException.getErrorResponse().getErrorCode() + " Error summary: " + apiException.getErrorResponse().getErrorSummary()); } } //requestStatus = responseAuthenticate.getStatusLine().getStatusCode(); //authnFailHandler(requestStatus, responseAuthenticate); } //Retrieve and parse the Okta response for session token /*BufferedReader br = new BufferedReader(new InputStreamReader( (responseAuthenticate.getEntity().getContent()))); String outputAuthenticate = br.readLine(); JSONObject jsonObjResponse = new JSONObject(outputAuthenticate); responseAuthenticate.close();*/ if (strAuthStatus.equalsIgnoreCase("MFA_REQUIRED")) { return mfa(authResult); } //else { // return jsonObjResponse.getString("sessionToken"); //} if (authResult != null) strSessionToken = authResult.getSessionToken(); return strSessionToken; }