下面列出了java.util.Properties#load ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void generateConfig(FileObject prjDir, String cfgFilePath, EditableProperties propsToWrite) throws IOException {
if (propsToWrite == null) {
// do not create anything if props is null
return;
}
FileObject jwsConfigFO = FileUtil.createData(prjDir, cfgFilePath);
Properties props = new Properties();
InputStream is = jwsConfigFO.getInputStream();
props.load(is);
is.close();
if (props.equals(propsToWrite)) {
// file already exists and props are the same
return;
}
OutputStream os = jwsConfigFO.getOutputStream();
propsToWrite.store(os);
os.close();
}
private Properties loadProperties(final Logger logger) throws IOException {
final Properties props = new Properties();
final File statusFile = getStatusFile(logger);
if (statusFile == null || !statusFile.exists()) {
logger.debug("No status file to load properties from");
return props;
}
try (final FileInputStream fis = new FileInputStream(getStatusFile(logger))) {
props.load(fis);
}
final Map<Object, Object> modified = new HashMap<>(props);
modified.remove("secret.key");
logger.debug("Properties: {}", modified);
return props;
}
public void loadLogParser() throws IOException {
if (parserPropertyFile == null) {
throw new IOException("Parser property file unset!");
}
if (logFile == null) {
throw new IOException("Log file unset!");
}
// close the previous parser
close();
List<String> logFilePaths = new ArrayList<>();
getLogFilePaths(logFile, logFilePaths);
String propertyFilePath = parserPropertyFile.getPath();
Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream(propertyFilePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
properties.load(bufferedInputStream);
}
logParser = new PatternLogParser(properties, logFilePaths.toArray(new String[logFilePaths.size()]));
}
public void displayConfigHelp(PrintStream out, String fraction) throws IOException, ModuleLoadException {
ModuleClassLoader cl = Module.getBootModuleLoader().loadModule("thorntail.application").getClassLoader();
Enumeration<URL> docs = cl.getResources("META-INF/configuration-meta.properties");
Properties props = new Properties();
while (docs.hasMoreElements()) {
URL each = docs.nextElement();
Properties fractionDocs = new Properties();
fractionDocs.load(each.openStream());
if (fraction.equals(ALL) || fraction.equals(fractionDocs.getProperty(FRACTION))) {
fractionDocs.remove(FRACTION);
props.putAll(fractionDocs);
}
}
props.stringPropertyNames().stream()
.sorted()
.forEach(key -> {
out.println("# " + key);
out.println();
out.println(formatDocs(" ", props.getProperty(key)));
out.println();
});
}
private void getPropertiesFromFile( Properties props, String fileName )
{
try {
File file = new File( fileName ) ;
if (!file.exists())
return ;
FileInputStream in = new FileInputStream( file ) ;
try {
props.load( in ) ;
} finally {
in.close() ;
}
} catch (Exception exc) {
if (debug)
System.out.println( "ORB properties file " + fileName +
" not found: " + exc) ;
}
}
private static Properties getConfigProps(InputStream stream)
throws IOException {
try {
Properties config = new Properties();
config.load(stream);
return config;
} finally {
stream.close();
}
}
private static Properties readProperties() {
Properties result = new Properties();
try {
File propFile = getPreferencesFile();
FileInputStream is = new FileInputStream(propFile);
try {
result.load(is);
} finally {
is.close();
}
} catch (IOException e) {
}
return result;
}
/**
* Load any previously-persisted service discovery configurations.
* This is necessary for checking previously-deployed topologies.
*/
private void loadDiscoveryConfiguration() {
File persistenceDir = getPersistenceDir();
if (persistenceDir != null) {
Collection<File> persistedConfigs = FileUtils.listFiles(persistenceDir, new String[]{"conf"}, false);
for (File persisted : persistedConfigs) {
Properties props = new Properties();
try (InputStream in = Files.newInputStream(persisted.toPath())) {
props.load(in);
addDiscoveryConfig(props.getProperty(PROP_CLUSTER_NAME), new ServiceDiscoveryConfig() {
@Override
public String getAddress() {
return props.getProperty(PROP_CLUSTER_SOURCE);
}
@Override
public String getCluster() {
return props.getProperty(PROP_CLUSTER_NAME);
}
@Override
public String getUser() {
return props.getProperty(PROP_CLUSTER_USER);
}
@Override
public String getPasswordAlias() {
return props.getProperty(PROP_CLUSTER_ALIAS);
}
});
} catch (IOException e) {
log.failedToLoadClusterMonitorServiceDiscoveryConfig(getType(), e);
}
}
}
}
public static void main(String[] args) {
Connection conn = null;
try {
// use the ij utility to read the property file and
// make the initial connection.
com.splicemachine.db.tools.ij.getPropertyArg(args);
conn = com.splicemachine.db.tools.ij.startJBMS();
// Test 1
// Derby 236 - boot password should not be written out
// into service.properties
String derbyHome = System.getProperty("derby.system.home");
// read in the properties in the service.properties file of the db
Properties serviceProperties = new Properties();
File f = new File(derbyHome + "/wombat/service.properties");
serviceProperties.load(new FileInputStream(f.getAbsolutePath()));
if (serviceProperties.getProperty("bootPassword") == null)
report("TEST PASSED");
else
report("FAIL -- bootPassword should not be written out into service.properties");
conn.close();
} catch (Throwable e) {
report("FAIL -- unexpected exception: " + e);
e.printStackTrace();
}
}
@VisibleForTesting
@SuppressWarnings("unchecked")
@NonNull
public static Map<String, String> loadErrorMessages() {
final Properties errors = new Properties();
try (InputStream is = CouchbaseLiteInternal.class.getResourceAsStream(ERRORS_PROPERTIES_PATH)) {
errors.load(is);
}
catch (IOException e) { Log.e(LogDomain.DATABASE, "Failed to load error messages!", e); }
return (Map<String, String>) (Map) errors;
}
protected static DatabaseConnection createDbConnection() throws Exception {
Properties properties = new Properties();
properties.load(DbScriptUtil.class.getClassLoader().getResourceAsStream("META-INF/activiti-app-test/TEST-db.properties"));
Connection connection = DriverManager.getConnection(properties.getProperty("datasource.url"),
properties.getProperty("datasource.username"), properties.getProperty("datasource.password"));
DatabaseConnection databaseConnection = new JdbcConnection(connection);
return databaseConnection;
}
private static Properties loadProperties(final InputStream is) {
final Properties props = new Properties();
if (is != null) {
try {
props.load(is);
} catch (final IOException e) {
LOGGER.error("Could not load properties from InputStream", e);
}
}
return props;
}
@Test
public void testRecommender() throws Exception {
Properties keyValues = new Properties();
keyValues.load(this.getClass().getResourceAsStream("/data/filmtrust.properties"));
keyValues.load(this.getClass().getResourceAsStream("/model/collaborative/rating/mfals-test.properties"));
Configurator configuration = new MapConfigurator(keyValues);
RatingTask job = new RatingTask(MFALSModel.class, configuration);
Object2FloatSortedMap<Class<? extends Evaluator>> measures = job.execute();
Assert.assertEquals(0.82939005F, measures.getFloat(MAEEvaluator.class), 0F);
Assert.assertEquals(0.9454853F, measures.getFloat(MPEEvaluator.class), 0F);
Assert.assertEquals(1.3054749F, measures.getFloat(MSEEvaluator.class), 0F);
}
public static CoreSettings load(String file) {
Properties properties = new Properties();
try (Reader reader = Files.newBufferedReader(Paths.get(file, (String) null))) {
properties.load(reader);
} catch (IOException ex) {
LOGGER.error("error loading properties file, using defaults", ex);
}
return load(properties);
}
@Test
public void testSimpleFileWithUnitRatio() throws Exception {
String fileName = this.getClass().getResource("file-01.hdr").getPath();
// HDR Log Reader
HdrLogProcessorWrapper processorWrapper = new DefaultHdrLogProcessorWrapper(10.0);
File sourceFile = new File(fileName);
Histogram histogram = Util.getAccumulated(sourceFile);
HdrData hdrData = processorWrapper.convertLog(histogram);
HdrPropertyWriter hdrPropertyWriter = new HdrPropertyWriter();
hdrPropertyWriter.postProcess(histogram, sourceFile, new DefaultHistogramHandler(10.0));
File propertiesFile = new File(sourceFile.getParentFile(), "latency.properties");
assertTrue(propertiesFile.exists());
assertTrue(propertiesFile.isFile());
Properties ps = new Properties();
try (InputStream inputStream = new FileInputStream(propertiesFile)) {
ps.load(inputStream);
}
assertEquals("2", ps.getProperty("latency99th"));
assertEquals("6", ps.getProperty("latency9999th"));
assertEquals("1", ps.getProperty("latency50th"));
assertEquals("9916", ps.getProperty("latencyTotalCount"));
assertEquals("6.1", ps.getProperty("latencyMaxValue"));
}
protected static void configLog4j() {
InputStream inStreamLog4j = ExternalFirewallRules.class.getClassLoader().getResourceAsStream("log4j.properties");
Properties propertiesLog4j = new Properties();
try {
propertiesLog4j.load(inStreamLog4j);
PropertyConfigurator.configure(propertiesLog4j);
} catch (Exception e) {
e.printStackTrace();
}
logger.debug("log4j configured");
}
@Override
public String get() {
Properties properties = new Properties();
try {
Path currentPath = Paths.get(".").toAbsolutePath().normalize();
Path configurationFilePath = currentPath.resolve("conf").resolve(CONFIGURATION_FILENAME);
BufferedReader bufferedReader = Files.newBufferedReader(configurationFilePath);
properties.load(bufferedReader);
} catch (IOException e) {
throw new UncheckedIOException("there is problem with " + CONFIGURATION_FILENAME, e);
}
return DEPLOY_OPTION + properties.getProperty("repository.id");
}
/**
* Sets the OS name and version from environment information.
*/
protected void setOsNameAndVersion(){
super.setOsNameAndVersion();
if (osName.equals("SunOS")) {
//don't care os name on Solaris
osName = null;
} else if (osName.equals("Linux")) {
try {
File f;
if ((f = new File("/etc/fedora-release")).canRead()) {
osName = "Fedora";
osVersion = getVersionString(f);
} else if ((f = new File("/etc/redhat-release")).canRead()) {
osName = "RedHat";
osVersion = getVersionString(f);
} else if ((f = new File("/etc/turbolinux-release")).canRead()) {
osName = "Turbo";
osVersion = getVersionString(f);
} else if ((f = new File("/etc/SuSE-release")).canRead()) {
osName = "SuSE";
osVersion = getVersionString(f);
} else if ((f = new File("/etc/lsb-release")).canRead()) {
/* Ubuntu and (perhaps others) use only lsb-release.
* Syntax and encoding is compatible with java properties.
* For Ubuntu the ID is "Ubuntu".
*/
Properties props = new Properties();
props.load(new FileInputStream(f));
osName = props.getProperty("DISTRIB_ID");
osVersion = props.getProperty("DISTRIB_RELEASE");
}
} catch (Exception e) {
}
}
return;
}
@Test
public void readPropertiesWithKeyprefix() throws Exception {
String keyPrefix = "testkey-prefix.";
File testPropertyFileWithoutPrefix = getPropertyFileForTesting();
Properties testPropertiesWithoutPrefix = new Properties();
testPropertiesWithoutPrefix.load(new FileReader(testPropertyFileWithoutPrefix));
// do the work
readPropertiesMojo.setKeyPrefix(keyPrefix);
readPropertiesMojo.setFiles(new File[]{testPropertyFileWithoutPrefix});
readPropertiesMojo.execute();
// load properties directly and add prefix for comparison later
Properties testPropertiesPrefix = new Properties();
testPropertiesPrefix.load(new FileReader(getPropertyFileForTesting(keyPrefix)));
// check results
Properties projectProperties = projectStub.getProperties();
assertNotNull(projectProperties);
// it should not be empty
assertNotEquals(0, projectProperties.size());
// we are adding prefix, so prefix properties should be same as in projectProperties
assertEquals(testPropertiesPrefix.size(), projectProperties.size());
assertEquals(testPropertiesPrefix, projectProperties);
// properties with and without prefix shouldn't be same
assertNotEquals(testPropertiesPrefix, testPropertiesWithoutPrefix);
assertNotEquals(testPropertiesWithoutPrefix, projectProperties);
}
public static void main(String[] args) {
try {
if (args.length != 2) {
System.err.println(String.format("Wrong arguments count. Should be %d but was %d", 2, args.length));
System.exit(1);
}
String mode = args[0];
String configurationFile = args[1];
if (!mode.equals(CHECK_MODE) && !mode.equals(MIGRATE_MODE)) {
throw new IllegalArgumentException("Unknown mode: " + mode);
}
Properties properties = new Properties();
try (InputStream in = new FileInputStream(configurationFile)) {
properties.load(in);
}
Map<String, String> settingsMap = new HashMap<>();
for (Entry<Object, Object> prop : properties.entrySet()) {
settingsMap.put(prop.getKey().toString(), prop.getValue().toString());
}
StatisticsServiceSettings settings = new StatisticsServiceSettings();
settings.fillFromMap(settingsMap);
HibernateStorageSettings hibSettings = settings.getStorageSettings();
DbmsType dbmsType = DbmsType.getTypeByName(hibSettings.getDbms());
dbmsType.setDbmsSettings(hibSettings);
StatisticsFlywayWrapper statisticsFlywayWrapper = new StatisticsFlywayWrapper();
try {
statisticsFlywayWrapper.init(settings.getStorageSettings());
} catch (OlderSchemaException ex) {
System.out.println(ex.getMessage());
}
switch (mode) {
case CHECK_MODE:
if (statisticsFlywayWrapper.isMigrationRequired()) {
System.exit(NEED_MIGRATION_CODE);
}
break;
case MIGRATE_MODE:
if (!statisticsFlywayWrapper.isMigrationRequired()) {
throw new IllegalStateException("Migrate isn't required");
}
statisticsFlywayWrapper.migrate();
break;
}
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}