Example usage for org.apache.commons.configuration PropertiesConfiguration save

List of usage examples for org.apache.commons.configuration PropertiesConfiguration save

Introduction

In this page you can find the example usage for org.apache.commons.configuration PropertiesConfiguration save.

Prototype

public void save() throws ConfigurationException 

Source Link

Document

Save the configuration.

Usage

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java

public static void main(String[] args) {
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String oldMSKey = null;//from  ww w  .  j a  v  a2s  .c  o m
    String oldDBKey = null;
    String newMSKey = null;
    String newDBKey = null;

    //Parse command-line args
    while (iter.hasNext()) {
        String arg = iter.next();
        // Old MS Key
        if (arg.equals("-m")) {
            oldMSKey = iter.next();
        }
        // Old DB Key
        if (arg.equals("-d")) {
            oldDBKey = iter.next();
        }
        // New MS Key
        if (arg.equals("-n")) {
            newMSKey = iter.next();
        }
        // New DB Key
        if (arg.equals("-e")) {
            newDBKey = iter.next();
        }
    }

    if (oldMSKey == null || oldDBKey == null) {
        System.out.println("Existing MS secret key or DB secret key is not provided");
        usage();
        return;
    }

    if (newMSKey == null && newDBKey == null) {
        System.out.println("New MS secret key and DB secret are both not provided");
        usage();
        return;
    }

    final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties");
    final Properties dbProps;
    EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger();
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
    keyChanger.initEncryptor(encryptor, oldMSKey);
    dbProps = new EncryptableProperties(encryptor);
    PropertiesConfiguration backupDBProps = null;

    System.out.println("Parsing db.properties file");
    try {
        dbProps.load(new FileInputStream(dbPropsFile));
        backupDBProps = new PropertiesConfiguration(dbPropsFile);
    } catch (FileNotFoundException e) {
        System.out.println("db.properties file not found while reading DB secret key" + e.getMessage());
    } catch (IOException e) {
        System.out.println("Error while reading DB secret key from db.properties" + e.getMessage());
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }

    String dbSecretKey = null;
    try {
        dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret");
    } catch (EncryptionOperationNotPossibleException e) {
        System.out.println("Failed to decrypt existing DB secret key from db.properties. " + e.getMessage());
        return;
    }

    if (!oldDBKey.equals(dbSecretKey)) {
        System.out.println("Incorrect MS Secret Key or DB Secret Key");
        return;
    }

    System.out.println("Secret key provided matched the key in db.properties");
    final String encryptionType = dbProps.getProperty("db.cloud.encryption.type");

    if (newMSKey == null) {
        System.out.println("No change in MS Key. Skipping migrating db.properties");
    } else {
        if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey)) {
            System.out.println("Failed to update db.properties");
            return;
        } else {
            //db.properties updated successfully
            if (encryptionType.equals("file")) {
                //update key file with new MS key
                try {
                    FileWriter fwriter = new FileWriter(keyFile);
                    BufferedWriter bwriter = new BufferedWriter(fwriter);
                    bwriter.write(newMSKey);
                    bwriter.close();
                } catch (IOException e) {
                    System.out.println("Failed to write new secret to file. Please update the file manually");
                }
            }
        }
    }

    boolean success = false;
    if (newDBKey == null || newDBKey.equals(oldDBKey)) {
        System.out.println("No change in DB Secret Key. Skipping Data Migration");
    } else {
        EncryptionSecretKeyChecker.initEncryptorForMigration(oldMSKey);
        try {
            success = keyChanger.migrateData(oldDBKey, newDBKey);
        } catch (Exception e) {
            System.out.println("Error during data migration");
            e.printStackTrace();
            success = false;
        }
    }

    if (success) {
        System.out.println("Successfully updated secret key(s)");
    } else {
        System.out.println("Data Migration failed. Reverting db.properties");
        //revert db.properties
        try {
            backupDBProps.save();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        if (encryptionType.equals("file")) {
            //revert secret key in file
            try {
                FileWriter fwriter = new FileWriter(keyFile);
                BufferedWriter bwriter = new BufferedWriter(fwriter);
                bwriter.write(oldMSKey);
                bwriter.close();
            } catch (IOException e) {
                System.out.println("Failed to revert to old secret to file. Please update the file manually");
            }
        }
    }
}

