List of usage examples for java.util Properties stringPropertyNames
public Set<String> stringPropertyNames()
From source file:org.commonjava.aprox.core.expire.ScheduleManager.java
@Override public void init() throws AproxLifecycleException { try {/*w w w. j a v a2 s . c o m*/ final Properties props = new Properties(); final Map<String, String> configuration = schedulerConfig.getConfiguration(); if (configuration != null) { props.putAll(configuration); } final StringBuilder sb = new StringBuilder(); for (final String key : props.stringPropertyNames()) { if (sb.length() > 0) { sb.append('\n'); } sb.append(key).append(" = ").append(props.getProperty(key)); } logger.info("Scheduler properties:\n\n{}\n\n", sb); final StdSchedulerFactory fac = new StdSchedulerFactory(props); scheduler = fac.getScheduler(); if (eventDispatcher != null) { scheduler.getListenerManager() .addSchedulerListener(new AproxScheduleListener(scheduler, eventDispatcher)); scheduler.getListenerManager().addTriggerListener(new AproxTriggerListener(eventDispatcher)); } scheduler.start(); } catch (final SchedulerException e) { throw new AproxLifecycleException("Failed to start scheduler", e); } }
From source file:pl.project13.maven.git.GitCommitIdMojoIntegrationTest.java
@Test @Parameters(method = "useNativeGit") public void shouldGenerateCommitIdOldFashioned(boolean useNativeGit) throws Exception { // given/*from w w w . j av a2 s. c om*/ mavenSandbox.withParentProject("my-pom-project", "pom").withChildProject("my-jar-module", "jar") .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY).create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); alterMojoSettings("useNativeGit", useNativeGit); alterMojoSettings("commitIdGenerationMode", "flat"); // when mojo.execute(); // then Properties properties = targetProject.getProperties(); assertThat(properties.stringPropertyNames()).contains("git.commit.id"); assertThat(properties.stringPropertyNames()).excludes("git.commit.id.full"); }
From source file:org.nd4j.linalg.jcublas.context.ContextHolder.java
/** * Configure the given information/*from w w w . j a v a 2 s. com*/ * based on the device */ public void configure() { if (confCalled) return; JCublas2.setExceptionsEnabled(true); JCudaDriver.setExceptionsEnabled(true); JCuda.setExceptionsEnabled(true); if (deviceSetup.get()) return; JCudaDriver.cuInit(0); int count[] = new int[1]; cuDeviceGetCount(count); numDevices = count[0]; log.debug("Found " + numDevices + " gpus"); if (numDevices < 1) numDevices = 1; bannedDevices = new ArrayList<>(); String props = System.getProperty(DEVICES_TO_BAN, "-1"); String[] split = props.split(","); //Should only be used in multi device scenarios; otherwise always use one device if (split.length >= 1) for (String s : split) { Integer i = Integer.parseInt(s); if (i >= 0) bannedDevices.add(Integer.parseInt(s)); } deviceSetup.set(true); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for (int i = 0; i < numDevices; i++) { for (Thread thread : threadSet) getContext(i, thread.getName()); } setContext(); try { KernelFunctionLoader.getInstance().load(); } catch (Exception e) { throw new RuntimeException(e); } // Check if the device supports mapped host memory cudaDeviceProp deviceProperties = new cudaDeviceProp(); JCuda.cudaGetDeviceProperties(deviceProperties, 0); if (deviceProperties.canMapHostMemory == 0) { System.err.println("This device can not map host memory"); System.err.println(deviceProperties.toFormattedString()); return; } //force certain ops to have a certain number of threads Properties threadProps = new Properties(); try { InputStream is = ContextHolder.class.getResourceAsStream("/function_threads.properties"); threadProps.load(is); } catch (IOException e) { e.printStackTrace(); } for (String prop : threadProps.stringPropertyNames()) { threads.put(prop, Integer.parseInt(threadProps.getProperty(prop))); } try { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setJmxEnabled(true); config.setBlockWhenExhausted(false); config.setMaxIdle(Runtime.getRuntime().availableProcessors()); config.setMaxTotal(Runtime.getRuntime().availableProcessors()); config.setMinIdle(Runtime.getRuntime().availableProcessors()); config.setJmxNameBase("handles"); handlePool = new CublasHandlePool(new CublasHandlePooledItemFactory(), config); GenericObjectPoolConfig confClone = config.clone(); confClone.setMaxTotal(Runtime.getRuntime().availableProcessors() * 10); confClone.setMaxIdle(Runtime.getRuntime().availableProcessors() * 10); confClone.setMinIdle(Runtime.getRuntime().availableProcessors() * 10); GenericObjectPoolConfig streamConf = confClone.clone(); streamConf.setJmxNameBase("streams"); streamPool = new StreamPool(new StreamItemFactory(), streamConf); GenericObjectPoolConfig oldStreamConf = streamConf.clone(); oldStreamConf.setJmxNameBase("oldstream"); oldStreamPool = new OldStreamPool(new OldStreamItemFactory(), oldStreamConf); setContext(); //seed with multiple streams to encourage parallelism for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) { streamPool.addObject(); oldStreamPool.addObject(); } //force context initialization to occur JCuda.cudaFree(Pointer.to(new int[] { 0 })); } catch (Exception e) { log.warn("Unable to initialize cuda", e); } for (int i = 0; i < numDevices; i++) { ClassPathResource confFile = new ClassPathResource("devices/" + i, ContextHolder.class.getClassLoader()); if (confFile.exists()) { Properties props2 = new Properties(); try { props2.load(confFile.getInputStream()); confs.put(i, new DeviceConfiguration(i, props2)); } catch (IOException e) { throw new RuntimeException(e); } } else confs.put(i, new DeviceConfiguration(i)); } confCalled = true; }
From source file:org.tros.utils.PropertiesInitializer.java
/** * Initialize from properties file if possible. * * @param dir//w w w. ja v a2 s. co m */ private void initializeFromProperties(String dir) { if (dir == null) { return; } Properties prop = new Properties(); String propFile = dir + '/' + this.getClass().getSimpleName() + ".properties"; File f = new File(propFile); if (f.exists()) { try (FileInputStream fis = new FileInputStream(f)) { PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors(); prop.load(fis); ArrayList<String> propKeys = new ArrayList<>(prop.stringPropertyNames()); for (PropertyDescriptor p : props) { if (p.getWriteMethod() != null && p.getReadMethod() != null && p.getReadMethod().getDeclaringClass() != Object.class) { boolean success = false; String val = prop.getProperty(p.getName()); if (val != null) { Object o = TypeHandler.fromString(p.getPropertyType(), val); if (o == null) { try { o = readValue(val, p.getPropertyType()); } catch (Exception ex) { o = null; LOGGER.warn(null, ex); LOGGER.warn(MessageFormat.format("PropertyName: {0}", new Object[] { val })); } } if (o != null) { p.getWriteMethod().invoke(this, o); success = true; } } if (!success && val != null) { // if (TypeHandler.isEnumeratedType(p)) { //// setEnumerated(p, val); // } else { setValueHelper(p, val); // } } } } for (String key : propKeys) { String value = prop.getProperty(key); setNameValuePair(key, value); } } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException ex) { } catch (IllegalAccessException ex) { LOGGER.debug(null, ex); } catch (IntrospectionException ex) { LOGGER.warn(null, ex); } } }
From source file:org.commonjava.maven.ext.manip.Cli.java
public int run(String[] args) { Options options = new Options(); options.addOption("h", false, "Print this help message."); options.addOption(Option.builder("d").longOpt("debug").desc("Enable debug").build()); options.addOption(Option.builder("t").longOpt("debug").desc("Enable trace").build()); options.addOption(Option.builder("h").longOpt("help").desc("Print help").build()); options.addOption(Option.builder("f").longOpt("file").hasArgs().numberOfArgs(1).desc("POM file").build()); options.addOption(/*w w w .j a va 2 s . c o m*/ Option.builder().longOpt("log-context").desc("Add log-context ID").numberOfArgs(1).build()); options.addOption( Option.builder("l").longOpt("log").desc("Log file to output logging to").numberOfArgs(1).build()); options.addOption(Option.builder("s").longOpt("settings").hasArgs().numberOfArgs(1) .desc("Optional settings.xml file").build()); options.addOption(Option.builder("P").longOpt("activeProfiles") .desc("Comma separated list of active profiles.").numberOfArgs(1).build()); options.addOption(Option.builder("o").longOpt("outputFile") .desc("outputFile to output dependencies to. Only used with '-p' (Print all project dependencies)") .numberOfArgs(1).build()); options.addOption(Option.builder("p").longOpt("printDeps").desc("Print all project dependencies").build()); options.addOption(Option.builder().longOpt("printGAVTC").desc( "Print all project dependencies in group:artifact:version:type:classifier with scope information") .build()); options.addOption(Option.builder().longOpt("printUnusedDepMgmt") .desc("Print unused managed dependencies in group:artifact:version format").build()); options.addOption( Option.builder("D").hasArgs().numberOfArgs(2).valueSeparator('=').desc("Java Properties").build()); options.addOption( Option.builder("x").hasArgs().numberOfArgs(2).desc("XPath tester ( file : xpath )").build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { logger.debug("Caught problem parsing ", e); System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("...", options); return 10; } if (cmd.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("...", options); System.exit(0); } if (cmd.hasOption('D')) { userProps = cmd.getOptionProperties("D"); } if (cmd.hasOption('f')) { target = new File(cmd.getOptionValue('f')); } if (cmd.hasOption('s')) { settings = new File(cmd.getOptionValue('s')); } if (cmd.hasOption("log-context")) { String mdc = cmd.getOptionValue("log-context"); if (isNotEmpty(mdc)) { // Append a space to split up level and log-context markers. MDC.put("LOG-CONTEXT", mdc + ' '); } } createSession(target, settings); final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); if (cmd.hasOption('l')) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); PatternLayoutEncoder ple = new PatternLayoutEncoder(); ple.setPattern("%mdc{LOG-CONTEXT}%level %logger{36} %msg%n"); ple.setContext(loggerContext); ple.start(); FileAppender<ILoggingEvent> fileAppender = new FileAppender<>(); fileAppender.setEncoder(ple); fileAppender.setContext(loggerContext); fileAppender.setName("fileLogging"); fileAppender.setAppend(false); fileAppender.setFile(cmd.getOptionValue("l")); fileAppender.start(); root.addAppender(fileAppender); root.setLevel(Level.INFO); } // Set debug logging after session creation else we get the log filled with Plexus // creation stuff. if (cmd.hasOption('d')) { root.setLevel(Level.DEBUG); } if (cmd.hasOption('t')) { root.setLevel(Level.TRACE); } if (!session.isEnabled()) { logger.info("Manipulation engine disabled via command-line option"); return 0; } if (!target.exists()) { logger.info("Manipulation engine disabled. Project {} cannot be found.", target); return 10; } // Don't bother skipping if we're just trying to analyse deps. else if (new File(target.getParentFile(), ManipulationManager.MARKER_FILE).exists() && !cmd.hasOption('p')) { logger.info("Skipping manipulation as previous execution found."); return 0; } try { Properties config = new ConfigIO().parse(target.getParentFile()); String value = session.getUserProperties().getProperty("allowConfigFilePrecedence"); if (isNotEmpty(value) && "true".equalsIgnoreCase(value)) { session.getUserProperties().putAll(config); } else { for (String key : config.stringPropertyNames()) { if (!session.getUserProperties().containsKey(key)) { session.getUserProperties().setProperty(key, config.getProperty(key)); } } } } catch (ManipulationException e) { logger.error("POM Manipulation failed: Unable to read config file ", e); return 10; } try { // Note : don't print out settings information earlier (like when we actually read it) as the logging // isn't setup then. if (settings != null) { logger.debug("Found settings file {} with contents \n{}", settings, settings.exists() ? FileUtils.readFileToString(settings) : "** File does not exist **"); } manipulationManager.init(session); Set<String> activeProfiles = null; if (cmd.hasOption('P')) { activeProfiles = new HashSet<>(); Collections.addAll(activeProfiles, cmd.getOptionValue('P').trim().split(",")); if (session.getActiveProfiles() != null) { session.getActiveProfiles().addAll(activeProfiles); } } if (cmd.hasOption('x')) { String[] params = cmd.getOptionValues('x'); if (params.length != 2) { throw new ManipulationException( "Invalid number of parameters (" + params.length + "); should be <file> <xpath>"); } XMLIO xmlIO = new XMLIO(); Document doc = xmlIO.parseXML(new File(params[0])); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate(params[1], doc, XPathConstants.NODESET); logger.info("Found {} node", nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); logger.info("Found node {} and value {} ", node.getNodeName(), node.getTextContent()); } } else if (cmd.hasOption('p') || cmd.hasOption("printGAVTC") || cmd.hasOption("printUnusedDepMgmt")) { Set<ArtifactRef> ts = RESTManipulator.establishAllDependencies(pomIO.parseProject(session.getPom()), activeProfiles); logger.info("Found {} dependencies.", ts.size()); File output = null; if (cmd.hasOption('o')) { output = new File(cmd.getOptionValue('o')); output.delete(); } if (cmd.hasOption("printUnusedDepMgmt")) { Set<ArtifactRef> nonMangedDeps = RESTManipulator .establishNonManagedDependencies(pomIO.parseProject(session.getPom()), activeProfiles); logger.info("Found {} non-managed dependencies.", nonMangedDeps.size()); // As the managed dependencies may have versions versus the non-managed strip off the versions to see what is left. Set<ProjectRef> tsNoV = new TreeSet<>(); for (ArtifactRef ar : ts) { tsNoV.add(ar.asProjectRef()); } Set<ProjectRef> nonManagedNoV = new TreeSet<>(); for (ArtifactRef ar : nonMangedDeps) { nonManagedNoV.add(ar.asProjectRef()); } tsNoV.removeAll(nonManagedNoV); for (ProjectRef pr : tsNoV) { if (cmd.hasOption('o')) { FileUtils.writeStringToFile(output, pr.toString(), true); } else { System.out.println(pr.toString()); } } } else { for (ArtifactRef a : ts) { String scope = null; if (a instanceof SimpleScopedArtifactRef) { scope = ((SimpleScopedArtifactRef) a).getScope(); } if (cmd.hasOption('o')) { if (cmd.hasOption("printGAVTC")) { FileUtils.writeStringToFile(output, String.format("%-80s%10s\n", a, scope), true); } else { FileUtils.writeStringToFile(output, a.asProjectVersionRef().toString() + '\n', true); } } else { if (cmd.hasOption("printGAVTC")) { System.out.format("%-80s%10s\n", a, scope); } else { System.out.println(a.asProjectVersionRef()); } } } } } else { manipulationManager.scanAndApply(session); } } catch (ManipulationException e) { logger.error("POM Manipulation failed; original error is {}", e.getMessage()); logger.debug("POM Manipulation error trace is", e); return 10; } catch (RestException e) { logger.error("REST communication with {} failed. {}", userProps.getProperty("restURL"), e.getMessage()); logger.trace("Exception trace is", e); return 100; } catch (Exception e) { logger.error("POM Manipulation failed.", e); return 100; } return 0; }
From source file:pl.project13.maven.git.GitCommitIdMojoIntegrationTest.java
@Test @Parameters(method = "useNativeGit") public void shouldUseDateFormatTimeZone(boolean useNativeGit) throws Exception { // given//from www . j av a 2 s . com mavenSandbox.withParentProject("my-pom-project", "pom").withChildProject("my-jar-module", "jar") .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY).create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); // RFC 822 time zone: Sign TwoDigitHours Minutes String dateFormat = "Z"; // we want only the timezone (formated in RFC 822) out of the dateformat (easier for asserts) String expectedTimeZoneOffset = "+0200"; String executionTimeZoneOffset = "-0800"; TimeZone expectedTimeZone = TimeZone.getTimeZone("GMT" + expectedTimeZoneOffset); TimeZone executionTimeZone = TimeZone.getTimeZone("GMT" + executionTimeZoneOffset); GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); alterMojoSettings("gitDescribe", gitDescribeConfig); alterMojoSettings("useNativeGit", useNativeGit); alterMojoSettings("dateFormat", dateFormat); alterMojoSettings("dateFormatTimeZone", expectedTimeZone.getID()); // override the default timezone for execution and testing TimeZone currentDefaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(executionTimeZone); // when mojo.execute(); // then Properties properties = targetProject.getProperties(); assertThat(properties.stringPropertyNames()).contains("git.commit.time"); assertThat(properties.getProperty("git.commit.time")).isEqualTo(expectedTimeZoneOffset); assertThat(properties.stringPropertyNames()).contains("git.build.time"); assertThat(properties.getProperty("git.build.time")).isEqualTo(expectedTimeZoneOffset); // set the timezone back TimeZone.setDefault(currentDefaultTimeZone); }
From source file:org.opencastproject.capture.impl.ConfigurationManagerTest.java
@Test public void testUpdate() throws IOException, ConfigurationException { Properties sourceProps = new Properties(); InputStream is = getClass().getClassLoader().getResourceAsStream("config/capture.properties"); if (is == null) { Assert.fail();/*from w ww . j a v a2s . c om*/ } sourceProps.load(is); IOUtils.closeQuietly(is); configManager.setItem("org.opencastproject.storage.dir", new File("./target", "configman-test").getAbsolutePath()); configManager.setItem("org.opencastproject.server.url", "http://localhost:8080"); configManager.updated(sourceProps); Properties configProps = configManager.getAllProperties(); for (Object key : sourceProps.stringPropertyNames()) { if (!configProps.containsKey(key)) { Assert.fail(); } } }
From source file:dinistiq.Dinistiq.java
/** * Fill bean as a map./* w w w. ja v a 2s. c o m*/ * Replaces object references but does not split compound values like sets or lists. * * @param bean must be of type Map<Object, Object> * @param mapProperties properties map with the values to be added to the map bean */ @SuppressWarnings("unchecked") private void fillMap(Object bean, Properties mapProperties) { Map<Object, Object> map = (Map<Object, Object>) bean; for (String name : mapProperties.stringPropertyNames()) { map.put(name, getReferenceValue(mapProperties.getProperty(name))); } // while }
From source file:org.kairosdb.core.Main.java
public Main(File propertiesFile) throws IOException { Properties props = new Properties(); InputStream is = getClass().getClassLoader().getResourceAsStream("kairosdb.properties"); props.load(is);// w w w . j ava 2s . c om is.close(); if (propertiesFile != null) { FileInputStream fis = new FileInputStream(propertiesFile); props.load(fis); fis.close(); loadPlugins(props, propertiesFile); } List<Module> moduleList = new ArrayList<Module>(); moduleList.add(new CoreModule(props)); for (String propName : props.stringPropertyNames()) { if (propName.startsWith(SERVICE_PREFIX)) { Class<?> aClass; try { if ("".equals(props.getProperty(propName))) continue; aClass = Class.forName(props.getProperty(propName)); if (Module.class.isAssignableFrom(aClass)) { Constructor<?> constructor = null; try { constructor = aClass.getConstructor(Properties.class); } catch (NoSuchMethodException ignore) { } /* Check if they have a constructor that takes the properties if not construct using the default constructor */ Module mod; if (constructor != null) mod = (Module) constructor.newInstance(props); else mod = (Module) aClass.newInstance(); moduleList.add(mod); } } catch (Exception e) { logger.error("Unable to load service " + propName, e); } } } m_injector = Guice.createInjector(moduleList); }
From source file:org.tolven.assembler.jboss6.JBoss6Assembler.java
private void assembleJNDI(Properties srcProperties) { JndiManager jndiManager = JndiManagerFactory.getInstance(); Properties jndiProperties = jndiManager.getJndiProperties(srcProperties); File stageAppServerDir = new File(getStageDir(), getAppServerDirname()); String relativeConfigExtDirPath = getDescriptor().getAttribute(ATTR_STAGE_DEPLOY_DIR).getValue(); File destDir = new File(stageAppServerDir, "/" + relativeConfigExtDirPath); File dest = new File(destDir, "tolven-jndi-service.xml"); StringBuffer buff = new StringBuffer(); try {//ww w . ja v a2 s. c o m buff.append(FileUtils.readFileToString(getFilePath("tolven-jndi-service-prefix.txt"))); List<String> keys = new ArrayList<String>(jndiProperties.stringPropertyNames()); Collections.sort(keys); for (String key : keys) { String value = xmlEscape(jndiProperties.getProperty(key)); if (value == null) { throw new RuntimeException("null value for JNDI property: " + key); } buff.append("\n" + TABS + "<tolven:property>"); buff.append("\n" + TABS + "\t<tolven:key>" + key + "</tolven:key>"); buff.append("\n" + TABS + "\t<tolven:value>" + value + "</tolven:value>"); buff.append("\n" + TABS + "</tolven:property>"); } buff.append("\n"); buff.append(FileUtils.readFileToString(getFilePath("tolven-jndi-service-suffix.txt"))); String substitutedString = substitute(buff.toString(), srcProperties); if (substitutedString.indexOf("${") != -1) { int index = substitutedString.indexOf("${"); String s = substitutedString.substring(index); throw new RuntimeException("Missing JNDI substitution: ${" + s.substring(0, s.indexOf("}")) + "}"); } FileUtils.writeStringToFile(dest, substitutedString); } catch (Exception ex) { throw new RuntimeException("Could not create " + dest.getPath(), ex); } }