Example usage for org.apache.commons.configuration2.builder FileBasedConfigurationBuilder save

List of usage examples for org.apache.commons.configuration2.builder FileBasedConfigurationBuilder save

Introduction

In this page you can find the example usage for org.apache.commons.configuration2.builder FileBasedConfigurationBuilder save.

Prototype

public void save() throws ConfigurationException 

Source Link

Document

Convenience method which saves the associated configuration.

Usage

From source file:com.streamsets.datacollector.cli.sch.SchAdmin.java

/**
 * Update dpm.properties file with new configuration.
 *///from   w  w w .j  a  va 2s.c  o  m
private static void updateDpmProperties(Context context, String dpmBaseURL, List<String> labels,
        boolean enableSch) {
    if (context.skipUpdatingDpmProperties) {
        return;
    }

    try {
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
                PropertiesConfiguration.class)
                        .configure(new Parameters().properties()
                                .setFileName(context.runtimeInfo.getConfigDir() + "/dpm.properties")
                                .setThrowExceptionOnMissing(true)
                                .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                                .setIncludesAllowed(false));
        PropertiesConfiguration config = null;
        config = builder.getConfiguration();
        config.setProperty(RemoteSSOService.DPM_ENABLED, Boolean.toString(enableSch));
        config.setProperty(RemoteSSOService.DPM_BASE_URL_CONFIG, dpmBaseURL);
        config.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, APP_TOKEN_FILE_PROP_VAL);
        if (labels != null && labels.size() > 0) {
            config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, StringUtils.join(labels, ','));
        } else {
            config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, "");
        }
        builder.save();
    } catch (ConfigurationException e) {
        throw new RuntimeException(Utils.format("Updating dpm.properties file failed: {}", e.getMessage()), e);
    }
}

From source file:com.haulmont.mp2xls.writer.LocalizationBatchFileWriter.java

/**
 * Writing all changed properties to the passed file. Using apache commons-configuration to write properties,
 * because it preserves the original file format unlike the java.util.Properties class.
 *
 * @param messagesFile - messages file/*  w  w  w.  ja  v  a2s . c o  m*/
 * @param diffs - differences
 */
protected void mergeLocalizationProperties(File messagesFile, Collection<LocalizationLog> diffs) {
    if (diffs == null || diffs.isEmpty())
        return;
    try {
        Parameters parameters = new Parameters();
        FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
                PropertiesConfiguration.class)
                        .configure(parameters.properties().setFile(messagesFile).setEncoding("UTF-8")
                                .setIOFactory(new MessagePropertiesIOFactory())
                                .setLayout(new PropertiesConfigurationLayout()));

        Configuration configuration = builder.getConfiguration();
        for (LocalizationLog diff : diffs) {
            if (LocalizationLog.Type.CHANGED.equals(diff.getType())) {
                configuration.setProperty(diff.getParameterName(), diff.getExcelValue());
            }
        }
        builder.save();
    } catch (Exception e) {
        throw new RuntimeException("Exception during properties file merging", e);
    }
}

From source file:edu.si.services.beans.cameratrap.CT_BlueprintTestSupport.java

@Before
@Override/*from w w  w. j a v  a2 s  . c  o  m*/
public void setUp() throws Exception {
    log.info("===================[ KARAF_HOME = {} ]===================", System.getProperty("karaf.home"));

    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
            PropertiesConfiguration.class)
                    .configure(params.fileBased().setFile(new File(defaultTestProperties)));
    config = builder.getConfiguration();

    List<String> propFileList = loadAdditionalPropertyFiles();
    if (loadAdditionalPropertyFiles() != null) {
        for (String propFile : propFileList) {

            FileBasedConfigurationBuilder<FileBasedConfiguration> builder2 = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
                    PropertiesConfiguration.class).configure(params.fileBased().setFile(new File(propFile)));

            for (Iterator<String> i = builder2.getConfiguration().getKeys(); i.hasNext();) {
                String key = i.next();
                Object value = builder2.getConfiguration().getProperty(key);
                if (!config.containsKey(key)) {
                    config.setProperty(key, value);
                }
            }
        }
    }

    if (fedoraHost != null && !fedoraHost.isEmpty()) {
        config.setProperty("si.fedora.host", fedoraHost);
    }
    if (fedoraUser != null && !fedoraUser.isEmpty()) {
        config.setProperty("si.fedora.user", fedoraUser);
    }
    if (fedoraPassword != null && !fedoraPassword.isEmpty()) {
        config.setProperty("si.fedora.password", fedoraPassword);
    }
    if (fusekiHost != null && !fusekiHost.isEmpty()) {
        config.setProperty("si.fuseki.endpoint", fusekiHost);
    }

    //Set a reasonable number of redeliveries for testing purposes
    config.setProperty("min.connectEx.redeliveries", 2);

    builder.save();

    //Initialize the Mock AmazonS3Client
    amazonS3Client = new AmazonS3ClientMock(config.getString("si.ct.uscbi.aws.accessKey"),
            config.getString("si.ct.uscbi.aws.secretKey"));

    super.setUp();
}

