Java Code Examples for java.util.Properties#load()

The following examples show how to use java.util.Properties#load() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: J2SEProjectConfigurations.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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();
    
}
 
Example 2
Source File: PortableRemoteObject.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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) ;
    }
}
 
Example 3
Source File: CommandLine.java    From thorntail with Apache License 2.0 6 votes vote down vote up
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();
            });
}
 
Example 4
Source File: LogVisualizer.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
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()]));
}
 
Example 5
Source File: RunNiFi.java    From nifi with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: ReadPropertiesMojoTest.java    From properties-maven-plugin with Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example 7
Source File: Cob2XsdConfig.java    From legstar-core2 with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Properties getConfigProps(InputStream stream)
        throws IOException {
    try {
        Properties config = new Properties();
        config.load(stream);
        return config;
    } finally {
        stream.close();
    }
}
 
Example 8
Source File: MFontConfiguration.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source File: RepositoryIdProvider.java    From maven-artifacts-uploader with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 10
Source File: ExternalFirewallRules.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
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");

}
 
Example 11
Source File: SimpleTestWithUnitRatio.java    From maestro-java with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 12
Source File: CoreSettings.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 13
Source File: MFALSModelTestCase.java    From jstarcraft-rns with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 14
Source File: Stanag4676ImageryChipService.java    From geowave with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: DbScriptUtil.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 16
Source File: CouchbaseLiteInternal.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 17
Source File: EncryptionTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
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();
    }

}
 
Example 18
Source File: AmbariConfigurationMonitor.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
            }
        }
    }
}
 
Example 19
Source File: HintTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 20
Source File: StatisticsMigration.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
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);
    }
}