Java Code Examples for java.util.Properties.stringPropertyNames()

The following are Jave code examples for showing how to use stringPropertyNames() of the java.util.Properties class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jdk8u-jdk   File: CompatibilityTest.java   View Source Code Vote up 6 votes
static void verifyProperites(Properties prop) {
    try {
        for (String key : prop.stringPropertyNames()) {
            String val = prop.getProperty(key);
            if (key.equals("Key1")) {
                if (!val.equals("value1")) {
                    fail("Key:" + key + "'s value: \nExpected: value1\nFound: " + val);
                }
            } else if (key.equals("Key2")) {
                if (!val.equals("<value2>")) {
                    fail("Key:" + key + "'s value: \nExpected: <value2>\nFound: " + val);
                }
            } else if (key.equals("Key3")) {
                if (!val.equals("value3")) {
                    fail("Key:" + key + "'s value: \nExpected: value3\nFound: " + val);
                }
            }
        }
    } catch (Exception e) {
        fail(e.getMessage());
    }

}
 
Example 2
Project: dds-examples   File: DynamicRoutingConnection.java   View Source Code Vote up 6 votes
DynamicRoutingConnection(
    final String routingServiceName,
    final String routingServiceGroupName,
    final Properties properties
) {
  LOGGER.info("Creating connection");

  if (LOGGER.isDebugEnabled()) {
    for (String key : properties.stringPropertyNames()) {
      LOGGER.debug(
          "key='{}', value='{}'",
          key,
          properties.getProperty(key)
      );
    }
  }

  dynamicRoutingManager = new DynamicRoutingManager(
      routingServiceName,
      routingServiceGroupName,
      "dynamic_routing_adapter.",
      properties
  );

  LOGGER.info("Connection created");
}
 
Example 3
Project: monarch   File: JMXMBeanDUnitTest.java   View Source Code Vote up 6 votes
private void configureAndStartLocator(final int locatorPort, final String serverHostName,
    final Properties properties) throws IOException {
  DistributedTestUtils.deleteLocatorStateFile();

  final String memberName = getUniqueName() + "-locator";
  final File workingDirectory = temporaryFolder.newFolder(memberName);

  LocatorLauncher.Builder builder = new LocatorLauncher.Builder();

  for (String propertyName : properties.stringPropertyNames()) {
    builder.set(propertyName, properties.getProperty(propertyName));
  }
  locatorLauncher = builder.setBindAddress(serverHostName).setHostnameForClients(serverHostName)
      .setMemberName(memberName).setPort(locatorPort)
      .setWorkingDirectory(workingDirectory.getCanonicalPath()).build();
  locatorLauncher.start();

}
 
Example 4
Project: openjdk-jdk10   File: VMSupport.java   View Source Code Vote up 6 votes
/**
 * Write the given properties list to a byte array and return it. Properties with
 * a key or value that is not a String is filtered out. The stream written to the byte
 * array is ISO 8859-1 encoded.
 */
private static byte[] serializePropertiesToByteArray(Properties p) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);

    Properties props = new Properties();

    // stringPropertyNames() returns a snapshot of the property keys
    Set<String> keyset = p.stringPropertyNames();
    for (String key : keyset) {
        String value = p.getProperty(key);
        props.put(key, value);
    }

    props.store(out, null);
    return out.toByteArray();
}
 
Example 5
Project: rapidminer   File: ParentResolvingMap.java   View Source Code Vote up 6 votes
public void parseProperties(String resourceName, String prefix, String suffix, ClassLoader classLoader, Plugin provider)
		throws IOException {
	Properties groupProps = new Properties();
	URL resource = classLoader.getResource(resourceName);
	if (resource == null) {
		// LogService.getRoot().warning("Group properties resource '"+resourceName +
		// "' not found.");
		LogService.getRoot().log(Level.WARNING,
				"com.rapidminer.tools.ParentResolvingMap.group_properties_resource_not_found", resourceName);
	} else {
		groupProps.load(resource.openStream());
		for (String propKey : groupProps.stringPropertyNames()) {
			if (propKey.startsWith(prefix) && propKey.endsWith(suffix)) {
				String keyString = propKey.substring(prefix.length());
				keyString = keyString.substring(0, keyString.length() - suffix.length());
				K mapKey = parseKey(keyString, classLoader, provider);
				V value = parseValue(groupProps.getProperty(propKey), classLoader, provider);
				delegate.put(mapKey, value);
			}
		}
	}
}
 