From source file:net.orpiske.ssps.common.repository.RepositorySettings.java

private static void addUserConfig(final RepositoryInfo repositoryInfo) throws RepositorySetupException {
    String repositoryPath = RepositoryUtils.getUserRepository();

    String path = repositoryPath + File.separator + repositoryInfo.getName() + File.separator + "user.conf";

    File file = new File(path);

    if (!file.exists()) {
        try {/*from w w  w . j  a v  a  2s  .c  o  m*/
            file.createNewFile();
        } catch (IOException e) {
            throw new RepositorySetupException("Unable to create user configuration " + "file", e);
        }
    } else {
        throw new RepositorySetupException("This user already exists");
    }

    PropertiesConfiguration userConfig;
    try {
        userConfig = new PropertiesConfiguration(path);

        userConfig.addProperty(repositoryInfo.getName() + ".auth.user", repositoryInfo.getUserName());
        userConfig.addProperty(repositoryInfo.getName() + ".auth.password", repositoryInfo.getPassword());
        userConfig.save();
    } catch (ConfigurationException e) {
        throw new RepositorySetupException(
                "Unable to save user configuration to " + path + ":" + e.getMessage(), e);
    }

}

From source file:com.xemantic.tadedon.configuration.Configurations.java

public static void merge(PropertiesConfiguration defaultConf, PropertiesConfiguration conf) {
    LOG.debug("Merging: {} <-> {}", defaultConf.getURL(), conf.getURL());
    for (@SuppressWarnings("unchecked")
    Iterator<String> iterator = defaultConf.getKeys(); iterator.hasNext();) {
        String key = iterator.next();
        if (!conf.containsKey(key)) {
            copyProperty(key, defaultConf, conf);
        }/*w  ww. j av  a  2s  .c  om*/
    }
    try {
        conf.save();
    } catch (ConfigurationException e) {
        throw new RuntimeException("Could no save configuration file: " + conf.getFileName(), e);
    }
}

From source file:eu.optimis.ecoefficiencytool.core.tools.EnergyCreditsManager.java

/**
 *
 * @param consumedEnergy Consumed energy in kWh.
 *///ww w . j a va2s .  c  om
private static void setRemainingEnergyInRECs(double consumedEnergy) throws ConfigurationException {
    PropertiesConfiguration configEnergyCredits = ConfigManager
            .getPropertiesConfiguration(ConfigManager.ENERGYCREDITS_CONFIG_FILE);
    Iterator recs = configEnergyCredits.getKeys("REC");
    while (recs.hasNext()) {
        String key = (String) recs.next();
        double remainingCredit = configEnergyCredits.getDouble(key);
        if (consumedEnergy < remainingCredit) {
            remainingCredit = remainingCredit - consumedEnergy;
            configEnergyCredits.setProperty(key, Double.toString(remainingCredit));
            configEnergyCredits.save();
            return;
        } else {
            consumedEnergy = consumedEnergy - remainingCredit;
            configEnergyCredits.setProperty(key, Double.toString(0.0));
        }
    }

    if (consumedEnergy > 0.0) {
        log.warn("All REC Energy credits are exhausted");
    }
    configEnergyCredits.save();
}

From source file:eu.optimis.ecoefficiencytool.core.tools.EnergyCreditsManager.java

/**
 *
 * @param emmittedCO2kg Kg of emmitted CO2.
 *///from w  w  w .  java 2  s.  c  o m
