Example usage for java.util Properties loadFromXML

List of usage examples for java.util Properties loadFromXML

Introduction

In this page you can find the example usage for java.util Properties loadFromXML.

Prototype

public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException 

Source Link

Document

Loads all of the properties represented by the XML document on the specified input stream into this properties table.

Usage

From source file:org.apache.ctakes.ytex.kernel.KernelUtilImpl.java

@Override
public void loadProperties(String propertyFile, Properties props)
        throws FileNotFoundException, IOException, InvalidPropertiesFormatException {
    InputStream in = null;//  w w w . j  a va2 s.c o m
    try {
        in = new FileInputStream(propertyFile);
        if (propertyFile.endsWith(".xml"))
            props.loadFromXML(in);
        else
            props.load(in);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:eu.dnetlib.maven.plugin.properties.WritePredefinedProjectProperties.java

/**
 * Creates properties for given location.
 * @param location/*from w  w w  .  j  a  v  a2  s. c o m*/
 * @return properties for given location
 * @throws MojoExecutionException
 */
protected Properties getProperties(String location) throws MojoExecutionException {
    InputStream in = null;
    try {
        Properties properties = new Properties();
        in = getInputStream(location);
        if (location.toLowerCase().endsWith(".xml")) {
            properties.loadFromXML(in);
        } else {
            properties.load(in);
        }
        return properties;
    } catch (IOException e) {
        throw new MojoExecutionException("Error reading properties file " + location, e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.onecmdb.utils.wsdl.OneCMDBTransform.java

public IDataSource getDataSource() throws Exception {
    if (this.source != null) {
        Properties p = new Properties();
        FileInputStream in = new FileInputStream(this.source);
        boolean loaded = false;
        try {//from w ww.j a v a  2s .  co m
            p.loadFromXML(in);
            loaded = true;
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            in.close();
        }
        if (!loaded) {
            in = new FileInputStream(this.source);
            try {
                p.load(in);
            } finally {
                in.close();
            }
        }
        return (getDataSource(p));
    }

    if (this.jdbcSource != null) {
        Properties p = new Properties();
        FileInputStream in = new FileInputStream(this.jdbcSource);
        try {
            p.loadFromXML(in);
        } finally {
            in.close();
        }
        BasicDataSource jdbcSrc = new BasicDataSource();
        jdbcSrc.setUrl(p.getProperty("db.url"));
        jdbcSrc.setDriverClassName(p.getProperty("db.driverClass"));
        jdbcSrc.setUsername(p.getProperty("db.user"));
        jdbcSrc.setPassword(p.getProperty("db.password"));

        JDBCDataSourceWrapper src = new JDBCDataSourceWrapper();
        src.setDataSource(jdbcSrc);

        return (src);
    }
    // Else plain file...
    if (fileSource == null) {
        throw new IOException("No data source specified!");
    }
    if ("xml".equalsIgnoreCase(sourceType) || fileSource.endsWith(".xml")) {
        XMLDataSource dSource = new XMLDataSource();
        dSource.addURL(new URL(fileSource));
        return (dSource);
    }
    if ("csv".equalsIgnoreCase(sourceType) || fileSource.endsWith(".csv")) {
        CSVDataSource dSource = new CSVDataSource();
        dSource.addURL(new URL("file:" + fileSource));
        if (csvProperty != null) {
            HashMap<String, String> map = toMap(csvProperty, ",");
            String headerLines = map.get("headerLines");
            String delimiter = map.get("delimiter");
            String colTextDel = map.get("colTextDel");
            if (headerLines != null) {
                dSource.setHeaderLines(Long.parseLong(headerLines));
            }
            dSource.setColDelimiter(delimiter);
            dSource.setTextDelimiter(colTextDel);
        }
        return (dSource);
    }
    throw new IOException("Data source <" + fileSource + "> extension not supported!");
}

From source file:org.webdavaccess.LocalFileSystemStorage.java

private Properties getPropertiesFor(String uri) {
    uri = normalize(uri);//from   w  w w . j  a  va  2s  . c o m
    File file = getPropertiesFile(uri);
    if (file == null || !file.exists()) {
        return null;
    }
    InputStream in = null;
    Properties persisted = new Properties();
    try {
        in = new FileInputStream(file);
        persisted.loadFromXML(in);
    } catch (Exception e) {
        log.warn("Failed to get properties from cache for " + uri);
        return null;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
    }
    Enumeration en = persisted.keys();
    Properties props = new Properties();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        if (isResourceProperty(uri, key)) {
            String newKey = getPropertyKey(uri, key);
            props.setProperty(newKey, persisted.getProperty(key));
        }
    }
    return (props.size() == 0) ? null : props;
}

From source file:org.wikipedia.nirvana.NirvanaBasicBot.java

public void startWithConfig(String cfg, Map<String, String> launch_params) {
    properties = new Properties();
    try {//from   w w  w  .j a v  a2 s. co m
        InputStream in = new FileInputStream(cfg);
        if (cfg.endsWith(".xml")) {
            properties.loadFromXML(in);
        } else {
            properties.load(in);
        }
        in.close();
    } catch (FileNotFoundException e) {
        System.out.println("ABORT: file " + cfg + " not found");
        return;
    } catch (IOException e) {
        System.out.println("ABORT: Error reading config: " + cfg);
        return;
    }

    initLog();

    String login = properties.getProperty("wiki-login");
    String pw = properties.getProperty("wiki-password");
    if (login == null || pw == null || login.isEmpty() || pw.isEmpty()) {
        String accountFile = properties.getProperty("wiki-account-file");
        if (accountFile == null || accountFile.isEmpty()) {
            System.out.println("ABORT: login info not found in properties");
            log.fatal("wiki-login or wiki-password or wiki-account-file is not specified in settings");
            return;
        }
        Properties loginProp = new Properties();
        try {
            InputStream in = new FileInputStream(accountFile);
            if (accountFile.endsWith(".xml")) {
                loginProp.loadFromXML(in);
            } else {
                loginProp.load(in);
            }
            in.close();
        } catch (FileNotFoundException e) {
            System.out.println("ABORT: file " + accountFile + " not found");
            log.fatal("ABORT: file " + accountFile + " not found");
            return;
        } catch (IOException e) {
            System.out.println("ABORT: failed to read " + accountFile);
            log.fatal("failed to read " + accountFile + " : " + e);
            return;
        }
        login = loginProp.getProperty("wiki-login");
        pw = loginProp.getProperty("wiki-password");
        if (login == null || pw == null || login.isEmpty() || pw.isEmpty()) {
            System.out.println("ABORT: login info not found in file " + accountFile);
            log.fatal("wiki-login or wiki-password or wiki-account-file is not found in file " + accountFile);
            return;
        }
    }

    log.info("login=" + login + ",password=(not shown)");

    LANGUAGE = properties.getProperty("wiki-lang", LANGUAGE);
    log.info("language=" + LANGUAGE);
    DOMAIN = properties.getProperty("wiki-domain", DOMAIN);
    log.info("domain=" + DOMAIN);
    PROTOCOL = properties.getProperty("wiki-protocol", PROTOCOL);
    log.info("protocol=" + PROTOCOL);
    COMMENT = properties.getProperty("update-comment", COMMENT);
    MAX_LAG = Integer.valueOf(properties.getProperty("wiki-maxlag", String.valueOf(MAX_LAG)));
    THROTTLE_TIME_MS = Integer
            .valueOf(properties.getProperty("wiki-throttle", String.valueOf(THROTTLE_TIME_MS)));
    log.info("comment=" + COMMENT);
    DEBUG_MODE = properties.getProperty("debug-mode", DEBUG_MODE ? YES : NO).equals(YES);
    log.info("DEBUG_MODE=" + DEBUG_MODE);

    if (!loadCustomProperties(launch_params)) {
        log.fatal("Failed to load all required properties. Exiting...");
        return;
    }
    String domain = DOMAIN;
    if (domain.startsWith(".")) {
        domain = LANGUAGE + DOMAIN;
    }
    wiki = createWiki(domain, SCRIPT_PATH, PROTOCOL);

    configureWikiBeforeLogin();

    log.info("login to " + domain + ", login: " + login + ", password: (not shown)");
    try {
        wiki.login(login, pw.toCharArray());
    } catch (FailedLoginException e) {
        log.fatal("Failed to login to " + LANGUAGE + ".wikipedia.org, login: " + login + ", password: " + pw);
        return;
    } catch (IOException e) {
        log.fatal(e.toString());
        e.printStackTrace();
        return;
    }

    if (DEBUG_MODE) {
        wiki.setDumpMode();
    }

    log.warn("BOT STARTED");

    try {
        go();
    } catch (InterruptedException e) {
        onInterrupted(e);
    }

    wiki.logout();
    log.warn("EXIT");
}

From source file:org.jspringbot.keyword.db.DbHelper.java

private void addExternalQueries(File file) throws IOException {
    String filename = file.getName();

    Properties properties = new Properties();

    if (StringUtils.endsWith(filename, ".properties")) {
        properties.load(new FileReader(file));
    } else if (StringUtils.endsWith(filename, ".xml")) {
        properties.loadFromXML(new FileInputStream(file));
    }/*from  w ww  . ja v a 2s.  c  om*/

    externalQueries.putAll(properties);
}

From source file:org.webdavaccess.LocalFileSystemStorage.java

/**
 * Delete properties for given resource/*from   w  w  w. j  a v  a 2s . c  o  m*/
 * 
 * @param resourceUri for which to delete properties
 */
public void deleteProperties(String resourceUri, Properties propertiesToDelete) {
    resourceUri = normalize(resourceUri);
    // Try cache first
    Properties props = (Properties) mPropertiesCache.get(resourceUri);
    if (props != null)
        mPropertiesCache.remove(resourceUri);
    File file = getPropertiesFile(resourceUri);
    if (file == null || !file.exists()) {
        return;
    }
    InputStream in = null;
    Properties persisted = new Properties();
    try {
        in = new FileInputStream(file);
        persisted.loadFromXML(in);
    } catch (Exception e) {
        log.warn("Failed to get properties from cache for " + resourceUri);
        return;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
    }
    boolean changed = false;
    Enumeration en = persisted.keys();
    HashMap toRemove = new HashMap();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        if (isResourceProperty(resourceUri, key)) {
            if (propertiesToDelete != null) {
                String newKey = getPropertyKey(resourceUri, key);
                if (propertiesToDelete.getProperty(newKey) != null)
                    toRemove.put(key, persisted.getProperty(key));
            } else {
                toRemove.put(key, persisted.getProperty(key));
            }
        }
    }
    changed = !toRemove.isEmpty();
    for (Iterator it = toRemove.keySet().iterator(); it.hasNext();) {
        String key = (String) it.next();
        persisted.remove(key);
    }
    if (changed) {
        // Store the updates properties
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            persisted.storeToXML(os, "");
        } catch (Exception e) {
            log.warn("Failed to store properties for " + resourceUri);
        } finally {
            if (os != null)
                try {
                    os.close();
                } catch (Exception e) {
                }
        }
    }
}

From source file:us.colloquy.index.IndexHandler.java

public Properties loadProperties() {
    Properties properties = new Properties();

    try (InputStream propertiesFileInputStream = IndexHandler.class.getClassLoader()
            .getResourceAsStream("properties.xml")) {

        if (propertiesFileInputStream != null) {
            properties.loadFromXML(propertiesFileInputStream);

            propertiesFileInputStream.close();

        } else {//from  w w w.  j av  a2 s. co m

            System.out.print("Property file not available");

        }

    } catch (Exception e) {
        e.printStackTrace();

    }
    return properties;
}

From source file:biz.wolschon.finance.jgnucash.panels.TaxReportPanel.java

/**
 * @param books the accounts and transactions we work with.
 *///from  w  w w . j  a va2s  . c  o m
private void initializeUI(final GnucashFile books) {
    this.setLayout(new BorderLayout());
    Properties props = new Properties();
    File configFile = new File(new File(System.getProperty("user.home"), ".jgnucash"), "TaxReportPanel.xml");
    if (configFile.exists()) {
        try {
            props.loadFromXML(new FileInputStream(configFile));
        } catch (Exception e) {
            LOGGER.error("Problem loading " + configFile.getAbsolutePath(), e);
            JLabel errorLabel = new JLabel(e.getMessage());
            this.add(errorLabel, BorderLayout.CENTER);
            return;
        }
    } else {
        throw new IllegalStateException(
                "To use the OPTIONAL tax-report panel, please create a file " + configFile.getAbsolutePath());
        /*try {
        props.loadFromXML(getClass().getResourceAsStream(
                "TaxReportPanel.xml"));
        props.storeToXML(new FileOutputStream(configFile),
                "UTF-8\n"
                + "sum.([0-9]*).name - name of the entry\n"
                + "sum.([0-9]*).target.([0-9]*) - (may be ommited) "
                + "Look at all transactions containing these accounts You can specify qualified names, unqualified names or ids\n"
                + "sum.([0-9]*).source.([0-9]*) - of these accounts add all splits that refer to these accounts\n"
                + "sum.([0-9]*).type = ONLYTO        - sum only the ones that increase the balance of the account (other values: ONLYFROM, ALL)\n"
                + "sum.([0-9]*).type = ONLYFROM      - sum only the ones that decrease the balance of the account (other values: ONLYFROM, ALL)\n"
                + "sum.([0-9]*).type = ALL           - sum all the ones that increase or decreas the balance of the account (other values: ONLYFROM, ALL)\n"
                + "sum.([0-9]*).type = ALLRECURSIVE  - ignore targets and build the recursive balance\n");
        LOGGER.info("demo-config-file for TaxReportPanel has been stored in "
                + configFile.getAbsolutePath());
        } catch (Exception e) {
        LOGGER.error("Problem loading or storing default-TaxReportPanel.xml", e);
        JLabel errorLabel = new JLabel(e.getMessage());
        this.add(errorLabel, BorderLayout.CENTER);
        return;
        }*/
    }

    LOGGER.info("calculating tax-panel...");
    for (int i = 0; props.containsKey("sum." + i + ".name"); i++) {
        try {
            createSum(books, props, i);
        } catch (Exception e) {
            LOGGER.error("[Exception] Problem in " + getClass().getName(), e);
        }
    }

    mySumsPanel.setLayout(new GridLayout(mySums.size(), 1));
    for (TransactionSum sum : mySums) {
        mySumsPanel.add(sum);
    }

    this.add(mySumsPanel, BorderLayout.CENTER);

    myExportButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent aE) {
            showExportCSVDialog();
        }
    });
    myExportPanel.add(myExportButton);
    myExportGranularityCombobox.setSelectedItem(ExportGranularities.Month);
    myExportGranularityCombobox.setEditable(false);
    myExportPanel.add(myExportGranularityCombobox);
    this.add(myExportPanel, BorderLayout.SOUTH);
    LOGGER.info("calculating tax-panel...DONE");
}

