Example usage for org.apache.commons.configuration HierarchicalConfiguration getString

List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getString

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalConfiguration getString.

Prototype

public String getString(String key) 

Source Link

Usage

From source file:org.wso2.carbon.device.mgt.iot.agent.kura.display.SequenceRunner.java

private List<ResourceType> getSequence() {
    List<ResourceType> sequence = new ArrayList<>();

    ConfigManager configManager = ConfigManager.getInstance();

    List<HierarchicalConfiguration> resources = configManager.getContentConfig()
            .configurationsAt("Content.DisplaySequence.Resource");

    for (HierarchicalConfiguration resource : resources) {

        String resourceTypeHandler = resource.getString("[@handler]");
        ResourceType resourceObj = null;

        try {/*from   ww w .  ja  v  a 2 s.  co  m*/
            resourceObj = (ResourceType) Class.forName(resourceTypeHandler).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            log.severe("Error occurred while resolving resource type: " + e.getMessage());
        }

        //read all init args
        Map<String, String> configArgs = new HashMap<>();
        ConfigurationNode node = resource.getRootNode();
        List<ConfigurationNode> attrs = node.getAttributes();

        for (ConfigurationNode attr : attrs) {
            configArgs.put(attr.getName(), attr.getValue().toString());
        }

        //initialize the resource with config args
        resourceObj.init(configArgs);

        //add it to the sequence
        sequence.add(resourceObj);
    }

    return sequence;
}

From source file:org.yamj.core.tools.CountryXmlTools.java

@PostConstruct
public void init() {
    String countryFileName = PropertyTools.getProperty("yamj3.country.fileName");
    if (StringUtils.isBlank(countryFileName)) {
        LOG.trace("No valid country file name configured");
        return;//from  w  w w  .j  a v  a2 s .  co m
    }
    if (!StringUtils.endsWithIgnoreCase(countryFileName, "xml")) {
        LOG.warn("Invalid country file name specified: {}", countryFileName);
        return;
    }

    File xmlFile;
    if (StringUtils.isBlank(FilenameUtils.getPrefix(countryFileName))) {
        // relative path given
        String path = System.getProperty("yamj3.home");
        if (StringUtils.isEmpty(path)) {
            path = ".";
        }
        xmlFile = new File(FilenameUtils.concat(path, countryFileName));
    } else {
        // absolute path given
        xmlFile = new File(countryFileName);
    }

    if (!xmlFile.exists() || !xmlFile.isFile()) {
        LOG.warn("Countries file does not exist: {}", xmlFile.getPath());
        return;
    }
    if (!xmlFile.canRead()) {
        LOG.warn("Countries file not readble: {}", xmlFile.getPath());
        return;
    }

    LOG.debug("Initialize countries from file: {}", xmlFile.getPath());

    try {
        XMLConfiguration c = new XMLConfiguration(xmlFile);

        List<HierarchicalConfiguration> countries = c.configurationsAt("country");
        for (HierarchicalConfiguration country : countries) {
            String masterCountry = country.getString("[@name]");
            List<Object> subCountries = country.getList("subcountry");
            for (Object subCountry : subCountries) {
                LOG.debug("New genre added to map: {} -> {}", subCountry, masterCountry);
                COUNTRIES_MAP.put(((String) subCountry).toLowerCase(), masterCountry);
            }
        }

        try {
            this.commonStorageService.updateCountriesXml(COUNTRIES_MAP);
        } catch (Exception ex) {
            LOG.warn("Failed update countries xml in database", ex);
        }
    } catch (Exception ex) {
        LOG.error("Failed parsing country input file: " + xmlFile.getPath(), ex);
    }
}

From source file:org.yamj.core.tools.GenreXmlTools.java