private static void setRemainingEmissionsInEUETSs(double emmittedCO2kg) throws ConfigurationException {

    updateCurrentEmissionsExcess();

    PropertiesConfiguration configEnergyCredits = ConfigManager
            .getPropertiesConfiguration(ConfigManager.ENERGYCREDITS_CONFIG_FILE);

    Iterator euas = configEnergyCredits.getKeys("EUA");
    while (euas.hasNext()) {
        String key = (String) euas.next();
        double remainingCredit = configEnergyCredits.getDouble(key);
        if (emmittedCO2kg < remainingCredit) {
            remainingCredit = remainingCredit - emmittedCO2kg;
            configEnergyCredits.setProperty(key, Double.toString(remainingCredit));
            configEnergyCredits.save();
            return;
        } else {
            emmittedCO2kg = emmittedCO2kg - remainingCredit;
            configEnergyCredits.setProperty(key, Double.toString(0.0));
        }
    }

    if (emmittedCO2kg > 0.0) {
        double currentExcess = configEnergyCredits.getDouble("exceededEmissions");
        currentExcess += emmittedCO2kg;
        configEnergyCredits.setProperty("exceededEmissions", Double.toString(currentExcess));
        log.warn("Exceeding allowed CO2 emissions by " + currentExcess + "kg.");
    }
    configEnergyCredits.save();
}

From source file:com.continuent.tungsten.common.security.SecurityHelper.java

/**
 * Save passwords from a TungstenProperties into a file
 * //from  w  ww .j ava2 s  .  co m
 * @param authenticationInfo containing password file location
 */
public static void saveCredentialsFromAuthenticationInfo(AuthenticationInfo authenticationInfo)
        throws ServerRuntimeException {
    String passwordFileLocation = authenticationInfo.getPasswordFileLocation();

    try {
        String username = authenticationInfo.getUsername();
        String password = authenticationInfo.getPassword();

        PropertiesConfiguration props = new PropertiesConfiguration(passwordFileLocation); // Use Apache commons-configuration:
                                                                                           // preserves comments in .properties
                                                                                           // !
        props.setProperty(username, password);
        props.save();
    } catch (org.apache.commons.configuration.ConfigurationException ce) {
        logger.error("Error while saving properties for file:" + authenticationInfo.getPasswordFileLocation(),
                ce);
        throw new ServerRuntimeException("Error while saving Credentials: " + ce.getMessage());
    }
}

From source file:com.continuent.tungsten.common.security.SecurityHelper.java

/**
 * Delete a user and password from a file
 * /*  w  w w  .  j  av a  2s. c  o m*/
 * @param authenticationInfo containing password file location
 */
public static void deleteUserFromAuthenticationInfo(AuthenticationInfo authenticationInfo)
        throws ServerRuntimeException {
    String username = authenticationInfo.getUsername();
    String passwordFileLocation = authenticationInfo.getPasswordFileLocation();

    try {
        PropertiesConfiguration props = new PropertiesConfiguration(passwordFileLocation);

        // --- Check that the user exists ---
        String usernameInFile = props.getString(username);
        if (usernameInFile == null) {
            throw new ServerRuntimeException(MessageFormat.format("Username does not exist: {0}", username));
        }

        props.clearProperty(username);
        props.save();
    } catch (org.apache.commons.configuration.ConfigurationException ce) {
        logger.error("Error while saving properties for file:" + authenticationInfo.getPasswordFileLocation(),
                ce);
        throw new ServerRuntimeException("Error while saving Credentials: " + ce.getMessage());
    }
}

From source file:eu.optimis.ecoefficiencytool.core.tools.EnergyCreditsManager.java

private static void updateCurrentEmissionsExcess() throws ConfigurationException {
    PropertiesConfiguration configEnergyCredits = ConfigManager
            .getPropertiesConfiguration(ConfigManager.ENERGYCREDITS_CONFIG_FILE);

    double currentExcess = configEnergyCredits.getDouble("exceededEmissions");
    if (currentExcess > 0.0) {
        Iterator euas = configEnergyCredits.getKeys("EUA");
        while (euas.hasNext()) {
            String key = (String) euas.next();
            double remainingCredit = configEnergyCredits.getDouble(key);
            if (currentExcess < remainingCredit) {
                remainingCredit = remainingCredit - currentExcess;
                configEnergyCredits.setProperty(key, Double.toString(remainingCredit));
                configEnergyCredits.setProperty("exceededEmissions", Double.toString(0.0));
                configEnergyCredits.save();
                return;
            } else {
                currentExcess = currentExcess - remainingCredit;
                configEnergyCredits.setProperty(key, Double.toString(0.0));
            }/*from www .  j a v a 2 s .com*/
        }
        if (currentExcess > 0.0) {
            configEnergyCredits.setProperty("exceededEmissions", Double.toString(currentExcess));
        }
        configEnergyCredits.save();
    }
}

