Example usage for org.apache.commons.configuration XMLConfiguration XMLConfiguration

List of usage examples for org.apache.commons.configuration XMLConfiguration XMLConfiguration

Introduction

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

Prototype

public XMLConfiguration(URL url) throws ConfigurationException 

Source Link

Document

Creates a new instance of XMLConfiguration.

Usage

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

private boolean loadFile(File file) {
    try {//  w  w  w .j  a va2 s. c om
        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.jf.javafx.plugins.impl.PluginRepositoryImpl.java

private XMLConfiguration getPluginConfig(Plugin p) {
    XMLConfiguration cfg = null;/*w ww.j  a va  2s. c  o  m*/

    try {
        cfg = new XMLConfiguration(p.getClass().getResource("plugin.xml"));
    } catch (ConfigurationException ex) {
        System.out.println("Failed while loading plugin configuration of: " + p.getClass().getName());
    }

    return cfg;
}

From source file:net.sf.jclal.experiment.ExperimentBuilder.java

/**
 * Expands the multi-valued elements for the jobFilename configuration file
 * /*from w w w.j  a  v a  2s  . c o m*/
 * @param jobFilename The job file name to execute
 * @return An arraylist of string
 */
private ArrayList<String> expandElements(String jobFilename) {
    combinationBase = new ArrayList<Integer>();

    ArrayList<String> configurationFileNames = new ArrayList<String>();

    // Try open job file
    File jobFile = new File(jobFilename);

    if (jobFile.exists()) {
        try {

            // Find the number of combinations to perform
            expandElementsIterateElements(new XMLConfiguration(jobFile).getDocument().getChildNodes());

            int numberCombinations = 1;

            // Calculate the amount of combinations
            for (Integer i : combinationBase) {
                numberCombinations *= i;
            }

            int[][] configurationSchema = new int[numberCombinations][];

            for (int i = 0; i < numberCombinations; i++) {
                configurationSchema[i] = new int[combinationBase.size()];
            }

            int consecutiveElements = numberCombinations;
            int accProduct = 1;

            // Calculate the combinations of each element
            for (int i = 0; i < combinationBase.size(); i++) {
                consecutiveElements /= combinationBase.get(i);

                for (int j = 0; j < combinationBase.get(i); j++) {
                    for (int k = 0; k < consecutiveElements; k++) {
                        for (int r = 0; r < accProduct; r++) {
                            int step = consecutiveElements * combinationBase.get(i);
                            configurationSchema[r * step + j * consecutiveElements + k][i] = j;
                        }
                    }
                }

                accProduct *= combinationBase.get(i);
            }

            XMLConfiguration[] configurations = new XMLConfiguration[numberCombinations];

            for (int i = 0; i < numberCombinations; i++) {
                configurations[i] = new XMLConfiguration(jobFile);

                expandElementsIterateElements(configurations[i].getDocument().getChildNodes(),
                        configurationSchema[i].clone());
            }

            for (int i = 0; i < numberCombinations; i++) {
                String fileName = jobFilename;

                for (int j = 0; j < configurationSchema[i].length; j++) {
                    fileName += "_" + configurationSchema[i][j];
                }

                configurations[i].save(new File(fileName));

                configurationFileNames.add(fileName);
            }
        } catch (Exception e) {
            Logger.getLogger(ExperimentBuilder.class.getName()).log(Level.SEVERE, null, e);
        }
    } else {
        System.out.println("Job file not found");
        System.exit(1);
    }

    return configurationFileNames;
}

From source file:com.beginner.core.utils.PropertyUtil.java

/**
 * ?XML?KEY?TestResourcesUtil/*from   ww  w.j  ava2s.  co  m*/
 * @param fileName      XML???
 * @return List<String>   ?
 * @throws Exception   ?
 */
public static List<String> getXmlProperties(String fileName) throws Exception {

    if (StringUtils.isBlank(fileName))
        throw new IllegalArgumentException("The fileName cannot be null and cannot be empty.");

    XMLConfiguration config = null;
    Iterator<String> properties = null;
    List<String> list = new ArrayList<String>();
    try {
        config = new XMLConfiguration(fileName);
        properties = config.getKeys();
        while (properties.hasNext()) {
            String key = (String) properties.next();
            list.add(key);
        }
    } catch (Exception e) {
        throw new Exception();
    }
    return list;
}

From source file:ch.astina.hesperid.installer.web.services.InstallationManager.java

public Configuration getMainConfiguration() {
    try {/*from   ww w  .ja  v  a  2s.  co m*/
        Configuration mainConfiguration = new XMLConfiguration(getConfigurationFilePath());
        return mainConfiguration;
    } catch (ConfigurationException e) {
        logger.error("Could not get configuration!", e);

        return new XMLConfiguration();
    }
}

From source file:com.termmed.reconciliation.test.GroupNumberReconciliationTest.java

/**
 * Gets the output file./* w w  w.j  av  a  2 s .  com*/
 *
 * @param configFile the config file
 * @return the output file
 * @throws ConfigurationException the configuration exception
 */
private String getOutputFile(File configFile) throws ConfigurationException {
    XMLConfiguration xmlConfig;

    xmlConfig = new XMLConfiguration(configFile);

    return xmlConfig.getString(I_Constants.RELATIONSHIP_FILE);

}

From source file:ch.kostceco.bento.sipval.service.impl.ConfigurationServiceImpl.java

private XMLConfiguration getConfig() {
    if (this.config == null) {

        try {/*  w  w w.j  a va  2s . c  o  m*/

            String path = "configuration/sipvalidator.conf.xml";

            URL locationOfJar = SipValidator.class.getProtectionDomain().getCodeSource().getLocation();
            String locationOfJarPath = locationOfJar.getPath();

            if (locationOfJarPath.endsWith(".jar")) {
                File file = new File(locationOfJarPath);
                String fileParent = file.getParent();
                path = fileParent + "/" + path;
            }

            config = new XMLConfiguration(path);

        } catch (ConfigurationException e) {
            System.out.print(
                    "\r                                                                                                                                     ");
            System.out.flush();
            System.out.print("\r");
            System.out.flush();

            LOGGER.logInfo(getTextResourceService().getText(MESSAGE_CONFIGURATION_ERROR_1));
            LOGGER.logInfo(getTextResourceService().getText(MESSAGE_CONFIGURATION_ERROR_2));
            LOGGER.logInfo(getTextResourceService().getText(MESSAGE_CONFIGURATION_ERROR_3));
            System.exit(1);
        }
    }
    return config;
}

From source file:de.ingrid.portal.portlets.admin.AdminPortalProfilePortlet.java

/**
 * @see org.apache.portals.bridges.velocity.GenericVelocityPortlet#processAction(javax.portlet.ActionRequest,
 *      javax.portlet.ActionResponse)//from  ww w  . j  a  v a 2  s.  c  om
 */
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {

    String action = request.getParameter("action");

    if (action != null && action.equals("switchProfile")) {
        String profileName = request.getParameter("profile");
        String databasePostfix = "_mysql";
        if (UtilsDB.isOracle()) {
            databasePostfix = "_oracle";
        }
        String profileDescriptor = getPortletConfig().getPortletContext()
                .getRealPath("/profiles/" + profileName + "/profile" + databasePostfix + ".xml");
        String pageName = null;
        try {
            XMLConfiguration profile = new XMLConfiguration(profileDescriptor);
            // set page configurations
            // this info will be held in the database
            List pages = profile.getList("pages.page.name");
            for (int i = 0; i < pages.size(); i++) {
                pageName = (String) pages.get(i);

                // set visibility of the page
                boolean hidden;
                Page p = pageManager.getPage(Folder.PATH_SEPARATOR + pageName);
                try {
                    hidden = profile.getBoolean("pages.page(" + i + ").hidden");
                    p.setHidden(hidden);
                } catch (ConversionException e) {
                    log.warn("No tag 'hidden' found for page '" + pageName + "'", e);
                }
                pageManager.updatePage(p);

                // set page layout configuration
                List portletNames = profile.getList("pages.page(" + i + ").portlets.portlet.name");
                if (portletNames != null && portletNames.size() > 0) {
                    // defragmentation
                    UtilsPageLayout.defragmentLayoutColumn((Fragment) p.getRootFragment(), 0);
                    UtilsPageLayout.defragmentLayoutColumn((Fragment) p.getRootFragment(), 1);
                    // remove all fragments
                    UtilsPageLayout.removeAllFragmentsInColumn(p, (Fragment) p.getRootFragment(), 0);
                    UtilsPageLayout.removeAllFragmentsInColumn(p, (Fragment) p.getRootFragment(), 1);
                    for (int j = 0; j < portletNames.size(); j++) {
                        String portletName = (String) portletNames.get(j);
                        //portletRegistry.getPortletDefinitionByIdentifier("IngridInformPortlet").getPreferenceSet();//portletRegistry.getAllPortletDefinitions();
                        try {
                            List portletPrefsNames = null;
                            List<FragmentPreference> prefs = new ArrayList<FragmentPreference>();

                            int row = profile.getInt("pages.page(" + i + ").portlets.portlet(" + j + ")[@row]");
                            int col = profile.getInt("pages.page(" + i + ").portlets.portlet(" + j + ")[@col]");
                            try {
                                // get the hidden information if it is available
                                portletPrefsNames = profile.getList(
                                        "pages.page(" + i + ").portlets.portlet(" + j + ").preference[@name]");
                                for (int k = 0; k < portletPrefsNames.size(); k++) {
                                    FragmentPreference f = pageManager.newFragmentPreference();
                                    // set the name of the preference
                                    f.setName((String) portletPrefsNames.get(k));
                                    // get the values for this preference
                                    List<String> pl = (List<String>) (List<?>) profile.getList("pages.page(" + i
                                            + ").portlets.portlet(" + j + ").preference(" + k + ").value");
                                    f.setValueList(pl);
                                    prefs.add(f);
                                }
                            } catch (Exception e) {
                                log.error(e.toString());
                            }
                            UtilsPageLayout.positionPortletOnPage(pageManager, p,
                                    (Fragment) p.getRootFragment(), portletName, row, col, prefs);
                        } catch (ConversionException e) {
                            log.warn("No 'x' or 'y' attribute found for portlet '" + portletName + "' on page '"
                                    + pageName + "'", e);
                        }
                    }
                    pageManager.updatePage(p);
                }
            }

            // process files copy actions
            List fileActions = profile.getList("files.file.action");
            for (int i = 0; i < fileActions.size(); i++) {
                String actionName = (String) fileActions.get(i);
                String src = profile.getString("files.file(" + i + ").src");
                String dst = profile.getString("files.file(" + i + ").dst");
                if (dst == null) {
                    dst = src;
                }
                String srcFileName = getPortletConfig().getPortletContext()
                        .getRealPath("/profiles/" + profileName + "/" + src);
                String dstContext = dst.substring(0, dst.indexOf("/"));
                String dstPath = dst.substring(dst.indexOf("/") + 1);
                String dstFileName = ((RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV))
                        .getConfig().getServletContext().getContext("/" + dstContext).getRealPath(dstPath);

                if (actionName.equalsIgnoreCase("copy")) {
                    if (!srcFileName.equals(dstFileName)) {
                        copy(srcFileName, dstFileName);
                    }
                } else if (actionName.equalsIgnoreCase("copy-dir")) {
                    if (!srcFileName.equals(dstFileName)) {
                        copyDir(srcFileName, dstFileName);
                    }
                }
            }

            // process sql actions
            List sqlActions = profile.getList("sql.execute");
            for (int i = 0; i < sqlActions.size(); i++) {
                String sqlAction = (String) sqlActions.get(i);
                UtilsDB.executeRawUpdateSQL(sqlAction);
            }

            response.setRenderParameter("switchedToProfile", profileName);

        } catch (ConfigurationException e) {
            log.error("Error reading profile configuration (" + profileDescriptor + ")", e);
        } catch (PageNotFoundException e) {
            log.error("Page not found from  (" + Folder.PATH_SEPARATOR + pageName + ")", e);
        } catch (NodeException e) {
            log.error("Error reading page (" + Folder.PATH_SEPARATOR + pageName + ")", e);
        }
    }
}

From source file:at.gv.egiz.bku.spring.ConfigurationFactoryBean.java

@Override
public Object getObject() throws Exception {

    log.info("Configuration resource is {}.", configurationResource);

    CompositeConfiguration configuration = null;
    if (configurationResource != null) {
        if (configurationResource.exists()) {
            // initialize with writable configuration
            URL url = configurationResource.getURL();
            XMLConfiguration writableConfiguration = new XMLConfiguration(url);
            configuration = new CompositeConfiguration(writableConfiguration);
            log.info("Initialized with configuration from '{}'.", url);
        } else if (failOnMissingResource) {
            StringBuilder message = new StringBuilder();
            message.append("ConfigurationResource '");
            message.append(configurationResource.getDescription());
            message.append("' does not exist!");
            log.error(message.toString());
            throw new MoccaConfigurationException(message.toString());
        }/*from  w w  w .ja v  a  2 s  .  co  m*/
    }

    if (configuration == null) {
        // initialize default configuration
        log.warn("Initializing with default configuration.");
        configuration = new CompositeConfiguration();
    }

    configuration.addConfiguration(getDefaultConfiguration());
    configuration.addConfiguration(getVersionConfiguration());
    return configuration;
}

From source file:com.termmed.statistics.runner.Runner.java

/**
 * Inits the file providers./*from  www .  ja  v a2 s . com*/
 *
 * @param file the file
 * @throws Exception the exception
 */
private static void initFileProviders(File file) throws Exception {
    logger.logInfo("Initializing file providers");
    XMLConfiguration xmlConfig;
    try {
        xmlConfig = new XMLConfiguration(file);
    } catch (ConfigurationException e) {
        logger.logInfo("ClassificationRunner - Error happened getting params configFile." + e.getMessage());
        throw e;
    }

    String releaseFolder = xmlConfig.getString("releaseFullFolder");
    if (releaseFolder == null || releaseFolder.trim().equals("") || !new File(releaseFolder).exists()) {
        throw new Exception("Release folder doesn't exist.");
    }

    File sourceFolder = new File(releaseFolder);

    Object prop = xmlConfig.getProperty("releaseDependencies.releaseFullFolder");
    HashSet<String> releaseDependencies = null;
    if (prop != null) {
        if (prop instanceof Collection) {
            releaseDependencies = new HashSet<String>();
            for (String loopProp : (Collection<String>) prop) {
                releaseDependencies.add(loopProp);
            }
        } else if (prop instanceof String) {
            releaseDependencies = new HashSet<String>();
            releaseDependencies.add((String) prop);
            System.out.println(prop);
        }

    }
    String releaseDate = xmlConfig.getString("releaseDate");
    String previousReleaseDate = xmlConfig.getString("previousReleaseDate");

    CurrentFile.init(sourceFolder, new File("release" + releaseDate), releaseDependencies, releaseDate);
    PreviousFile.init(sourceFolder, new File("release" + previousReleaseDate), releaseDependencies,
            previousReleaseDate);

    String dependentRelease = xmlConfig.getString("dependentReleaseFullFolder");
    if (dependentRelease != null && !dependentRelease.trim().equals("")) {
        String dependentReleaseDate = xmlConfig.getString("dependentReleaseDate");
        if (dependentReleaseDate == null || dependentReleaseDate.trim().equals("")) {
            dependentReleaseDate = releaseDate;
        }
        DependentFile.init(new File(dependentRelease), new File("dependentrelease" + dependentReleaseDate),
                dependentReleaseDate);

    }

}