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.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    String file = filterConfig.getInitParameter("configFile");
    if (file != null) {

        try {//from   w w w. j ava 2 s  . c  o m
            XMLConfiguration config = new XMLConfiguration(file);

            useCsrfToken = config.getBoolean(SecurityConstant.USECSRFHEADER_PARAM);
            csrfHeaderName = config.getString(SecurityConstant.CSRFHEADERNAME_PARAM);
            csrfCookieName = config.getString(SecurityConstant.CSRFCOOKIENAME_PARAM);
            methodExclusionList = config.getStringArray("httpMethodExclusions");

            logger.info("init: useCsrfToken=" + useCsrfToken);
            logger.info("init: csrfHeaderName=" + csrfHeaderName);
            logger.info("init: httpMethodExclusions=" + Arrays.asList(methodExclusionList));
        } catch (Exception cex) {
            logger.error("init: unable to load configFile " + file, cex);

        }
    } else {
        logger.error("init: No configFile specified");
    }
}

From source file:it.imtech.configuration.ChooseServer.java

/**
 * Setta il percorso del file di configurazione se  la prima volta che
 * viene avviata l'applicazione/*from   w ww. ja v a 2s.  com*/
 *
 * @param change Definisce se  l'avvio dell'applicazione o se si vuole
 * modificare il percorso
 * @throws MalformedURLException
 * @throws ConfigurationException
 */
private XMLConfiguration setConfigurationPaths(boolean change, XMLConfiguration internalConf,
        ResourceBundle bundle) {
    URL urlConfig = null;
    XMLConfiguration configuration = null;

    try {
        String text = Utility.getBundleString("setconf", bundle);
        String title = Utility.getBundleString("setconf2", bundle);

        internalConf.setAutoSave(true);

        String n = internalConf.getString("configurl[@path]");

        if (n.isEmpty()) {
            String s = (String) JOptionPane.showInputDialog(new Frame(), text, title, JOptionPane.PLAIN_MESSAGE,
                    null, null, "http://phaidrastatic.cab.unipd.it/xml/config.xml");

            //If a string was returned, say so.
            if ((s != null) && (s.length() > 0)) {
                internalConf.setProperty("configurl[@path]", s);
                urlConfig = new URL(s);
            } else {
                logger.info("File di configurazione non settato");
            }
        } else {
            urlConfig = new URL(n);
        }

        if (urlConfig != null) {
            if (Globals.DEBUG)
                configuration = new XMLConfiguration(new File(Globals.JRPATH + Globals.DEBUG_XML));
            else
                configuration = new XMLConfiguration(urlConfig);
        }
    } catch (final MalformedURLException ex) {
        logger.error(ex.getMessage());
        JOptionPane.showMessageDialog(new Frame(), Utility.getBundleString("exc_conf_1", bundle));
    } catch (final ConfigurationException ex) {
        logger.error(ex.getMessage());
        JOptionPane.showMessageDialog(new Frame(), Utility.getBundleString("exc_conf_2", bundle));
    }

    return configuration;
}

From source file:au.com.dw.testdatacapturej.config.Configuration.java

/**
 * Load the collection configurations from file. 
 * /* w w  w.  j ava2 s .c om*/
 * An example of the XML structure:
 * 
 * <collection-config>
 *
 *   <container class="dummy.ClassName">
 *      <argument>
 *        <field-name>collectionFieldName</field-name>
 *        <adder-method>adderMethodName</adder-method>
 *      </argument>
 *   </container>
 *   .
 *   .
 *   .
 * 
 */
