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.aurel.track.dbase.HandleHome.java

/**
 * Obtain the Torque.properties from TRACKPLUS_HOME or if not available from the WAR.
 * @return/*from   ww w  .  j  a v a2s .  c  om*/
 */
public static PropertiesConfiguration getTrackplusHomePropFile(String propFile) {
    PropertiesConfiguration pc = null;
    File props = null;
    InputStream in = null;
    String trackplusHome = HandleHome.getTrackplus_Home();
    try {
        // First check if we have a configuration file pointed to by the environment
        if (trackplusHome != null && !"".equals(trackplusHome)) {
            String fileName = trackplusHome + File.separator + propFile;
            props = new File(fileName);
            LOGGER.debug("Read file " + fileName);
            if (props.exists() && props.canRead()) {
                LOGGER.info("Retrieving configuration from " + fileName);
                in = new FileInputStream(props);
                pc = new PropertiesConfiguration();
                pc.load(in);
                in.close();
            }
        }
    } catch (Exception e) {
        LOGGER.error("Could not read " + propFile + " from TRACKPLUS_HOME " + trackplusHome + ". Exiting. "
                + e.getMessage());
    }
    return pc;
}

From source file:com.aurel.track.ApplicationStarter.java

private void setVersionFromVersionProperties(ServletContext servletContext) {
    ApplicationBean applicationBean = ApplicationBean.getInstance();
    String appTypeString = "";
    Integer appType = -1;//ww w . jav a2  s  .  c om
    String theVersion = "";
    String theBuild = "";
    String theVersionDate = "";
    Integer theVersionNo = 370;
    try {
        URL versionURL = servletContext.getResource("/WEB-INF/Version.properties");
        PropertiesConfiguration vcfg = new PropertiesConfiguration();
        InputStream in = versionURL.openStream();
        vcfg.load(in);
        theVersion = (String) vcfg.getProperty("version");
        theBuild = (String) vcfg.getProperty("build");
        if (theVersion == null) {
            theVersion = "4.X";
        }
        if (theBuild == null) {
            theBuild = "1";
        }
        theVersionDate = (String) vcfg.getProperty("date");
        if (theVersionDate == null) {
            theVersionDate = "2015-01-01";
        }
        theVersionNo = new Integer((String) vcfg.getProperty("app.version"));
        try {
            appType = new Integer((String) vcfg.getProperty("ntype"));
        } catch (Exception e) {
            appType = ApplicationBean.APPTYPE_FULL;
        }

        appTypeString = (String) vcfg.getProperty("type");
        if (appTypeString == null) {
            appTypeString = "Genji";
        }
    } catch (Exception e) {
        theVersion = "1.x";
        theBuild = "0";
        theVersionDate = "2015-01-01";
    }
    applicationBean.setServletContext(servletContext);
    applicationBean.setVersion(theVersion);
    applicationBean.setVersionNo(theVersionNo);
    applicationBean.setBuild(theBuild);
    applicationBean.setVersionDate(theVersionDate);
    applicationBean.setAppType(appType);
    applicationBean.setAppTypeString(appTypeString);

}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

