List of usage examples for java.util Properties keySet
@Override
public Set<Object> keySet()
From source file:com.tacitknowledge.util.migration.jdbc.util.ConfigurationUtil.java
/** * Returns the value of the specified configuration parameter. * * @param props the properties file containing the values * @param param the parameter to return//from w w w .j a va 2 s . c o m * @return the value of the specified configuration parameter * @throws IllegalArgumentException if the parameter does not exist */ public static String getRequiredParam(Properties props, String param) throws IllegalArgumentException { String value = props.getProperty(param); if (value == null) { log.warn("Parameter named: " + param + " was not found."); log.warn("-----Parameters found-----"); Iterator propNameIterator = props.keySet().iterator(); while (propNameIterator.hasNext()) { String name = (String) propNameIterator.next(); String val = props.getProperty(name); log.warn(name + " = " + val); } log.warn("--------------------------"); throw new IllegalArgumentException( "'" + param + "' is a required " + "initialization parameter. Aborting."); } return value; }
From source file:com.htmlhifive.pitalium.core.config.PtlTestConfig.java
/** * JVM???????//from w w w . j a va 2 s.co m * * @return ? */ static Map<String, String> getSystemStartupArguments() { Properties properties = System.getProperties(); Map<String, String> results = new HashMap<String, String>(); int prefixLength = SYSTEM_STARTUP_ARGUMENTS_PREFIX.length(); for (Object key : properties.keySet()) { String propertyKey = (String) key; if (!propertyKey.startsWith(SYSTEM_STARTUP_ARGUMENTS_PREFIX)) { continue; } String value = properties.getProperty(propertyKey); results.put(propertyKey.substring(prefixLength), value); } LOG.debug("System startup arguments: {}", results); return results; }
From source file:com.glaf.core.util.CalendarUtils.java
public static boolean saveCalendarProperties(Properties props) { try {//from w w w .j a v a 2 s. c o m List<SystemParam> rows = new java.util.concurrent.CopyOnWriteArrayList<SystemParam>(); java.util.Set<Object> set = props.keySet(); java.util.Iterator<Object> iter = set.iterator(); while (iter.hasNext()) { String key = (String) iter.next(); String value = props.getProperty(key); SystemParam p = new SystemParam(); p.setBusinessKey("calendar"); p.setServiceKey("calendar"); p.setTypeCd("calendar"); p.setJavaType("String"); p.setKeyName(key); p.setStringVal(value); rows.add(p); } getSystemParamService().saveAll("calendar", "calendar", rows); return true; } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:org.esgf.web.FacetFileController.java
/** * New helper method for extracting facet info from the facets.properties file in /esg/config * // w w w . j a va 2 s . c o m * @return */ private static String[] getFacetInfo() { String[] facetTokens = null; Properties properties = new Properties(); String propertiesFile = FACET_PROPERTIES_FILE; boolean createDefault = false; try { properties.load(new FileInputStream(propertiesFile)); facetTokens = new String[properties.size()]; for (Object key : properties.keySet()) { String value = (String) properties.get(key); String[] valueTokens = value.split(":"); try { int index = Integer.parseInt(valueTokens[0]); if (index > -1) { if (index < properties.size()) { String facetInfo = (String) key + ":" + valueTokens[1] + ":" + valueTokens[2]; facetTokens[index] = facetInfo; } } } //Note: need to fix this. This will only work if ALL facet readings are wrong catch (Exception e) { System.out.println("COULD NOT INDEX: " + key); createDefault = true; } } List<String> fixedFacetTokens = new ArrayList<String>(); //"fix" the array here (for any index collisions for (int i = 0; i < facetTokens.length; i++) { if (facetTokens[i] != null) { fixedFacetTokens.add(facetTokens[i]); } } facetTokens = (String[]) fixedFacetTokens.toArray(new String[fixedFacetTokens.size()]); } catch (FileNotFoundException f) { System.out.println("Using default facet list"); facetTokens = getDefaultFacets(); } catch (Exception e) { e.printStackTrace(); } if (createDefault) { System.out.println("Using default facet list"); facetTokens = getDefaultFacets(); } return facetTokens; }
From source file:com.cloud.consoleproxy.ConsoleProxy.java
private static void configProxy(Properties conf) { s_logger.info("Configure console proxy..."); for (Object key : conf.keySet()) { s_logger.info("Property " + (String) key + ": " + conf.getProperty((String) key)); }/*from w ww . j ava 2 s . c om*/ String s = conf.getProperty("consoleproxy.httpListenPort"); if (s != null) { httpListenPort = Integer.parseInt(s); s_logger.info("Setting httpListenPort=" + s); } s = conf.getProperty("premium"); if (s != null && s.equalsIgnoreCase("true")) { s_logger.info( "Premium setting will override settings from consoleproxy.properties, listen at port 443"); httpListenPort = 443; factoryClzName = "com.cloud.consoleproxy.ConsoleProxySecureServerFactoryImpl"; } else { factoryClzName = ConsoleProxyBaseServerFactoryImpl.class.getName(); } s = conf.getProperty("consoleproxy.httpCmdListenPort"); if (s != null) { httpCmdListenPort = Integer.parseInt(s); s_logger.info("Setting httpCmdListenPort=" + s); } s = conf.getProperty("consoleproxy.reconnectMaxRetry"); if (s != null) { reconnectMaxRetry = Integer.parseInt(s); s_logger.info("Setting reconnectMaxRetry=" + reconnectMaxRetry); } s = conf.getProperty("consoleproxy.readTimeoutSeconds"); if (s != null) { readTimeoutSeconds = Integer.parseInt(s); s_logger.info("Setting readTimeoutSeconds=" + readTimeoutSeconds); } }
From source file:com.panet.imeta.core.database.ConnectionPoolUtil.java
private static void createPool(DatabaseMeta databaseMeta, String partitionId, int initialSize, int maximumSize) throws KettleDatabaseException { LogWriter.getInstance().logBasic(databaseMeta.toString(), Messages.getString("Database.CreatingConnectionPool", databaseMeta.getName())); GenericObjectPool gpool = new GenericObjectPool(); gpool.setMaxIdle(-1);// w ww.ja v a 2 s . c om gpool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); gpool.setMaxActive(maximumSize); String clazz = databaseMeta.getDriverClass(); try { Class.forName(clazz).newInstance(); } catch (Exception e) { throw new KettleDatabaseException(Messages.getString( "Database.UnableToLoadConnectionPoolDriver.Exception", databaseMeta.getName(), clazz), e); } String url; String userName; String password; try { url = databaseMeta.environmentSubstitute(databaseMeta.getURL(partitionId)); userName = databaseMeta.environmentSubstitute(databaseMeta.getUsername()); password = databaseMeta.environmentSubstitute(databaseMeta.getPassword()); } catch (RuntimeException e) { url = databaseMeta.getURL(partitionId); userName = databaseMeta.getUsername(); password = databaseMeta.getPassword(); } // Get the list of pool properties Properties originalProperties = databaseMeta.getConnectionPoolingProperties(); //Add user/pass originalProperties.setProperty("user", Const.NVL(userName, "")); originalProperties.setProperty("password", Const.NVL(password, "")); // Now, replace the environment variables in there... Properties properties = new Properties(); Iterator<Object> iterator = originalProperties.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = originalProperties.getProperty(key); properties.put(key, databaseMeta.environmentSubstitute(value)); } // Create factory using these properties. // ConnectionFactory cf = new DriverManagerConnectionFactory(url, properties); new PoolableConnectionFactory(cf, gpool, null, null, false, false); for (int i = 0; i < initialSize; i++) { try { gpool.addObject(); } catch (Exception e) { throw new KettleDatabaseException( Messages.getString("Database.UnableToPreLoadConnectionToConnectionPool.Exception"), e); } } pd.registerPool(databaseMeta.getName(), gpool); LogWriter.getInstance().logBasic(databaseMeta.toString(), Messages.getString("Database.CreatedConnectionPool", databaseMeta.getName())); }
From source file:io.amient.yarn1.YarnClient.java
/** * This method should be called by the implementing application static main * method. It does all the work around creating a yarn application and * submitting the request to the yarn resource manager. The class given in * the appClass argument will be run inside the yarn-allocated master * container.//from w ww.ja v a2 s .c om */ public static void submitApplicationMaster(Properties appConfig, Class<? extends YarnMaster> masterClass, String[] args, Boolean awaitCompletion) throws Exception { log.info("Yarn1 App Configuration:"); for (Object param : appConfig.keySet()) { log.info(param.toString() + " = " + appConfig.get(param).toString()); } String yarnConfigPath = appConfig.getProperty("yarn1.site", "/etc/hadoop"); String masterClassName = masterClass.getName(); appConfig.setProperty("yarn1.master.class", masterClassName); String applicationName = appConfig.getProperty("yarn1.application.name", masterClassName); log.info("--------------------------------------------------------------"); if (Boolean.valueOf(appConfig.getProperty("yarn1.local.mode", "false"))) { YarnMaster.run(appConfig, args); return; } int masterPriority = Integer.valueOf( appConfig.getProperty("yarn1.master.priority", String.valueOf(YarnMaster.DEFAULT_MASTER_PRIORITY))); int masterMemoryMb = Integer.valueOf(appConfig.getProperty("yarn1.master.memory.mb", String.valueOf(YarnMaster.DEFAULT_MASTER_MEMORY_MB))); int masterNumCores = Integer.valueOf( appConfig.getProperty("yarn1.master.num.cores", String.valueOf(YarnMaster.DEFAULT_MASTER_CORES))); String queue = appConfig.getProperty("yarn1.queue"); Configuration yarnConfig = new YarnConfiguration(); yarnConfig.addResource(new FileInputStream(yarnConfigPath + "/core-site.xml")); yarnConfig.addResource(new FileInputStream(yarnConfigPath + "/hdfs-site.xml")); yarnConfig.addResource(new FileInputStream(yarnConfigPath + "/yarn-site.xml")); for (Map.Entry<Object, Object> entry : appConfig.entrySet()) { yarnConfig.set(entry.getKey().toString(), entry.getValue().toString()); } final org.apache.hadoop.yarn.client.api.YarnClient yarnClient = org.apache.hadoop.yarn.client.api.YarnClient .createYarnClient(); yarnClient.init(yarnConfig); yarnClient.start(); for (NodeReport report : yarnClient.getNodeReports(NodeState.RUNNING)) { log.debug("Node report:" + report.getNodeId() + " @ " + report.getHttpAddress() + " | " + report.getCapability()); } log.info("Submitting application master class " + masterClassName); YarnClientApplication app = yarnClient.createApplication(); GetNewApplicationResponse appResponse = app.getNewApplicationResponse(); final ApplicationId appId = appResponse.getApplicationId(); if (appId == null) { System.exit(111); } else { appConfig.setProperty("am.timestamp", String.valueOf(appId.getClusterTimestamp())); appConfig.setProperty("am.id", String.valueOf(appId.getId())); } YarnClient.distributeResources(yarnConfig, appConfig, applicationName); String masterJvmArgs = appConfig.getProperty("yarn1.master.jvm.args", ""); YarnContainerContext masterContainer = new YarnContainerContext(yarnConfig, appConfig, masterJvmArgs, masterPriority, masterMemoryMb, masterNumCores, applicationName, YarnMaster.class, args); ApplicationSubmissionContext appContext = app.getApplicationSubmissionContext(); appContext.setApplicationName(masterClassName); appContext.setResource(masterContainer.capability); appContext.setPriority(masterContainer.priority); appContext.setQueue(queue); appContext.setApplicationType(appConfig.getProperty("yarn1.application.type", "YARN")); appContext.setAMContainerSpec(masterContainer.createContainerLaunchContext()); log.info("Master container spec: " + masterContainer.capability); yarnClient.submitApplication(appContext); ApplicationReport report = yarnClient.getApplicationReport(appId); log.info("Tracking URL: " + report.getTrackingUrl()); if (awaitCompletion) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (!yarnClient.isInState(Service.STATE.STOPPED)) { log.info("Killing yarn application in shutdown hook"); try { yarnClient.killApplication(appId); } catch (Throwable e) { log.error("Failed to kill yarn application - please check YARN Resource Manager", e); } } } }); float lastProgress = -0.0f; while (true) { try { Thread.sleep(10000); report = yarnClient.getApplicationReport(appId); if (lastProgress != report.getProgress()) { lastProgress = report.getProgress(); log.info(report.getApplicationId() + " " + (report.getProgress() * 100.00) + "% " + (System.currentTimeMillis() - report.getStartTime()) + "(ms) " + report.getDiagnostics()); } if (!report.getFinalApplicationStatus().equals(FinalApplicationStatus.UNDEFINED)) { log.info(report.getApplicationId() + " " + report.getFinalApplicationStatus()); log.info("Tracking url: " + report.getTrackingUrl()); log.info("Finish time: " + ((System.currentTimeMillis() - report.getStartTime()) / 1000) + "(s)"); break; } } catch (Throwable e) { log.error("Master Heart Beat Error - terminating", e); yarnClient.killApplication(appId); Thread.sleep(2000); } } yarnClient.stop(); if (!report.getFinalApplicationStatus().equals(FinalApplicationStatus.SUCCEEDED)) { System.exit(112); } } yarnClient.stop(); }
From source file:com.joseflavio.unhadegato.Concentrador.java
/** * {@link CopaibaGerenciador#iniciar() Iniciar}, {@link CopaibaGerenciador#atualizar(String, int, boolean, boolean, String, String, int) atualizar} * e/ou {@link CopaibaGerenciador#encerrar() encerrar} {@link CopaibaGerenciador}'s. * @param arquivo Arquivo de configurao de {@link CopaibaConexao}'s. *//*w w w .j av a 2s . c o m*/ private static void executarCopaibas(File arquivo) { try { if (!arquivo.exists()) { try (InputStream is = Concentrador.class.getResourceAsStream("/copaibas.conf"); OutputStream os = new FileOutputStream(arquivo);) { IOUtils.copy(is, os); } } Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(arquivo)) { props.load(fis); } for (Object chave : props.keySet()) { try { String nome = chave.toString(); String[] p = props.getProperty(nome).split("\",\""); String endereco = p[0].substring(1); int porta = Integer.parseInt(p[1]); boolean segura = p[2].equals("TLS") || p[2].equals("SSL"); boolean ignorarCert = p[3].equals("S"); String usuario = p[4]; String senha = p.length >= 7 ? p[5] : p[5].substring(0, p[5].length() - 1); int conexoes = p.length >= 7 ? Integer.parseInt(p[6].substring(0, p[6].length() - 1)) : 5; CopaibaGerenciador gerenciador = gerenciadores.get(nome); if (gerenciador == null) { log.info(Util.getMensagem("copaiba.iniciando", nome)); gerenciador = new CopaibaGerenciador(nome, endereco, porta, segura, ignorarCert, usuario, senha, conexoes); gerenciadores.put(nome, gerenciador); gerenciador.iniciar(); log.info(Util.getMensagem("copaiba.iniciada", nome)); } else { log.info(Util.getMensagem("copaiba.verificando", nome)); if (gerenciador.atualizar(endereco, porta, segura, ignorarCert, usuario, senha, conexoes)) { log.info(Util.getMensagem("copaiba.atualizada", nome)); } else { log.info(Util.getMensagem("copaiba.inalterada", nome)); } } try (CopaibaConexao cc = new CopaibaConexao(endereco, porta, segura, ignorarCert, usuario, senha)) { cc.verificar(); log.info(Util.getMensagem("copaiba.conexao.teste.exito", nome)); } catch (Exception e) { log.info(Util.getMensagem("copaiba.conexao.teste.erro", nome, e.getMessage())); log.error(e.getMessage(), e); } } catch (Exception e) { log.error(e.getMessage(), e); } } Iterator<CopaibaGerenciador> it = gerenciadores.values().iterator(); while (it.hasNext()) { CopaibaGerenciador gerenciador = it.next(); String nome = gerenciador.getNome(); if (!props.containsKey(nome)) { try { log.info(Util.getMensagem("copaiba.encerrando", nome)); it.remove(); gerenciador.encerrar(); log.info(Util.getMensagem("copaiba.encerrada", nome)); } catch (Exception e) { log.error(e.getMessage(), e); } } } } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:it.cnr.icar.eric.common.AbstractProperties.java
/** * Logs all properties as name=value pairs. Requires debug level. * * @param propsName name for the properties set. * @param props Properties to be logged. *//*from w ww .j a v a 2 s . co m*/ protected static void logProperties(String propsName, Properties props) { if (log.isDebugEnabled()) { log.debug("=================================================="); log.debug(propsName + ":"); Iterator<Object> names = (new TreeSet<Object>(props.keySet())).iterator(); while (names.hasNext()) { String name = (String) names.next(); String value = props.getProperty(name); log.debug(name + "=" + value); } log.debug("=================================================="); } }
From source file:org.apache.pig.impl.util.PropertiesUtil.java
/** * Loads the default properties from pig-default.properties and * pig.properties./*from ww w. j a va 2s.co m*/ * @param properties Properties object that needs to be loaded with the * properties' values. */ public static void loadDefaultProperties(Properties properties) { loadPropertiesFromFile(properties, System.getProperty("user.home") + "/.pigrc"); loadPropertiesFromClasspath(properties, DEFAULT_PROPERTIES_FILE); loadPropertiesFromClasspath(properties, PROPERTIES_FILE); setDefaultsIfUnset(properties); //Now set these as system properties only if they are not already defined. if (log.isDebugEnabled()) { for (Object o : properties.keySet()) { String propertyName = (String) o; StringBuilder sb = new StringBuilder(); sb.append("Found property "); sb.append(propertyName); sb.append("="); sb.append(properties.get(propertyName).toString()); log.debug(sb.toString()); } } // Add System properties which include command line overrides // Any existing keys will be overridden for (Entry<Object, Object> entry : System.getProperties().entrySet()) { String key = (String) entry.getKey(); if (key.startsWith("sun.") || key.startsWith("java.")) { continue; } properties.put(key, entry.getValue()); } // For telling error fast when there are problems ConfigurationValidator.validatePigProperties(properties); }