private void readCollectionConfigFile(String[] configFileNames) {
    XMLConfiguration xmlConfig = null;

    try {
        for (String fileName : configFileNames) {
            xmlConfig = new XMLConfiguration(fileName);

            if (xmlConfig != null) {
                // get all the collection nodes and iterate through them
                List<?> collectionNodes = xmlConfig.configurationsAt("container");
                for (Iterator<?> it = collectionNodes.iterator(); it.hasNext();) {
                    HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
                    // sub contains now all data about a single field

                    String className = sub.getString("[@class]");

                    List<String> collectionFieldNames = configUtil
                            .toStringList(sub.getList("argument.field-name"));
                    // not sure if this is the best way to handle multiple sub elements
                    List<String> adderMethodNames = configUtil
                            .toStringList(sub.getList("argument.adder-method"));

                    // TODO need more error checking here in case of incorrect configuration
                    if (collectionFieldNames != null && !collectionFieldNames.isEmpty()
                            && adderMethodNames != null && !adderMethodNames.isEmpty()) {
                        List<CollectionAdderConfig> collectionConfigs = new ArrayList<CollectionAdderConfig>();
                        for (int i = 0; i < collectionFieldNames.size(); i++) {
                            CollectionAdderConfig collectionConfig = new CollectionAdderConfig();
                            collectionConfig.setFieldName(collectionFieldNames.get(i));
                            collectionConfig.setAdderMethodName(adderMethodNames.get(i));

                            collectionConfigs.add(collectionConfig);
                        }

                        adderCollections.put(className, collectionConfigs);
                    }
                }
            }
        }
    } catch (ConfigurationException cex) {
        cex.printStackTrace();
    }
}

From source file:com.litt.core.security.license.gui.ValidatePanel.java

/**
 * Create the panel.//  w  ww .  ja  v a  2  s.  c o  m
 */
