@Test public void testState() throws IOException { final File fcontent = File.createTempFile("foo", "bar"); final Properties properties = new Properties(); final Date dt = new Date(); properties.put("int", 10453); properties.put("long", 1000000L); properties.put("date", dt); final OutputStream out = new FileOutputStream(fcontent); properties.store(out); final Properties loadProperties = new Properties(); final InputStream in = new FileInputStream(fcontent); loadProperties.load(in); assertNotNull(properties.get("int")); assertNotNull(properties.get("long")); assertNotNull(properties.get("date")); assertEquals(10453, properties.get("int")); assertEquals(1000000L, properties.get("long")); assertEquals(dt, properties.get("date")); }
private void target(Info info) { if (raidTarget.containsKey(info.getChannel())) { info.sendMessage( COLOR + "The raid target is " + raidTarget.get(info.getChannel()) + " located at " + raidLocation.get(info.getChannel())); } else info.sendMessage("No target is set."); }
@Test public void testProperties() { final Properties properties = config.getProperties(); assertNotNull(properties); assertEquals("5", properties.get(GroupProperties.PROP_MERGE_FIRST_RUN_DELAY_SECONDS)); assertEquals("5", properties.get(GroupProperties.PROP_MERGE_NEXT_RUN_DELAY_SECONDS)); final Config config2 = instance.getConfig(); final Properties properties2 = config2.getProperties(); assertNotNull(properties2); assertEquals("5", properties2.get(GroupProperties.PROP_MERGE_FIRST_RUN_DELAY_SECONDS)); assertEquals("5", properties2.get(GroupProperties.PROP_MERGE_NEXT_RUN_DELAY_SECONDS)); }
private void go(Info info) { String msg = COLOR + Colors.BOLD + "MOVE OUT!"; if (raidTarget.get(info.getChannel()) != null) { msg += Colors.NORMAL + COLOR + " Target is " + raidTarget.get(info.getChannel()) + " " + raidLocation.get(info.getChannel()); } info.sendMessage(msg); }
String inferHttpResponseCode(CachedUrl cu, Properties cuProps) { if (cuProps.get("location") == null) { return "HTTP/1.1 200 OK"; } else { return "HTTP/1.1 302 Found"; } }
public static Map<String, String> readProperties(InputStream inputStream) { Map<String, String> propertiesMap = null; try { propertiesMap = new LinkedHashMap<String, String>(); Properties properties = new Properties(); properties.load(inputStream); Enumeration<?> enumeration = properties.propertyNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String value = (String) properties.get(key); propertiesMap.put(key, value); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return propertiesMap; }
public Color getColor(String key) { Color tempColor = null; Integer tempInt = null; String hexTriplet = (String) properties.get(key); // Convert to char arrays char[] hexChars = hexTriplet.toCharArray(); char[] red = {hexChars[0], hexChars[1]}; char[] green = {hexChars[2], hexChars[3]}; char[] blue = {hexChars[4], hexChars[5]}; // Convert to Strings String r = new String(red); String g = new String(green); String b = new String(blue); // Convert to ints tempInt = Integer.parseInt(r); int rValue = tempInt.intValue(); tempInt = Integer.parseInt(g); int gValue = tempInt.intValue(); tempInt = Integer.parseInt(b); int bValue = tempInt.intValue(); tempColor = new Color(rValue, gValue, bValue); return tempColor; }
public static void main(String[] args) { Properties prop = System.getProperties(); // 因为Properties是Hashtable的子类,也就是Map集合的一个子类对象。 // 那么可以通过map的方法取出该集合中的元素。 // 该集合中存储的都是字符串。没有泛型定义。 // 如何在系统中自定义一些系统信息 System.setProperty("mykey", "myvalue"); // 获取指定属性信息 String osvalue = System.getProperty("os.name"); System.out.println("value=" + osvalue); // 可不可以在JVM启动时,动态地加载一些属性信息 // -D<name>=<value> 设置系统属性 // 获取所有属性信息 for (Object obj : prop.keySet()) { String value = (String) prop.get(obj); System.out.println(obj + "::" + value); } }
public String getPluginID() { String id = (String) props.get("plugin.id"); // hack alert - azupdater needs to change its plugin id due to general hackage if (id != null && id.equals("azupdater")) { plugin_id_to_use = id; } if (plugin_id_to_use != null) { return plugin_id_to_use; } // Calculate what plugin ID value to use - look at the properties file // first, and if that isn't correct, base it on the given plugin ID // value we were given. if (id == null) { id = given_plugin_id; } if (id == null) { id = "<none>"; } plugin_id_to_use = id; return plugin_id_to_use; }
private XmlUIElement getXmlUIElementFor(String typeArg) { if (typeToClassMappingProp == null) { setUpMappingsHM(); } String clsName = (String) typeToClassMappingProp.get(typeArg); if ((clsName != null) && !(clsName.equals("*NOTFOUND*")) && !(clsName.equals("*EXCEPTION*"))) { try { Class cls = Class.forName(clsName); return (XmlUIElement) cls.newInstance(); } catch (Throwable th) { typeToClassMappingProp.put(typeArg, "*EXCEPTION*"); showErrorMessage( MessageFormat.format( ProvClientUtils.getString( "{0} occurred when trying to get the XmlUIElement for type : {1}"), new Object[] {th.getClass().getName(), typeArg})); th.printStackTrace(); return null; } } else if (clsName == null) { typeToClassMappingProp.put(typeArg, "*NOTFOUND*"); showErrorMessage( MessageFormat.format( ProvClientUtils.getString( "The type {0} does not have the corresponding XMLUIElement specified in the TypeToUIElementMapping.txt file"), new Object[] {typeArg})); } return null; }
public EmbeddedKafka(Map<String, String> customProps) throws Exception { super(); Map<String, String> defaultProps = Maps.newHashMap(); defaultProps.put("broker.id", "0"); defaultProps.put("host.name", "127.0.0.1"); defaultProps.put("port", "9092"); defaultProps.put("advertised.host.name", "127.0.0.1"); defaultProps.put("advertised.port", "9092"); defaultProps.put("log.dir", createTempDir().getAbsolutePath()); defaultProps.put("zookeeper.connect", package$.MODULE$.ZookeeperConnectionString()); defaultProps.put("replica.high.watermark.checkpoint.interval.ms", "5000"); defaultProps.put("log.flush.interval.messages", "1"); defaultProps.put("replica.socket.timeout.ms", "500"); defaultProps.put("controlled.shutdown.enable", "false"); defaultProps.put("auto.leader.rebalance.enable", "false"); Properties props = new Properties(); props.putAll(defaultProps); props.putAll(customProps); final KafkaConfig kafkaConfig = new KafkaConfig(props); zookeeper = new EmbeddedZookeeper((String) props.get("zookeeper.connect")); awaitCond(aVoid -> zookeeper.isRunning(), 3000, 100); server = new KafkaServer(kafkaConfig, SystemTime$.MODULE$); Thread.sleep(2000); log.info("Starting the Kafka server at {}", kafkaConfig.zkConnect()); server.startup(); Thread.sleep(2000); }
@Override public void init(Context context, Properties initProps) { initProps = decryptPwd(initProps); Object o = initProps.get(CONVERT_TYPE); if (o != null) convertType = Boolean.parseBoolean(o.toString()); factory = createConnectionFactory(context, initProps); String bsz = initProps.getProperty("batchSize"); if (bsz != null) { bsz = context.replaceTokens(bsz); try { batchSize = Integer.parseInt(bsz); if (batchSize == -1) batchSize = Integer.MIN_VALUE; } catch (NumberFormatException e) { LOG.warn("Invalid batch size: " + bsz); } } for (Map<String, String> map : context.getAllEntityFields()) { String n = map.get(DataImporter.COLUMN); String t = map.get(DataImporter.TYPE); if ("sint".equals(t) || "integer".equals(t)) fieldNameVsType.put(n, Types.INTEGER); else if ("slong".equals(t) || "long".equals(t)) fieldNameVsType.put(n, Types.BIGINT); else if ("float".equals(t) || "sfloat".equals(t)) fieldNameVsType.put(n, Types.FLOAT); else if ("double".equals(t) || "sdouble".equals(t)) fieldNameVsType.put(n, Types.DOUBLE); else if ("date".equals(t)) fieldNameVsType.put(n, Types.DATE); else if ("boolean".equals(t)) fieldNameVsType.put(n, Types.BOOLEAN); else if ("binary".equals(t)) fieldNameVsType.put(n, Types.BLOB); else fieldNameVsType.put(n, Types.VARCHAR); } }
public String getPluginName() { String name = null; if (props != null) { name = (String) props.get("plugin.name"); } if (name == null) { try { name = new File(pluginDir).getName(); } catch (Throwable e) { } } if (name == null || name.length() == 0) { name = plugin.getClass().getName(); } return (name); }
public String getPluginVersion() { String version = (String) props.get("plugin.version"); if (version == null) { version = plugin_version; } return (version); }
public Map getSystemProperties() { Map map = new HashMap(); Properties props = System.getProperties(); for (Enumeration e = props.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); String val = (String) props.get(key); map.put(key, val); } return map; }
/** * Load the Configuration file with the values from the command line and config files, and place * stuff in the DistrubutedCacheService as needed * * @param conf The Configuration to populate * @param args The command line arguments * @throws Exception */ public static void initalizeConf(Configuration conf, String[] args) throws Exception { // Parse the arguments and make sure the required args are there final CommandLine commandLine; final Options options = constructGnuOptions(); try { commandLine = new GnuParser().parse(options, args); } catch (MissingOptionException ex) { HelpFormatter help = new HelpFormatter(); help.printHelp("hadoop jar <jarFile> " + FrameworkDriver.class.getCanonicalName(), options); return; } catch (Exception ex) { ex.printStackTrace(); return; } final String userConfFilePath = commandLine.getOptionValue("amino_config_file_path", ""); final String aminoDefaultConfigPath = commandLine.getOptionValue("amino_default_config_path"); final String baseDir = commandLine.getOptionValue("base_dir"); stopOnFirstPhase = commandLine.hasOption("stop"); // Set the base dir config value if it was provided. if (StringUtils.isNotEmpty(baseDir)) { conf.set(AminoConfiguration.BASE_DIR, baseDir); } conf.set(AminoConfiguration.DEFAULT_CONFIGURATION_PATH_KEY, aminoDefaultConfigPath); // create a single DistributedCacheService so that multiple cache entries are deduped. // Cache files are added after each config is loaded in case the the property value changes. final DistributedCacheService distributedCacheService = new DistributedCacheService(); // 1. load AminoDefaults AminoConfiguration.loadAndMergeWithDefault(conf, true); distributedCacheService.addFilesToDistributedCache(conf); // 2. load user config files, allowing them to overwrite if (!StringUtils.isEmpty(userConfFilePath)) { for (String path : getUserConfigFiles(userConfFilePath)) { Configuration userConf = new Configuration(false); logger.info("Grabbing configuration information from: " + path); userConf.addResource(new FileInputStream(path)); HadoopConfigurationUtils.mergeConfs(conf, userConf); } } distributedCacheService.addFilesToDistributedCache(conf); // 3. load command line arguments as properties, allowing them to overwrite final Properties propertyOverrides = commandLine.getOptionProperties("property_override"); for (Object key : propertyOverrides.keySet()) { conf.set((String) key, (String) propertyOverrides.get(key)); } distributedCacheService.addFilesToDistributedCache(conf); }
protected propertyWrapper(Properties _props) { Iterator it = _props.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); put(key, _props.get(key)); } initialising = false; }
@Override public void open() { out = new ByteArrayOutputStream(); flinkConf = new org.apache.flink.configuration.Configuration(); Properties intpProperty = getProperty(); for (Object k : intpProperty.keySet()) { String key = (String) k; String val = toString(intpProperty.get(key)); flinkConf.setString(key, val); } if (localMode()) { startFlinkMiniCluster(); } flinkIloop = new FlinkILoop( getHost(), getPort(), flinkConf, (BufferedReader) null, new PrintWriter(out)); flinkIloop.settings_$eq(createSettings()); flinkIloop.createInterpreter(); imain = flinkIloop.intp(); org.apache.flink.api.scala.ExecutionEnvironment benv = flinkIloop.scalaBenv(); // new ExecutionEnvironment(remoteBenv) org.apache.flink.streaming.api.scala.StreamExecutionEnvironment senv = flinkIloop.scalaSenv(); senv.getConfig().disableSysoutLogging(); benv.getConfig().disableSysoutLogging(); // prepare bindings imain.interpret("@transient var _binder = new java.util.HashMap[String, Object]()"); Map<String, Object> binder = (Map<String, Object>) getLastObject(); // import libraries imain.interpret("import scala.tools.nsc.io._"); imain.interpret("import Properties.userHome"); imain.interpret("import scala.compat.Platform.EOL"); imain.interpret("import org.apache.flink.api.scala._"); imain.interpret("import org.apache.flink.api.common.functions._"); binder.put("benv", benv); imain.interpret( "val benv = _binder.get(\"benv\").asInstanceOf[" + benv.getClass().getName() + "]"); binder.put("senv", senv); imain.interpret( "val senv = _binder.get(\"senv\").asInstanceOf[" + senv.getClass().getName() + "]"); }
@SuppressWarnings({"unchecked", "rawtypes"}) private int executeScriptWithCaching(CommandLine commandLine, String scriptName, String env) { List<File> potentialScripts; List<File> allScripts = getAvailableScripts(); GantBinding binding = new GantBinding(); binding.setVariable("scriptName", scriptName); setDefaultInputStream(binding); // Now find what scripts match the one requested by the user. potentialScripts = getPotentialScripts(scriptName, allScripts); if (potentialScripts.size() == 0) { try { File aliasFile = new File(settings.getUserHome(), ".grails/.aliases"); if (aliasFile.exists()) { Properties aliasProperties = new Properties(); aliasProperties.load(new FileReader(aliasFile)); if (aliasProperties.containsKey(commandLine.getCommandName())) { String aliasValue = (String) aliasProperties.get(commandLine.getCommandName()); String[] aliasPieces = aliasValue.split(" "); String commandName = aliasPieces[0]; String correspondingScriptName = GrailsNameUtils.getNameFromScript(commandName); potentialScripts = getPotentialScripts(correspondingScriptName, allScripts); if (potentialScripts.size() > 0) { String[] additionalArgs = new String[aliasPieces.length - 1]; System.arraycopy(aliasPieces, 1, additionalArgs, 0, additionalArgs.length); insertArgumentsInFrontOfExistingArguments(commandLine, additionalArgs); } } } } catch (Exception e) { console.error(e); } } // First try to load the script from its file. If there is no // file, then attempt to load it as a pre-compiled script. If // that fails, then let the user know and then exit. if (potentialScripts.size() > 0) { potentialScripts = (List) DefaultGroovyMethods.unique(potentialScripts); final File scriptFile = potentialScripts.get(0); if (!isGrailsProject() && !isExternalScript(scriptFile)) { return handleScriptExecutedOutsideProjectError(); } return executeScriptFile(commandLine, scriptName, env, binding, scriptFile); } return attemptPrecompiledScriptExecute(commandLine, scriptName, env, binding, allScripts); }
public static void dumpSystemProperties() { out("System Properties:"); Properties props = System.getProperties(); Iterator it = props.keySet().iterator(); while (it.hasNext()) { String name = (String) it.next(); out("\t".concat(name).concat(" = '").concat(props.get(name).toString()).concat("'")); } }
private void saveNewProperties(String path, Properties oldProps) throws Exception { File newPropsFile = new File(path + FileSystemPage.propertiesFilename); WikiPageProperties newProps = new WikiPageProperties(); for (Iterator iterator = oldProps.keySet().iterator(); iterator.hasNext(); ) { String key = (String) iterator.next(); String value = (String) oldProps.get(key); if (!"false".equals(value)) newProps.set(key, value); } FileOutputStream os = new FileOutputStream(newPropsFile); newProps.save(os); os.close(); }
private void loadConfiguration() throws RuntimeConfigException { trace(String.format("Loading configuration from [%s]", configFilePath)); try { InputStream stream = new FileInputStream(configFilePath); // InputStream stream1 = new FileInputStream("config/ocsswws.config"); try { Properties fileProperties = new Properties(); fileProperties.load(stream); // @todo check tests - code was not backward compatible with Java 5 // so i changed it - but this is not the only place of uncompatibilty // add default properties so that they override file properties // Set<String> propertyNames = fileProperties.stringPropertyNames(); // for (String propertyName : propertyNames) { // String propertyValue = fileProperties.getProperty(propertyName); // if (!isPropertySet(propertyName)) { // setProperty(propertyName, propertyValue); // trace(String.format("Configuration property [%s] added", // propertyName)); // } else { // trace(String.format("Configuration property [%s] ignored", // propertyName)); // } // } Enumeration<?> enumeration = fileProperties.propertyNames(); while (enumeration.hasMoreElements()) { final Object key = enumeration.nextElement(); if (key instanceof String) { final Object value = fileProperties.get(key); if (value instanceof String) { final String keyString = (String) key; String propertyValue = fileProperties.getProperty(keyString); if (!isPropertySet(keyString)) { setProperty(keyString, propertyValue); trace(String.format("Configuration property [%s] added", keyString)); } else { trace(String.format("Configuration property [%s] ignored", keyString)); } } } } } finally { stream.close(); } } catch (IOException e) { throw new RuntimeConfigException( String.format("Failed to load configuration [%s]", configFilePath), e); } }
Properties runProperties() { Properties props = new Properties(); props.putAll(this.properties); Properties sysProps = System.getProperties(); Set<String> names = sysProps.stringPropertyNames(); for (String name : names) { if (name.startsWith("jboss") || name.startsWith("wildfly") || name.startsWith("swarm")) { props.put(name, sysProps.get(name)); } } return props; }
public Object getService(Properties properties) throws ApiException { Object response = null; String key = (String) properties.get("key"); try { ApiService service = this.getApiCatalogManager().getApiService(key); if (null == service) { throw new ApiException( IApiErrorCodes.API_SERVICE_INVALID, "Service '" + key + "' does not exist"); } if (!service.isActive()) { throw new ApiException( IApiErrorCodes.API_SERVICE_ACTIVE_FALSE, "Service '" + key + "' is not active"); } this.checkServiceAuthorization(service, properties, true); Properties serviceParameters = new Properties(); serviceParameters.putAll(service.getParameters()); Iterator<Object> paramIter = properties.keySet().iterator(); List<String> reservedParameters = Arrays.asList(SystemConstants.API_RESERVED_PARAMETERS); while (paramIter.hasNext()) { Object paramName = paramIter.next(); String paramNameString = paramName.toString(); if (reservedParameters.contains(paramNameString) || service.isFreeParameter(paramNameString)) { serviceParameters.put(paramNameString, properties.get(paramName)); } } response = this.getResponseBuilder().createResponse(service.getMaster(), serviceParameters); } catch (ApiException e) { throw e; } catch (Throwable t) { ApsSystemUtils.logThrowable( t, this, "getService", "Error invocating service - key '" + key + "'"); throw new ApiException(IApiErrorCodes.SERVER_ERROR, "Internal error"); } return response; }
private Map<String, Pack> loadInstallationInformation(boolean modifyInstallation) { Map<String, Pack> installedpacks = new HashMap<String, Pack>(); if (!modifyInstallation) { return installedpacks; } // installation shall be modified // load installation information ObjectInputStream oin = null; try { FileInputStream fin = new FileInputStream( new File( installData.getInstallPath() + File.separator + InstallData.INSTALLATION_INFORMATION)); oin = new ObjectInputStream(fin); List<Pack> packsinstalled = (List<Pack>) oin.readObject(); for (Pack installedpack : packsinstalled) { installedpacks.put(installedpack.getName(), installedpack); } this.removeAlreadyInstalledPacks(installData.getSelectedPacks()); logger.fine("Found " + packsinstalled.size() + " installed packs"); Properties variables = (Properties) oin.readObject(); for (Object key : variables.keySet()) { installData.setVariable((String) key, (String) variables.get(key)); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (oin != null) { try { oin.close(); } catch (IOException e) { } } } return installedpacks; }
/* * Read system packages from a properties file * //TODO: we should probably grab this file from the Karaf distro itself instead of duplicating it in the plugin */ private void readSystemPackages() throws IOException { Properties properties = new Properties(); if (karafConfig.equals("config.properties")) { properties.load(getClass().getClassLoader().getResourceAsStream("config.properties")); } else { properties.load(new FileInputStream(new File(karafConfig))); } String packages = (String) properties.get(jreVersion); for (String pkg : packages.split(";")) { systemExports.add(pkg.trim()); } for (String pkg : packages.split(",")) { systemExports.add(pkg.trim()); } }
/** * Creates a URL from the passed in parameters. It has the following look:<br> * webpage?param1=value1¶m2=value2...... * * @param webpage - the destination we are headed to * @param params - the parameters we append to the Destination, note the order of these parameters * is random * @return String - the constructed Destination */ public static String constructURL(String webpage, Properties params) { final String METHOD_NAME = "constructURL(): "; StringBuffer sb = new StringBuffer(); sb.append(webpage); sb.append("?"); Iterator iter = params.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); String value = (String) params.get(key); sb.append(key); sb.append("="); sb.append(value); if (iter.hasNext()) { sb.append("&"); } } return sb.toString(); }
@Before public void before() throws IOException { InputStream in = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("my-librato-config.properties"); Assert.assertNotNull( "File src/test/resources/my-librato-config.properties is missing. See librato-config.template.properties for details", in); Properties config = new Properties(); config.load(in); libratoWriter = new LibratoWriter(); Map<String, Object> settings = new HashMap<String, Object>(); settings.put(AbstractOutputWriter.SETTING_USERNAME, config.get("LIBRATO_USER")); settings.put(AbstractOutputWriter.SETTING_TOKEN, config.getProperty("LIBRATO_TOKEN")); libratoWriter.setSettings(settings); libratoWriter.start(); }
public void setLanguage(String par1Str) { if (!par1Str.equals(this.currentLanguage)) { Properties var2 = new Properties(); try { this.loadLanguage(var2, "en_US"); } catch (IOException var8) {; } this.isUnicode = false; if (!"en_US".equals(par1Str)) { try { this.loadLanguage(var2, par1Str); Enumeration var3 = var2.propertyNames(); while (var3.hasMoreElements() && !this.isUnicode) { Object var4 = var3.nextElement(); Object var5 = var2.get(var4); if (var5 != null) { String var6 = var5.toString(); for (int var7 = 0; var7 < var6.length(); ++var7) { if (var6.charAt(var7) >= 256) { this.isUnicode = true; break; } } } } } catch (IOException var9) { var9.printStackTrace(); return; } } this.currentLanguage = par1Str; this.translateTable = var2; } }
/** * This method is used to get the String that contain key value pair from the propertise. * * @param String * @return String. */ public String list(String propfile) { Properties properties = (Properties) cachedPropertyFiles.get(propfile); if (properties == null) return ""; synchronized (properties) { StringBuffer buf = new StringBuffer(properties.size() * 50); for (Enumeration e = properties.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); String val = (String) properties.get(key); if (val.length() > 40) { val = val.substring(0, 37) + "..."; } buf.append(key); buf.append('='); buf.append(val); buf.append('\n'); } return buf.toString(); } }