List of usage examples for java.util Properties stringPropertyNames
public Set<String> stringPropertyNames()
From source file:org.apache.hive.beeline.BeeLine.java
int initArgsFromCliVars(String[] args) { List<String> commands = Collections.emptyList(); CliOptionsProcessor optionsProcessor = new CliOptionsProcessor(); if (!optionsProcessor.process(args)) { return 1; }//from w w w . ja v a 2 s .c o m CommandLine commandLine = optionsProcessor.getCommandLine(); Properties confProps = commandLine.getOptionProperties("hiveconf"); for (String propKey : confProps.stringPropertyNames()) { setHiveConfVar(propKey, confProps.getProperty(propKey)); } Properties hiveVars = commandLine.getOptionProperties("define"); for (String propKey : hiveVars.stringPropertyNames()) { getOpts().getHiveConfVariables().put(propKey, hiveVars.getProperty(propKey)); } Properties hiveVars2 = commandLine.getOptionProperties("hivevar"); for (String propKey : hiveVars2.stringPropertyNames()) { getOpts().getHiveConfVariables().put(propKey, hiveVars2.getProperty(propKey)); } getOpts().setScriptFile(commandLine.getOptionValue("f")); if (commandLine.getOptionValues("i") != null) { getOpts().setInitFiles(commandLine.getOptionValues("i")); } dbName = commandLine.getOptionValue("database"); getOpts().setVerbose(Boolean.parseBoolean(commandLine.getOptionValue("verbose"))); getOpts().setSilent(Boolean.parseBoolean(commandLine.getOptionValue("slient"))); int code = 0; if (commandLine.getOptionValues("e") != null) { commands = Arrays.asList(commandLine.getOptionValues("e")); } if (!commands.isEmpty() && getOpts().getScriptFile() != null) { System.err.println("The '-e' and '-f' options cannot be specified simultaneously"); optionsProcessor.printCliUsage(); return 1; } if (!commands.isEmpty()) { embeddedConnect(); connectDBInEmbededMode(); for (Iterator<String> i = commands.iterator(); i.hasNext();) { String command = i.next().toString(); debug(loc("executing-command", command)); if (!dispatch(command)) { code++; } } exit = true; // execute and exit } return code; }
From source file:org.commonjava.indy.core.conf.DefaultIndyConfigFactory.java
@Override public synchronized void load(final String configPath) throws ConfigurationException { Properties props = getBaseSystemProperties(); logger.info(// www . j a v a 2 s .c o m "\n\n\n\n[CONFIG] Reading Indy configuration in: '{}'\n\nAdding configuration section listeners:", Thread.currentThread().getName()); logger.info("Adding configuration sections..."); if (configSections != null) { for (final IndyConfigInfo section : configSections) { String sectionName = ConfigUtils.getSectionName(section.getClass()); logger.info("Adding configuration section: {}", sectionName); with(sectionName, section); } } final String config = configPath(configPath); logger.info("\n\n[CONFIG] Reading configuration in: '{}'\n\nfrom {}", Thread.currentThread().getName(), config); File configFile = new File(config); if (configFile.isDirectory()) { configFile = new File(configFile, "main.conf"); } if (!configFile.exists()) { File dir = configFile; if (dir.getName().equals("main.conf")) { dir = dir.getParentFile(); } logger.warn( "Cannot find configuration in: {}. Writing default configurations there for future modification.", dir); if (!dir.exists() && !dir.mkdirs()) { throw new ConfigurationException( "Failed to create configuration directory: %s, in order to write defaults.", dir); } writeDefaultConfigs(dir); } List<ConfigurationListener> listeners = new ArrayList<>(); listeners.add(this); if (configListeners != null) { configListeners.forEach((listener) -> listeners.add(listener)); } InputStream stream = null; try { stream = ConfigFileUtils.readFileWithIncludes(config, props); new DotConfConfigurationReader(listeners).loadConfiguration(stream); Properties sysprops = System.getProperties(); props.stringPropertyNames().forEach((name) -> sysprops.setProperty(name, props.getProperty(name))); configSections.forEach((section) -> { if (section instanceof SystemPropertyProvider) { Properties p = ((SystemPropertyProvider) section).getSystemProperties(); p.stringPropertyNames().forEach((name) -> sysprops.setProperty(name, p.getProperty(name))); } }); System.setProperties(sysprops); } catch (final IOException e) { throw new ConfigurationException("Cannot open configuration file: {}. Reason: {}", e, configPath, e.getMessage()); } finally { closeQuietly(stream); } logger.info("[CONFIG] Indy configuration complete for: '{}'.\n\n\n\n", Thread.currentThread().getName()); }
From source file:org.apache.oozie.cli.OozieCLI.java
private void scriptLanguageCommand(CommandLine commandLine, String jobType) throws IOException, OozieCLIException { List<String> args = commandLine.getArgList(); if (args.size() > 0) { // checking if args starts with -X (because CLIParser cannot check this) if (!args.get(0).equals("-X")) { throw new OozieCLIException("Unrecognized option: " + args.get(0) + " Expecting -X"); }//from w w w . jav a 2 s. c o m args.remove(0); } if (!commandLine.hasOption(SCRIPTFILE_OPTION)) { throw new OozieCLIException("Need to specify -file <scriptfile>"); } if (!commandLine.hasOption(CONFIG_OPTION)) { throw new OozieCLIException("Need to specify -config <configfile>"); } try { XOozieClient wc = createXOozieClient(commandLine); Properties conf = getConfiguration(wc, commandLine); String script = commandLine.getOptionValue(SCRIPTFILE_OPTION); List<String> paramsList = new ArrayList<String>(); if (commandLine.hasOption("P")) { Properties params = commandLine.getOptionProperties("P"); for (String key : params.stringPropertyNames()) { paramsList.add(key + "=" + params.getProperty(key)); } } System.out.println( JOB_ID_PREFIX + wc.submitScriptLanguage(conf, script, args.toArray(new String[args.size()]), paramsList.toArray(new String[paramsList.size()]), jobType)); } catch (OozieClientException ex) { throw new OozieCLIException(ex.toString(), ex); } }
From source file:org.apache.hadoop.hive.kududb.KuduHandler.KuduStorageHandler.java
private void configureJobProperties(TableDesc tableDesc, Map<String, String> jobProperties) { //This will always have the DB Name qualifier of Hive. Dont use this to set Kudu Tablename. String tblName = tableDesc.getTableName(); LOG.debug("Hive Table Name:" + tblName); Properties tblProps = tableDesc.getProperties(); String columnNames = tblProps.getProperty(HiveKuduConstants.LIST_COLUMNS); String columnTypes = tblProps.getProperty(HiveKuduConstants.LIST_COLUMN_TYPES); LOG.debug("Columns names:" + columnNames); LOG.debug("Column types:" + columnTypes); if (columnNames.length() == 0) { //TODO: Place keeper to insert SerDeHelper code to connect to Kudu to extract column names. LOG.warn("SerDe currently doesn't support column names and types. Please provide it explicitly"); }//from w w w .j a v a 2s. co m //set map reduce properties. jobProperties.put(HiveKuduConstants.MR_INPUT_TABLE_NAME, tblProps.getProperty(HiveKuduConstants.TABLE_NAME)); jobProperties.put(HiveKuduConstants.MR_OUTPUT_TABLE_NAME, tblProps.getProperty(HiveKuduConstants.TABLE_NAME)); jobProperties.put(HiveKuduConstants.MR_MASTER_ADDRESS_NAME, tblProps.getProperty(HiveKuduConstants.MASTER_ADDRESS_NAME)); LOG.debug("Kudu Table Name: " + tblProps.getProperty(HiveKuduConstants.TABLE_NAME)); LOG.debug("Kudu Master Addresses: " + tblProps.getProperty(HiveKuduConstants.MASTER_ADDRESS_NAME)); //set configuration property conf.set(HiveKuduConstants.MR_INPUT_TABLE_NAME, tblProps.getProperty(HiveKuduConstants.TABLE_NAME)); conf.set(HiveKuduConstants.MR_OUTPUT_TABLE_NAME, tblProps.getProperty(HiveKuduConstants.TABLE_NAME)); conf.set(HiveKuduConstants.MR_MASTER_ADDRESS_NAME, tblProps.getProperty(HiveKuduConstants.MASTER_ADDRESS_NAME)); conf.set(HiveKuduConstants.TABLE_NAME, tblProps.getProperty(HiveKuduConstants.TABLE_NAME)); conf.set(HiveKuduConstants.MASTER_ADDRESS_NAME, tblProps.getProperty(HiveKuduConstants.MASTER_ADDRESS_NAME)); //set class variables kuduMaster = conf.get(HiveKuduConstants.MASTER_ADDRESS_NAME); kuduTableName = conf.get(HiveKuduConstants.TABLE_NAME); for (String key : tblProps.stringPropertyNames()) { if (key.startsWith(HiveKuduConstants.MR_PROPERTY_PREFIX)) { String value = tblProps.getProperty(key); jobProperties.put(key, value); //Also set configuration for Non Map Reduce Hive calls to the Handler conf.set(key, value); } } }
From source file:org.xmlsh.sh.shell.Shell.java
private void setGlobalVars() throws InvalidArgumentException { // System env first Map<String, String> env = new HashMap<>(); env.putAll(System.getenv());// w w w.ja va 2 s .c om Properties props = System.getProperties(); props.stringPropertyNames().stream().filter(s -> s.startsWith(ShellConstants.kXMLSH_PROP_PREFIX)) .forEach(key -> env.putIfAbsent(key.substring(ShellConstants.kXMLSH_PROP_PREFIX.length()), props.getProperty(key))); env.keySet().stream() .filter(name -> (!Util.isBlank(name) && !Util.isPath(name) && name.matches("^[a-zA-Z_0-9]+$") && // Ignore reserved vars that are set internally !Util.contains(_reservedEnvVars, name))) .forEach(name -> getEnv().initVariable( XVariable.newInstance(name, XValue.newXValue(env.get(name)), XVariable.systemFlags()))); // Builtins may come from env or properties // Export path to shell path String path = FileUtils.toJavaPath(getSystemProperty(ShellConstants.PATH)); getEnv().initVariable(XVariable.newInstance(ShellConstants.PATH, Util.isBlank(path) ? XValue.empytSequence() : XValue.newXValue(path.split(File.pathSeparator)), XVariable.systemFlags())); String xpath = FileUtils.toJavaPath(getSystemProperty(ShellConstants.ENV_XPATH)); getEnv().initVariable(XVariable.newInstance(ShellConstants.ENV_XPATH, Util.isBlank(xpath) ? XValue.newXValue(".") : XValue.newXValue(xpath.split(File.pathSeparator)), XVariable.systemFlags())); String xmlsh = getSystemProperty(ShellConstants.ENV_XMLSH); String xmlshhome = getSystemProperty(ShellConstants.ENV_XMLSH_HOME); if (Util.isBlank(xmlshhome)) xmlshhome = xmlsh; if (Util.isBlank(xmlshhome)) xmlshhome = tryFindHome(); if (Util.isBlank(xmlsh)) xmlsh = xmlshhome; if (Util.isBlank(xmlshhome)) { getLogger().warn("Required property {} missing - limited functionalty.", ShellConstants.ENV_XMLSH_HOME); } getEnv().setVar(ShellConstants.ENV_XMLSH, XValue.newXValue(FileUtils.toJavaPath(xmlsh)), XVariable.standardFlags()); getEnv().setVar(ShellConstants.ENV_XMLSH_HOME, XValue.newXValue(FileUtils.toJavaPath(xmlshhome)), XVariable.standardFlags()); String xmpath = FileUtils.toJavaPath(getSystemProperty(ShellConstants.ENV_XMODPATH)); getEnv().setVar(ShellConstants.ENV_XMODPATH, Util.isBlank(xmpath) ? XValue.empytSequence() : XValue.newXValue(xmpath.split(File.pathSeparator)), XVariable.standardFlags()); // PWD getEnv().initVariable( new XDynamicVariable(ShellConstants.ENV_PWD, EnumSet.of(XVarFlag.READONLY, XVarFlag.EXPORT)) { @Override public XValue getValue() { return XValue.newXValue(FileUtils.toJavaPath(getEnv().getCurdir().getAbsolutePath())); } }); // RANDOM getEnv().initVariable(new XDynamicVariable(ShellConstants.VAR_RANDOM, EnumSet.of(XVarFlag.READONLY)) { Random mRand = new Random(); @Override public XValue getValue() { return XValue.newXValue(mRand.nextInt(0x7FFF)); } }); // RANDOM32 getEnv().initVariable(new XDynamicVariable(ShellConstants.VAR_RANDOM32, EnumSet.of(XVarFlag.READONLY)) { Random mRand = new Random(); @Override public XValue getValue() { long v = mRand.nextInt(); v &= 0x7FFFFFFFL; return XValue.newXValue((int) v); } }); // RANDOM getEnv().initVariable(new XDynamicVariable(ShellConstants.VAR_RANDOM64, EnumSet.of(XVarFlag.READONLY)) { Random mRand = new Random(); @Override public XValue getValue() { return XValue.newXValue(mRand.nextLong() & 0x7FFFFFFFFFFFFFFFL); } }); getEnv().setVar(ShellConstants.ENV_TMPDIR, XValue.newXValue(FileUtils.toJavaPath(System.getProperty(ShellConstants.PROP_JAVA_IO_TMPDIR))), XVariable.systemFlags()); if (getEnv().getVar(ShellConstants.ENV_HOME) == null) getEnv().setVar(ShellConstants.ENV_HOME, XValue.newXValue(FileUtils.toJavaPath(System.getProperty(ShellConstants.PROP_USER_HOME))), XVariable.systemFlags()); }
From source file:org.apache.drill.exec.client.DrillClient.java
public synchronized void connect(String connect, Properties props) throws RpcException { if (connected) { return;//from w w w. j av a 2 s . com } final List<DrillbitEndpoint> endpoints = new ArrayList<>(); if (isDirectConnection) { // Populate the endpoints list with all the drillbit information provided in the connection string endpoints.addAll(parseAndVerifyEndpoints(props.getProperty("drillbit"), config.getString(ExecConstants.INITIAL_USER_PORT))); } else { if (ownsZkConnection) { try { this.clusterCoordinator = new ZKClusterCoordinator(this.config, connect); this.clusterCoordinator.start(10000); } catch (Exception e) { throw new RpcException("Failure setting up ZK for client.", e); } } endpoints.addAll(clusterCoordinator.getAvailableEndpoints()); // Make sure we have at least one endpoint in the list checkState(!endpoints.isEmpty(), "No active Drillbit endpoint found from ZooKeeper"); } // shuffle the collection then get the first endpoint Collections.shuffle(endpoints); final DrillbitEndpoint endpoint = endpoints.get(0); if (props != null) { final UserProperties.Builder upBuilder = UserProperties.newBuilder(); for (final String key : props.stringPropertyNames()) { upBuilder.addProperties(Property.newBuilder().setKey(key).setValue(props.getProperty(key))); } this.props = upBuilder.build(); } eventLoopGroup = createEventLoop(config.getInt(ExecConstants.CLIENT_RPC_THREADS), "Client-"); executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("drill-client-executor-")) { @Override protected void afterExecute(final Runnable r, final Throwable t) { if (t != null) { logger.error("{}.run() leaked an exception.", r.getClass().getName(), t); } super.afterExecute(r, t); } }; client = new UserClient(clientName, config, supportComplexTypes, allocator, eventLoopGroup, executor); logger.debug("Connecting to server {}:{}", endpoint.getAddress(), endpoint.getUserPort()); connect(endpoint); connected = true; }
From source file:net.ssehub.easy.instantiation.core.model.buildlangModel.BuildlangExecution.java
/** * Loads properties from <code>file</code> into <code>prop</code> possibly overriding existing * properties. /*from ww w . j a va 2s. com*/ * * @param file the file name * @param prop the loaded properties (to be modified as a side effect) * @param os if not <b>null</b> to be inserted after the last "." with a following ".". If file * not exists, no exception will be thrown. * @throws VilException in case of loading problems */ private void loadProperties(File file, Properties prop, String os) throws VilException { boolean loadFile = true; if (null != os) { String f = file.toString(); int pos = f.lastIndexOf('.'); if (pos > 0 && pos < f.length()) { f = f.substring(0, pos + 1) + os + "." + f.substring(pos + 1); file = new File(f); loadFile = file.exists(); } else { loadFile = false; } } if (loadFile) { try { FileInputStream fis = new FileInputStream(file); Properties p = new Properties(); p.load(fis); prop.putAll(p); fis.close(); for (String key : prop.stringPropertyNames()) { String value = prop.getProperty(key); // Replace value try { value = StringReplacer.substitute(value, new Resolver(environment), getExpressionParser(), this, null); } catch (VilException e) { EASyLoggerFactory.INSTANCE.getLogger(getClass(), Bundle.ID).exception(e); } prop.setProperty(key, value); } } catch (IOException e) { throw new VilException(e.getMessage(), e, VilException.ID_IO); } } }
From source file:org.eclipse.gyrex.cloud.internal.preferences.ZooKeeperBasedPreferences.java
/** * Updates the local node properties with properties from ZooKeeper. * <p>//www. j a v a2s .com * This method is called by {@link ZooKeeperPreferencesService} when * properties have been loaded from ZooKeeper. * <p> * The local properties will be completely replaced with the properties * loaded from the specified bytes. Properties that exist locally but not * remotely will be removed locally. Properties that exist remotely but not * locally will be added locally. Proper events will be fired. * </p> * <p> * The replace strategy relies on the node version provided by ZooKeeper. * The version of a ZooKeeper node is used as the properties version. When * writing properties to ZooKeeper we'll receive a response * </p> * * @param remotePropertyBytes * @param propertiesVersion * @throws IOException */ final void loadProperties(final byte[] remotePropertyBytes, final int propertiesVersion) throws IOException { // don't do anything if removed if (removed) { return; } // collect events final List<PreferenceChangeEvent> events = new ArrayList<PreferenceChangeEvent>(); // prevent concurrent property modification (eg. remote _and_ local flush) propertiesModificationLock.lock(); try { if (removed) { return; } if (CloudDebug.zooKeeperPreferences) { LOG.debug("Loading properties for node {} (version {})", this, propertiesVersion); } // load remote properties // (note, can be null if there is a node in ZooKeeper but without data) final Properties loadedProps = new Properties(); if (remotePropertyBytes != null) { loadedProps.load(new ByteArrayInputStream(remotePropertyBytes)); // check version final Object formatVersion = loadedProps.remove(VERSION_KEY); if ((formatVersion == null) || !VERSION_VALUE.equals(formatVersion)) { // ignore for now LOG.warn("Properties with incompatible storage format version ({}) found for node {}.", formatVersion, this); return; } } // update properties version (after they were de-serialized successfully) this.propertiesVersion = propertiesVersion; propertiesLoadTimestamp = System.currentTimeMillis(); // collect all property names final Set<String> propertyNames = new HashSet<String>(); propertyNames.addAll(loadedProps.stringPropertyNames()); propertyNames.addAll(properties.stringPropertyNames()); // note, the policy here is very simple: we completely // replace the local properties with the loaded properties; // this keeps the implementation simple and also delegates // the coordination of concurrent updates in a distributed // system a layer higher to the clients of preferences API // discover new, updated and removed properties for (final String key : propertyNames) { final String newValue = loadedProps.getProperty(key); final String oldValue = properties.getProperty(key); if (newValue == null) { // does not exists in ZooKeeper, assume removed properties.remove(key); if (CloudDebug.zooKeeperPreferences) { LOG.debug("Node {} property removed: {}", this, key); } // create event events.add(new PreferenceChangeEvent(this, key, oldValue, newValue)); } else if ((oldValue == null) || !oldValue.equals(newValue)) { // assume added or updated in ZooKeeper properties.put(key, newValue); if (CloudDebug.zooKeeperPreferences) { if (oldValue == null) { LOG.debug("Node {} property added: {}={}", new Object[] { this, key, newValue }); } else { LOG.debug("Node {} property updated: {}={}", new Object[] { this, key, newValue }); } } // create event events.add(new PreferenceChangeEvent(this, key, oldValue, newValue)); } } if (CloudDebug.zooKeeperPreferences) { LOG.debug("Loaded properties for node {} (now at version {})", this, propertiesVersion); } } finally { propertiesModificationLock.unlock(); } // fire events outside of lock // TODO we need to understand event ordering better (eg. concurrent remote updates) // (this may result in sending events asynchronously through an ordered queue, but for now we do it directly) for (final PreferenceChangeEvent event : events) { firePreferenceEvent(event); } }
From source file:com.datatorrent.stram.plan.logical.LogicalPlanConfiguration.java
/** * Read node configurations from opProps. The opProps can be in any * random order, as long as they represent a consistent configuration in their * entirety.//from w w w . j a va 2s. c o m * * @param props * @param conf configuration for variable substitution and evaluation * @return Logical plan configuration. */ public LogicalPlanConfiguration addFromProperties(Properties props, Configuration conf) { if (conf != null) { StramClientUtils.evalProperties(props, conf); } for (final String propertyName : props.stringPropertyNames()) { String propertyValue = props.getProperty(propertyName); this.properties.setProperty(propertyName, propertyValue); if (propertyName.startsWith(StreamingApplication.DT_PREFIX)) { String[] keyComps = propertyName.split(KEY_SEPARATOR_SPLIT_REGEX); parseStramPropertyTokens(keyComps, 1, propertyName, propertyValue, stramConf); } } return this; }
From source file:me.mast3rplan.phantombot.PhantomBot.java
public static void main(String[] args) throws IOException { /* List of properties that must exist. */ String requiredProperties[] = new String[] { "oauth", "channel", "owner", "user" }; String requiredPropertiesErrorMessage = ""; /* Properties configuration */ Properties startProperties = new Properties(); /* Indicates that the botlogin.txt file should be overwritten/created. */ Boolean changed = false;/* ww w . java 2 s. c o m*/ /* Print the user dir */ com.gmt2001.Console.out.println("The working directory is: " + System.getProperty("user.dir")); /* Load up the bot info from the bot login file */ try { if (new File("./botlogin.txt").exists()) { try { FileInputStream inputStream = new FileInputStream("botlogin.txt"); startProperties.load(inputStream); inputStream.close(); if (startProperties.getProperty("debugon", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Mode Enabled via botlogin.txt"); PhantomBot.enableDebugging = true; } if (startProperties.getProperty("debuglog", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Log Only Mode Enabled via botlogin.txt"); PhantomBot.enableDebugging = true; PhantomBot.enableDebuggingLogOnly = true; } if (startProperties.getProperty("reloadscripts", "false").equals("true")) { com.gmt2001.Console.out.println("Enabling Script Reloading"); PhantomBot.reloadScripts = true; } if (startProperties.getProperty("rhinodebugger", "false").equals("true")) { com.gmt2001.Console.out.println("Rhino Debugger will be launched if system supports it."); PhantomBot.enableRhinoDebugger = true; } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } 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", "18.75"); startProperties.setProperty("musicenable", "true"); startProperties.setProperty("whisperlimit60", "60.0"); } } catch (Exception ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* 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 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 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 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 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 or Tweet at us!\r\n"); com.gmt2001.Console.out.print("Forum: https://community.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("Twitter: https://twitter.com/phantombotapp/\r\n"); com.gmt2001.Console.out.print("PhantomBot Knowledgebase: https://docs.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("PhantomBot WebPanel: https://docs.phantombot.tv/kb/panel/\r\n"); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("1. Please enter the bot's Twitch username: "); startProperties.setProperty("user", System.console().readLine().trim()); 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()); 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()); 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()); 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()); 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()); 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("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); }