public ValidatePanel() {
    GridBagLayout gbl_validatePanel = new GridBagLayout();
    gbl_validatePanel.columnWidths = new int[] { 0, 0, 0 };
    gbl_validatePanel.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    gbl_validatePanel.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
    gbl_validatePanel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            Double.MIN_VALUE };
    this.setLayout(gbl_validatePanel);

    JLabel label_10 = new JLabel("");
    GridBagConstraints gbc_label_10 = new GridBagConstraints();
    gbc_label_10.insets = new Insets(0, 0, 5, 5);
    gbc_label_10.anchor = GridBagConstraints.EAST;
    gbc_label_10.gridx = 0;
    gbc_label_10.gridy = 0;
    this.add(label_10, gbc_label_10);

    field_pubKeyFilePath = new JTextField();
    field_pubKeyFilePath.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            //fileChooser.setVisible(true);
            LicenseFileFilter fileFilter = new LicenseFileFilter(new String[] { "key" });
            fileChooser.setFileFilter(fileFilter);
            fileChooser.addChoosableFileFilter(fileFilter);
            fileChooser.showOpenDialog(e.getComponent());
            File pubKeyFile = fileChooser.getSelectedFile();

            field_pubKeyFilePath.setText(pubKeyFile.getAbsolutePath());

        }
    });
    GridBagConstraints gbc_field_pubKeyFilePath = new GridBagConstraints();
    gbc_field_pubKeyFilePath.insets = new Insets(0, 0, 5, 0);
    gbc_field_pubKeyFilePath.fill = GridBagConstraints.HORIZONTAL;
    gbc_field_pubKeyFilePath.gridx = 1;
    gbc_field_pubKeyFilePath.gridy = 0;
    this.add(field_pubKeyFilePath, gbc_field_pubKeyFilePath);
    field_pubKeyFilePath.setColumns(10);

    JLabel label_19 = new JLabel("?");
    GridBagConstraints gbc_label_19 = new GridBagConstraints();
    gbc_label_19.anchor = GridBagConstraints.EAST;
    gbc_label_19.insets = new Insets(0, 0, 5, 5);
    gbc_label_19.gridx = 0;
    gbc_label_19.gridy = 1;
    this.add(label_19, gbc_label_19);

    field_licenseFilePath = new JTextField();
    field_licenseFilePath.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            //fileChooser.setVisible(true);
            LicenseFileFilter fileFilter = new LicenseFileFilter(new String[] { "xml" });
            fileChooser.setFileFilter(fileFilter);
            fileChooser.addChoosableFileFilter(fileFilter);
            fileChooser.showOpenDialog(e.getComponent());
            File licenseFile = fileChooser.getSelectedFile();

            field_licenseFilePath.setText(licenseFile.getAbsolutePath());
        }
    });
    GridBagConstraints gbc_textField1 = new GridBagConstraints();
    gbc_textField1.insets = new Insets(0, 0, 5, 0);
    gbc_textField1.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField1.gridx = 1;
    gbc_textField1.gridy = 1;
    this.add(field_licenseFilePath, gbc_textField1);
    field_licenseFilePath.setColumns(10);

    JLabel lblid = new JLabel("?ID");
    lblid.setHorizontalAlignment(SwingConstants.CENTER);
    GridBagConstraints gbc_lblid = new GridBagConstraints();
    gbc_lblid.insets = new Insets(0, 0, 5, 5);
    gbc_lblid.gridx = 0;
    gbc_lblid.gridy = 2;
    this.add(lblid, gbc_lblid);

    label_licenseId = new JLabel("");
    label_licenseId.setHorizontalAlignment(SwingConstants.CENTER);
    GridBagConstraints gbc_label_licenseId = new GridBagConstraints();
    gbc_label_licenseId.insets = new Insets(0, 0, 5, 0);
    gbc_label_licenseId.gridx = 1;
    gbc_label_licenseId.gridy = 2;
    this.add(label_licenseId, gbc_label_licenseId);

    JLabel label_12 = new JLabel("?");
    GridBagConstraints gbc_label_12 = new GridBagConstraints();
    gbc_label_12.insets = new Insets(0, 0, 5, 5);
    gbc_label_12.gridx = 0;
    gbc_label_12.gridy = 3;
    this.add(label_12, gbc_label_12);

    label_licenseType = new JLabel("");
    GridBagConstraints gbc_label_licenseType = new GridBagConstraints();
    gbc_label_licenseType.insets = new Insets(0, 0, 5, 0);
    gbc_label_licenseType.gridx = 1;
    gbc_label_licenseType.gridy = 3;
    this.add(label_licenseType, gbc_label_licenseType);

    JLabel label_13 = new JLabel("???");
    GridBagConstraints gbc_label_13 = new GridBagConstraints();
    gbc_label_13.insets = new Insets(0, 0, 5, 5);
    gbc_label_13.gridx = 0;
    gbc_label_13.gridy = 4;
    this.add(label_13, gbc_label_13);

    label_productName = new JLabel("");
    GridBagConstraints gbc_label_productName = new GridBagConstraints();
    gbc_label_productName.insets = new Insets(0, 0, 5, 0);
    gbc_label_productName.gridx = 1;
    gbc_label_productName.gridy = 4;
    this.add(label_productName, gbc_label_productName);

    JLabel label_14 = new JLabel("???");
    GridBagConstraints gbc_label_14 = new GridBagConstraints();
    gbc_label_14.insets = new Insets(0, 0, 5, 5);
    gbc_label_14.gridx = 0;
    gbc_label_14.gridy = 5;
    this.add(label_14, gbc_label_14);

    label_companyName = new JLabel("");
    GridBagConstraints gbc_label_companyName = new GridBagConstraints();
    gbc_label_companyName.insets = new Insets(0, 0, 5, 0);
    gbc_label_companyName.gridx = 1;
    gbc_label_companyName.gridy = 5;
    this.add(label_companyName, gbc_label_companyName);

    JLabel label_15 = new JLabel("??");
    GridBagConstraints gbc_label_15 = new GridBagConstraints();
    gbc_label_15.insets = new Insets(0, 0, 5, 5);
    gbc_label_15.gridx = 0;
    gbc_label_15.gridy = 6;
    this.add(label_15, gbc_label_15);

    label_customerName = new JLabel("");
    GridBagConstraints gbc_label_customerName = new GridBagConstraints();
    gbc_label_customerName.insets = new Insets(0, 0, 5, 0);
    gbc_label_customerName.gridx = 1;
    gbc_label_customerName.gridy = 6;
    this.add(label_customerName, gbc_label_customerName);

    JLabel label_16 = new JLabel("");
    GridBagConstraints gbc_label_16 = new GridBagConstraints();
    gbc_label_16.insets = new Insets(0, 0, 5, 5);
    gbc_label_16.gridx = 0;
    gbc_label_16.gridy = 7;
    this.add(label_16, gbc_label_16);

    label_version = new JLabel("");
    GridBagConstraints gbc_label_version = new GridBagConstraints();
    gbc_label_version.insets = new Insets(0, 0, 5, 0);
    gbc_label_version.gridx = 1;
    gbc_label_version.gridy = 7;
    this.add(label_version, gbc_label_version);

    JLabel label_11 = new JLabel("");
    GridBagConstraints gbc_label_11 = new GridBagConstraints();
    gbc_label_11.insets = new Insets(0, 0, 5, 5);
    gbc_label_11.gridx = 0;
    gbc_label_11.gridy = 8;
    this.add(label_11, gbc_label_11);

    label_createDate = new JLabel("");
    GridBagConstraints gbc_label_createDate = new GridBagConstraints();
    gbc_label_createDate.insets = new Insets(0, 0, 5, 0);
    gbc_label_createDate.gridx = 1;
    gbc_label_createDate.gridy = 8;
    this.add(label_createDate, gbc_label_createDate);

    JLabel label_17 = new JLabel("");
    GridBagConstraints gbc_label_17 = new GridBagConstraints();
    gbc_label_17.insets = new Insets(0, 0, 5, 5);
    gbc_label_17.gridx = 0;
    gbc_label_17.gridy = 9;
    this.add(label_17, gbc_label_17);

    label_expiredDate = new JLabel("");
    GridBagConstraints gbc_label_expiredDate = new GridBagConstraints();
    gbc_label_expiredDate.insets = new Insets(0, 0, 5, 0);
    gbc_label_expiredDate.gridx = 1;
    gbc_label_expiredDate.gridy = 9;
    this.add(label_expiredDate, gbc_label_expiredDate);

    JButton button_2 = new JButton("");
    button_2.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {

            String licenseFilePath = Utility.trimNull(field_licenseFilePath.getText());
            String pubKeyFilePath = Utility.trimNull(field_pubKeyFilePath.getText());
            if (Utility.isEmpty(licenseFilePath)) {
                JOptionPane.showMessageDialog(e.getComponent(), "?!");
                return;
            }
            if (Utility.isEmpty(pubKeyFilePath)) {
                JOptionPane.showMessageDialog(e.getComponent(), "!");
                return;
            }
            File licenseFile = new File(licenseFilePath);
            try {
                XMLConfiguration config = new XMLConfiguration(licenseFile);
                config.setAutoSave(true);

                label_licenseId.setText(config.getString(("licenseId")));
                label_licenseType.setText(config.getString("licenseType"));
                label_productName.setText(config.getString("productName"));
                label_companyName.setText(config.getString("companyName"));
                label_customerName.setText(config.getString("customerName"));
                label_version.setText(config.getString("version"));
                label_createDate.setText(config.getString("createDate"));
                label_expiredDate.setText(config.getString("expiredDate"));

            } catch (Exception e1) {
                // TODO Auto-generated catch block
                JOptionPane.showMessageDialog(e.getComponent(), e1.getMessage());
            }

            try {
                LicenseManager.validateLicense(licenseFile.getAbsolutePath(), pubKeyFilePath);
                JOptionPane.showMessageDialog(e.getComponent(), "?");
            } catch (LicenseException e1) {
                // TODO Auto-generated catch block
                JOptionPane.showMessageDialog(e.getComponent(), e1.getMessage());
            }

        }
    });
    GridBagConstraints gbc_button_2 = new GridBagConstraints();
    gbc_button_2.gridx = 1;
    gbc_button_2.gridy = 10;
    this.add(button_2, gbc_button_2);
}

