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

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

Introduction

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

Prototype

public synchronized void load(Reader in) throws ConfigurationException 

Source Link

Document

Load the properties from the given reader.

Usage

From source file:com.kjt.service.common.SoafwConfigMojo.java

private PropertiesConfiguration load() throws MojoExecutionException {
    PropertiesConfiguration config = new PropertiesConfiguration();
    InputStream is = SoafwConfigMojo.class.getClassLoader()
            .getResourceAsStream("META-INF/config/template/template.properties");
    try {/* ww  w  .j  a  va  2s.  co  m*/
        config.load(is);
    } catch (ConfigurationException e) {
        throw new MojoExecutionException("?'template.properties'");
    }
    return config;
}

From source file:gobblin.util.PullFileLoader.java

/**
 * Load a {@link Properties} compatible path using fallback as fallback.
 * @return The {@link Config} in path with fallback as fallback.
 * @throws IOException/*from w  ww . ja  v  a  2s  .c o m*/
 */
private Config loadJavaPropsWithFallback(Path propertiesPath, Config fallback) throws IOException {

    PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
    try (InputStreamReader inputStreamReader = new InputStreamReader(this.fs.open(propertiesPath),
            Charsets.UTF_8)) {
        propertiesConfiguration.load(inputStreamReader);

        Config configFromProps = ConfigUtils
                .propertiesToConfig(ConfigurationConverter.getProperties(propertiesConfiguration));

        return ConfigFactory
                .parseMap(ImmutableMap.of(ConfigurationKeys.JOB_CONFIG_FILE_PATH_KEY,
                        PathUtils.getPathWithoutSchemeAndAuthority(propertiesPath).toString()))
                .withFallback(configFromProps).withFallback(fallback);
    } catch (ConfigurationException ce) {
        throw new IOException(ce);
    }
}

From source file:eu.trentorise.game.managers.DroolsEngine.java

private StatelessKieSession loadGameConstants(StatelessKieSession kSession, String gameId) {

    // load game constants
    InputStream constantsFileStream = null;
    Game g = gameSrv.loadGameDefinitionById(gameId);
    if (g != null && g.getRules() != null) {
        for (String ruleUrl : g.getRules()) {
            Rule r = gameSrv.loadRule(gameId, ruleUrl);
            if ((r != null && r.getName() != null && r.getName().equals("constants"))
                    || r instanceof UrlRule && ((UrlRule) r).getUrl().contains("constants")) {
                try {
                    constantsFileStream = r.getInputStream();
                } catch (IOException e) {
                    logger.error("Exception loading constants file", e);
                }//  w  w  w .j av a2s  . c  o m
            }
        }
    }

    if (constantsFileStream != null) {
        try {
            PropertiesConfiguration constants = new PropertiesConfiguration();
            constants.load(constantsFileStream);
            constants.setListDelimiter(',');
            logger.debug("constants file loaded for game {}", gameId);
            Iterator<String> constantsIter = constants.getKeys();
            while (constantsIter.hasNext()) {
                String constant = constantsIter.next();
                kSession.setGlobal(constant, numberConversion(constants.getProperty(constant)));
                logger.debug("constant {} loaded", constant);
            }
        } catch (ConfigurationException e) {
            logger.error("constants loading exception");
        }
    } else {
        logger.info("Rule constants file not found");
    }
    return kSession;
}

From source file:com.qmetry.qaf.automation.util.PropertyUtil.java

private boolean loadFile(File file) {
    try {/*from   w w  w  .  j a v  a  2 s.  c  o m*/
        if (file.getName().endsWith("xml") || file.getName().contains(".xml.")) {
            super.load(new FileInputStream(file));
            XMLConfiguration xmlConfiguration = new XMLConfiguration(file);
            copy(xmlConfiguration);
            xmlConfiguration.clear();
        } else {
            PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
            propertiesConfiguration
                    .setEncoding(getString(ApplicationProperties.LOCALE_CHAR_ENCODING.key, "UTF-8"));
            propertiesConfiguration.load(new FileInputStream(file));
            copy(propertiesConfiguration);
            propertiesConfiguration.clear();
            // super.load(new FileInputStream(file));
        }
        return true;
    } catch (ConfigurationException e) {
        logger.error(e.getMessage());
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
    }

    return false;
}