Example 6
Project: OpenDA   File: BBTemplateFile.java   View Source Code Vote up 6 votes
public void generateTargetFile(File fileOrDir) {
    File workingDir = fileOrDir.isDirectory() ? fileOrDir : fileOrDir.getParentFile();

    File templateFile = new File(workingDir,templateFileName);
    File targetFile = new File(workingDir, targetFileName);
    File valuesFile = new File(workingDir, valuesFileName);

    String[] contents = FileSupport.readContentOfFile(templateFile);

    Properties valueProperties = new Properties();
    try {
        valueProperties.load(new FileInputStream(valuesFile));
    } catch (IOException e) {
        throw new RuntimeException("Problem reading key value pairs from valuesFile " + valuesFile.getAbsolutePath());
    }
    for (String keyId: valueProperties.stringPropertyNames()) {
        String value = valueProperties.getProperty(keyId);
        TemplateKeyDefinition keyDefinition = getKeyDefinitionByKeyId(keyId);
        if (keyDefinition == null) continue;
        writeValueToContent(contents, keyDefinition, value);
    }

    FileSupport.writeContentOfFile(targetFile,contents);
}
 
Example 7
Project: azeroth   File: CCPropertyPlaceholderConfigurer.java   View Source Code Vote up 5 votes
/**
 * 同步最终配置到ZK
 * @param properties
 */
private void publishPropsToZK(Properties properties) {
    if (zkClient == null)
        return;
    Map<String, Object> props = new HashMap<>();
    for (String key : properties.stringPropertyNames()) {
        String value = properties.getProperty(key);
        if (value != null && !"".equals(value.toString().trim())) {
            props.put(key, value);
        }
    }
    //
    zkClient.writeData("", JsonUtils.toJson(props));
}
 
Example 8
Project: personium-core   File: StatusResource.java   View Source Code Vote up 5 votes
/**
 * GETメソッドに対する処理.
 * @return JAS-RS Response
 */
@SuppressWarnings("unchecked")
@GET
@Produces("application/json")
public Response get() {
    StringBuilder sb = new StringBuilder();

    // プロパティ一覧
    Properties props = PersoniumUnitConfig.getProperties();
    JSONObject responseJson = new JSONObject();
    JSONObject propertiesJson = new JSONObject();
    for (String key : props.stringPropertyNames()) {
        String value = props.getProperty(key);
        propertiesJson.put(key, value);
    }
    responseJson.put("properties", propertiesJson);

    // Cell作成/削除
    //responseJson.put("service", checkServiceStatus());

    // ElasticSearch Health
    EsClient client = EsModel.client();
    JSONObject esJson = new JSONObject();
    esJson.put("health", client.checkHealth());
    responseJson.put("ElasticSearch", esJson);

    sb.append(responseJson.toJSONString());
    return Response.status(HttpStatus.SC_OK).entity(sb.toString()).build();
}
 
Example 9
Project: bibliome-java-utils   File: TabularPattern.java   View Source Code Vote up 5 votes
private void loadProfiles(Properties props) {
	for (String name : props.stringPropertyNames()) {
		String v = props.getProperty(name);
		List<String> values = Strings.splitAndTrim(v, ',', 0);
		profiles.put(name, values);
	}
}
 
Example 10
Project: ParquetUtils   File: ParquetGenerator.java   View Source Code Vote up 5 votes
public static Map<String, String> propertiesToMap(Properties props) {

		LinkedHashMap<String, String> convToMap = new LinkedHashMap<String, String>();
		Set<String> propertyNames = props.stringPropertyNames();

		for (String Property : propertyNames) {
			convToMap.put(Property, props.getProperty(Property));
		}
		return convToMap;
	}
 
Example 11
Project: wherehowsX   File: EtlJob.java   View Source Code Vote up 5 votes
@Deprecated
private PySystemState configFromFile(Integer appId, Integer dbId, long whExecId, String configFile) {

  prop = new Properties();
  if (appId != null) {
    prop.setProperty(Constant.APP_ID_KEY, String.valueOf(appId));
  }
  if (dbId != null) {
    prop.setProperty(Constant.DB_ID_KEY, String.valueOf(dbId));
  }
  prop.setProperty(Constant.WH_EXEC_ID_KEY, String.valueOf(whExecId));

  try {
    InputStream propFile = new FileInputStream(configFile);
    prop.load(propFile);
    propFile.close();
  } catch (IOException e) {
    logger.error("property file '{}' not found", configFile);
    e.printStackTrace();
  }

  PyDictionary config = new PyDictionary();

  for (String key : prop.stringPropertyNames()) {
    String value = prop.getProperty(key);
    config.put(new PyString(key), new PyString(value));
  }

  PySystemState sys = new PySystemState();
  sys.argv.append(config);
  return sys;
}
 
Example 12
Project: apollo-custom   File: DefaultConfig.java   View Source Code Vote up 5 votes
@Override
public Set<String> getPropertyNames() {
  Properties properties = m_configProperties.get();
  if (properties == null) {
    return Collections.emptySet();
  }

  return properties.stringPropertyNames();
}
 
