List of usage examples for java.util Properties stringPropertyNames
public Set<String> stringPropertyNames()
From source file:edu.snu.leader.spatial.observer.ResultsReporterSimObserver.java
/** * Initializes this observer/*from ww w .j ava 2 s. c om*/ * * @param simState The simulation state * @param keyPrefix Prefix for configuration property keys * @see edu.snu.leader.spatial.observer.AbstractSimObserver#initialize(edu.snu.leader.spatial.SimulationState, java.lang.String) */ @Override public void initialize(SimulationState simState, String keyPrefix) { _LOG.trace("Entering initialize( simState, keyPrefix )"); // Call the superclass implementation super.initialize(simState, keyPrefix); // Grab the properties Properties props = simState.getProperties(); // Load the results filename String resultsFile = props.getProperty(_RESULTS_FILE_KEY); Validate.notEmpty(resultsFile, "Results file may not be empty"); _LOG.info("Sending results to [" + resultsFile + "]"); // Create the statistics writer try { _writer = new PrintWriter(new BufferedWriter(new FileWriter(resultsFile))); } catch (IOException ioe) { _LOG.error("Unable to open results file [" + resultsFile + "]", ioe); throw new RuntimeException("Unable to open results file [" + resultsFile + "]", ioe); } // Log the system properties to the stats file for future reference _writer.println("# Started: " + (new Date())); _writer.println(_SPACER); _writer.println("# Simulation properties"); _writer.println(_SPACER); List<String> keyList = new ArrayList<String>(props.stringPropertyNames()); Collections.sort(keyList); Iterator<String> iter = keyList.iterator(); while (iter.hasNext()) { String key = iter.next(); String value = props.getProperty(key); _writer.println("# " + key + " = " + value); } _writer.println(_SPACER); _writer.println(); _writer.flush(); _LOG.trace("Leaving initialize( simState, keyPrefix )"); }
From source file:org.apache.tomee.embedded.Container.java
public void start() throws Exception { if (base == null || !base.exists()) { setup(configuration);//from www . j ava 2 s. c om } final Properties props = configuration.getProperties(); if (props != null) { StrSubstitutor substitutor = null; for (final String s : props.stringPropertyNames()) { final String v = props.getProperty(s); if (v != null && v.contains("${")) { if (substitutor == null) { final Map<String, String> placeHolders = new HashMap<>(); placeHolders.put("tomee.embedded.http", Integer.toString(configuration.getHttpPort())); placeHolders.put("tomee.embedded.https", Integer.toString(configuration.getHttpsPort())); placeHolders.put("tomee.embedded.stop", Integer.toString(configuration.getStopPort())); substitutor = new StrSubstitutor(placeHolders); } props.put(s, substitutor.replace(v)); } } // inherit from system props final Properties properties = new Properties(System.getProperties()); properties.putAll(configuration.getProperties()); Logger.configure(properties); } else { Logger.configure(); } final File conf = new File(base, "conf"); final File webapps = new File(base, "webapps"); final String catalinaBase = base.getAbsolutePath(); // set the env before calling anoything on tomcat or Catalina!! System.setProperty("catalina.base", catalinaBase); System.setProperty("openejb.deployments.classpath", "false"); System.setProperty("catalina.home", catalinaBase); System.setProperty("catalina.base", catalinaBase); System.setProperty("openejb.home", catalinaBase); System.setProperty("openejb.base", catalinaBase); System.setProperty("openejb.servicemanager.enabled", "false"); copyFileTo(conf, "catalina.policy"); copyTemplateTo(conf, "catalina.properties"); copyFileTo(conf, "context.xml"); copyFileTo(conf, "openejb.xml"); copyFileTo(conf, "tomcat-users.xml"); copyFileTo(conf, "web.xml"); final boolean initialized; if (configuration.hasServerXml()) { final File file = new File(conf, "server.xml"); final FileOutputStream fos = new FileOutputStream(file); try { IO.copy(configuration.getServerXmlFile(), fos); } finally { IO.close(fos); } // respect config (host/port) of the Configuration final QuickServerXmlParser ports = QuickServerXmlParser.parse(file); if (configuration.isKeepServerXmlAsThis()) { // force ports to be able to stop the server and get @ArquillianResource configuration.setHttpPort(Integer.parseInt(ports.http())); configuration.setStopPort(Integer.parseInt(ports.stop())); } else { final Map<String, String> replacements = new HashMap<String, String>(); replacements.put(ports.http(), String.valueOf(configuration.getHttpPort())); replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort())); replacements.put(ports.stop(), String.valueOf(configuration.getStopPort())); IO.copy(IO.slurp(new ReplaceStringsInputStream(IO.read(file), replacements)).getBytes(), file); } tomcat.server(createServer(file.getAbsolutePath())); initialized = true; } else { copyFileTo(conf, "server.xml"); initialized = false; } if (props != null && !props.isEmpty()) { final FileWriter systemProperties = new FileWriter(new File(conf, "system.properties")); try { props.store(systemProperties, ""); } finally { IO.close(systemProperties); } } // Need to use JULI so log messages from the tests are visible // using openejb logging conf in embedded mode /* if we use our config (Logger.configure()) don't override it copyFileTo(conf, "logging.properties"); System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager"); final File logging = new File(conf, "logging.properties"); if (logging.exists()) { System.setProperty("java.util.logging.config.file", logging.getAbsolutePath()); } */ // Trigger loading of catalina.properties CatalinaProperties.getProperty("foo"); tomcat.setBaseDir(base.getAbsolutePath()); tomcat.setHostname(configuration.getHost()); if (!initialized) { tomcat.getHost().setAppBase(webapps.getAbsolutePath()); tomcat.getEngine().setDefaultHost(configuration.getHost()); tomcat.setHostname(configuration.getHost()); } if (configuration.getRealm() != null) { tomcat.getEngine().setRealm(configuration.getRealm()); } if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) { final Connector connector = new Connector(Http11Protocol.class.getName()); connector.setPort(configuration.getHttpPort()); connector.setAttribute("connectionTimeout", "3000"); tomcat.getService().addConnector(connector); tomcat.setConnector(connector); } // create https connector if (configuration.isSsl()) { final Connector httpsConnector = new Connector(Http11Protocol.class.getName()); httpsConnector.setPort(configuration.getHttpsPort()); httpsConnector.setSecure(true); httpsConnector.setProperty("SSLEnabled", "true"); httpsConnector.setProperty("sslProtocol", configuration.getSslProtocol()); if (configuration.getKeystoreFile() != null) { httpsConnector.setAttribute("keystoreFile", configuration.getKeystoreFile()); } if (configuration.getKeystorePass() != null) { httpsConnector.setAttribute("keystorePass", configuration.getKeystorePass()); } httpsConnector.setAttribute("keystoreType", configuration.getKeystoreType()); httpsConnector.setAttribute("clientAuth", configuration.getClientAuth()); httpsConnector.setAttribute("keyAlias", configuration.getKeyAlias()); tomcat.getService().addConnector(httpsConnector); if (configuration.isSkipHttp()) { tomcat.setConnector(httpsConnector); } } // Bootstrap Tomcat Logger.getInstance(LogCategory.OPENEJB_STARTUP, Container.class) .info("Starting TomEE from: " + base.getAbsolutePath()); // create it after Logger is configured if (configuration.getUsers() != null) { for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) { tomcat.addUser(user.getKey(), user.getValue()); } } if (configuration.getRoles() != null) { for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) { for (final String role : user.getValue().split(" *, *")) { tomcat.addRole(user.getKey(), role); } } } if (!initialized) { tomcat.init(); } tomcat.start(); // Bootstrap OpenEJB final Properties properties = new Properties(); properties.setProperty("openejb.deployments.classpath", "false"); properties.setProperty("openejb.loader", "tomcat-system"); properties.setProperty("openejb.home", catalinaBase); properties.setProperty("openejb.base", catalinaBase); properties.setProperty("openejb.servicemanager.enabled", "false"); if (configuration.getProperties() != null) { properties.putAll(configuration.getProperties()); } if (properties.getProperty("openejb.system.apps") == null) { // will make startup faster and it is rarely useful for embedded case properties.setProperty("openejb.system.apps", "false"); } if (configuration.isQuickSession()) { properties.put("openejb.session.manager", QuickSessionManager.class.getName()); } try { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final Properties tomcatServerInfo = IO.readProperties( classLoader.getResourceAsStream("org/apache/catalina/util/ServerInfo.properties"), new Properties()); String serverNumber = tomcatServerInfo.getProperty("server.number"); if (serverNumber == null) { // Tomcat5 only has server.info final String serverInfo = tomcatServerInfo.getProperty("server.info"); if (serverInfo != null) { final int slash = serverInfo.indexOf('/'); serverNumber = serverInfo.substring(slash + 1); } } if (serverNumber != null) { System.setProperty("tomcat.version", serverNumber); } final String serverBuilt = tomcatServerInfo.getProperty("server.built"); if (serverBuilt != null) { System.setProperty("tomcat.built", serverBuilt); } } catch (final Throwable e) { // no-op } final TomcatLoader loader = new TomcatLoader(); loader.initDefaults(properties); // need to add properties after having initialized defaults // to properties passed to SystemInstance otherwise we loose some of them final Properties initProps = new Properties(); initProps.putAll(System.getProperties()); initProps.putAll(properties); if (SystemInstance.isInitialized()) { SystemInstance.get().getProperties().putAll(initProps); } else { SystemInstance.init(initProps); } SystemInstance.get().setComponent(StandardServer.class, (StandardServer) tomcat.getServer()); SystemInstance.get().setComponent(Server.class, tomcat.getServer()); // needed again cause of init() loader.initialize(properties); assembler = SystemInstance.get().getComponent(Assembler.class); configurationFactory = new ConfigurationFactory(); if (configuration.isWithEjbRemote()) { tomcat.getHost().addChild(new TomEERemoteWebapp()); } }
From source file:com.netflix.exhibitor.standalone.ExhibitorCreator.java
private void addInitialConfigFile(CommandLine commandLine, Properties properties) throws IOException { Properties defaultProperties = new Properties(); String defaultConfigFile = commandLine.getOptionValue(INITIAL_CONFIG_FILE); if (defaultConfigFile == null) { return;/*from w w w. j av a 2 s . c o m*/ } InputStream in = new BufferedInputStream(new FileInputStream(defaultConfigFile)); try { defaultProperties.load(in); } finally { Closeables.closeQuietly(in); } Set<String> propertyNames = Sets.newHashSet(); for (StringConfigs config : StringConfigs.values()) { propertyNames.add(PropertyBasedInstanceConfig.toName(config, "")); } for (IntConfigs config : IntConfigs.values()) { propertyNames.add(PropertyBasedInstanceConfig.toName(config, "")); } for (String name : defaultProperties.stringPropertyNames()) { if (propertyNames.contains(name)) { String value = defaultProperties.getProperty(name); properties.setProperty(PropertyBasedInstanceConfig.ROOT_PROPERTY_PREFIX + name, value); } else { log.warn("Ignoring unknown config: " + name); } } }
From source file:org.apache.hadoop.hbase.util.LoadTestTool.java
private void addAuthInfoToConf(Properties authConfig, Configuration conf, String owner, String userList) throws IOException { List<String> users = Arrays.asList(userList.split(",")); users.add(owner);//from w w w.ja v a 2 s . com for (String user : users) { String keyTabFileConfKey = "hbase." + user + ".keytab.file"; String principalConfKey = "hbase." + user + ".kerberos.principal"; if (!authConfig.containsKey(keyTabFileConfKey) || !authConfig.containsKey(principalConfKey)) { throw new IOException("Authentication configs missing for user : " + user); } } for (String key : authConfig.stringPropertyNames()) { conf.set(key, authConfig.getProperty(key)); } LOG.debug("Added authentication properties to config successfully."); }
From source file:org.voyanttools.trombone.input.extract.XmlExtractor.java
@Override public InputSource getExtractableInputSource(StoredDocumentSource storedDocumentSource) throws IOException { // no format specified, so let's have a peek at the contents to see if we can determine a sub-format DocumentFormat guessedFormat = DocumentFormat.UNKNOWN; if (parameters.getParameterValue("inputFormat", "").isEmpty()) { InputStream is = null;// ww w. java 2 s . c o m try { is = storedDocumentSourceStorage.getStoredDocumentSourceInputStream(storedDocumentSource.getId()); XmlRootExtractor xmlRootExtractor = new XmlRootExtractor(); QName qname = xmlRootExtractor.extractRootElement(is); String name = qname.getLocalPart(); if (name.equals("feed") && qname.getNamespaceURI().toLowerCase().contains("atom")) guessedFormat = DocumentFormat.ATOM; else if (name.equals("TEI")) guessedFormat = DocumentFormat.TEI; else if (name.equals("teiCorpus")) guessedFormat = DocumentFormat.TEICORPUS; else if (name.equals("rss")) guessedFormat = DocumentFormat.RSS; else if (name.equals("EEBO")) guessedFormat = DocumentFormat.EEBODREAM; } finally { if (is != null) is.close(); } } if (parameters.getParameterValue("inputFormat", "").isEmpty() == false || guessedFormat != DocumentFormat.UNKNOWN) { if (guessedFormat == DocumentFormat.UNKNOWN) { guessedFormat = DocumentFormat .valueOf(parameters.getParameterValue("inputFormat", "").toUpperCase()); } Properties properties = new Properties(); String resourcePath = "/org/voyanttools/trombone/input-formats/" + guessedFormat.name().toLowerCase() + ".xml"; URL url = this.getClass().getResource(resourcePath); if (url != null) { File file = new File(url.getPath()); if (file.exists()) { FileInputStream in = null; try { in = new FileInputStream(file); properties.loadFromXML(in); } finally { if (in != null) { in.close(); } } } if (parameters.getParameterBooleanValue("splitDocuments")) { for (String key : properties.stringPropertyNames()) { if (key.contains(".splitDocuments")) { parameters.setParameter(key.split("\\.")[0], properties.getProperty(key)); // overwrite prefix key } } } for (String key : properties.stringPropertyNames()) { if (parameters.getParameterValue(key, "").isEmpty() == true) { parameters.setParameter(key, properties.getProperty(key)); } } } } String[] relevantParameters = new String[] { "xmlContentXpath", "xmlTitleXpath", "xmlAuthorXpath", "xmlPubPlaceXpath", "xmlPublisherXpath", "xmlPubDateXpath", "xmlExtraMetadataXpath" }; StringBuilder parametersBuilder = new StringBuilder(); for (String p : relevantParameters) { if (parameters.getParameterValue(p, "").isEmpty() == false) { parametersBuilder.append(p); for (String s : parameters.getParameterValues(p)) { parametersBuilder.append(s); } } } /* This was skipped, but we probably need to extract anyway to strip XML comments, detect language, etc. * // no special parameters and nothing to extract from XML, so just return the original stored document if (parametersBuilder.length()==0) { return new StoredDocumentSourceInputSource(storedDocumentSourceStorage, storedDocumentSource); } */ return new ExtractableXmlInputSource( DigestUtils.md5Hex( storedDocumentSource.getId() + relevantParameters + String.valueOf(serialVersionUID)), storedDocumentSource); }
From source file:org.pentaho.platform.repository2.unified.jcr.JcrRepositoryFileUtils.java
public static Node updateFileLocaleProperties(final Session session, final Serializable fileId, String locale, Properties properties) throws RepositoryException { PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session); Node fileNode = session.getNodeByIdentifier(fileId.toString()); String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS); Assert.hasText(prefix);//from w ww .j av a 2s. c o m Node localesNode = null; if (!fileNode.hasNode(pentahoJcrConstants.getPHO_LOCALES())) { // Auto-create pho:locales node if doesn't exist localesNode = fileNode.addNode(pentahoJcrConstants.getPHO_LOCALES(), pentahoJcrConstants.getPHO_NT_LOCALE()); } else { localesNode = fileNode.getNode(pentahoJcrConstants.getPHO_LOCALES()); } try { Node localeNode = NodeHelper.checkGetNode(localesNode, locale); for (String propertyName : properties.stringPropertyNames()) { localeNode.setProperty(propertyName, properties.getProperty(propertyName)); } } catch (PathNotFoundException pnfe) { // locale doesn't exist, create a new locale node Map<String, Properties> propertiesMap = new HashMap<String, Properties>(); propertiesMap.put(locale, properties); setLocalePropertiesMap(session, pentahoJcrConstants, localesNode, propertiesMap); } return fileNode; }
From source file:com.thinkbiganalytics.feedmgr.rest.controller.FeedsController.java
private Map<String, Object> updateProperties(final Properties props, com.thinkbiganalytics.metadata.api.feed.Feed domain, boolean replace) { return metadata.commit(() -> { Map<String, Object> newProperties = new HashMap<String, Object>(); for (String name : props.stringPropertyNames()) { newProperties.put(name, props.getProperty(name)); }/*from w ww. j a va2s. c om*/ if (replace) { feedProvider.replaceProperties(domain.getId(), newProperties); } else { feedProvider.mergeFeedProperties(domain.getId(), newProperties); } return domain.getProperties(); }); }
From source file:org.apache.geode.management.internal.cli.commands.GfshCommandJUnitTest.java
@Test public void testAddGemFireSystemPropertiesToCommandLineWithRestAPI() { final List<String> commandLine = new ArrayList<>(); assertTrue(commandLine.isEmpty());//from w ww .j a va 2s.co m StartMemberUtils.addGemFireSystemProperties(commandLine, new Properties()); assertTrue(commandLine.isEmpty()); final Properties gemfireProperties = new Properties(); gemfireProperties.setProperty(LOCATORS, "localhost[11235]"); gemfireProperties.setProperty(LOG_LEVEL, "config"); gemfireProperties.setProperty(LOG_FILE, StringUtils.EMPTY); gemfireProperties.setProperty(MCAST_PORT, "0"); gemfireProperties.setProperty(NAME, "machine"); gemfireProperties.setProperty(START_DEV_REST_API, "true"); gemfireProperties.setProperty(HTTP_SERVICE_PORT, "8080"); gemfireProperties.setProperty(HTTP_SERVICE_BIND_ADDRESS, "localhost"); StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties); assertFalse(commandLine.isEmpty()); assertEquals(7, commandLine.size()); for (final String propertyName : gemfireProperties.stringPropertyNames()) { final String propertyValue = gemfireProperties.getProperty(propertyName); if (StringUtils.isBlank(propertyValue)) { for (final String systemProperty : commandLine) { assertFalse(systemProperty.startsWith( "-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("="))); } } else { assertTrue(commandLine.contains("-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("=").concat(propertyValue))); } } }
From source file:org.dasein.cloud.ibm.sce.compute.vm.SCEVirtualMachine.java
@Override public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException { Logger logger = SCE.getLogger(SCEVirtualMachine.class, "launch"); ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new SCEConfigException("No context was configured for this request"); }// w w w . j ava 2 s. c o m ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(); String keypair = withLaunchOptions.getBootstrapKey(); String password = null; parameters.add(new BasicNameValuePair("name", withLaunchOptions.getHostName())); parameters.add(new BasicNameValuePair("instanceType", withLaunchOptions.getStandardProductId())); parameters.add(new BasicNameValuePair("imageID", withLaunchOptions.getMachineImageId())); parameters.add(new BasicNameValuePair("location", ctx.getRegionId())); MachineImage launchImage = provider.getComputeServices().getImageSupport() .getImage(withLaunchOptions.getMachineImageId()); if (launchImage.getPlatform().isUnix()) { if (keypair == null) { keypair = identifyKeypair(); } parameters.add(new BasicNameValuePair("publicKey", keypair)); } else if (launchImage.getPlatform().isWindows()) { if (withLaunchOptions.getBootstrapUser() != null) { logger.debug("Adding UserName parameter: " + withLaunchOptions.getBootstrapUser()); parameters.add(new BasicNameValuePair("UserName", withLaunchOptions.getBootstrapUser())); } password = getRandomPassword(withLaunchOptions.getBootstrapUser()); parameters.add(new BasicNameValuePair("Password", password)); } if (withLaunchOptions.getVlanId() != null) { logger.debug("Adding vlanID parameter: " + withLaunchOptions.getVlanId()); parameters.add(new BasicNameValuePair("vlanID", withLaunchOptions.getVlanId())); } String[] ips = withLaunchOptions.getStaticIpIds(); if (ips.length > 0) { parameters.add(new BasicNameValuePair("ip", ips[0])); if (ips.length > 1) { for (int i = 1; i < ips.length; i++) { if (i > 3) { logger.warn( "Attempt to assign more than 3 secondary IPs to a VM in IBM SmartCloud for account " + ctx.getAccountNumber()); break; } parameters.add(new BasicNameValuePair("SecondaryIP", ips[i])); } } } String userData = withLaunchOptions.getUserData(); if (userData != null) { Properties p = new Properties(); try { p.load(new ByteArrayInputStream(userData.getBytes("utf-8"))); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } catch (IOException e) { throw new InternalException(e); } for (String key : p.stringPropertyNames()) { String value = p.getProperty(key); if (value != null) { parameters.add(new BasicNameValuePair(key, value)); } } } SCEMethod method = new SCEMethod(provider); String response = method.post("instances", parameters); if (response == null) { throw new CloudException("Cloud accepted the post, but no body was in the response"); } Document doc = method.parseResponse(response, true); NodeList locations = doc.getElementsByTagName("Instance"); for (int i = 0; i < locations.getLength(); i++) { Node item = locations.item(i); VirtualMachine vm = toVirtualMachine(ctx, item); if (vm != null) { vm.setRootPassword(password); vm.setRootUser(withLaunchOptions.getBootstrapUser()); return vm; } } throw new CloudException("No instance was in the XML response"); }
From source file:au.org.ala.biocache.web.OccurrenceController.java
/** * Custom handler for the welcome view./*w ww .j av a 2 s . com*/ * <p> * Note that this handler relies on the RequestToViewNameTranslator to * determine the logical view name based on the request URL: "/welcome.do" * -> "welcome". * * @return viewname to render */ @RequestMapping("/") public String homePageHandler(Model model) { model.addAttribute("webservicesRoot", hostUrl); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("/git.properties"); if (input != null) { try { Properties versionProperties = new Properties(); versionProperties.load(input); model.addAttribute("versionInfo", versionProperties); StringBuffer sb = new StringBuffer(); for (String name : versionProperties.stringPropertyNames()) { sb.append(name + " : " + versionProperties.getProperty(name) + "\n"); } model.addAttribute("versionInfoString", sb.toString()); } catch (Exception e) { logger.error(e.getMessage(), e); } } return HOME; }