public void migrateKeystore() {
    PropertiesConfiguration properties = new PropertiesConfiguration();
    properties.setDelimiterParsingDisabled(true);

    try {//w  w w  .j a  v  a  2 s .  c o m
        if (getProperty(PROPERTIES_CORE, "encryption.key") != null) {
            // load the keystore path and passwords
            properties.load(ResourceUtil.getResourceStream(this.getClass(), "mirth.properties"));
            File keyStoreFile = new File(properties.getString("keystore.path"));
            char[] keyStorePassword = properties.getString("keystore.storepass").toCharArray();
            char[] keyPassword = properties.getString("keystore.keypass").toCharArray();

            // delete the old JKS keystore
            keyStoreFile.delete();

            // create and load a new one as type JCEKS
            KeyStore keyStore = KeyStore.getInstance("JCEKS");
            keyStore.load(null, keyStorePassword);

            // deserialize the XML secret key to an Object
            ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
            String xml = getProperty(PROPERTIES_CORE, "encryption.key");

            /*
             * This is a fix to account for an error that occurred when testing migration from
             * version 1.8.2 to 3.0.0. The key was serialized as an instance of
             * com.sun.crypto.provider.DESedeKey, but fails to correctly deserialize as an
             * instance of java.security.KeyRep. The fix below extracts the "<default>" node
             * from the serialized xml and uses that to deserialize to java.security.KeyRep.
             * (MIRTH-2552)
             */
            Document document = new DocumentSerializer().fromXML(xml);
            DonkeyElement root = new DonkeyElement(document.getDocumentElement());
            DonkeyElement keyRep = root.getChildElement("java.security.KeyRep");

            if (keyRep != null) {
                DonkeyElement defaultElement = keyRep.getChildElement("default");

                if (defaultElement != null) {
                    defaultElement.setNodeName("java.security.KeyRep");
                    xml = defaultElement.toXml();
                }
            }

            SecretKey secretKey = serializer.deserialize(xml, SecretKey.class);

            // add the secret key entry to the new keystore
            KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey);
            keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword));

            // save the keystore to the filesystem
            OutputStream keyStoreOuputStream = new FileOutputStream(keyStoreFile);

            try {
                keyStore.store(keyStoreOuputStream, keyStorePassword);
            } finally {
                IOUtils.closeQuietly(keyStoreOuputStream);
            }

            // remove the property from CONFIGURATION
            removeProperty(PROPERTIES_CORE, "encryption.key");

            // reinitialize the security settings
            initializeSecuritySettings();
        }
    } catch (Exception e) {
        logger.error("Error migrating encryption key from database to keystore.", e);
    }
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