From source file:net.sf.mpaxs.spi.server.DrmaaComputeHostLauncher.java

/**
 * Submits a new ComputeHost to the GridEngine.
 * Settings from the Settings class are used and converted to <code>Configuration</code>.
 *
 * @param cfg the configuration to use// w ww .  j  a  va  2 s  . c o  m
 * @see net.sf.mpaxs.spi.computeHost.Settings
 */
@Override
public void startComputeHost(Configuration cfg) {
    String drmaaImplementation = SessionFactory.getFactory().getSession().getDrmaaImplementation();
    System.out.println("Drmaa Implementation: " + drmaaImplementation);
    File configLocation = new File(cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR),
            "computeHost.properties");
    try {
        PropertiesConfiguration pc = new PropertiesConfiguration(configLocation);
        ConfigurationUtils.copy(cfg, pc);
        pc.save();
    } catch (ConfigurationException ex) {
        Logger.getLogger(DrmaaComputeHostLauncher.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<String> arguments = new ArrayList<String>();
    arguments.add("-cp");
    arguments.add(cfg.getString(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR));
    arguments.add(cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_MAIN_CLASS));
    arguments.add("-c");
    try {
        arguments.add(configLocation.toURI().toURL().toString());
    } catch (MalformedURLException ex) {
        Logger.getLogger(DrmaaComputeHostLauncher.class.getName()).log(Level.SEVERE, null, ex);
    }
    Logger.getLogger(this.getClass().getName()).log(Level.INFO, "ComputeHost configuration: {0}",
            ConfigurationUtils.toString(cfg));
    try {
        SessionFactory factory = SessionFactory.getFactory();
        Session session = factory.getSession();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO,
                "DRM System: {0} Implementation: {1} Version: {2}", new Object[] { session.getDrmSystem(),
                        session.getDrmaaImplementation(), session.getVersion() });
        session.init("");
        JobTemplate jt = session.createJobTemplate();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Remote command: {0}",
                cfg.getString(ConfigurationKeys.KEY_PATH_TO_JAVA));
        jt.setRemoteCommand(cfg.getString(ConfigurationKeys.KEY_PATH_TO_JAVA));
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Working dir: {0}",
                cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR));
        jt.setWorkingDirectory(cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR));
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Arguments: {0}", arguments);
        jt.setArgs(arguments);
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Error path: {0}",
                cfg.getString(ConfigurationKeys.KEY_ERROR_FILE));
        jt.setErrorPath(":" + cfg.getString(ConfigurationKeys.KEY_ERROR_FILE));
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Output path: {0}",
                cfg.getString(ConfigurationKeys.KEY_OUTPUT_FILE));
        jt.setOutputPath(":" + cfg.getString(ConfigurationKeys.KEY_OUTPUT_FILE));
        jt.setNativeSpecification(cfg.getString(ConfigurationKeys.KEY_NATIVE_SPEC, ""));
        jt.setJobName("mpaxs-chost");
        session.runJob(jt);
        session.deleteJobTemplate(jt);
        session.exit();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Session started!");
    } catch (DrmaaException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.jorge.propiedades.CorreoConfiguracion.java

public CorreoConfiguracion() {
    try {/*from  w w  w  .ja  v  a  2  s  .c  o m*/
        PropertiesConfiguration config = new PropertiesConfiguration("./quijotelu/Correo.properties");
        if (config.getProperty("correo.correo") == null) {
            config.setProperty("correo.correo", "jorjoluiso@gmail.com");
            config.save();
        }
        if (config.getProperty("correo.clave") == null) {
            config.setProperty("correo.clave", "suclave");
            config.save();
        }
        correo = (String) config.getProperty("correo.correo");
        clave = (String) config.getProperty("correo.clave");
    } catch (ConfigurationException ex) {
        Logger.getLogger(CorreoConfiguracion.class.getName()).log(Level.SEVERE, null, ex);
    }
}