From source file:edu.si.services.sidora.rest.mci.MCI_BlueprintTestSupport.java

@Before
@Override/*  w  ww. j  a  v a2 s .  c o m*/
public void setUp() throws Exception {
    log.info("===================[ KARAF_HOME = {} ]===================", System.getProperty("karaf.home"));

    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
            PropertiesConfiguration.class)
                    .configure(params.fileBased().setFile(new File(defaultTestProperties)));
    config = builder.getConfiguration();

    List<String> propFileList = loadAdditionalPropertyFiles();
    if (loadAdditionalPropertyFiles() != null) {
        for (String propFile : propFileList) {

            FileBasedConfigurationBuilder<FileBasedConfiguration> builder2 = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
                    PropertiesConfiguration.class).configure(params.fileBased().setFile(new File(propFile)));

            for (Iterator<String> i = builder2.getConfiguration().getKeys(); i.hasNext();) {
                String key = i.next();
                Object value = builder2.getConfiguration().getProperty(key);
                if (!config.containsKey(key)) {
                    config.setProperty(key, value);
                }
            }
        }
    }

    if (fedoraHost != null && !fedoraHost.isEmpty()) {
        config.setProperty("si.fedora.host", fedoraHost);
    }
    if (fedoraUser != null && !fedoraUser.isEmpty()) {
        config.setProperty("si.fedora.user", fedoraUser);
    }
    if (fedoraPassword != null && !fedoraPassword.isEmpty()) {
        config.setProperty("si.fedora.password", fedoraPassword);
    }
    if (fusekiHost != null && !fusekiHost.isEmpty()) {
        config.setProperty("si.fuseki.endpoint", fusekiHost);
    }
    if (fitsHost != null && !fitsHost.isEmpty()) {
        config.setProperty("si.fits.host", fitsHost);
    }
    if (sidoraMciHost != null && !sidoraMciHost.isEmpty()) {
        config.setProperty("sidora.mci.service.address", sidoraMciHost);
    }

    builder.save();
    super.setUp();
}

From source file:edu.si.services.beans.edansidora.EDAN_CT_BlueprintTestSupport.java

@Before
@Override/*from   w  w w  .  j a v a 2s  . c  om*/
public void setUp() throws Exception {
    log.info("===================[ KARAF_HOME = {} ]===================", System.getProperty("karaf.home"));

    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
            PropertiesConfiguration.class)
                    .configure(params.fileBased().setFile(new File(defaultTestProperties)));
    config = builder.getConfiguration();

    List<String> propFileList = loadAdditionalPropertyFiles();
    if (loadAdditionalPropertyFiles() != null) {
        for (String propFile : propFileList) {

            FileBasedConfigurationBuilder<FileBasedConfiguration> builder2 = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
                    PropertiesConfiguration.class).configure(params.fileBased().setFile(new File(propFile)));

            for (Iterator<String> i = builder2.getConfiguration().getKeys(); i.hasNext();) {
                String key = i.next();
                Object value = builder2.getConfiguration().getProperty(key);
                if (!config.containsKey(key)) {
                    config.setProperty(key, value);
                }
            }
        }
    }

    if (fedoraHost != null && !fedoraHost.isEmpty()) {
        config.setProperty("si.fedora.host", fedoraHost);
    }
    if (fedoraUser != null && !fedoraUser.isEmpty()) {
        config.setProperty("si.fedora.user", fedoraUser);
    }
    if (fedoraPassword != null && !fedoraPassword.isEmpty()) {
        config.setProperty("si.fedora.password", fedoraPassword);
    }
    if (fusekiHost != null && !fusekiHost.isEmpty()) {
        config.setProperty("si.fuseki.endpoint", fusekiHost);
    }
    if (fitsHost != null && !fitsHost.isEmpty()) {
        config.setProperty("si.fits.host", fitsHost);
    }
    if (sidoraEdanHost != null && !sidoraEdanHost.isEmpty()) {
        config.setProperty("si.ct.uscbi.server", sidoraEdanHost);
    }

    config.setProperty("min.connectEx.redeliveries", 2);
    config.setProperty("min.edan.redeliveries", 2);

    config.setProperty("si.ct.uscbi.edanService", "/addEdanTest");

    builder.save();

    super.setUp();
}