@PostConstruct
public void init() {
    String genreFileName = PropertyTools.getProperty("yamj3.genre.fileName");
    if (StringUtils.isBlank(genreFileName)) {
        LOG.trace("No valid genre file name configured");
        return;//ww  w. j a v  a2s .co  m
    }
    if (!StringUtils.endsWithIgnoreCase(genreFileName, "xml")) {
        LOG.warn("Invalid genre file name specified: {}", genreFileName);
        return;
    }

    File xmlFile;
    if (StringUtils.isBlank(FilenameUtils.getPrefix(genreFileName))) {
        // relative path given
        String path = System.getProperty("yamj3.home");
        if (StringUtils.isEmpty(path)) {
            path = ".";
        }
        xmlFile = new File(FilenameUtils.concat(path, genreFileName));
    } else {
        // absolute path given
        xmlFile = new File(genreFileName);
    }

    if (!xmlFile.exists() || !xmlFile.isFile()) {
        LOG.warn("Genres file does not exist: {}", xmlFile.getPath());
        return;
    }
    if (!xmlFile.canRead()) {
        LOG.warn("Genres file not readble: {}", xmlFile.getPath());
        return;
    }

    LOG.debug("Initialize genres from file: {}", xmlFile.getPath());

    try {
        XMLConfiguration c = new XMLConfiguration(xmlFile);

        List<HierarchicalConfiguration> genres = c.configurationsAt("genre");
        for (HierarchicalConfiguration genre : genres) {
            String masterGenre = genre.getString("[@name]");
            List<Object> subGenres = genre.getList("subgenre");
            for (Object subGenre : subGenres) {
                LOG.debug("New genre added to map: {} -> {}", subGenre, masterGenre);
                GENRES_MAP.put(((String) subGenre).toLowerCase(), masterGenre);
            }
        }

        try {
            this.commonStorageService.updateGenresXml(GENRES_MAP);
        } catch (Exception ex) {
            LOG.warn("Failed update genres xml in database", ex);
        }
    } catch (Exception ex) {
        LOG.error("Failed parsing genre input file: " + xmlFile.getPath(), ex);
    }
}

From source file:org.zaproxy.zap.control.ZapVersionsAddOnEntry.java

@Override
protected void readAdditionalData(HierarchicalConfiguration zapAddOnData) {
    status = zapAddOnData.getString(STATUS);
    file = zapAddOnData.getString(FILE);
    size = zapAddOnData.getLong(SIZE);/*from  w w w  . j  a  va  2 s  .  c o  m*/
    info = zapAddOnData.getString(INFO);
    hash = zapAddOnData.getString(HASH, null);
}

From source file:org.zaproxy.zap.extension.proxies.ProxiesParam.java

@Override
protected void parse() {
    try {//from w w  w  . j  av a  2s .  c  om
        List<HierarchicalConfiguration> fields = ((HierarchicalConfiguration) getConfig())
                .configurationsAt(ALL_PROXIES_KEY);
        this.proxies = new ArrayList<>(fields.size() + 1);

        for (HierarchicalConfiguration sub : fields) {
            this.proxies.add(new ProxiesParamProxy(sub.getString(PROXY_ADDRESS_KEY), sub.getInt(PROXY_PORT_KEY),
                    sub.getBoolean(PROXY_ENABLED_KEY, true), sub.getBoolean(PROXY_ANY_LOCAL_KEY),
                    sub.getBoolean(PROXY_REM_UNSUPPORTED), sub.getBoolean(PROXY_DECODE_KEY),
                    sub.getBoolean(PROXY_BEHIND_NAT_KEY)));
        }
    } catch (ConversionException e) {
        logger.error("Error while loading proxies: " + e.getMessage(), e);
    }

    this.confirmRemoveProxy = getBoolean(CONFIRM_REMOVE_PROXY_KEY, true);
}

From source file:pl.psnc.synat.wrdz.mdz.config.MdzConfiguration.java

/**
 * Reads the configuration form the {@value #CONFIG_FILE} file.
 *///from www. j av a  2  s.co  m