From source file:com.aol.advertising.qiao.config.AgentXmlConfiguration.java

/**
 * Load configuration file and interpolate variables. Note that due to the
 * way Apache Commons Configuration treats property keys, user should avoid
 * using dot ('.') in the property key. Otherwise ACC may not substitute
 * some value if the variable contains valid element name(s).
 *
 * @param xmlConfigFile/*  ww w. j a va  2 s. c o  m*/
 * @param propConfigFiles
 * @return
 * @throws ConfigurationException
 */
protected HierarchicalConfiguration readConfigurationFiles(String xmlConfigFile, String propConfigFiles)
        throws ConfigurationException {
    try {
        // convert URI to URL
        URL[] prop_urls = null;
        URL xml_url = CommonUtils.uriToURL(xmlConfigFile);
        if (propConfigFiles != null) {
            String[] prop_files = propConfigFiles.split(",");
            prop_urls = new URL[prop_files.length];
            for (int i = 0; i < prop_files.length; i++) {
                prop_urls[i] = CommonUtils.uriToURL(prop_files[i]);
            }
        }

        // combine xml and properties configurations
        CombinedConfiguration combined_cfg = new CombinedConfiguration(new OverrideCombiner());

        XMLConfiguration cfg_xml = new XMLConfiguration();
        cfg_xml.setDelimiterParsingDisabled(true);
        cfg_xml.setAttributeSplittingDisabled(true);
        cfg_xml.load(xml_url);

        combined_cfg.addConfiguration(cfg_xml);

        if (prop_urls != null) {
            // properties in the earlier files take precedence if duplicate
            for (int i = 0; i < prop_urls.length; i++) {
                PropertiesConfiguration cfg_props = new PropertiesConfiguration();
                cfg_props.setDelimiterParsingDisabled(true);
                cfg_props.load(prop_urls[i]);

                combined_cfg.addConfiguration(cfg_props);

            }
        }

        HierarchicalConfiguration config = (HierarchicalConfiguration) combined_cfg.interpolatedConfiguration(); // !!! resolve variables

        return config;
    } catch (Exception e) {
        throw new ConfigurationException(e.getMessage(), e);
    }

}

From source file:com.liferay.ide.project.core.tests.UpgradeLiferayProjectsOpTests.java

