List of usage examples for java.util Properties stringPropertyNames
public Set<String> stringPropertyNames()
From source file:org.sonar.batch.scan.ProjectReactorBuilderTest.java
private Map<String, String> loadProps(String projectFolder) { Map<String, String> props = Maps.<String, String>newHashMap(); Properties runnerProps = toProperties( getResource(this.getClass(), projectFolder + "/sonar-project.properties")); for (final String name : runnerProps.stringPropertyNames()) { props.put(name, runnerProps.getProperty(name)); }//from w w w. j a v a 2s. co m props.put("sonar.projectBaseDir", getResource(this.getClass(), projectFolder).getAbsolutePath()); return props; }
From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceObjectProviderBase.java
/** * Tries to figure out which artifact contains the desired resource, tries to acquire it and * add it to the loader. The dependencyManagement information from the POM of the caller is * taken into account if possible./*from www . j a v a 2s . c o m*/ */ private void resolveDependency(Properties aProps) throws IOException, IllegalStateException { Set<String> names = aProps.stringPropertyNames(); if (names.contains(ARTIFACT_ID) && names.contains(GROUP_ID)) { String artifactId = pph.replacePlaceholders(aProps.getProperty(ARTIFACT_ID), aProps); String groupId = pph.replacePlaceholders(aProps.getProperty(GROUP_ID), aProps); String version = pph.replacePlaceholders(aProps.getProperty(VERSION, ""), aProps); // Try getting better information about the model version. try { version = getModelVersionFromMavenPom(); } catch (IOException e) { // Ignore - this will be tried and reported again later by handleResolvingError } catch (IllegalStateException e) { // Ignore - this will be tried and reported again later by handleResolvingError } // Register files with loader try { List<File> files = resolveWithIvy(groupId, artifactId, version); for (File file : files) { loader.addURL(file.toURI().toURL()); } } catch (ParseException e) { throw new IllegalStateException(e); } } }
From source file:org.geoserver.jdbcconfig.internal.DbMappings.java
/** * @return//from w ww. java 2 s. c o m */ private Multimap<Class<?>, PropertyTypeDef> loadNestedPropertyTypeDefs() { Properties properties = loadTypeDefsFromResource(); Multimap<Class<?>, PropertyTypeDef> byTypePropDefs = ArrayListMultimap.create(); for (String classPropName : properties.stringPropertyNames()) { final String propertyName; final Class<?> objectType; final boolean collectionProperty; final Class<?> targetObjectType; final String targetPropertyName; final Boolean textProperty; { int classNameSeparatorIndex = classPropName.indexOf('.'); String simpleClassName = classPropName.substring(0, classNameSeparatorIndex); objectType = toClass(simpleClassName); propertyName = classPropName.substring(1 + classNameSeparatorIndex); final String propertySpec = properties.getProperty(classPropName); String[] propTarget = propertySpec.split(":"); String targetClassPropName = propTarget.length > 0 ? propTarget[0] : null; if (targetClassPropName.trim().length() == 0) { targetObjectType = null; targetPropertyName = null; } else { classNameSeparatorIndex = targetClassPropName.indexOf('.'); simpleClassName = targetClassPropName.substring(0, classNameSeparatorIndex); targetObjectType = toClass(simpleClassName); targetPropertyName = targetClassPropName.substring(1 + classNameSeparatorIndex); } String colType = propTarget.length > 1 ? propTarget[1] : null; String textType = propTarget.length > 1 ? (propTarget.length > 2 ? propTarget[1] : propTarget[1]) : null; collectionProperty = "list".equalsIgnoreCase(colType) || "set".equalsIgnoreCase(colType); if ("text".equalsIgnoreCase(textType)) { textProperty = Boolean.TRUE; } else { textProperty = null; } } PropertyTypeDef ptd = new PropertyTypeDef(objectType, propertyName, targetObjectType, targetPropertyName, collectionProperty, textProperty); byTypePropDefs.put(objectType, ptd); } return byTypePropDefs; }
From source file:org.kuali.rice.core.impl.config.property.JAXBConfigImpl.java
protected String getPropertyValuesAsString(Properties p) { StringBuilder sb = new StringBuilder(); SortedSet<String> keys = new TreeSet<String>(p.stringPropertyNames()); for (String key : keys) { String rawValue = p.getProperty(key); String logValue = flatten(ConfigLogger.getDisplaySafeValue(key, rawValue)); sb.append(key);/*from w w w. j ava 2 s. c o m*/ sb.append("="); sb.append("["); sb.append(logValue); sb.append("]\n"); } return sb.toString(); }
From source file:org.jahia.configuration.configurators.PropertiesManager.java
/** * Default constructor.//from w ww . j a va 2s .c o m * * @param properties The properties object used to define base properties. */ public PropertiesManager(Properties properties) { this.properties.clear(); for (String propertyName : properties.stringPropertyNames()) { setProperty(propertyName, properties.getProperty(propertyName)); } }
From source file:com.rsmart.kuali.kfs.sys.context.PropertyLoadingFactoryBean.java
/** * Decrypts encrypted values in properties. Interprets that any property in the {@link Properties} instance * provided with a key ending with the {@code ENCRYPTED_PROPERTY_EXTENSION} is considered to be encrypted. * It is then decrypted and replaced with a key of the same name only using the {@code PASSWORD_PROPERTY_EXTENSION} * /*w w w . jav a 2s.c om*/ * @param props the {@link Properties} to decrypt * @throws {@link Exception} if there's any problem decrypting/encrypting properties. */ protected void decryptProps(final Properties props) throws Exception { final String keystore = props.getProperty(KEYSTORE_LOCATION_PROPERTY); final String storepass = props.getProperty(KEYSTORE_PASSWORD_PROPERTY); final FileInputStream fs = new FileInputStream(keystore); final KeyStore jks = KeyStore.getInstance(KEYSTORE_TYPE); jks.load(fs, storepass.toCharArray()); fs.close(); final Cipher cipher = Cipher.getInstance(ENCRYPTION_STRATEGY); cipher.init(Cipher.DECRYPT_MODE, (PrivateKey) jks.getKey(RICE_RSA_KEY_NAME, storepass.toCharArray())); for (final String key : props.stringPropertyNames()) { if (key.endsWith(ENCRYPTED_PROPERTY_EXTENSION)) { final String prefix = key.substring(0, key.indexOf(ENCRYPTED_PROPERTY_EXTENSION)); final String encrypted_str = props.getProperty(key); props.setProperty(prefix + PASSWORD_PROPERTY_EXTENSION, new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(encrypted_str)))); } } }
From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceObjectProviderBase.java
private IOException handleResolvingError(Throwable aCause, String aLocation, Properties aProps) { StringBuilder sb = new StringBuilder(); Set<String> names = aProps.stringPropertyNames(); if (names.contains(ARTIFACT_ID) && names.contains(GROUP_ID)) { String artifactId = pph.replacePlaceholders(aProps.getProperty(ARTIFACT_ID), aProps); String groupId = pph.replacePlaceholders(aProps.getProperty(GROUP_ID), aProps); String version = pph.replacePlaceholders(aProps.getProperty(VERSION, ""), aProps); // Try getting better information about the model version. String extraErrorInfo = ""; try {//from ww w . ja va 2 s . com version = getModelVersionFromMavenPom(); } catch (IOException ex) { extraErrorInfo = ExceptionUtils.getRootCauseMessage(ex); } catch (IllegalStateException ex) { extraErrorInfo = ExceptionUtils.getRootCauseMessage(ex); } // Tell user how to add model dependency sb.append("\nPlease make sure that [").append(artifactId).append(']'); if (StringUtils.isNotBlank(version)) { sb.append(" version [").append(version).append(']'); } sb.append(" is on the classpath.\n"); if (StringUtils.isNotBlank(version)) { sb.append("If the version ").append("shown here is not available, try a recent version.\n"); sb.append('\n'); sb.append("If you are using Maven, add the following dependency to your pom.xml file:\n"); sb.append('\n'); sb.append("<dependency>\n"); sb.append(" <groupId>").append(groupId).append("</groupId>\n"); sb.append(" <artifactId>").append(artifactId).append("</artifactId>\n"); sb.append(" <version>").append(version).append("</version>\n"); sb.append("</dependency>\n"); } else { sb.append("I was unable to determine which version of the desired model is " + "compatible with this component:\n").append(extraErrorInfo).append("\n"); } } if (NOT_REQUIRED.equals(aLocation)) { return new IOException("Unable to load resource: \n" + ExceptionUtils.getRootCauseMessage(aCause) + "\n" + sb.toString()); } else { return new IOException("Unable to load resource [" + aLocation + "]: \n" + ExceptionUtils.getRootCauseMessage(aCause) + "\n" + sb.toString()); } }
From source file:xolpoc.core.ModuleRunner.java
private ModuleDescriptor descriptorFor(String moduleDefinition, Properties options) { String[] tokens = moduleDefinition.split("\\."); Assert.isTrue(tokens.length == 4,/* ww w . j a va 2s .c o m*/ "required module property format: streamname.moduletype.modulename.moduleindex"); String streamName = tokens[0]; ModuleType moduleType = ModuleType.valueOf(tokens[1]); String moduleName = tokens[2]; int moduleIndex = Integer.parseInt(tokens[3]); ModuleDefinition definition = registry.findDefinition(moduleName, moduleType); ModuleDescriptor.Builder builder = new ModuleDescriptor.Builder().setModuleDefinition(definition) .setModuleName(moduleName).setType(moduleType).setGroup(streamName).setIndex(moduleIndex); builder.setSourceChannelName(input); builder.setSinkChannelName(output); for (String key : options.stringPropertyNames()) { builder.setParameter(key, options.getProperty(key)); } return builder.build(); }
From source file:$.PropertyLoadingFactoryBean.java
/** * Decrypts encrypted values in properties. Interprets that any property in the {@link Properties} instance * provided with a key ending with the {@code ENCRYPTED_PROPERTY_EXTENSION} is considered to be encrypted. * It is then decrypted and replaced with a key of the same name only using the {@code PASSWORD_PROPERTY_EXTENSION} * /* w w w .j av a 2 s . com*/ * @param props the {@link Properties} to decrypt * @throws {@link Exception} if there's any problem decrypting/encrypting properties. */ protected void decryptProps(final Properties props) throws Exception { final String keystore = props.getProperty(KEYSTORE_LOCATION_PROPERTY); final String storepass = props.getProperty(KEYSTORE_PASSWORD_PROPERTY); final FileInputStream fs = new FileInputStream(keystore); final KeyStore jks = KeyStore.getInstance(KEYSTORE_TYPE); jks.load(fs, storepass.toCharArray()); fs.close(); final Cipher cipher = Cipher.getInstance(ENCRYPTION_STRATEGY); cipher.init(Cipher.DECRYPT_MODE, (PrivateKey) jks.getKey(RICE_RSA_KEY_NAME, storepass.toCharArray())); for (final String key : props.stringPropertyNames()) { if (key.endsWith(ENCRYPTED_PROPERTY_EXTENSION)) { final String prefix = key.substring(0, key.indexOf(ENCRYPTED_PROPERTY_EXTENSION)); final String encrypted_str = props.getProperty(key); props.setProperty(prefix + PASSWORD_PROPERTY_EXTENSION, new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(encrypted_str)))); } } }
From source file:org.commonjava.maven.ext.cli.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("trace").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(/*from www.j ava 2 s . com*/ 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("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 Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) rootLogger; 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. logger.debug( "Using local repository \n{} and found global settings file in {} with contents \n{} and user settings file in {} with contents \n{}", session.getLocalRepository(), DEFAULT_GLOBAL_SETTINGS_FILE, DEFAULT_GLOBAL_SETTINGS_FILE.exists() ? FileUtils.readFileToString(DEFAULT_GLOBAL_SETTINGS_FILE) : "** File does not exist **", settings, (settings != null && 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(",")); session.getUserProperties().setProperty(PROFILE_SCANNING, "true"); 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")) { Set<ArtifactRef> ts = RESTCollector.establishAllDependencies(session, pomIO.parseProject(session.getPom()), activeProfiles); logger.info("Found {} dependencies. {}", ts.size(), ts); File output = null; if (cmd.hasOption('o')) { output = new File(cmd.getOptionValue('o')); output.delete(); } 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; }