@PostConstruct
protected void init() {
    try {
        XMLConfiguration config = new XMLConfiguration(CONFIG_FILE);
        checkFormats = config.getBoolean(FORMAT_ENABLED, true);
        checkIntegrity = config.getBoolean(INTEGRITY_ENABLED, true);
        analyzeMasterObjectFileFormats = config.getBoolean(FORMAT_ANALYZE_MASTER, true);
        analyzeOptimizedObjectFileFormats = config.getBoolean(FORMAT_ANALYZE_OPTIMIZED, false);
        analyzeConvertedObjectFileFormats = config.getBoolean(FORMAT_ANALYZE_CONVERTED, false);
        formatWorkerAlwaysActive = config.getBoolean(FORMAT_WORKER_ALWAYS_ACTIVE, false);
        formatWorkerActivationSchedule = readSchedule(config.subset(FORMAT_WORKER_ACTIVATION_SCHEDULE));
        formatWorkerDeactivationSchedule = readSchedule(config.subset(FORMAT_WORKER_DEACTIVATION_SCHEDULE));
        formatWorkInitializerSchedule = readSchedule(config.subset(FORMAT_INITIALIZER_SCHEDULE));
        formatVerifierThreshold = config.getInt(FORMAT_VERIFIER_THRESHOLD);
        integrityWorkerActivationSchedule = readSchedule(config.subset(INTEGRITY_WORKER_ACTIVATION_SCHEDULE));
        integrityWorkerDeactivationSchedule = readSchedule(
                config.subset(INTEGRITY_WORKER_DEACTIVATION_SCHEDULE));
        zmdObjectUrl = config.getString(INTEGRITY_ZMD_OBJECT_URL);

        plugins = new ArrayList<PluginInfo>();

        @SuppressWarnings("unchecked")
        List<HierarchicalConfiguration> pluginConfigs = config.configurationsAt(PLUGINS);
        for (HierarchicalConfiguration pluginConfig : pluginConfigs) {
            String name = pluginConfig.getString(PLUGIN_NAME);
            String clazz = pluginConfig.getString(PLUGIN_CLASS);

            VerificationPlugin plugin;
            try {
                plugin = (VerificationPlugin) Class.forName(clazz).newInstance();
            } catch (ClassNotFoundException e) {
                logger.warn("Could not load the plugin class", e);
                continue;
            } catch (InstantiationException e) {
                logger.warn("Could not load the plugin class", e);
                continue;
            } catch (IllegalAccessException e) {
                logger.warn("Could not load the plugin class", e);
                continue;
            } catch (ClassCastException e) {
                logger.warn("Could not load the plugin class", e);
                continue;
            }

            ScheduleExpression activationSchedule = readSchedule(
                    pluginConfig.subset(PLUGIN_ACTIVATION_SCHEDULE));
            ScheduleExpression deactivationSchedule = readSchedule(
                    pluginConfig.subset(PLUGIN_DEACTIVATION_SCHEDULE));

            plugins.add(new PluginInfo(name, plugin, activationSchedule, deactivationSchedule));
        }

        plugins = Collections.unmodifiableList(plugins);

    } catch (ConfigurationException e) {
        throw new WrdzConfigurationError("Error while loading the MDZ configuration.", e);
    }
}

From source file:pl.psnc.synat.wrdz.zmkd.config.ZdtConfiguration.java

/**
 * Creates the configuration object form the {@value #CONFIG_FILE} file.
 *///  w w  w . j  a  va2  s.  co  m
@PostConstruct
@SuppressWarnings("unchecked")
protected void init() {
    try {
        config = new XMLConfiguration(CONFIG_FILE);

        formatsByName = new HashMap<String, Format>();
        formatsByPlugin = new HashMap<Plugin, Set<Format>>();

        List<HierarchicalConfiguration> formats = config.configurationsAt("formats.format");
        for (HierarchicalConfiguration format : formats) {
            String name = format.getString("name");
            FormatType type = FormatType.valueOf(format.getString("type").toUpperCase());
            List<String> iris = format.getList("iri");

            List<String> plugins = format.getList("supported-by.plugin");
            EnumSet<Plugin> supportedBy = EnumSet.noneOf(Plugin.class);
            for (String plugin : plugins) {
                supportedBy.add(Plugin.valueOf(plugin));
            }

            formatsByName.put(name, new Format(name, type, iris, supportedBy));
        }

        for (Format format : formatsByName.values()) {
            for (Plugin plugin : format.getSupportedBy()) {
                if (!formatsByPlugin.containsKey(plugin)) {
                    formatsByPlugin.put(plugin, new HashSet<Format>());
                }
                formatsByPlugin.get(plugin).add(format);
            }
        }

        for (Entry<Plugin, Set<Format>> entry : formatsByPlugin.entrySet()) {
            entry.setValue(Collections.unmodifiableSet(entry.getValue()));
        }

    } catch (IllegalArgumentException e) {
        logger.error("Loading the configuration failed.", e);
        throw new WrdzConfigurationError(e);
    } catch (ConfigurationException e) {
        logger.error("Loading the configuration failed.", e);
        throw new WrdzConfigurationError(e);
    }
}

From source file:put.semantic.fcanew.ui.EntryImpl.java