From source file:org.dspace.servicemanager.config.DSpaceConfigurationServiceTest.java

/**
 * Tests the ability of our ConfigurationService to automatically reload properties after a set period
 * of time./*from   www.java2 s .c  o  m*/
 */
@Test
public void testAutomaticReload() throws ConfigurationException, InterruptedException {
    // Initialize new config service
    DSpaceConfigurationService dscs = new DSpaceConfigurationService();

    // Assert a property exists with a specific initial value
    assertNotNull(dscs.getProperty("prop.to.auto.reload"));
    assertEquals("D-space", dscs.getProperty("prop.to.auto.reload"));

    // Now, change the value of that Property in the file itself (using a separate builder instance)
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new Configurations()
            .propertiesBuilder(propertyFilePath);
    PropertiesConfiguration config = builder.getConfiguration();
    // Clear out current value. Add in a new value
    config.clearProperty("prop.to.auto.reload");
    config.addProperty("prop.to.auto.reload", "DSpace");
    // Save updates to file
    builder.save();

    // Check immediately. Property should be unchanged
    // NOTE: If this fails, then somehow the configuration reloaded *immediately*
    assertEquals("D-space", dscs.getProperty("prop.to.auto.reload"));

    // Wait now for 3 seconds
    Thread.sleep(3_000);

    // Check again. Property should have reloaded
    // NOTE: reload time is set in config-definition.xml to reload every 2 seconds
    assertEquals("DSpace", dscs.getProperty("prop.to.auto.reload"));
}

From source file:org.jbb.system.impl.install.InstallationFileManager.java