private void checkProperties(IFile file, String propertyName, String propertiesValue) {
    try {/* w  ww .j  a v  a 2  s  .  c om*/
        File osfile = new File(file.getLocation().toOSString());
        PropertiesConfiguration pluginPackageProperties = new PropertiesConfiguration();
        pluginPackageProperties.load(osfile);
        String value = (String) pluginPackageProperties.getProperty(propertyName);
        assertTrue(value.contains(propertiesValue));
        file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
    } catch (Exception e) {
        ProjectCore.logError(e);
    }
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void mergePortalProperties(String portalWebDir, ServletContext servletContext) throws Exception {
    URL pluginPropsURL = servletContext
            .getResource("WEB-INF/ext-web/docroot/WEB-INF/classes/portal-ext.properties");
    if (pluginPropsURL == null) {
        if (_log.isDebugEnabled()) {
            _log.debug("Ext Plugin's portal-ext.properties not found");
        }/*from   www. j  a v a  2s. c om*/
        return;
    }
    if (_log.isDebugEnabled()) {
        _log.debug("Loading portal-ext.properties from " + pluginPropsURL);
    }
    PropertiesConfiguration pluginProps = new PropertiesConfiguration(pluginPropsURL);

    PropertiesConfiguration portalProps = new PropertiesConfiguration(
            this.getClass().getClassLoader().getResource("portal.properties"));

    File extPluginPropsFile = new File(portalWebDir + "WEB-INF/classes/portal-ext-plugin.properties");
    PropertiesConfiguration extPluginPortalProps = new PropertiesConfiguration();
    if (extPluginPropsFile.exists()) {
        extPluginPortalProps.load(extPluginPropsFile);
    }

    for (Iterator it = pluginProps.getKeys(); it.hasNext();) {
        String key = (String) it.next();
        List value = pluginProps.getList(key);
        if (key.endsWith("+")) {
            key = key.substring(0, key.length() - 1);
            List newValue = new ArrayList();
            if (extPluginPortalProps.containsKey(key)) {
                // already rewrited
                newValue.addAll(extPluginPortalProps.getList(key));
            } else {
                newValue.addAll(portalProps.getList(key));
            }

            newValue.addAll(value);
            extPluginPortalProps.setProperty(key, newValue);
        } else {
            extPluginPortalProps.setProperty(key, value);
        }
    }

    extPluginPortalProps.save(extPluginPropsFile);
}

From source file:com.mirth.connect.client.ui.SettingsPanelMap.java

public void doImportMap() {
    File file = getFrame().browseForFile("PROPERTIES");

    if (file != null) {
        try {//from www.j  ava2 s.co m
            PropertiesConfiguration properties = new PropertiesConfiguration();
            properties.setDelimiterParsingDisabled(true);
            properties.setListDelimiter((char) 0);
            properties.load(file);

            Map<String, ConfigurationProperty> configurationMap = new HashMap<String, ConfigurationProperty>();
            Iterator<String> iterator = properties.getKeys();

            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = properties.getString(key);
                String comment = properties.getLayout().getCanonicalComment(key, false);

                configurationMap.put(key, new ConfigurationProperty(value, comment));
            }

            updateConfigurationTable(configurationMap);
            setSaveEnabled(true);
        } catch (Exception e) {
            getFrame().alertThrowable(getFrame(), e, "Error importing configuration map");
        }
    }
}

From source file:com.nesscomputing.migratory.mojo.database.AbstractDatabaseMojo.java

@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
    ConfigureLog4j.start(this);

    try {/*www  . j  a v a  2  s  .  com*/
        // Load the default manifest information.
        //
        final CombinedConfiguration config = new CombinedConfiguration(new OverrideCombiner());
        // everything can be overridden by system properties.
        config.addConfiguration(new SystemConfiguration(), "systemProperties");

        final String userHome = System.getProperty("user.home");
        if (userHome != null) {
            final File propertyFile = new File(userHome, MIGRATORY_PROPERTIES_FILE);
            if (propertyFile.exists() && propertyFile.canRead() && propertyFile.isFile()) {
                config.addConfiguration(new PropertiesConfiguration(propertyFile));
            }
        }

        final ConfigurationObjectFactory initialConfigFactory = new ConfigurationObjectFactory(
                new CommonsConfigSource(config));

        // Load the initial config from the local config file
        this.initialConfig = initialConfigFactory.build(InitialConfig.class);

        if (this.manifestUrl == null) {
            this.manifestUrl = initialConfig.getManifestUrl();
        }

        if (this.manifestName == null) {
            this.manifestName = initialConfig.getManifestName();
        }

        if (manifestUrl == null) {
            throw new MojoExecutionException(
                    "no manifest url found (did you create a .migratory.properties file?)");
        }

        if (manifestName == null) {
            throw new MojoExecutionException(
                    "no manifest name found (did you create a .migratory.properties file?)");
        }

        LOG.debug("Manifest URL:      %s", manifestUrl);
        LOG.debug("Manifest Name:     %s", manifestName);

        this.optionList = parseOptions(options);

        final StringBuilder location = new StringBuilder(manifestUrl);
        if (!this.manifestUrl.endsWith("/")) {
            location.append("/");
        }

        // After here, the manifestUrl is guaranteed to have a / at the end!
        this.manifestUrl = location.toString();

        location.append(manifestName);
        location.append(".manifest");

        LOG.debug("Manifest Location: %s", location);

        final MigratoryConfig initialMigratoryConfig = initialConfigFactory.build(MigratoryConfig.class);
        final LoaderManager initialLoaderManager = createLoaderManager(initialMigratoryConfig);
        final String contents = initialLoaderManager.loadFile(URI.create(location.toString()));

        if (contents == null) {
            throw new MojoExecutionException(
                    format("Could not load manifest '%s' from '%s'", manifestName, manifestUrl));
        }

        //
        // Now add the contents of the manifest file to the configuration creating the
        // final configuration for building the sql migration sets.
        //
        final PropertiesConfiguration pc = new PropertiesConfiguration();
        pc.load(new StringReader(contents));
        config.addConfiguration(pc);

        if (!validateConfiguration(config)) {
            throw new MojoExecutionException(
                    format("Manifest '%s' is not valid. Refusing to execute!", manifestName));
        }

        this.config = config;
        this.factory = new ConfigurationObjectFactory(new CommonsConfigSource(config));
        this.migratoryConfig = factory.build(MigratoryConfig.class);
        this.loaderManager = createLoaderManager(migratoryConfig);

        LOG.debug("Configuration: %s", this.config);

        this.rootDBIConfig = getDBIConfig(getPropertyName("default.root_"));

        stateCheck();

        doExecute();
    } catch (Exception e) {
        Throwables.propagateIfInstanceOf(e, MojoExecutionException.class);

        LOG.errorDebug(e, "While executing Mojo %s", this.getClass().getSimpleName());
        throw new MojoExecutionException("Failure:", e);
    } finally {
        ConfigureLog4j.stop(this);
    }
}

