List of usage examples for org.apache.commons.configuration PropertiesConfiguration setProperty
public void setProperty(String key, Object value)
From source file:eu.tango.energymodeller.datastore.DefaultDatabaseConnector.java
/** * This reads the settings for the database connection from file. *///from w w w .j av a2 s . co m protected final void loadSettings() { try { PropertiesConfiguration config; if (new File(CONFIG_FILE).exists()) { config = new PropertiesConfiguration(CONFIG_FILE); } else { config = new PropertiesConfiguration(); config.setFile(new File(CONFIG_FILE)); } config.setAutoSave(true); //This will save the configuration file back to disk. In case the defaults need setting. databaseURL = config.getString("energy.modeller.db.url", databaseURL); config.setProperty("energy.modeller.db.url", databaseURL); databaseDriver = config.getString("energy.modeller.db.driver", databaseDriver); try { Class.forName(databaseDriver); } catch (ClassNotFoundException ex) { //If the driver is not found on the class path revert to mysql connector. databaseDriver = "com.mysql.jdbc.Driver"; } config.setProperty("energy.modeller.db.driver", databaseDriver); databasePassword = config.getString("energy.modeller.db.password", ""); config.setProperty("energy.modeller.db.password", databasePassword); databaseUser = config.getString("energy.modeller.db.user", databaseUser); config.setProperty("energy.modeller.db.user", databaseUser); } catch (ConfigurationException ex) { Logger.getLogger(DefaultDatabaseConnector.class.getName()).log(Level.INFO, "Error loading database configuration information", ex); } }
From source file:com.liferay.ide.sdk.core.SDK.java
protected void persistAppServerProperties(Map<String, String> properties) throws FileNotFoundException, IOException, ConfigurationException { IPath loc = getLocation();//w w w . j a v a 2 s . c om // check for build.<username>.properties String userName = System.getProperty("user.name"); //$NON-NLS-1$ File userBuildFile = loc.append("build." + userName + ".properties").toFile(); //$NON-NLS-1$ //$NON-NLS-2$ if (userBuildFile.exists()) { /* * the build file exists so we need to check the following conditions 1. if the header in the comment * contains the text written by a previous SDK operation then we can write it again 2. if the file was not * previously written by us we will need to prompt the user with permission yes/no to update the * build.<username>.properties file */ PropertiesConfiguration propsConfig = new PropertiesConfiguration(userBuildFile); String header = propsConfig.getHeader(); boolean shouldUpdateBuildFile = false; if (header != null && header.contains(MSG_MANAGED_BY_LIFERAY_IDE)) { shouldUpdateBuildFile = true; } else { String overwrite = getPrefStore().get(SDKCorePlugin.PREF_KEY_OVERWRITE_USER_BUILD_FILE, ALWAYS); if (ALWAYS.equals(overwrite)) { shouldUpdateBuildFile = true; } else { shouldUpdateBuildFile = false; } } if (shouldUpdateBuildFile) { for (String key : properties.keySet()) { propsConfig.setProperty(key, properties.get(key)); } propsConfig.setHeader(MSG_MANAGED_BY_LIFERAY_IDE); propsConfig.save(userBuildFile); } } else { Properties props = new Properties(); props.putAll(properties); props.store(new FileOutputStream(userBuildFile), MSG_MANAGED_BY_LIFERAY_IDE); } }
From source file:eu.tango.energymodeller.EnergyModeller.java
/** * This is common code for the constructors *//* www. ja va 2s.com*/ private void startup(boolean performDataGathering) { try { if (datasource == null) { PropertiesConfiguration config; if (new File(CONFIG_FILE).exists()) { config = new PropertiesConfiguration(CONFIG_FILE); } else { config = new PropertiesConfiguration(); config.setFile(new File(CONFIG_FILE)); } config.setAutoSave(true); //This will save the configuration file back to disk. In case the defaults need setting. String datasourceStr = config.getString("energy.modeller.datasource", "SlurmDataSourceAdaptor"); setDataSource(datasourceStr); config.setProperty("energy.modeller.datasource", datasourceStr); String predictorStr = config.getString("energy.modeller.predictor", "CpuAndAcceleratorEnergyPredictor"); setEnergyPredictor(predictorStr); config.setProperty("energy.modeller.predictor", predictorStr); if (!new File(CONFIG_FILE).exists()) { config.save(); } } } catch (ConfigurationException ex) { Logger.getLogger(EnergyModeller.class.getName()).log(Level.INFO, "Error loading the configuration of the energy modeller", ex); } dataGatherer = new DataGatherer(datasource, database); dataGatherer.setPerformDataGathering(performDataGathering); try { dataGatherThread = new Thread(dataGatherer); dataGatherThread.setDaemon(true); dataGatherThread.start(); } catch (Exception ex) { Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, "The energry modeller failed to start correctly", ex); } }
From source file:com.mirth.connect.server.migration.ServerMigrator.java
private void runConfigurationMigrator(ConfigurationMigrator configurationMigrator, PropertiesConfiguration mirthConfig, Version version) { configurationMigrator.updateConfiguration(mirthConfig); HashMap<String, Object> addedProperties = new LinkedHashMap<String, Object>(); Map<String, Object> propertiesToAdd = configurationMigrator.getConfigurationPropertiesToAdd(); if (propertiesToAdd != null) { for (Entry<String, Object> propertyToAdd : propertiesToAdd.entrySet()) { if (!mirthConfig.containsKey(propertyToAdd.getKey())) { PropertiesConfigurationLayout layout = mirthConfig.getLayout(); String key = propertyToAdd.getKey(); Object value;/*from w w w. j av a 2 s. c o m*/ String comment = ""; if (propertyToAdd.getValue() instanceof Pair) { // If a pair is used, get both the value and comment Pair<Object, String> pair = (Pair<Object, String>) propertyToAdd.getValue(); value = pair.getLeft(); comment = pair.getRight(); } else { // Only the value was specified value = propertyToAdd.getValue(); } mirthConfig.setProperty(key, value); // If this is the first added property, add a general comment about the added properties before it if (addedProperties.isEmpty()) { if (StringUtils.isNotEmpty(comment)) { comment = "\n\n" + comment; } comment = "The following properties were automatically added on startup for version " + version + comment; } if (StringUtils.isNotEmpty(comment)) { // When a comment is specified, always put a blank line before it layout.setBlancLinesBefore(key, 1); layout.setComment(key, comment); } addedProperties.put(key, value); } } } List<String> removedProperties = new ArrayList<String>(); String[] propertiesToRemove = configurationMigrator.getConfigurationPropertiesToRemove(); if (propertiesToRemove != null) { for (String propertyToRemove : propertiesToRemove) { if (mirthConfig.containsKey(propertyToRemove)) { mirthConfig.clearProperty(propertyToRemove); removedProperties.add(propertyToRemove); } } } if (!addedProperties.isEmpty() || !removedProperties.isEmpty()) { if (!addedProperties.isEmpty()) { logger.info("Adding properties in mirth.properties: " + addedProperties); } if (!removedProperties.isEmpty()) { logger.info("Removing properties in mirth.properties: " + removedProperties); } try { mirthConfig.save(); } catch (ConfigurationException e) { logger.error("There was an error updating mirth.properties.", e); if (!addedProperties.isEmpty()) { logger.error("The following properties should be added to mirth.properties manually: " + addedProperties.toString()); } if (!removedProperties.isEmpty()) { logger.error("The following properties should be removed from mirth.properties manually: " + removedProperties.toString()); } } } }
From source file:com.ibm.replication.iidr.utils.Settings.java
/** * Load the properties//w w w .j a v a 2 s. c o m */ private void loadProperties(String propertiesFile) throws ConfigurationException { PropertiesConfiguration config = new PropertiesConfiguration( System.getProperty("user.dir") + File.separatorChar + "conf" + File.separator + propertiesFile); checkFrequencySeconds = config.getInt("checkFrequencySeconds", checkFrequencySeconds); connectionResetFrequencyMin = config.getInt("connectionResetFrequencyMin", connectionResetFrequencyMin); logMetricsToDB = config.getBoolean("logMetricsToDB", logMetricsToDB); logSubscriptionStatusToDB = config.getBoolean("logSubscriptionStatusToDB", logSubscriptionStatusToDB); logEventsToDB = config.getBoolean("logEventsToDB", logEventsToDB); logMetricsToCsv = config.getBoolean("logMetricsToCsv", logMetricsToCsv); logSubscriptionStatusToCsv = config.getBoolean("logSubscriptionStatusToCsv", logSubscriptionStatusToCsv); logEventsToCsv = config.getBoolean("logEventsToCsv", logEventsToCsv); // Number of events to retrieve numberOfEvents = config.getInt("numberOfEvents", numberOfEvents); // Access Server settings asHostName = config.getString("asHostName"); asUserName = config.getString("asUserName"); String encryptedAsPassword = config.getString("asPassword"); asPort = config.getInt("asPort", 10101); // Check if the password has already been encrypted // If not, encrypt and save the properties try { asPassword = Encryptor.decodeAndDecrypt(encryptedAsPassword); } catch (EncryptedDataException e) { logger.debug("Encrypting asPassword"); asPassword = encryptedAsPassword; encryptedAsPassword = Encryptor.encryptAndEncode(encryptedAsPassword); config.setProperty("asPassword", encryptedAsPassword); config.save(); } // Metrics to include // if (includeMetrics.isEmpty()) // includeMetricsList = new ArrayList<String>(); // else includeMetricsList = new ArrayList<String>(Arrays.asList(config.getStringArray("includeMetrics"))); includeMetricsList.removeAll(Arrays.asList("")); // Metrics to exclude excludeMetricsList = new ArrayList<String>(Arrays.asList(config.getStringArray("excludeMetrics"))); excludeMetricsList.removeAll(Arrays.asList("")); // Database connection settings dbHostName = config.getString("dbHostName"); dbPort = config.getInt("dbPort"); dbDatabase = config.getString("dbDatabase"); dbUserName = config.getString("dbUserName"); String encryptedDbPassword = config.getString("dbPassword"); dbDriverName = config.getString("dbDriverName"); dbUrl = config.getString("dbUrl"); dbSchema = config.getString("dbSchema"); try { dbPassword = Encryptor.decodeAndDecrypt(encryptedDbPassword); } catch (EncryptedDataException e) { logger.debug("Encrypting dbPassword"); dbPassword = encryptedDbPassword; encryptedDbPassword = Encryptor.encryptAndEncode(encryptedDbPassword); config.setProperty("dbPassword", encryptedDbPassword); config.save(); } // CSV logging settings csvSeparator = config.getString("csvSeparator", csvSeparator); // Now report the settings logSettings(config); }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
private void initialize() { try {/*ww w . j ava2 s.c om*/ // Disable delimiter parsing so getString() returns the whole // property, even if there are commas mirthConfig.setDelimiterParsingDisabled(true); mirthConfig.setFile(new File(ClassPathResource.getResourceURI("mirth.properties"))); mirthConfig.load(); MigrationController.getInstance().migrateConfiguration(mirthConfig); // load the server version versionConfig.setDelimiterParsingDisabled(true); InputStream versionPropertiesStream = ResourceUtil.getResourceStream(this.getClass(), "version.properties"); versionConfig.load(versionPropertiesStream); IOUtils.closeQuietly(versionPropertiesStream); if (mirthConfig.getString(PROPERTY_TEMP_DIR) != null) { File tempDataDirFile = new File(mirthConfig.getString(PROPERTY_TEMP_DIR)); if (!tempDataDirFile.exists()) { if (tempDataDirFile.mkdirs()) { logger.debug("created tempdir: " + tempDataDirFile.getAbsolutePath()); } else { logger.error("error creating tempdir: " + tempDataDirFile.getAbsolutePath()); } } System.setProperty("java.io.tmpdir", tempDataDirFile.getAbsolutePath()); logger.debug("set temp data dir: " + tempDataDirFile.getAbsolutePath()); } File appDataDirFile = null; if (mirthConfig.getString(PROPERTY_APP_DATA_DIR) != null) { appDataDirFile = new File(mirthConfig.getString(PROPERTY_APP_DATA_DIR)); if (!appDataDirFile.exists()) { if (appDataDirFile.mkdir()) { logger.debug("created app data dir: " + appDataDirFile.getAbsolutePath()); } else { logger.error("error creating app data dir: " + appDataDirFile.getAbsolutePath()); } } } else { appDataDirFile = new File("."); } appDataDir = appDataDirFile.getAbsolutePath(); logger.debug("set app data dir: " + appDataDir); baseDir = new File(ClassPathResource.getResourceURI("mirth.properties")).getParentFile().getParent(); logger.debug("set base dir: " + baseDir); if (mirthConfig.getString(CHARSET) != null) { System.setProperty(CHARSET, mirthConfig.getString(CHARSET)); } String[] httpsClientProtocolsArray = mirthConfig.getStringArray(HTTPS_CLIENT_PROTOCOLS); if (ArrayUtils.isNotEmpty(httpsClientProtocolsArray)) { // Support both comma separated and multiline values List<String> httpsClientProtocolsList = new ArrayList<String>(); for (String protocol : httpsClientProtocolsArray) { httpsClientProtocolsList.addAll(Arrays.asList(StringUtils.split(protocol, ','))); } httpsClientProtocols = httpsClientProtocolsList .toArray(new String[httpsClientProtocolsList.size()]); } else { httpsClientProtocols = MirthSSLUtil.DEFAULT_HTTPS_CLIENT_PROTOCOLS; } String[] httpsServerProtocolsArray = mirthConfig.getStringArray(HTTPS_SERVER_PROTOCOLS); if (ArrayUtils.isNotEmpty(httpsServerProtocolsArray)) { // Support both comma separated and multiline values List<String> httpsServerProtocolsList = new ArrayList<String>(); for (String protocol : httpsServerProtocolsArray) { httpsServerProtocolsList.addAll(Arrays.asList(StringUtils.split(protocol, ','))); } httpsServerProtocols = httpsServerProtocolsList .toArray(new String[httpsServerProtocolsList.size()]); } else { httpsServerProtocols = MirthSSLUtil.DEFAULT_HTTPS_SERVER_PROTOCOLS; } String[] httpsCipherSuitesArray = mirthConfig.getStringArray(HTTPS_CIPHER_SUITES); if (ArrayUtils.isNotEmpty(httpsCipherSuitesArray)) { // Support both comma separated and multiline values List<String> httpsCipherSuitesList = new ArrayList<String>(); for (String cipherSuite : httpsCipherSuitesArray) { httpsCipherSuitesList.addAll(Arrays.asList(StringUtils.split(cipherSuite, ','))); } httpsCipherSuites = httpsCipherSuitesList.toArray(new String[httpsCipherSuitesList.size()]); } else { httpsCipherSuites = MirthSSLUtil.DEFAULT_HTTPS_CIPHER_SUITES; } String deploy = String.valueOf(mirthConfig.getProperty(STARTUP_DEPLOY)); if (StringUtils.isNotBlank(deploy)) { startupDeploy = Boolean.parseBoolean(deploy); } // Check for server GUID and generate a new one if it doesn't exist PropertiesConfiguration serverIdConfig = new PropertiesConfiguration( new File(getApplicationDataDir(), "server.id")); if ((serverIdConfig.getString("server.id") != null) && (serverIdConfig.getString("server.id").length() > 0)) { serverId = serverIdConfig.getString("server.id"); } else { serverId = generateGuid(); logger.debug("generated new server id: " + serverId); serverIdConfig.setProperty("server.id", serverId); serverIdConfig.save(); } passwordRequirements = PasswordRequirementsChecker.getInstance().loadPasswordRequirements(mirthConfig); apiBypassword = mirthConfig.getString(API_BYPASSWORD); if (StringUtils.isNotBlank(apiBypassword)) { apiBypassword = new String(Base64.decodeBase64(apiBypassword), "US-ASCII"); } statsUpdateInterval = NumberUtils.toInt(mirthConfig.getString(STATS_UPDATE_INTERVAL), DonkeyStatisticsUpdater.DEFAULT_UPDATE_INTERVAL); // Check for configuration map properties if (mirthConfig.getString(CONFIGURATION_MAP_PATH) != null) { configurationFile = mirthConfig.getString(CONFIGURATION_MAP_PATH); } else { configurationFile = getApplicationDataDir() + File.separator + "configuration.properties"; } PropertiesConfiguration configurationMapProperties = new PropertiesConfiguration(); configurationMapProperties.setDelimiterParsingDisabled(true); configurationMapProperties.setListDelimiter((char) 0); try { configurationMapProperties.load(new File(configurationFile)); } catch (ConfigurationException e) { logger.warn("Failed to find configuration map file"); } Map<String, ConfigurationProperty> configurationMap = new HashMap<String, ConfigurationProperty>(); Iterator<String> iterator = configurationMapProperties.getKeys(); while (iterator.hasNext()) { String key = iterator.next(); String value = configurationMapProperties.getString(key); String comment = configurationMapProperties.getLayout().getCanonicalComment(key, false); configurationMap.put(key, new ConfigurationProperty(value, comment)); } setConfigurationProperties(configurationMap, false); } catch (Exception e) { logger.error("Failed to initialize configuration controller", e); } }
From source file:com.jaspersoft.buildomatic.crypto.MasterPropertiesObfuscator.java
@Override public void execute() throws BuildException { try {/*from w w w.jav a2s. c o m*/ //load master props PropertiesConfiguration config = new PropertiesConfiguration(new File(propsFile)); PropertiesConfigurationLayout configLayout = config.getLayout(); configLayout.setGlobalSeparator("="); Boolean encFlag = Boolean.parseBoolean(config.getString(ENCRYPT_FLAG)); Boolean encDoneFlag = Boolean.parseBoolean(config.getString(ENCRYPT_DONE_FLAG)); if (encFlag && !encDoneFlag) { String blockSzStr = config.getString(CRYPTO_BLOCK_SIZE_PARAM); EncryptionProperties encProps = new EncryptionProperties( blockSzStr != null ? Integer.parseInt(blockSzStr) : null, config.getString(CRYPTO_TRANSFORMATION_PARAM)); List<Object> propsToEncryptList = config.getList(PROPS_TO_ENCRYPT_PARAM, Arrays.<Object>asList(PROPS_TO_ENCRYPT_DEF)); log("Encrypt " + StringUtils.join(propsToEncryptList.toArray(), ','), Project.MSG_INFO); log("Encryption block size: " + encProps.getBlockSize(), Project.MSG_DEBUG); log("Encryption mode: " + encProps.getCipherTransformation(), Project.MSG_DEBUG); //obtain Keystore Manager KeystoreManager.init(this.ksp); KeystoreManager ksManager = KeystoreManager.getInstance(); //obtain key Key secret = ksManager.getBuildKey(); Set<String> paramSet = new HashSet<String>(propsToEncryptList.size()); for (Object prop : propsToEncryptList) { String propNameToEnc = prop.toString().trim(); if (paramSet.contains(propNameToEnc)) continue; //was already encrypted once paramSet.add(propNameToEnc); String pVal = config.getString(propNameToEnc); if (pVal != null) { if (EncryptionEngine.isEncrypted(pVal)) log("encrypt=true was set, but param " + propNameToEnc + " was found already encrypted. " + " Skipping its encryption.", Project.MSG_WARN); else { String ct = EncryptionEngine.encrypt(secret, pVal, encProps); config.setProperty(propNameToEnc, ct); } } } //set encryption to done config.clearProperty(ENCRYPT_FLAG); config.setProperty(ENCRYPT_DONE_FLAG, "true"); //write master props back config.save(); } else if (encDoneFlag) { log("The master properties have already been encrypted. To re-enable the encryption, " + "make sure the passwords are in plain text, set master property " + "encrypt to true and remove encrypt.done.", Project.MSG_INFO); } } catch (Exception e) { throw new BuildException(e, getLocation()); } }
From source file:com.mirth.connect.cli.CommandLineInterface.java
private void commandExportMap(Token[] arguments) throws ClientException { if (hasInvalidNumberOfArguments(arguments, 1)) { return;//ww w . jav a 2 s.com } // file path String path = arguments[1].getText(); File file = new File(path); if (file != null) { try { PropertiesConfiguration properties = new PropertiesConfiguration(file); properties.clear(); PropertiesConfigurationLayout layout = properties.getLayout(); Map<String, ConfigurationProperty> configurationMap = client.getConfigurationMap(); Map<String, ConfigurationProperty> sortedMap = new TreeMap<String, ConfigurationProperty>( String.CASE_INSENSITIVE_ORDER); sortedMap.putAll(configurationMap); for (Entry<String, ConfigurationProperty> entry : sortedMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue().getValue(); String comment = entry.getValue().getComment(); if (StringUtils.isNotBlank(key)) { properties.setProperty(key, value); layout.setComment(key, StringUtils.isBlank(comment) ? null : comment); } } properties.save(); out.println("Configuration map export complete."); } catch (ConfigurationException e) { error("Unable to export configuration map.", e); } } }
From source file:ninja.utils.NinjaPropertiesImplTool.java
/** * This method checks that your configurations have set a * application.secret=23r213r12r123/*w ww. jav a 2 s. c o m*/ * * If application.secret is missing or is empty it will do the following: * - In dev and test mode it'll generate a new application secret and write the secret * to both src/main/java/conf/application.conf and the classes dir were the compiled stuff * goes. * - In prod it will throw a runtime exception and stop the server. */ public static void checkThatApplicationSecretIsSet(boolean isProd, String baseDirWithoutTrailingSlash, PropertiesConfiguration defaultConfiguration, Configuration compositeConfiguration) { String applicationSecret = compositeConfiguration.getString(NinjaConstant.applicationSecret); if (applicationSecret == null || applicationSecret.isEmpty()) { // If in production we stop the startup process. It simply does not make // sense to run in production if the secret is not set. if (isProd) { String errorMessage = "Fatal error. Key application.secret not set. Please fix that."; logger.error(errorMessage); throw new RuntimeException(errorMessage); } logger.info("Key application.secret not set. Generating new one and setting in conf/application.conf."); // generate new secret String secret = SecretGenerator.generateSecret(); // set in overall composite configuration => this enables this instance to // start immediately. Otherwise we would have another build cycle. compositeConfiguration.setProperty(NinjaConstant.applicationSecret, secret); // defaultConfiguration is: conf/application.conf (not prefixed) defaultConfiguration.setProperty(NinjaConstant.applicationSecret, secret); try { // STEP 1: Save in source directories: // save to compiled version => in src/main/target/ String pathToApplicationConfInSrcDir = baseDirWithoutTrailingSlash + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + NinjaProperties.CONF_FILE_LOCATION_BY_CONVENTION; Files.createParentDirs(new File(pathToApplicationConfInSrcDir)); // save to source defaultConfiguration.save(pathToApplicationConfInSrcDir); // STEP 2: Save in classes dir (target/classes or similar). // save in target directory (compiled version aka war aka classes dir) defaultConfiguration.save(); } catch (ConfigurationException e) { logger.error("Error while saving new secret to application.conf.", e); } catch (IOException e) { logger.error("Error while saving new secret to application.conf.", e); } } }
From source file:nl.tudelft.graphalytics.configuration.GraphParserTest.java
private static Fixture constructBasicGraph(String rootDir) { final String NAME = "Graph name"; final long NUM_VERTICES = 123; final long NUM_EDGES = 765; final boolean IS_DIRECTED = true; final String VERTEX_FILE_PATH = "example.graph.v"; final String EDGE_FILE_PATH = "other.example.graph.edges"; Graph graph = new Graph(NAME, NUM_VERTICES, NUM_EDGES, IS_DIRECTED, Paths.get(rootDir, VERTEX_FILE_PATH).toString(), Paths.get(rootDir, EDGE_FILE_PATH).toString(), new PropertyList(), new PropertyList()); PropertiesConfiguration configuration = new PropertiesConfiguration(); configuration.setProperty("meta.vertices", NUM_VERTICES); configuration.setProperty("meta.edges", NUM_EDGES); configuration.setProperty("directed", IS_DIRECTED); configuration.setProperty("vertex-file", VERTEX_FILE_PATH); configuration.setProperty("edge-file", EDGE_FILE_PATH); return new Fixture(NAME, graph, configuration); }