public void createInstallationFile(InstallationData installationData) {
    Parameters params = new Parameters();
    File installFile = getInstallFile();
    try {// www. j  av  a 2s.  c  om
        FileUtils.touch(installFile);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
            PropertiesConfiguration.class).configure(params.fileBased().setFile(installFile));
    builder.setAutoSave(true);

    try {
        FileBasedConfiguration configuration = builder.getConfiguration();
        configuration.addProperty("installationId", UUID.randomUUID().toString());
        configuration.addProperty("installationVersion", jbbMetaData.jbbVersion());
        configuration.addProperty("installationDate", LocalDateTime.now().toString());
        configuration.addProperty("boardFounderUsername", installationData.getAdminUsername());
        builder.save();
    } catch (ConfigurationException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.mitre.mpf.wfm.util.MpfPropertiesConfigurationBuilder.java

public synchronized ImmutableConfiguration setAndSaveCustomProperties(List<PropertyModel> propertyModels) {

    // create a new builder and configuration to write the properties to disk
    // without affecting the values of the composite config
    FileBasedConfigurationBuilder<PropertiesConfiguration> tmpMpfCustomPropertiesConfigBuilder = createFileBasedConfigurationBuilder(
            customPropFile);//from   w  w w . j  a  v  a2s  . c  om

    Configuration tmpMpfCustomPropertiesConfig;
    try {
        tmpMpfCustomPropertiesConfig = tmpMpfCustomPropertiesConfigBuilder.getConfiguration();
    } catch (ConfigurationException e) {
        throw new IllegalStateException("Cannot create configuration from " + customPropFile + ".", e);
    }

    for (PropertyModel propModel : propertyModels) {
        String key = propModel.getKey();
        String value = propModel.getValue();

        // update all properties that will be written to disk
        tmpMpfCustomPropertiesConfig.setProperty(key, value);

        // update only the detection.* values in the composite config used by the WFM
        if (key.startsWith(DETECTION_KEY_PREFIX)) {
            mpfCustomPropertiesConfig.setProperty(key, value);
        }
    }

    try {
        tmpMpfCustomPropertiesConfigBuilder.save();
    } catch (ConfigurationException e) {
        throw new IllegalStateException("Cannot save configuration to " + customPropFile + ".", e);
    }

    updateConfigurationSnapshot();

    return mpfConfigSnapshot;
}

From source file:org.mitre.mpf.wfm.util.TestPropertiesUtil.java

@Test
public void testBuilderSave() throws ConfigurationException, IOException {
    ImmutableConfiguration mpfPropertiesconfig = mpfPropertiesConfigurationBuilder.getCompleteConfiguration();

    List<PropertyModel> newCustomPropertyModels = new ArrayList<>();
    newCustomPropertyModels.add(new PropertyModel(FRAME_INTERVAL_KEY, "4", false));
    newCustomPropertyModels.add(new PropertyModel(MODELS_DIR_KEY, "${" + SHARE_PATH_KEY + "}/new/dir/", false));
    newCustomPropertyModels.add(new PropertyModel(TIMEOUT_KEY, "60", false));

    ImmutableConfiguration newMpfPropertiesConfig = mpfPropertiesConfigurationBuilder
            .setAndSaveCustomProperties(newCustomPropertyModels);

    String mpfHome = System.getenv(MPF_HOME_ENV_VAR);
    Assert.assertNotNull(mpfHome);// ww  w  .  jav  a  2 s.  c  o m

    // ensure that current config isn't modified
    Assert.assertEquals(1, mpfPropertiesconfig.getInt(FRAME_INTERVAL_KEY));
    Assert.assertEquals(mpfHome + "/share/models/", mpfPropertiesconfig.getString(MODELS_DIR_KEY));
    Assert.assertEquals(30, mpfPropertiesconfig.getInt(TIMEOUT_KEY));

    // get updated config
    mpfPropertiesconfig = newMpfPropertiesConfig; // mpfPropertiesConfigurationBuilder.getConfiguration();

    // ensure detection value sticks
    Assert.assertEquals(4, mpfPropertiesconfig.getInt(FRAME_INTERVAL_KEY));

    // ensure that interpolation is performed on recently-set values
    Assert.assertEquals(mpfHome + "/share/new/dir/", mpfPropertiesconfig.getString(MODELS_DIR_KEY));

    // ensure non-detection value doesn't stick
    Assert.assertEquals(30, mpfPropertiesconfig.getInt(TIMEOUT_KEY));

    // ensure all values written to disk
    Configurations configs = new Configurations();

    FileBasedConfigurationBuilder<PropertiesConfiguration> mpfCustomPropertiesConfigBuilder = configs
            .propertiesBuilder(customPropFile.getURL());
    Configuration mpfCustomPropertiesConfig = mpfCustomPropertiesConfigBuilder.getConfiguration();

    Assert.assertEquals(4, mpfCustomPropertiesConfig.getInt(FRAME_INTERVAL_KEY));
    Assert.assertEquals("${" + SHARE_PATH_KEY + "}/new/dir/",
            mpfCustomPropertiesConfig.getString(MODELS_DIR_KEY));
    Assert.assertEquals(60, mpfCustomPropertiesConfig.getInt(TIMEOUT_KEY));

    // reset
    mpfCustomPropertiesConfig.clear();
    mpfCustomPropertiesConfigBuilder.save();
}

From source file:org.roda_project.commons_ip.model.impl.bagit.BagitUtils.java

public static IPDescriptiveMetadata createBagitMetadata(Map<String, String> metadata, List<String> ancestors,
        Path metadataPath) {//w  w  w  . j a  v  a2s.c  om
    try {
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new Configurations()
                .propertiesBuilder(metadataPath.toFile());
        Files.createFile(metadataPath);
        PropertiesConfiguration config = builder.getConfiguration();

        for (Entry<String, String> entry : metadata.entrySet()) {
            config.setProperty(entry.getKey(), entry.getValue());
        }

        for (String ancestor : ancestors) {
            config.addProperty(IPConstants.BAGIT_PARENT, ancestor);
        }

        builder.save();
    } catch (IOException | ConfigurationException e) {
        LOGGER.error("Could not save bagit metadata content on file", e);
    }

    return new IPDescriptiveMetadata(metadataPath.getFileName().toString(), new IPFile(metadataPath),
            new MetadataType(BAGIT), "");
}