From source file:edu.kit.dama.mdm.core.MetaDataManagement.java

/**
 * Load configuration from XML-File/*w w w .j  a v  a  2 s. c  o  m*/
 */
private void loadConfiguration() {
    String firstImplementation = null;
    String firstPersistenceUnit = null;
    HierarchicalConfiguration hc = null;
    List<String> persistenceUnits = null;
    URL configURL = null;
    try {
        configURL = DataManagerSettings.getConfigurationURL();
        LOGGER.debug("Loading configuration from {}", configURL);
        hc = new HierarchicalConfiguration(new XMLConfiguration(configURL));
        LOGGER.debug("Configuration successfully loaded");
    } catch (ConfigurationException ex) {
        // error in configuration
        // reason see debug log message:
        LOGGER.error("Failed to load configuration.", ex);
        throw new RuntimeException(ex);
    }
    SubnodeConfiguration configurationAt = hc.configurationAt(CONFIG_ROOT);
    List fields = configurationAt.configurationsAt(CONFIG_PERSISTENCE_IMPL);
    LOGGER.debug("Found {} configured persistence implementations", fields.size());
    persistenceUnitMap = new HashMap<>();
    persistenceClassMap = new HashMap<>();
    persistenceUnitDefaultMap = new HashMap<>();

    String implementationName;
    IPersistenceFactory iPersistenceFactory = null;
    for (Iterator it = fields.iterator(); it.hasNext();) {
        HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
        LOGGER.debug("Reading sub-configuration");
        // First get all persistence units.
        persistenceUnits = new ArrayList<>();
        try {
            List<HierarchicalConfiguration> persistenceUnitsList = sub
                    .configurationsAt(CONFIG_PERSISTENCE_UNIT);
            if (persistenceUnitsList == null) {
                persistenceUnitsList = new LinkedList<>();
            }
            LOGGER.debug("Configuration contains {} persistence units.", persistenceUnitsList.size());
            firstPersistenceUnit = null;
            for (HierarchicalConfiguration item : persistenceUnitsList) {
                String value = item.getString(".");
                String defaultAttribute = item.getString("[@default]");

                LOGGER.debug("PersistenceUnit found: " + value);
                LOGGER.debug("@default = {}", defaultAttribute);

                if (Boolean.parseBoolean(defaultAttribute)) {
                    if (firstPersistenceUnit == null) {
                        LOGGER.debug("{} is used as default persistence unit.", value);
                        firstPersistenceUnit = value;
                    } else {
                        LOGGER.warn(
                                "{} is an additional persistence unit defined as default. We'll ignore this.",
                                value);
                    }
                }

                LOGGER.debug("Adding persistence unit to list of units.");
                persistenceUnits.add(value);
            }

        } catch (Exception any) {
            LOGGER.error("Failed to read persistence units.", any);
        }
        LOGGER.debug("firstPersistenceUnit: " + firstPersistenceUnit);
        if ((persistenceUnits.size() > 0) && (firstPersistenceUnit == null)) {
            LOGGER.debug("No default persistence unit defined. Using first entry ({})",
                    persistenceUnits.get(0));
            firstPersistenceUnit = persistenceUnits.get(0);
        }
        LOGGER.debug("Getting implementation name.");
        implementationName = sub.getString(CONFIG_PERSISTENCE_NAME);
        LOGGER.debug("Implementation name '{}' found.", implementationName);
        if (firstImplementation == null) {
            LOGGER.debug("Using implementation '{}' as first implementation.", implementationName);
            firstImplementation = implementationName;
        }
        LOGGER.debug("Testing implementation '{}'", implementationName);
        if (sub.containsKey(CONFIG_DEFAULT_PERSISTENCE)) {
            LOGGER.debug("'{}' is configured as default implementation.", implementationName);
            if (defaultImplementation != null) {
                LOGGER.warn("{} is an additional implementation defined as default. We'll ignore this.",
                        implementationName);
            } else {
                defaultImplementation = implementationName;
            }
        }
        Class<?> loadClass;
        boolean success = false;
        String persistenceClass = sub.getString(CONFIG_PERSISTENCE_CLASS);
        try {

            LOGGER.debug("Loading class '{}': ", persistenceClass);
            loadClass = getClass().getClassLoader().loadClass(persistenceClass);
            LOGGER.debug("Checking IPersistenceFactory.class.assignableFrom({})", persistenceClass);
            success = IPersistenceFactory.class.isAssignableFrom(loadClass);
            iPersistenceFactory = null;
            if (success) {
                LOGGER.debug("Creating instance of class {}", persistenceClass);
                iPersistenceFactory = (IPersistenceFactory) loadClass.newInstance();
                LOGGER.debug("Persistence factory successfully instantiated.");
            } else {
                LOGGER.error("IPersistenceFactory seems not to be assignable from class {}", persistenceClass);
            }
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
            LOGGER.error("Failed to create instance of persistence implementation " + persistenceClass, ex);
            success = false;
        }
        if (success) {
            persistenceUnitMap.put(implementationName, persistenceUnits);
            persistenceClassMap.put(implementationName, iPersistenceFactory);
            persistenceUnitDefaultMap.put(implementationName, firstPersistenceUnit);
        } else {
            throw new edu.kit.dama.mdm.core.exception.ConfigurationException(
                    "Failed to initialize persistence factory from URL '" + configURL
                            + "'. See logfile for details.");
        }
    }
    if (defaultImplementation == null) {
        LOGGER.debug("Default implementation not set, yet. Using first one ({}) as default.",
                firstImplementation);
        defaultImplementation = firstImplementation;
    }
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java

public ArrayList<Connector> initDevices(ObjectBroker objectBroker) {
    log.info("KNX ETS device loader starting. - connectorsConfig: " + connectorsConfig);
    setConfiguration(connectorsConfig);//from   w w  w. java  2 s  . co  m

    ArrayList<Connector> connectors = new ArrayList<Connector>();

    log.info("connectors config now: " + connectorsConfig);
    Object knxConnectors = connectorsConfig.getProperty("knx-ets.connector.name");

    int connectorsSize = 0;

    if (knxConnectors != null) {
        connectorsSize = 1;
    }

    if (knxConnectors instanceof Collection<?>) {
        connectorsSize = ((Collection<?>) knxConnectors).size();
    }

    // Networks
    List networks = new List();
    networks.setName("networks");
    networks.setOf(new Contract(Network.CONTRACT));
    networks.setHref(new Uri("/networks"));

    boolean networkEnabled = false;

    for (int connector = 0; connector < connectorsSize; connector++) {
        HierarchicalConfiguration subConfig = connectorsConfig
                .configurationAt("knx-ets.connector(" + connector + ")");

        // String connectorName = subConfig.getString("name");
        String routerIP = subConfig.getString("router.ip");
        int routerPort = subConfig.getInteger("router.port", 3671);
        String localIP = subConfig.getString("localIP");
        Boolean enabled = subConfig.getBoolean("enabled", false);
        Boolean forceRefresh = subConfig.getBoolean("forceRefresh", false);
        String knxProj = subConfig.getString("knx-proj");

        Boolean enableGroupComm = subConfig.getBoolean("groupCommEnabled", false);

        Boolean enableHistories = subConfig.getBoolean("historyEnabled", false);

        if (enabled) {
            if (!networkEnabled) {
                objectBroker.addObj(networks, true);
                networkEnabled = true;
            }
            File file = new File(knxProj);

            if (!file.exists() || file.isDirectory() || !file.getName().endsWith(".knxproj")
                    || file.getName().length() < 8) {
                log.warning("KNX project file " + knxProj + " is not a valid KNX project file.");
                continue;
            }

            String projDirName = knxProj.substring(0, knxProj.length() - 8);

            File projDir = new File(projDirName);

            if (!projDir.exists() || forceRefresh) {
                log.info("Expanding " + knxProj + " into directory " + projDirName);
                unZip(knxProj, projDirName);
            }

            String directory = "./" + knxProj.substring(knxProj.indexOf("/") + 1).replaceFirst(".knxproj", "");

            // now the unpacked ETS project should be available in the directory
            String transformFileName = knxProj.replaceFirst(".knxproj", "") + "/"
                    + file.getName().replaceFirst(".knxproj", "") + ".xml";

            File transformFile = new File(transformFileName);

            if (!transformFile.exists() || forceRefresh) {
                log.info("Transforming ETS configuration.");
                //               System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
                // Create a transform factory instance.
                TransformerFactory tfactory = TransformerFactory.newInstance();

                // Create a transformer for the stylesheet.
                Transformer transformer;

                try {
                    transformer = tfactory.newTransformer(new StreamSource("knx-config/stylesheet_knx.xsl"));
                    Collection<File> listFiles = FileUtils.listFiles(projDir,
                            FileFilterUtils.nameFileFilter("0.xml"), new IOFileFilter() {

                                @Override
                                public boolean accept(File file) {
                                    return true;
                                }

                                @Override
                                public boolean accept(File dir, String name) {
                                    return true;
                                }

                            });
                    if (listFiles.size() != 1) {
                        log.severe("Found no or more than one 0.xml file in " + projDirName);
                        continue;
                    }

                    log.info("Transforming with directory parameter set to " + directory);

                    transformer.setParameter("directory", directory);
                    transformer.transform(new StreamSource(listFiles.iterator().next().getAbsoluteFile()),
                            new StreamResult(transformFileName));

                    log.info("Transformation completed and result written to: " + transformFileName);
                } catch (TransformerConfigurationException e) {
                    e.printStackTrace();
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            }

            try {
                devicesConfig = new XMLConfiguration(transformFileName);
            } catch (Exception e) {
                log.log(Level.SEVERE, e.getMessage(), e);
            }

            KNXConnector knxConnector = new KNXConnector(routerIP, routerPort, localIP);

            connect(knxConnector);

            initNetworks(knxConnector, objectBroker, networks, enableGroupComm, enableHistories);

            connectors.add(knxConnector);
        }
    }

    return connectors;
}

From source file:com.vangent.hieos.empi.config.EMPIConfig.java

/**
 * /*from  ww  w.j av a 2 s  . c o  m*/
 * @throws EMPIException
 */
private void loadConfiguration() throws EMPIException {
    String empiConfigDir = XConfig.getConfigLocation(XConfig.ConfigItem.EMPI_DIR);
    String configLocation = empiConfigDir + "/" + EMPIConfig.EMPI_CONFIG_FILE_NAME;
    String codesConfigLocation = empiConfigDir + "/" + EMPIConfig.EMPI_CODES_CONFIG_FILE_NAME;
    try {
        XMLConfiguration xmlConfig = new XMLConfiguration(configLocation);
        jndiResourceName = xmlConfig.getString(JNDI_RESOURCE_NAME, DEFAULT_JNDI_RESOURCE_NAME);
        subjectSequenceGeneratorSQL = xmlConfig.getString(SUBJECT_SEQUENCE_GENERATOR_SQL,
                "UNKNOWN SUBJECT SEQUENCE GENERATOR SQL");
        updateNotificationEnabled = xmlConfig.getBoolean(UPDATE_NOTIFICATION_ENABLED, false);
        identitySourceFilteringEnabled = xmlConfig.getBoolean(IDENTITY_SOURCE_FILTERING_ENABLED, false);
        validateCodesEnabled = xmlConfig.getBoolean(VALIDATE_CODES_ENABLED, true);
        validateIdentitySourcesEnabled = xmlConfig.getBoolean(VALIDATE_IDENTITY_SOURCES_ENABLED, true);
        empiDeviceIds = xmlConfig.getStringArray(EMPI_DEVICE_IDS);

        // Load account number treatment configuration.
        this.loadAccountNumberTreatmentConfig(xmlConfig);

        // Load the candidate finder.
        this.loadCandidateFinder(xmlConfig);

        // Load the match algorithm.
        this.loadMatchAlgorithm(xmlConfig);

        // Load function configurations.
        this.loadFunctionConfigs(xmlConfig);

        // Load field configurations.
        this.loadFieldConfigs(xmlConfig);

        // Load matching configurations.

        // Configuration to support feeds.
        matchConfigFeed = new MatchConfig();
        matchConfigFeed.load(xmlConfig.configurationAt(MATCH_CONFIG_FEED), this);

        // Configuration to support finds.
        matchConfigFind = new MatchConfig();
        matchConfigFind.load(xmlConfig.configurationAt(MATCH_CONFIG_FIND), this);

        // Load EUID configuration.
        euidConfig = new EUIDConfig();
        euidConfig.load(xmlConfig.configurationAt(EUID_CONFIG), this);

        // Load identity sources.
        this.loadIdentitySources(xmlConfig);

        // Load codes configuration.
        codesConfig = new CodesConfig();
        codesConfig.loadConfiguration(codesConfigLocation);

    } catch (ConfigurationException ex) {
        throw new EMPIException(
                "EMPIConfig: Could not load configuration from " + configLocation + " " + ex.getMessage());
    }
}

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

private ArrayList<String> expandAttributes(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 {/*  w w w  .  j  ava  2  s. co  m*/

            // Find the number of combinations to perform
            expandAttributesIterateElements(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);

                //Build the document for each combination
                expandAttributesIterateElements(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.termmed.statistics.runner.Runner.java

/**
 * Gets the params.//from   ww  w.  j  a  v  a2  s  .  c o m
 *
 * @param configFile the config file
 * @return the params
 * @throws Exception the exception
 */
private static void getParams(File configFile) throws Exception {
    XMLConfiguration xmlConfig;
    try {
        xmlConfig = new XMLConfiguration(configFile);
    } catch (ConfigurationException e) {
        logger.logError("ClassificationRunner - Error happened getting params configFile." + e.getMessage());
        throw e;
    }

    releaseDate = xmlConfig.getString("releaseDate");
    previousReleaseDate = xmlConfig.getString("previousReleaseDate");
    if (releaseDate == null || releaseDate.length() != 8) {
        throw new Exception("Release date param is wrong.");
    }
    if (previousReleaseDate == null || previousReleaseDate.length() != 8) {
        throw new Exception("Release date param is wrong.");
    }
}

From source file:it.imtech.configuration.StartWizard.java

/**
 * Creates necessary folders in home user menu
 * @return /*  ww w  .  j  a v  a 2s .c  om*/
 */
private boolean checkAppDataFiles() {
    boolean result = false;

    try {
        File appdata = new File(Globals.USER_DIR);
        String currentpath = Globals.JRPATH + "appdata" + Utility.getSep();
        File blank = new File(currentpath + "config" + Utility.getSep() + "blankpage.jpg");
        File xmlconfnew = new File(currentpath + "config" + Utility.getSep() + "config.xml");
        File logforj = new File(currentpath + "config" + Utility.getSep() + "log4j.xml");
        File upllogforj = new File(currentpath + "config" + Utility.getSep() + "upllog4j.xml");

        if (!appdata.exists()) {
            appdata.mkdir();
        }

        File templates = new File(Globals.USER_DIR + "templates");
        if (!templates.exists()) {
            templates.mkdir();
        }

        File backupxml = new File(currentpath + "xml");
        File remotexml = new File(Globals.USER_DIR + "xml");
        FileUtils.copyDirectory(backupxml, remotexml);

        File config = new File(Globals.USER_DIR + "config");
        if (!config.exists()) {
            config.mkdir();
        }

        File undo = new File(Globals.USER_DIR + "undo");
        if (!undo.exists()) {
            undo.mkdir();
        }

        File certs = new File(Globals.USER_DIR + "certs");
        if (!certs.exists()) {
            certs.mkdir();
        }

        File uploads = new File(Globals.USER_DIR + "duplication");
        if (!uploads.exists()) {
            uploads.mkdir();
        }

        File xmlconfold = new File(Globals.USER_DIR + "config" + Utility.getSep() + "config.xml");
        if (xmlconfold.exists()) {
            try {
                XMLConfiguration configureold = new XMLConfiguration(xmlconfold);
                XMLConfiguration configurenew = new XMLConfiguration(xmlconfnew);

                String versioneold = configureold.getString("version[@current]");
                String versionenew = configurenew.getString("version[@current]");

                String urlold = configureold.getString("configurl[@path]");
                String urlnew = configurenew.getString("configurl[@path]");
                if ((!versioneold.equals(versionenew)) || (!urlold.equals(urlnew))) {
                    xmlconfold.delete();
                    FileUtils.copyFile(xmlconfnew, xmlconfold);
                }
            } catch (ConfigurationException ex) {
                result = false;
            }
        } else {
            FileUtils.copyFile(xmlconfnew, xmlconfold);
        }

        File logforjnew = new File(Globals.USER_DIR + "config" + Utility.getSep() + "log4j.xml");
        FileUtils.copyFile(logforj, logforjnew);
        File upllogforjnew = new File(Globals.USER_DIR + "config" + Utility.getSep() + "upllog4j.xml");
        FileUtils.copyFile(upllogforj, upllogforjnew);

        File blanknew = new File(Globals.USER_DIR + "config" + Utility.getSep() + "blankpage.jpg");
        if (!blanknew.exists()) {
            FileUtils.copyFile(blank, blanknew);
        }

        result = true;
    } catch (IOException ex) {
        result = false;
    }
    return result;
}