public void load(File f) {
    try {// w w w.j  a v  a 2 s. c  o  m
        XMLConfiguration c = new XMLConfiguration();
        c.setDelimiterParsingDisabled(true);
        c.load(f);
        endpoint = c.getString("mappings.endpoint");
        prefixes = c.getString("mappings.prefixes");
        for (HierarchicalConfiguration m : c.configurationsAt("mappings.mapping")) {
            String attr = m.getString("attribute");
            for (EntryImpl e : entries) {
                if (attr.equals(e.getAttribute().toString())) {
                    e.setPattern(m.getString("pattern"));
                }
            }
        }
        tableModel.fireTableDataChanged();
    } catch (ConfigurationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:uk.ac.ebi.arrayexpress.components.DbConnectionPool.java

public void initialize() throws Exception {
    HierarchicalConfiguration connsConf = (HierarchicalConfiguration) getPreferences()
            .getConfSubset("bs.db.connections");
    if (null != connsConf) {
        List conns = connsConf.configurationsAt("connection");
        for (Object conn : conns) {
            HierarchicalConfiguration connConf = (HierarchicalConfiguration) conn;
            String connName = connConf.getString("name");
            logger.debug("Configuring pool for connection [{}]", connName);
            try {
                Class.forName(connConf.getString("driver"));
            } catch (ClassNotFoundException x) {
                logger.error("Unable to load driver [{}] for connection [{}]", connConf.getString("driver"),
                        connName);//from   w ww.j  a  v  a  2s .com
            }

            BoneCPConfig cpConf = new BoneCPConfig();
            cpConf.setJdbcUrl(connConf.getString("url"));
            cpConf.setUsername(connConf.getString("username"));
            cpConf.setPassword(connConf.getString("password"));
            cpConf.setConnectionTestStatement(connConf.getString("testStatement"));
            cpConf.setMinConnectionsPerPartition(connConf.getInt("minConnections"));
            cpConf.setMaxConnectionsPerPartition(connConf.getInt("maxConnections"));
            cpConf.setPartitionCount(1);
            this.configs.put(connName, cpConf);
        }
    }
}

From source file:uk.ac.ebi.arrayexpress.components.SetupDirectoryCheck.java

public void initialize() throws Exception {
    HierarchicalConfiguration connsConf = (HierarchicalConfiguration) Application.getInstance().getPreferences()
            .getConfSubset("bs");

    String emailError = "";

    if (null != connsConf) {
        setupDirectory = connsConf.getString("setupDirectory");
        globalSetupDirectory = connsConf.getString("globalSetupDirectory");
        globalSetupLuceneDirectory = connsConf.getString("globalSetupLuceneDirectory");
        backupDirectory = connsConf.getString("backupDirectory");

        logger.debug("setupDirectory->" + setupDirectory);
        logger.debug("globalSetupLuceneDirectory->" + globalSetupLuceneDirectory);
        logger.debug("backupDirectory->" + backupDirectory);
    } else {//from  w w  w  .  j a  v  a2s  . co m
        logger.error("bs Configuration is missing!!");
    }
    try {
        File fileSetup = new File(setupDirectory);
        File fileGlobalSetupLucene = new File(
                globalSetupDirectory + File.separator + globalSetupLuceneDirectory);
        logger.debug("fileGlobalSetup->" + fileGlobalSetupLucene.getAbsolutePath());
        if (!fileGlobalSetupLucene.exists()) {
            this.getApplication().sendEmail(null, null, "BIOSAMPLES: ##### INITIALIZATION WARNING #######",
                    "The globalSetupLuceneDirectory doesnt exist and it can cause problems (temporary directories removed during the servers restart)");
        }

        // Now I will try the backupdirectory
        File fileBackup = new File(backupDirectory);
        if (!fileBackup.exists()) {
            emailError += "The backupDirectory (" + backupDirectory + ") doesnt exist!!!! ERROR\n";
            FileUtils.forceMkdir(fileBackup);
        }

        // setupDirectory test
        boolean exists = fileSetup.exists();
        if (!exists) {
            // send an email warning and copy it from a globalSetupDirectory
            emailError = "The Setup directory does not exist (" + setupDirectory + ")\n";
            if (fileGlobalSetupLucene.exists()) {
                emailError += "The Setup directory is being populated with the data from globalSetupLuceneDirectory ("
                        + globalSetupLuceneDirectory + ")\n";
                // FileUtils.copyDirectoryToDirectory(fileGlobalSetup,
                // fileSetupPreviousDirectory); (this also copies the own
                // directores
                FileUtilities.copyFolder(fileGlobalSetupLucene, fileSetup);

            } else {
                emailError += "The globalSetupLuceneDirectory (" + globalSetupLuceneDirectory
                        + ") also doesnt exist!!!! ERROR\n";
            }
            this.getApplication().sendEmail(null, null, "BIOSAMPLES: ##### INITIALIZATION ERROR #######",
                    emailError);
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        this.getApplication().sendEmail(null, null, "BIOSAMPLES: ##### INITIALIZATION ERROR #######",
                emailError);
        logger.error("Exception:->[{}]", e.getMessage());
        e.printStackTrace();
    }
}