Example 13
Project: powsybl-core   File: PropertiesPlatformConfig.java   View Source Code Vote up 5 votes
public static void writeXml(Path configDir, Path xmlFile) throws IOException, XMLStreamException {
    XMLOutputFactory output = XMLOutputFactory.newInstance();
    try (Writer writer = Files.newBufferedWriter(xmlFile, StandardCharsets.UTF_8)) {
        XMLStreamWriter xmlWriter = output.createXMLStreamWriter(writer);
        try {
            xmlWriter.writeStartDocument(StandardCharsets.UTF_8.toString(), "1.0");
            xmlWriter.writeStartElement("config");
            try (DirectoryStream<Path> ds = Files.newDirectoryStream(configDir, entry -> Files.isRegularFile(entry) && entry.getFileName().toString().endsWith(".properties"))) {
                for (Path file : ds) {
                    String fileName = file.getFileName().toString();
                    String fileNameWithoutExtension = fileName.substring(0, fileName.length() - 11);
                    xmlWriter.writeStartElement(fileNameWithoutExtension);
                    Properties properties = new Properties();
                    try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
                        properties.load(reader);
                    }
                    for (String name : properties.stringPropertyNames()) {
                        String value = properties.getProperty(name);
                        xmlWriter.writeStartElement(name);
                        xmlWriter.writeCharacters(value);
                        xmlWriter.writeEndElement();
                    }
                    xmlWriter.writeEndElement();
                }
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
        } finally {
            xmlWriter.close();
        }
    }
}
 
Example 14
Project: oscm   File: ServiceInstance.java   View Source Code Vote up 5 votes
private void rollbackInstanceAttributes(Properties backup, EntityManager em)
        throws BadResultException {
    HashMap<String, Setting> rollbackParams = new HashMap<>();

    for (String name : backup.stringPropertyNames()) {
        rollbackParams.put(name,
                new Setting(name, backup.getProperty(name)));
    }
    this.removeAttrs(rollbackParams, em);
    this.setInstanceAttributes(rollbackParams);
    this.setRollbackInstanceAttributes(null);
}
 
Example 15
Project: bubichain-sdk-java   File: RequestUtils.java   View Source Code Vote up 5 votes
public static List<NameValuePair> createQueryParameters(Properties queryParams){
    if (queryParams == null || queryParams.size() == 0) {
        return Collections.EMPTY_LIST;
    }
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    for (String propName : queryParams.stringPropertyNames()) {
        params.add(new BasicNameValuePair(propName, queryParams.getProperty(propName)));
    }
    return params;
}
 
Example 16
Project: connectors   File: SqlStoredCommon.java   View Source Code Vote up 5 votes
public Connection setupConnectionAndStoredProcedure(Connection connection, Properties properties) throws Exception {

        InputStream is = SqlStoredCommon.class.getClassLoader().getResourceAsStream("application.properties");
        properties.load(is);
        String user     = String.valueOf(properties.get("sql-stored-start-connector.user"));
        String password = String.valueOf(properties.get("sql-stored-start-connector.password"));
        String url      = String.valueOf(properties.get("sql-stored-start-connector.url"));

        System.out.println("Connecting to the database for unit tests");
        try {
            connection = DriverManager.getConnection(url,user,password);
            String databaseProductName = connection.getMetaData().getDatabaseProductName();
            SqlStoredConnectorMetaDataExtension ext = new SqlStoredConnectorMetaDataExtension();
            Map<String,Object> parameters = new HashMap<String,Object>();
            for (final String name: properties.stringPropertyNames()) {
                parameters.put(name.substring(name.indexOf(".")+1), properties.getProperty(name));
            }
            Map<String,StoredProcedureMetadata> storedProcedures = ext.getStoredProcedures(parameters);

            if (!storedProcedures.keySet().contains("DEMO_OUT") 
                    && databaseProductName.equalsIgnoreCase(DatabaseProduct.APACHE_DERBY.nameWithSpaces())) {
                try (Statement stmt = connection.createStatement()) {
                    //Create procedure
                    stmt.execute(SampleStoredProcedures.DERBY_DEMO_OUT_SQL);
                } catch (Exception e) {
                    fail("Exception during Stored Procedure Creation.");
                }
            }
        } catch (Exception ex) {
            fail("Exception during database startup.");
        }
        return connection;
    }
 
Example 17
Project: airlock.gate   File: Application.java   View Source Code Vote up 5 votes
private static ValidatorFactory getValidatorFactory() throws IOException {
    Properties apiKeysProps = Application.getProperties("apikeys.properties");
    Map<String, String[]> apiKeysToRoutingKeyPatterns = new HashMap<>();
    for (String key : apiKeysProps.stringPropertyNames()) {
        String[] routingKeyPatterns = apiKeysProps.getProperty(key, "").trim().split("\\s*,\\s*");
        apiKeysToRoutingKeyPatterns.put(key, routingKeyPatterns);
    }
    return new ValidatorFactory(apiKeysToRoutingKeyPatterns);
}
 