From source file:com.mirth.connect.server.servlets.WebStartServlet.java

private Document getAdministratorJnlp(HttpServletRequest request) throws Exception {
    InputStream is = ResourceUtil.getResourceStream(this.getClass(), "mirth-client.jnlp");
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    IOUtils.closeQuietly(is);/*from   www. jav a  2 s.c o m*/

    Element jnlpElement = document.getDocumentElement();

    // Change the title to include the version of Mirth Connect
    PropertiesConfiguration versionProperties = new PropertiesConfiguration();
    versionProperties.setDelimiterParsingDisabled(true);
    versionProperties.load(ResourceUtil.getResourceStream(getClass(), "version.properties"));
    String version = versionProperties.getString("mirth.version");

    Element informationElement = (Element) jnlpElement.getElementsByTagName("information").item(0);
    Element title = (Element) informationElement.getElementsByTagName("title").item(0);
    String titleText = title.getTextContent() + " " + version;

    // If a server name is set, prepend the application title with it
    String serverName = configurationController.getServerSettings().getServerName();
    if (StringUtils.isNotBlank(serverName)) {
        titleText = serverName + " - " + titleText;
    }

    title.setTextContent(titleText);

    String scheme = request.getScheme();
    String serverHostname = request.getServerName();
    int serverPort = request.getServerPort();
    String contextPath = request.getContextPath();
    String codebase = scheme + "://" + serverHostname + ":" + serverPort + contextPath;

    PropertiesConfiguration mirthProperties = new PropertiesConfiguration();
    mirthProperties.setDelimiterParsingDisabled(true);
    mirthProperties.load(ResourceUtil.getResourceStream(getClass(), "mirth.properties"));

    String server = null;

    if (StringUtils.isNotBlank(mirthProperties.getString("server.url"))) {
        server = mirthProperties.getString("server.url");
    } else {
        int httpsPort = mirthProperties.getInt("https.port", 8443);
        String contextPathProp = mirthProperties.getString("http.contextpath", "");

        // Add a starting slash if one does not exist
        if (!contextPathProp.startsWith("/")) {
            contextPathProp = "/" + contextPathProp;
        }

        // Remove a trailing slash if one exists
        if (contextPathProp.endsWith("/")) {
            contextPathProp = contextPathProp.substring(0, contextPathProp.length() - 1);
        }

        server = "https://" + serverHostname + ":" + httpsPort + contextPathProp;
    }

    jnlpElement.setAttribute("codebase", codebase);

    Element resourcesElement = (Element) jnlpElement.getElementsByTagName("resources").item(0);

    String maxHeapSize = request.getParameter("maxHeapSize");
    if (StringUtils.isBlank(maxHeapSize)) {
        maxHeapSize = mirthProperties.getString("administrator.maxheapsize");
    }
    if (StringUtils.isNotBlank(maxHeapSize)) {
        Element j2se = (Element) resourcesElement.getElementsByTagName("j2se").item(0);
        j2se.setAttribute("max-heap-size", maxHeapSize);
    }

    List<String> defaultClientLibs = new ArrayList<String>();
    defaultClientLibs.add("mirth-client.jar");
    defaultClientLibs.add("mirth-client-core.jar");
    defaultClientLibs.add("mirth-crypto.jar");
    defaultClientLibs.add("mirth-vocab.jar");

    for (String defaultClientLib : defaultClientLibs) {
        Element jarElement = document.createElement("jar");
        jarElement.setAttribute("download", "eager");
        jarElement.setAttribute("href", "webstart/client-lib/" + defaultClientLib);

        if (defaultClientLib.equals("mirth-client.jar")) {
            jarElement.setAttribute("main", "true");
        }

        resourcesElement.appendChild(jarElement);
    }

    List<String> clientLibs = ControllerFactory.getFactory().createExtensionController().getClientLibraries();

    for (String clientLib : clientLibs) {
        if (!defaultClientLibs.contains(clientLib)) {
            Element jarElement = document.createElement("jar");
            jarElement.setAttribute("download", "eager");
            jarElement.setAttribute("href", "webstart/client-lib/" + clientLib);
            resourcesElement.appendChild(jarElement);
        }
    }

    List<MetaData> allExtensions = new ArrayList<MetaData>();
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getConnectorMetaData().values());
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getPluginMetaData().values());

    // we are using a set so that we don't have duplicates
    Set<String> extensionPathsToAddToJnlp = new HashSet<String>();

    for (MetaData extension : allExtensions) {
        if (doesExtensionHaveClientOrSharedLibraries(extension)) {
            extensionPathsToAddToJnlp.add(extension.getPath());
        }
    }

    for (String extensionPath : extensionPathsToAddToJnlp) {
        Element extensionElement = document.createElement("extension");
        extensionElement.setAttribute("href", "webstart/extensions/" + extensionPath + ".jnlp");
        resourcesElement.appendChild(extensionElement);
    }

    Element applicationDescElement = (Element) jnlpElement.getElementsByTagName("application-desc").item(0);
    Element serverArgumentElement = document.createElement("argument");
    serverArgumentElement.setTextContent(server);
    applicationDescElement.appendChild(serverArgumentElement);
    Element versionArgumentElement = document.createElement("argument");
    versionArgumentElement.setTextContent(version);
    applicationDescElement.appendChild(versionArgumentElement);

    String[] protocols = configurationController.getHttpsClientProtocols();
    String[] cipherSuites = configurationController.getHttpsCipherSuites();

    // Only add arguments for the protocols / cipher suites if they are non-default
    if (!Arrays.areEqual(protocols, MirthSSLUtil.DEFAULT_HTTPS_CLIENT_PROTOCOLS)
            || !Arrays.areEqual(cipherSuites, MirthSSLUtil.DEFAULT_HTTPS_CIPHER_SUITES)) {
        Element sslArgumentElement = document.createElement("argument");
        sslArgumentElement.setTextContent("-ssl");
        applicationDescElement.appendChild(sslArgumentElement);

        Element protocolsArgumentElement = document.createElement("argument");
        protocolsArgumentElement.setTextContent(StringUtils.join(protocols, ','));
        applicationDescElement.appendChild(protocolsArgumentElement);

        Element cipherSuitesArgumentElement = document.createElement("argument");
        cipherSuitesArgumentElement.setTextContent(StringUtils.join(cipherSuites, ','));
        applicationDescElement.appendChild(cipherSuitesArgumentElement);
    }

    return document;
}