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(Writer writer) throws ConfigurationException 

Source Link

Document

Save the configuration to the specified stream.

Usage

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

protected void saveSecure(final PropertiesConfiguration conf) throws ConfigurationException {
    final File file = conf.getFile();
    try {//from ww w.  j a v  a2  s  .  co  m
        if (file == null) {
            throw new ConfigurationException("No file name has been set!");
        } else if ((file.createNewFile() || true) && !file.canWrite()) {
            throw new IOException("Cannot write to file " + file.getAbsolutePath() + ". Is it read-only?");
        }
    } catch (IOException e) {
        throw new ConfigurationException(e.getMessage(), e);
    }
    log.debug("Saving {}", file.getAbsolutePath());

    final String fName = file.getName();
    try {
        int lastDot = fName.lastIndexOf('.');
        lastDot = lastDot > 0 ? lastDot : fName.length();

        final Path configPath = file.toPath();
        // Create a tmp file next to the original
        final Path tmp = Files.createTempFile(configPath.getParent(), fName.substring(0, lastDot) + ".",
                fName.substring(lastDot));
        try {
            Files.copy(configPath, tmp, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException iox) {
            log.error("Could not create temp-file {}: {}", tmp, iox.getMessage());
            throw iox;
        }
        log.trace("using temporary file: {}", tmp);
        // Save the config to the tmp file
        conf.save(tmp.toFile());

        log.trace("tmp saved, now replacing the original file: {}", configPath);
        // Replace the original with the tmp file
        try {
            try {
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException amnx) {
                log.trace("atomic move not available: {}, trying without", amnx.getMessage());
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException iox) {
            log.error("Could not write to {}, a backup was created in {}", configPath, tmp);
            throw iox;
        }
        log.info("configuration successfully saved to {}", configPath);
    } catch (final Throwable t) {
        throw new ConfigurationException("Unable to save the configuration to the file " + fName, t);
    }
}

From source file:org.dataconservancy.packaging.tool.model.PropertiesConfigurationParametersBuilder.java

@Override
public void buildParameters(PackageGenerationParameters params, OutputStream outputStream)
        throws ParametersBuildException {
    PropertiesConfiguration props = new PropertiesConfiguration();

    for (String key : params.getKeys()) {
        props.setProperty(key, params.getParam(key));
    }/*from w ww . j a  va2  s.c om*/

    try {
        props.save(new OutputStreamWriter(outputStream));
    } catch (ConfigurationException e) {
        throw new ParametersBuildException(e);
    }
}

From source file:org.eclipse.winery.repository.export.CSARExporter.java

/**
 * Writes the configured mapping namespaceprefix -> namespace to the archive
 * //from w ww  .  ja v a  2s  .co m
 * This is kind of a quick hack. TODO: during the import, the prefixes should be extracted using
 * JAXB and stored in the NamespacesResource
 * 
 * @throws IOException
 */
private void addNamespacePrefixes(ArchiveOutputStream zos) throws IOException {
    Configuration configuration = Repository.INSTANCE.getConfiguration(new NamespacesId());
    if (configuration instanceof PropertiesConfiguration) {
        // Quick hack: direct serialization only works for PropertiesConfiguration
        PropertiesConfiguration pconf = (PropertiesConfiguration) configuration;
        ArchiveEntry archiveEntry = new ZipArchiveEntry(CSARExporter.PATH_TO_NAMESPACES_PROPERTIES);
        zos.putArchiveEntry(archiveEntry);
        try {
            pconf.save(zos);
        } catch (ConfigurationException e) {
            CSARExporter.logger.debug(e.getMessage(), e);
            zos.write("#Could not export properties".getBytes());
            zos.write(("#" + e.getMessage()).getBytes());
        }
        zos.closeArchiveEntry();
    }
}

From source file:org.eclipse.winery.repository.export.ZipExporter.java

/**
 * Writes the configured mapping namespaceprefix -> namespace to the archive
 * //from   w  ww  .j  a  va  2s .  c o  m
 * This is kind of a quick hack. TODO: during the import, the prefixes should be extracted using
 * JAXB and stored in the NamespacesResource
 * 
 * @throws IOException
 */
private void addNamespacePrefixes(ArchiveOutputStream zos) throws IOException {
    Configuration configuration = Repository.INSTANCE.getConfiguration(new NamespacesId());
    if (configuration instanceof PropertiesConfiguration) {
        // Quick hack: direct serialization only works for PropertiesConfiguration
        PropertiesConfiguration pconf = (PropertiesConfiguration) configuration;
        ArchiveEntry archiveEntry = new ZipArchiveEntry(ZipExporter.PATH_TO_NAMESPACES_PROPERTIES);
        zos.putArchiveEntry(archiveEntry);
        try {
            pconf.save(zos);
        } catch (ConfigurationException e) {
            ZipExporter.logger.debug(e.getMessage(), e);
            zos.write("#Could not export properties".getBytes());
            zos.write(("#" + e.getMessage()).getBytes());
        }
        zos.closeArchiveEntry();
    }
}

From source file:org.lockss.crawljax.TestDefLockssConfigurationBuilder.java

private void createMockConfig(String fileName, int maxStates, int depth, long runtime, String browser,
        String proxy) throws ConfigurationException {
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setProperty(DefLockssConfigurationBuilder.MAX_STATES_PARAM, maxStates);
    config.setProperty(DefLockssConfigurationBuilder.DEPTH_PARAM, depth);
    config.setProperty(DefLockssConfigurationBuilder.TIMEOUT_PARAM, runtime);
    config.setProperty(DefLockssConfigurationBuilder.BROWSER_PARAM, browser);
    config.setProperty(DefLockssConfigurationBuilder.PROXY_PARAM, proxy);
    config.save(fileName);
}

From source file:org.okinawaopenlabs.ofpm.utils.ConfigImpl.java

@Override
public String getContents() {
    PropertiesConfiguration prop = new PropertiesConfiguration();
    prop.append(this.config);
    StringWriter sw = new StringWriter();
    try {/* w ww.j av  a 2s.com*/
        prop.save(sw);
    } catch (ConfigurationException e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
    return sw.toString();
}

From source file:org.rzo.yajsw.config.YajswConfigurationImpl.java

public String getCachedPath(boolean save) {
    if (_fileConfiguration == null)
        return null;
    if (isLocalFile())
        try {//from  w  w  w  .j a v a  2  s. c o m
            return new File(_fileConfiguration.getURL().toURI()).getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
            return _fileConfiguration.getFileName();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    try {
        String cache = getCache() + "/conf";
        String fileName = _fileConfiguration.getFileSystem().getFileName(_fileConfiguration.getFileName());
        File cf = new File(cache);
        if (!cf.exists())
            cf.mkdirs();
        if (fileName.endsWith(".jnlp"))
            fileName = fileName + ".conf";
        // configuration file in the cache
        File cn = new File(cf, fileName);

        if (save) {
            // interpolate the file so that no includes are required
            PropertiesConfiguration c2 = (PropertiesConfiguration) _fileConfiguration
                    .interpolatedConfiguration();

            // save the file
            c2.save(cn);
        }
        return cn.getCanonicalPath();

    } catch (Exception ex) {
        ex.printStackTrace();
        return _fileConfiguration.getFileName();
    }

}

From source file:org.silverpeas.settings.file.ModifProperties.java

/**
 * lance la modification du fichier properties
 * @throws Exception/*from  w ww. j  a  v a2 s.c  o m*/
 */
@Override
public void executeModification() throws Exception {
    File file = new File(path);
    if (file.exists()) {
        PropertiesConfiguration configuration = new PropertiesConfiguration(file);
        for (ElementModif em : listeModifications) {
            if (configuration.containsKey(em.getSearch())) {
                if (!em.getModif().equals(configuration.getProperty(em.getSearch()))) {
                    if (!isModified) {
                        isModified = true;
                        BackupFile bf = new BackupFile(new File(path));
                        bf.makeBackup();
                    }
                    configuration.setProperty(em.getSearch(), em.getModif());
                }
            } else {
                configuration.setProperty(em.getSearch(), em.getModif());
            }
        }
        configuration.save(file);
    } else {
        throw new Exception("ATTENTION le fichier:" + path + " n'existe pas");
    }
}

From source file:org.structr.api.config.Settings.java

public static void storeConfiguration(final String fileName) throws IOException {

    try {/* w w  w  . j av  a  2 s.co m*/

        PropertiesConfiguration.setDefaultListDelimiter('\0');

        final PropertiesConfiguration config = new PropertiesConfiguration();

        // store settings
        for (final Setting setting : settings.values()) {

            // story only modified settings and the super user password
            if (setting.isModified() || "superuser.password".equals(setting.getKey())) {

                config.setProperty(setting.getKey(), setting.getValue());
            }
        }

        config.save(fileName);

    } catch (ConfigurationException ex) {
        System.err.println("Unable to store configuration: " + ex.getMessage());
    }

}

From source file:org.talend.mdm.commmon.util.core.EncryptUtil.java

public static void encryptProperties(String location, String[] properties) {
    try {/*from  w w w .  ja  v  a  2 s.  c o  m*/
        File file = new File(location);
        if (file.exists()) {
            PropertiesConfiguration config = new PropertiesConfiguration();
            config.setDelimiterParsingDisabled(true);
            config.load(file);
            if (file.getName().equals("mdm.conf")) { //$NON-NLS-1$
                dataSourceName = config.getString(DB_DEFAULT_DATASOURCE) == null ? StringUtils.EMPTY
                        : config.getString(DB_DEFAULT_DATASOURCE);
            }
            updated = false;
            for (String property : properties) {
                String password = config.getString(property);
                if (StringUtils.isNotEmpty(password) && !password.endsWith(Crypt.ENCRYPT)) {
                    password = Crypt.encrypt(password);
                    config.setProperty(property, password);
                    updated = true;
                }
            }
            if (updated) {
                config.save(file);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Encrypt password in '" + location + "' error.", e); //$NON-NLS-1$ //$NON-NLS-2$
    }
}