From source file:com.wallabystreet.kinjo.common.transport.ws.ServiceDescriptor.java

/**
 * Loads the configuration of the described service, assuming that the file
 * is stored in the service package's folder with the file name
 * <i>properties.xml</i>. It is expected that the file corresponds to the
 * <a href="http://java.sun.com/dtd/properties.dtd">Java Property File DTD<a/>.
 * //from w ww  .  j  a  v  a2  s  .c  o  m
 * @return The configuration of this service as a
 *         <code>java.util.Properties</code> instance.
 * @throws MalformedServiceException,
 *             IIF the property file is missing or invalid.
 * 
 * @see java.util.Properties
 */
private Properties loadProperties() throws MalformedServiceException {
    // constant for the property file name
    final String PROPERTIES_FILENAME = "properties.xml";

    Properties p = new Properties();
    try {
        p.loadFromXML(
                ClassLoader.getSystemResourceAsStream(this.pkg.replace('.', '/') + "/" + PROPERTIES_FILENAME));

        /*
         * due to the stoopid implementation of
         * Properties#loadFromXML(InputStream), leading and trailing
         * whitespace of values is preserved; we have to fix this to prevent
         * ClassLoader#getSystemResource(String) and
         * ClassLoader#getSystemResourceAsStream(String) from wreckage.
         */
        Enumeration e = p.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            Object o = p.getProperty(key);
            if (o instanceof String) {
                String value = (String) o;
                p.setProperty(key, value.trim());
            }
        }

        /* return the demoronized result */
        return p;
    } catch (InvalidPropertiesFormatException e) {
        String msg = "invalid configuration file: " + this.pkg.replace('.', '/') + "/" + PROPERTIES_FILENAME;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    } catch (IOException e) {
        String msg = "could not open configuration file: " + this.pkg.replace('.', '/') + "/"
                + PROPERTIES_FILENAME;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    }
}