private void initialize() {
    try {//from   www  . j av  a  2s  .c o  m
        // Disable delimiter parsing so getString() returns the whole
        // property, even if there are commas
        mirthConfig.setDelimiterParsingDisabled(true);
        mirthConfig.setFile(new File(ClassPathResource.getResourceURI("mirth.properties")));
        mirthConfig.load();

        MigrationController.getInstance().migrateConfiguration(mirthConfig);

        // load the server version
        versionConfig.setDelimiterParsingDisabled(true);
        InputStream versionPropertiesStream = ResourceUtil.getResourceStream(this.getClass(),
                "version.properties");
        versionConfig.load(versionPropertiesStream);
        IOUtils.closeQuietly(versionPropertiesStream);

        if (mirthConfig.getString(PROPERTY_TEMP_DIR) != null) {
            File tempDataDirFile = new File(mirthConfig.getString(PROPERTY_TEMP_DIR));

            if (!tempDataDirFile.exists()) {
                if (tempDataDirFile.mkdirs()) {
                    logger.debug("created tempdir: " + tempDataDirFile.getAbsolutePath());
                } else {
                    logger.error("error creating tempdir: " + tempDataDirFile.getAbsolutePath());
                }
            }

            System.setProperty("java.io.tmpdir", tempDataDirFile.getAbsolutePath());
            logger.debug("set temp data dir: " + tempDataDirFile.getAbsolutePath());
        }

        File appDataDirFile = null;

        if (mirthConfig.getString(PROPERTY_APP_DATA_DIR) != null) {
            appDataDirFile = new File(mirthConfig.getString(PROPERTY_APP_DATA_DIR));

            if (!appDataDirFile.exists()) {
                if (appDataDirFile.mkdir()) {
                    logger.debug("created app data dir: " + appDataDirFile.getAbsolutePath());
                } else {
                    logger.error("error creating app data dir: " + appDataDirFile.getAbsolutePath());
                }
            }
        } else {
            appDataDirFile = new File(".");
        }

        appDataDir = appDataDirFile.getAbsolutePath();
        logger.debug("set app data dir: " + appDataDir);

        baseDir = new File(ClassPathResource.getResourceURI("mirth.properties")).getParentFile().getParent();
        logger.debug("set base dir: " + baseDir);

        if (mirthConfig.getString(CHARSET) != null) {
            System.setProperty(CHARSET, mirthConfig.getString(CHARSET));
        }

        String[] httpsClientProtocolsArray = mirthConfig.getStringArray(HTTPS_CLIENT_PROTOCOLS);
        if (ArrayUtils.isNotEmpty(httpsClientProtocolsArray)) {
            // Support both comma separated and multiline values
            List<String> httpsClientProtocolsList = new ArrayList<String>();
            for (String protocol : httpsClientProtocolsArray) {
                httpsClientProtocolsList.addAll(Arrays.asList(StringUtils.split(protocol, ',')));
            }
            httpsClientProtocols = httpsClientProtocolsList
                    .toArray(new String[httpsClientProtocolsList.size()]);
        } else {
            httpsClientProtocols = MirthSSLUtil.DEFAULT_HTTPS_CLIENT_PROTOCOLS;
        }

        String[] httpsServerProtocolsArray = mirthConfig.getStringArray(HTTPS_SERVER_PROTOCOLS);
        if (ArrayUtils.isNotEmpty(httpsServerProtocolsArray)) {
            // Support both comma separated and multiline values
            List<String> httpsServerProtocolsList = new ArrayList<String>();
            for (String protocol : httpsServerProtocolsArray) {
                httpsServerProtocolsList.addAll(Arrays.asList(StringUtils.split(protocol, ',')));
            }
            httpsServerProtocols = httpsServerProtocolsList
                    .toArray(new String[httpsServerProtocolsList.size()]);
        } else {
            httpsServerProtocols = MirthSSLUtil.DEFAULT_HTTPS_SERVER_PROTOCOLS;
        }

        String[] httpsCipherSuitesArray = mirthConfig.getStringArray(HTTPS_CIPHER_SUITES);
        if (ArrayUtils.isNotEmpty(httpsCipherSuitesArray)) {
            // Support both comma separated and multiline values
            List<String> httpsCipherSuitesList = new ArrayList<String>();
            for (String cipherSuite : httpsCipherSuitesArray) {
                httpsCipherSuitesList.addAll(Arrays.asList(StringUtils.split(cipherSuite, ',')));
            }
            httpsCipherSuites = httpsCipherSuitesList.toArray(new String[httpsCipherSuitesList.size()]);
        } else {
            httpsCipherSuites = MirthSSLUtil.DEFAULT_HTTPS_CIPHER_SUITES;
        }

        String deploy = String.valueOf(mirthConfig.getProperty(STARTUP_DEPLOY));
        if (StringUtils.isNotBlank(deploy)) {
            startupDeploy = Boolean.parseBoolean(deploy);
        }

        // Check for server GUID and generate a new one if it doesn't exist
        PropertiesConfiguration serverIdConfig = new PropertiesConfiguration(
                new File(getApplicationDataDir(), "server.id"));

        if ((serverIdConfig.getString("server.id") != null)
                && (serverIdConfig.getString("server.id").length() > 0)) {
            serverId = serverIdConfig.getString("server.id");
        } else {
            serverId = generateGuid();
            logger.debug("generated new server id: " + serverId);
            serverIdConfig.setProperty("server.id", serverId);
            serverIdConfig.save();
        }

        passwordRequirements = PasswordRequirementsChecker.getInstance().loadPasswordRequirements(mirthConfig);

        apiBypassword = mirthConfig.getString(API_BYPASSWORD);
        if (StringUtils.isNotBlank(apiBypassword)) {
            apiBypassword = new String(Base64.decodeBase64(apiBypassword), "US-ASCII");
        }

        statsUpdateInterval = NumberUtils.toInt(mirthConfig.getString(STATS_UPDATE_INTERVAL),
                DonkeyStatisticsUpdater.DEFAULT_UPDATE_INTERVAL);

        // Check for configuration map properties
        if (mirthConfig.getString(CONFIGURATION_MAP_PATH) != null) {
            configurationFile = mirthConfig.getString(CONFIGURATION_MAP_PATH);
        } else {
            configurationFile = getApplicationDataDir() + File.separator + "configuration.properties";
        }

        PropertiesConfiguration configurationMapProperties = new PropertiesConfiguration();
        configurationMapProperties.setDelimiterParsingDisabled(true);
        configurationMapProperties.setListDelimiter((char) 0);
        try {
            configurationMapProperties.load(new File(configurationFile));
        } catch (ConfigurationException e) {
            logger.warn("Failed to find configuration map file");
        }

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

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

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

        setConfigurationProperties(configurationMap, false);
    } catch (Exception e) {
        logger.error("Failed to initialize configuration controller", e);
    }
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

public TranslationData loadTranslationData(File transZipFile) throws IOException, ConfigurationException {
    TranslationData td = null;/*from  w  ww  .ja  va 2  s  .  c  o m*/
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(transZipFile);
        InputStream is = zipFile.getInputStream(new ZipEntry(ApplicationPath.TRANSLATION_DESC));
        if (is == null) {
            logger.warn("Will ignore invalid translation archive \"" + zipFile.getName() + "\".");
            return null;
        }
        Reader reader = new InputStreamReader(is, "UTF-8");
        PropertiesConfiguration pc = new PropertiesConfiguration();
        pc.load(reader);
        reader.close();
        is.close();

        td = new TranslationData();
        td.version = pc.getString(VERSION_ATTR);
        td.id = pc.getString(ID_ATTR);
        td.locale = new Locale(pc.getString(LANG_ATTR, "en"), pc.getString(COUNTRY_ATTR, "US"));
        td.encoding = pc.getString(ENCODING_ATTR, "ISO-8859-1");
        td.direction = pc.getString(DIRECTION_ATTR, "ltr");
        td.file = pc.getString(FILE_ATTR);
        td.name = pc.getString(NAME_ATTR);
        td.localizedName = pc.getString(LOCALIZED_NAME_ATTR, td.name);
        td.archiveFile = transZipFile;
        td.delimiter = pc.getString(LINE_DELIMITER_ATTR, "\n");
        String sig = pc.getString(SIGNATURE_ATTR);
        td.signature = sig == null ? null : Base64.decodeBase64(sig.getBytes("US-ASCII"));

        //create a LocalizedInstance for this translation.
        // <patch>
        LocalizedResource localizedResource = new LocalizedResource();
        localizedResource.loadLocalizedNames(pc, NAME_ATTR);
        localizedResource.setLanguage(td.locale.getLanguage());
        td.setLocalizedResource(localizedResource);
        td.setFile(transZipFile);
        // </patch>

        if (StringUtils.isBlank(td.id) || StringUtils.isBlank(td.name) || StringUtils.isBlank(td.file)
                || StringUtils.isBlank(td.version)) {
            logger.warn("Invalid translation: \"" + td + "\".");
            return null;
        }

        if (zipFile.getEntry(td.file) == null) {
            logger.warn("Invalid translation format. File not exists in the archive: " + td.file);
            return null;
        }
    } finally {
        if (zipFile != null) {
            ZipUtils.closeQuietly(zipFile);
        }
    }

    return td;
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

@SuppressWarnings("unchecked")
private void extractViewProps() {
    ThemeData td;/*from   w  w  w  . ja va  2 s  .  c  om*/
    Reader reader;
    String def = props.getString("theme.default");
    logger.info("Loading theme .properties files.");

    String[] paths = { ApplicationPath.THEME_DIR, Naming.getThemeDir() };
    for (int pathIndex = 0; pathIndex < paths.length; pathIndex++) {
        File targetThemeDir = new File(paths[pathIndex]);
        if (!targetThemeDir.exists()) {
            continue;
        }

        logger.info("Loading theme files info from \"" + paths[pathIndex]);
        File[] targetThemes = targetThemeDir.listFiles();

        File origThemeDir = new File(paths[pathIndex]);
        File[] origThemes = origThemeDir.listFiles();
        for (int i = 0; i < origThemes.length; i++) {
            String targetThemeDesc = Naming.getThemePropsDir() + "/" + origThemes[i].getName() + ".properties";
            File origThemeDesc = new File(origThemes[i] + "/" + ApplicationPath.THEME_DESC);
            File targetThemeFile = new File(targetThemeDesc);

            if (!origThemeDesc.exists()) {
                logger.warn("\"" + origThemes[i] + "\" is not a standard theme! Will ignore it.");
                continue;
            }

            try {
                if (!targetThemeFile.exists() || FileUtils.isFileNewer(origThemeDesc, targetThemeFile)) {
                    logger.info("Copy theme " + origThemes[i].getName() + " to " + Naming.getThemePropsDir());
                    FileUtils.copyFile(origThemeDesc, targetThemeFile);
                }
                FileInputStream fis = new FileInputStream(targetThemeFile);
                reader = new InputStreamReader(fis, "UTF-8");
                PropertiesConfiguration pc = new PropertiesConfiguration();
                pc.load(reader);
                reader.close();
                fis.close();

                td = new ThemeData();
                td.props = new LinkedHashMap<String, String>(); // order is important for options table!
                for (Iterator<String> iter = pc.getKeys(); iter.hasNext();) {
                    String key = iter.next();
                    td.props.put(key, CollectionUtils.toString(pc.getList(key), ", "));
                }
                td.author = pc.getString("author");
                td.name = pc.getString("name");
                td.version = pc.getString("version");
                td.id = origThemes[i].getName();
                td.fileName = targetThemeFile.getName();
                td.baseDir = paths[pathIndex];
                td.props.remove("author");
                td.props.remove("name");
                td.props.remove("version");

                // extractTransProps must be called before it!
                if (getTranslation().getDefault() != null) {
                    td.process(getTranslation().getDefault().locale.getLanguage());
                } else {
                    td.process("en");
                }

                theme.add(td);

                if (td.id.equals(def)) {
                    theme.setCurrent(td);
                }
            } catch (Exception e) {
                logger.warn("Can not load theme \"" + targetThemes[i].getName()
                        + "\", because of the following exception:");
                logger.log(e);
            }
        }
    }
    if (theme.getCurrent() == null) {
        logger.doFatal(new ZekrBaseException("Could not find default theme: " + def));
    }
}

From source file:br.com.bgslibrary.gui.MainFrame.java

private void load() {
    try {/*from   w ww  .j  av  a  2 s .c om*/
        PropertiesConfiguration pc = new PropertiesConfiguration();
        pc.load("bgslibrary_gui.properties");

        basePath = pc.getString("base.path");
        configPath = basePath + pc.getString("config.path");

        String paths[] = pc.getStringArray("run.path");
        loadConfigComboBox.setModel(new DefaultComboBoxModel(paths));

        String methods[] = pc.getStringArray("bgs.methods");
        tictocComboBox.setModel(new DefaultComboBoxModel(methods));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:ninja.utils.SwissKnife.java

/**
 * This is important: We load stuff as UTF-8.
 *
 * We are using in the default Apache Commons loading mechanism.
 *
 * With two little tweaks: 1. We don't accept any delimimter by default 2.
 * We are reading in UTF-8/*from  w ww .  ja  v a  2  s  .  co m*/
 *
 * More about that:
 * http://commons.apache.org/configuration/userguide/howto_filebased
 * .html#Loading
 *
 * From the docs: - If the combination from base path and file name is a
 * full URL that points to an existing file, this URL will be used to load
 * the file. - If the combination from base path and file name is an
 * absolute file name and this file exists, it will be loaded. - If the
 * combination from base path and file name is a relative file path that
 * points to an existing file, this file will be loaded. - If a file with
 * the specified name exists in the user's home directory, this file will be
 * loaded. - Otherwise the file name is interpreted as a resource name, and
 * it is checked whether the data file can be loaded from the classpath.
 *
 * @param fileOrUrlOrClasspathUrl Location of the file. Can be on file
 * system, or on the classpath. Will both work.
 * @return A PropertiesConfiguration or null if there were problems getting
 * it.
 */
public static PropertiesConfiguration loadConfigurationInUtf8(String fileOrUrlOrClasspathUrl) {

    PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
    propertiesConfiguration.setEncoding(NinjaConstant.UTF_8);
    propertiesConfiguration.setDelimiterParsingDisabled(true);
    propertiesConfiguration.setFileName(fileOrUrlOrClasspathUrl);
    propertiesConfiguration.getLayout().setSingleLine(NinjaConstant.applicationSecret, true);

    try {

        propertiesConfiguration.load(fileOrUrlOrClasspathUrl);

    } catch (ConfigurationException e) {

        logger.info("Could not load file " + fileOrUrlOrClasspathUrl
                + " (not a bad thing necessarily, but I am returing null)");

        return null;
    }

    return propertiesConfiguration;
}

From source file:org.apache.accumulo.core.client.ClientConfiguration.java

private ClientConfiguration(PropertiesConfiguration propertiesConfiguration, String configFile)
        throws ConfigurationException {
    super(propertiesConfiguration);
    // Don't do list interpolation
    this.setListDelimiter('\0');
    propertiesConfiguration.setListDelimiter('\0');
    propertiesConfiguration.load(configFile);
}

From source file:org.apache.accumulo.core.client.ClientConfiguration.java

private ClientConfiguration(PropertiesConfiguration propertiesConfiguration, File configFile)
        throws ConfigurationException {
    super(propertiesConfiguration);
    // Don't do list interpolation
    this.setListDelimiter('\0');
    propertiesConfiguration.setListDelimiter('\0');
    propertiesConfiguration.load(configFile);
}