Example 18
Project: hadoop   File: QueueConfigurationParser.java   View Source Code Vote up 4 votes
/**
 * Construct an {@link Element} for a single queue, constructing the inner
 * queue &lt;name/&gt;, &lt;properties/&gt;, &lt;state/&gt; and the inner
 * &lt;queue&gt; elements recursively.
 * 
 * @param document
 * @param jqi
 * @return
 */
static Element getQueueElement(Document document, JobQueueInfo jqi) {

  // Queue
  Element q = document.createElement(QUEUE_TAG);

  // Queue-name
  Element qName = document.createElement(QUEUE_NAME_TAG);
  qName.setTextContent(getSimpleQueueName(jqi.getQueueName()));
  q.appendChild(qName);

  // Queue-properties
  Properties props = jqi.getProperties();
  Element propsElement = document.createElement(PROPERTIES_TAG);
  if (props != null) {
    Set<String> propList = props.stringPropertyNames();
    for (String prop : propList) {
      Element propertyElement = document.createElement(PROPERTY_TAG);
      propertyElement.setAttribute(KEY_TAG, prop);
      propertyElement.setAttribute(VALUE_TAG, (String) props.get(prop));
      propsElement.appendChild(propertyElement);
    }
  }
  q.appendChild(propsElement);

  // Queue-state
  String queueState = jqi.getState().getStateName();
  if (queueState != null
      && !queueState.equals(QueueState.UNDEFINED.getStateName())) {
    Element qStateElement = document.createElement(STATE_TAG);
    qStateElement.setTextContent(queueState);
    q.appendChild(qStateElement);
  }

  // Queue-children
  List<JobQueueInfo> children = jqi.getChildren();
  if (children != null) {
    for (JobQueueInfo child : children) {
      q.appendChild(getQueueElement(document, child));
    }
  }

  return q;
}
 
Example 19
Project: incubator-netbeans   File: TopLogging.java   View Source Code Vote up 4 votes
/** Initializes the logging configuration. Invoked by <code>LogManager.readConfiguration</code> method.
 */
public TopLogging() {
    AWTHandler.install();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);

    Collection<Logger> keep = new LinkedList<Logger>();
    Properties properties = System.getProperties();
    for (String key : properties.stringPropertyNames()) {
        
        if ("sun.os.patch.level".equals(key)) { // NOI18N
            // skip this property as it does not mean level of logging
            continue;
        }

        String v = properties.getProperty(key);
        if (v == null) {
            continue;
        }

        if (key.endsWith(".level")) {
            ps.print(key);
            ps.print('=');
            ps.println(v);
            keep.add(Logger.getLogger(key.substring(0, key.length() - 6)));
        }
    }
    ps.close();
    try {
        StartLog.unregister();
        LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(os.toByteArray()));
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        StartLog.register();
    }


    Logger logger = Logger.getLogger (""); // NOI18N

    Handler[] old = logger.getHandlers();
    for (int i = 0; i < old.length; i++) {
        logger.removeHandler(old[i]);
    }
    logger.addHandler(defaultHandler ());
    if (!disabledConsole) { // NOI18N
        logger.addHandler (streamHandler ());
    }
    logger.addHandler(new LookupDel());
}
 
Example 20
Project: scoold   File: LanguageUtils.java   View Source Code Vote up 4 votes
private Map<String, String> readLanguageFromFile(String langCode) {
	if (langCode != null && langCode.length() == 2) {
		Properties lang = new Properties();
		String file = "lang_" + langCode + ".properties";
		InputStream ins = null;
		try {
			ins = LanguageUtils.class.getClassLoader().getResourceAsStream(file);
			if (ins != null) {
				lang.load(ins);
				if (!lang.isEmpty()) {
					int progress = 0;
					Map<String, String> langmap = new TreeMap<String, String>();
					for (String propKey : lang.stringPropertyNames()) {
						String propVal = lang.getProperty(propKey);
						if (!langCode.equals(getDefaultLanguageCode())) {
							String defaultVal = getDefaultLanguage().get(propKey);
							if (!StringUtils.isBlank(propVal) && !StringUtils.equalsIgnoreCase(propVal, defaultVal)) {
								progress++;
							}
						}
						langmap.put(propKey, propVal);
					}
					if (langCode.equals(getDefaultLanguageCode())) {
						progress = langmap.size(); // 100%
					}
					if (progress > 0) {
						updateTranslationProgressMap(langCode, progress);
					}
					return langmap;
				}
			}
		} catch (Exception e) {
			logger.info("Could not read language file " + file + ": ", e);
		} finally {
			try {
				if (ins != null) {
					ins.close();
				}
			} catch (IOException ex) {
				logger.error(null, ex);
			}
		}
	}
	return null;
}