Example usage for org.apache.commons.configuration HierarchicalINIConfiguration getSection

List of usage examples for org.apache.commons.configuration HierarchicalINIConfiguration getSection

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalINIConfiguration getSection.

Prototype

public SubnodeConfiguration getSection(String name) 

Source Link

Document

Returns a configuration with the content of the specified section.

Usage

From source file:au.org.intersect.dms.instrument.harvester.WindowsIniLogParser.java

private String parseLogIniFile(HierarchicalINIConfiguration iniConf) {
    StringTemplate template = ST_HARVESTERS.getInstanceOf(templateFilePath);
    Map<String, Map<String, Object>> values = new HashMap<String, Map<String, Object>>();
    for (String sectionName : (Set<String>) iniConf.getSections()) {
        Map<String, Object> sectionMap = new HashMap<String, Object>();
        SubnodeConfiguration section = iniConf.getSection(sectionName);
        if (sectionChecker == null || sectionChecker.includeSection(section)) {
            for (Iterator it = section.getRootNode().getChildren().iterator(); it.hasNext();) {
                ConfigurationNode node = (ConfigurationNode) it.next();
                sectionMap = parseFields(sectionName, sectionMap, node);
            }// www .  ja  v  a2  s.c om
            if (!sectionMap.isEmpty()) {
                values.put(AbstractHarvester.toXML(sectionName), sectionMap);
            }
        }
    }
    template.setAttribute("sections", values);
    return template.toString();
}

From source file:ee.ria.xroad.common.SystemPropertiesLoader.java

private void load(FileWithSections file) {
    try {/*w ww. j a v  a2  s. com*/
        // turn off list delimiting (before parsing),
        // otherwise we lose everything after first ","
        // in loadSection/sec.getString(key)
        HierarchicalINIConfiguration ini = new HierarchicalINIConfiguration();
        ini.setDelimiterParsingDisabled(true);
        ini.load(file.getName());

        for (String sectionName : ini.getSections()) {
            if (isEmpty(file.getSections()) || contains(file.getSections(), sectionName)) {
                loadSection(sectionName, ini.getSection(sectionName));
            }
        }
    } catch (ConfigurationException e) {
        log.warn("Error while loading {}: {}", file.getName(), e);
    }
}

From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java

private void writeWp43Configs(List<Contingency> contingencies, Path workingDir)
        throws IOException, ConfigurationException {
    Path baseWp43ConfigFile = PlatformConfig.CONFIG_DIR.resolve(WP43_CONFIGS_FILE_NAME);

    // generate one variant of the base config for all the contingency
    // this allow to add extra variables for some indexes
    HierarchicalINIConfiguration configuration = new HierarchicalINIConfiguration(baseWp43ConfigFile.toFile());
    SubnodeConfiguration node = configuration.getSection("smallsignal");
    node.setProperty("f_instant", parameters.getFaultEventInstant());
    for (int i = 0; i < contingencies.size(); i++) {
        Contingency contingency = contingencies.get(i);
        if (contingency.getElements().isEmpty()) {
            throw new AssertionError("Empty contingency " + contingency.getId());
        }//  w  w w  .ja v a  2  s  .  c o  m
        Iterator<ContingencyElement> it = contingency.getElements().iterator();
        // compute the maximum fault duration
        double maxDuration = getFaultDuration(contingency, it.next());
        while (it.hasNext()) {
            maxDuration = Math.max(maxDuration, getFaultDuration(contingency, it.next()));
        }
        node.setProperty("f_duration", maxDuration);
        Path wp43Config = workingDir.resolve(WP43_CONFIGS_PER_FAULT_FILE_NAME
                .replace(Command.EXECUTION_NUMBER_PATTERN, Integer.toString(i)));
        try (Writer writer = Files.newBufferedWriter(wp43Config, StandardCharsets.UTF_8)) {
            configuration.save(writer);
        }
    }
}

From source file:eu.itesla_project.dymola.DymolaImpactAnalysis.java

private List<String> writeDymolaInputs(Path workingDir, List<Contingency> contingencies) throws IOException {
    LOGGER.info(" Start writing dymola inputs");

    List<String> retList = new ArrayList<>();

    DdbConfig ddbConfig = DdbConfig.load();
    String jbossHost = ddbConfig.getJbossHost();
    String jbossPort = ddbConfig.getJbossPort();
    String jbossUser = ddbConfig.getJbossUser();
    String jbossPassword = ddbConfig.getJbossPassword();

    Path dymolaExportPath = workingDir.resolve(MO_EXPORT_DIRECTORY);
    if (!Files.exists(dymolaExportPath)) {
        Files.createDirectory(dymolaExportPath);
    }//from w ww  .j  a v a2s  .co  m

    //retrieve modelica export parameters from configuration
    String modelicaVersion = config.getModelicaVersion();
    String sourceEngine = config.getSourceEngine();
    String sourceVersion = config.getSourceEngineVersion();
    Path modelicaPowerSystemLibraryPath = Paths.get(config.getModelicaPowerSystemLibraryFile());

    //write the modelica events file, to feed the modelica exporter
    Path eventsPath = workingDir.resolve(MODELICA_EVENTS_CSV_FILENAME);
    writeModelicaExporterContingenciesFile(eventsPath, contingencies);

    //these are only optional params needed if the source is eurostag
    Path modelicaLibPath = null;

    String slackId = config.getSlackId();
    if ("".equals(slackId)) {
        slackId = null; // null when not specified ()
    }

    LoadFlowFactory loadFlowFactory;
    try {
        loadFlowFactory = config.getLoadFlowFactoryClass().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    LOGGER.info("Exporting modelica data for network {}, working state-id {} ", network,
            network.getStateManager().getWorkingStateId());
    ModelicaMainExporter exporter = new ModelicaMainExporter(network, slackId, jbossHost, jbossPort, jbossUser,
            jbossPassword, modelicaVersion, sourceEngine, sourceVersion, modelicaLibPath, loadFlowFactory);
    exporter.export(dymolaExportPath);
    ModEventsExport eventsExporter = new ModEventsExport(
            dymolaExportPath.resolve(network.getId() + ".mo").toFile(), eventsPath.toFile());
    eventsExporter.export(dymolaExportPath);
    LOGGER.info(" modelica data exported.");

    // now assemble the input files to feed dymola
    //  one .zip per contingency; in the zip, the .mo file and the powersystem library
    //TODO here it is assumed that contingencies ids in csv file start from 0 (i.e. 0 is the first contingency); id should be decoupled from the implementation
    try (final Stream<Path> pathStream = Files.walk(dymolaExportPath)) {
        pathStream.filter((p) -> !p.toFile().isDirectory() && p.toFile().getAbsolutePath().contains("events_")
                && p.toFile().getAbsolutePath().endsWith(".mo")).forEach(p -> {
                    GenericArchive archive = ShrinkWrap.createDomain().getArchiveFactory()
                            .create(GenericArchive.class);
                    try (FileSystem fileSystem = ShrinkWrapFileSystems.newFileSystem(archive)) {
                        Path rootDir = fileSystem.getPath("/");
                        Files.copy(modelicaPowerSystemLibraryPath,
                                rootDir.resolve(modelicaPowerSystemLibraryPath.getFileName()));
                        Files.copy(Paths.get(p.toString()),
                                rootDir.resolve(DymolaUtil.DYMOLA_SIM_MODEL_INPUT_PREFIX + ".mo"));

                        String[] c = p.getFileName().toString().replace(".mo", "").split("_");
                        try (OutputStream os = Files.newOutputStream(dymolaExportPath.getParent().resolve(
                                DymolaUtil.DYMOLAINPUTZIPFILENAMEPREFIX + "_" + c[c.length - 1] + ".zip"))) {
                            archive.as(ZipExporter.class).exportTo(os);
                            retList.add(new String(c[c.length - 1]));
                        } catch (IOException e) {
                            //e.printStackTrace();
                            throw new RuntimeException(e);
                        }

                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                });
    }
    retList.sort(Comparator.<String>naturalOrder());

    //prepare param inputs for indexes from indexes properties file
    LOGGER.info("writing input indexes parameters in  .mat format - start ");
    try {
        Path baseWp43ConfigFile = PlatformConfig.CONFIG_DIR.resolve(WP43_CONFIG_FILE_NAME);
        HierarchicalINIConfiguration configuration = new HierarchicalINIConfiguration(
                baseWp43ConfigFile.toFile());

        //fix params for smallsignal index (cfr EurostagImpactAnalysis sources)
        SubnodeConfiguration node = configuration.getSection("smallsignal");
        node.setProperty("f_instant", Double.toString(parameters.getFaultEventInstant()));
        for (int i = 0; i < contingencies.size(); i++) {
            Contingency contingency = contingencies.get(i);
            if (contingency.getElements().isEmpty()) {
                throw new AssertionError("Empty contingency " + contingency.getId());
            }
            Iterator<ContingencyElement> it = contingency.getElements().iterator();
            // compute the maximum fault duration
            double maxDuration = getFaultDuration(it.next());
            while (it.hasNext()) {
                maxDuration = Math.max(maxDuration, getFaultDuration(it.next()));
            }
            node.setProperty("f_duration", Double.toString(maxDuration));
        }

        DymolaAdaptersMatParamsWriter writer = new DymolaAdaptersMatParamsWriter(configuration);
        for (String cId : retList) {
            String parFileNamePrefix = DymolaUtil.DYMOLA_SIM_MAT_OUTPUT_PREFIX + "_" + cId + "_wp43_";
            String parFileNameSuffix = "_pars.mat";
            String zippedParFileNameSuffix = "_pars.zip";

            try (OutputStream os = Files.newOutputStream(dymolaExportPath.getParent()
                    .resolve(DymolaUtil.DYMOLAINPUTZIPFILENAMEPREFIX + "_" + cId + zippedParFileNameSuffix))) {
                JavaArchive archive = ShrinkWrap.create(JavaArchive.class);
                Path sfile1 = ShrinkWrapFileSystems.newFileSystem(archive).getPath("/");

                Arrays.asList(config.getIndexesNames()).forEach(indexName -> writer.write(indexName,
                        sfile1.resolve(parFileNamePrefix + indexName + parFileNameSuffix)));

                archive.as(ZipExporter.class).exportTo(os);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    } catch (ConfigurationException exc) {
        throw new RuntimeException(exc);
    }

    LOGGER.info("writing input indexes parameters in  .mat format - end - {}", retList);
    return retList;
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Tests querying the properties of a section that was merged from two
 * sections with the same name.// www  . j a va 2  s.  c o m
 */
@Test
public void testGetSectionMerged() throws ConfigurationException {
    final String data = INI_DATA + "[section1]" + LINE_SEPARATOR + "var3 = merged" + LINE_SEPARATOR;
    HierarchicalINIConfiguration config = setUpConfig(data);
    SubnodeConfiguration section = config.getSection("section1");
    assertEquals("Wrong value of var1", "foo", section.getString("var1"));
    assertEquals("Wrong value of var2", "451", section.getString("var2"));
    assertEquals("Wrong value of var3", "merged", section.getString("var3"));
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Tests whether a section that has been cleared can be manipulated and
 * saved later.// ww  w  .j a v  a2 s.  c o m
 */
@Test
public void testSaveClearedSection() throws ConfigurationException {
    final String data = "[section]\ntest = failed\n";
    HierarchicalINIConfiguration config = setUpConfig(data);
    SubnodeConfiguration sub = config.getSection("section");
    assertFalse("No content", sub.isEmpty());
    sub.clear();
    sub.setProperty("test", "success");
    StringWriter writer = new StringWriter();
    config.save(writer);
    HierarchicalConfiguration config2 = setUpConfig(writer.toString());
    assertEquals("Wrong value", "success", config2.getString("section.test"));
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Tests querying the content of the global section if there is none.
 *//*from  w ww  .j ava  2  s.  c o  m*/
@Test
public void testGetSectionGlobalNonExisting() throws ConfigurationException {
    HierarchicalINIConfiguration config = setUpConfig(INI_DATA);
    SubnodeConfiguration section = config.getSection(null);
    assertTrue("Sub config not empty", section.isEmpty());
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Tests querying a non existing section.
 *//*from  w  ww  .  j a v  a2 s. c  o  m*/
@Test
public void testGetSectionNonExisting() throws ConfigurationException {
    HierarchicalINIConfiguration config = setUpConfig(INI_DATA);
    SubnodeConfiguration section = config.getSection("Non existing section");
    assertTrue("Sub config not empty", section.isEmpty());
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Tests querying the properties of an existing section.
 *///from ww w.  ja  v a  2  s .c  om
@Test
public void testGetSectionExisting() throws ConfigurationException {
    HierarchicalINIConfiguration config = setUpConfig(INI_DATA);
    SubnodeConfiguration section = config.getSection("section1");
    assertEquals("Wrong value of var1", "foo", section.getString("var1"));
    assertEquals("Wrong value of var2", "451", section.getString("var2"));
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Tests whether a section that was created by getSection() can be
 * manipulated./*from  ww w.ja v a 2s  .  co  m*/
 */
@Test
public void testGetSectionNonExistingManipulate() throws ConfigurationException {
    HierarchicalINIConfiguration config = setUpConfig(INI_DATA);
    SubnodeConfiguration section = config.getSection("newSection");
    section.addProperty("test", "success");
    assertEquals("Main config not updated", "success", config.getString("newSection.test"));
    StringWriter writer = new StringWriter();
    config.save(writer);
    HierarchicalINIConfiguration config2 = setUpConfig(writer.toString());
    section = config2.getSection("newSection");
    assertEquals("Wrong value", "success", section.getString("test"));
}