Example usage for org.apache.commons.digester Digester parse

List of usage examples for org.apache.commons.digester Digester parse

Introduction

In this page you can find the example usage for org.apache.commons.digester Digester parse.

Prototype

public Object parse(URL url) throws IOException, SAXException 

Source Link

Document

Parse the content of the specified URL using this Digester.

Usage

From source file:com.apache.struts2.interceptor.ParameterToActionObjectMappingInterceptor.java

/**
 *
 *///from w  ww  .  j a  v a  2s . c o m
public String intercept(ActionInvocation invocation) throws Exception {

    ActionProxy actProxy = invocation.getProxy();
    Object object = actProxy.getAction();

    if (actProxy.getAction().getClass().getResourceAsStream(actProxy.getActionName() + XML_EXTENSION) != null) {
        Digester digester = new Digester();
        digester.setValidating(false);

        digester.addObjectCreate("mapping", ObjectMappingVO.class);

        digester.addObjectCreate("mapping/requestParameter", PropertyVO.class);
        digester.addSetProperties("mapping/requestParameter", "name", "name");

        digester.addObjectCreate("mapping/requestParameter/objectMapping", PropertyNameVO.class);
        digester.addBeanPropertySetter("mapping/requestParameter/objectMapping/property", "name");
        digester.addSetNext("mapping/requestParameter/objectMapping", "addObjectProperty");

        digester.addSetNext("mapping/requestParameter", "addProperty");

        ObjectMappingVO objectMappingVO = (ObjectMappingVO) digester.parse(
                actProxy.getAction().getClass().getResourceAsStream(actProxy.getActionName() + XML_EXTENSION));

        if (log.isDebugEnabled()) {
            log.debug("Object Mapping for Action :" + actProxy.getAction().getClass());
            log.debug("Object Mapping : " + objectMappingVO);
        }

        try {
            processParameters(objectMappingVO, object);
        } catch (IllegalAccessException ie) {
            log.error("IllegalAccessException", ie);
        } catch (InstantiationException ie) {
            log.error("InstantiationException", ie);
        } catch (IntrospectionException ie) {
            log.error("IntrospectionException", ie);
        }
    }
    return invocation.invoke();

}

From source file:com.tonbeller.jpivot.mondrian.script.ScriptableMondrianDrillThroughTableModel.java

/**
 * execute sql query//w ww.  j  av a 2s .  c  o  m
 * @throws Exception
 */
private void executeQuery() {
    Connection con = null;
    try {
        InputStream catExtIs = ScriptableMondrianDrillThroughTableModel.class.getClassLoader()
                .getResourceAsStream("/" + catalogExtension);
        if (catExtIs != null) {
            Digester catExtDigester = new Digester();
            catExtDigester.push(this);
            catExtDigester.addSetProperties("extension");
            catExtDigester.addObjectCreate("extension/script",
                    "com.tonbeller.jpivot.mondrian.script.ScriptColumn");
            catExtDigester.addSetProperties("extension/script");
            catExtDigester.addSetNext("extension/script", "addScript");
            catExtDigester.parse(catExtIs);

            URL scriptsBaseURL = Thread.currentThread().getContextClassLoader().getResource(scriptRootUrl);
            scriptEngine = new GroovyScriptEngine(new URL[] { scriptsBaseURL });
        }
        con = getConnection();
        Statement s = con.createStatement();
        s.setMaxRows(maxResults);
        ResultSet rs = s.executeQuery(sql);
        ResultSetMetaData md = rs.getMetaData();
        int numCols = md.getColumnCount();
        List columnTitlesList = new ArrayList();
        // set column headings
        for (int i = 0; i < numCols; i++) {
            //   columns are 1 based
            columnTitlesList.add(i, md.getColumnName(i + 1));
        }
        // loop on script columns
        for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) {
            final ScriptColumn sc = (ScriptColumn) sIt.next();
            columnTitlesList.add(sc.getPosition() - 1, sc.getTitle());
        }
        columnTitles = (String[]) columnTitlesList.toArray(new String[0]);
        // loop through rows
        List tempRows = new ArrayList();
        Map scriptInput = new HashMap();
        Binding binding = new Binding();
        while (rs.next()) {
            List rowList = new ArrayList();
            scriptInput.clear();
            // loop on columns, 1 based
            for (int i = 0; i < numCols; i++) {
                rowList.add(i, rs.getObject(i + 1));
                scriptInput.put(columnTitles[i], rs.getObject(i + 1));
            }
            binding.setVariable("input", scriptInput);
            // loop on script columns
            for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) {
                final ScriptColumn sc = (ScriptColumn) sIt.next();
                scriptEngine.run(sc.getFile(), binding);
                final Object output = binding.getVariable("output");
                if (output instanceof Map) {
                    Map outMap = (Map) output;
                    rowList.add(sc.getPosition() - 1,
                            new DefaultCell((String) outMap.get("URL"), (String) outMap.get("Value")));
                } else if (output instanceof String) {
                    rowList.add(sc.getPosition() - 1, (String) output);
                } else {
                    throw new Exception("Unknown groovy script return type (not a Map nor String).");
                }
            }
            tempRows.add(new DefaultTableRow(rowList.toArray()));
        }
        rs.close();
        rows = (TableRow[]) tempRows.toArray(new TableRow[0]);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("?", e);
        // problem occured, set table model to zero size
        rows = new TableRow[1];
        columnTitles = new String[1];
        columnTitles[0] = "An error occured";
        Object[] row = new Object[1];
        row[0] = e.toString();
        rows[0] = new DefaultTableRow(row);
        ready = false;
        return;
    } finally {
        try {
            con.close();
        } catch (Exception e1) {
            // ignore
        }
    }
    ready = true;
}

From source file:catalina.startup.Catalina.java

/**
 * Start a new server instance.//w  w  w . j  a va2s .c o m
 */
protected void start() {

    // Create and execute our Digester
    Digester digester = createStartDigester();
    File file = configFile();
    try {
        InputSource is = new InputSource("file://" + file.getAbsolutePath());
        FileInputStream fis = new FileInputStream(file);
        is.setByteStream(fis);
        digester.push(this);
        digester.parse(is);
        fis.close();
    } catch (Exception e) {
        System.out.println("Catalina.start: " + e);
        e.printStackTrace(System.out);
        System.exit(1);
    }

    // Setting additional variables
    if (!useNaming) {
        System.setProperty("catalina.useNaming", "false");
    } else {
        System.setProperty("catalina.useNaming", "true");
        String value = "org.apache.naming";
        String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
        if (oldValue != null) {
            value = value + ":" + oldValue;
        }
        System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
        value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
        if (value == null) {
            System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                    "org.apache.naming.java.javaURLContextFactory");
        }
    }

    // If a SecurityManager is being used, set properties for
    // checkPackageAccess() and checkPackageDefinition
    if (System.getSecurityManager() != null) {
        String access = Security.getProperty("package.access");
        if (access != null && access.length() > 0)
            access += ",";
        else
            access = "sun.,";
        Security.setProperty("package.access", access + "org.apache.catalina.,org.apache.jasper.");
        String definition = Security.getProperty("package.definition");
        if (definition != null && definition.length() > 0)
            definition += ",";
        else
            definition = "sun.,";
        Security.setProperty("package.definition",
                // FIX ME package "javax." was removed to prevent HotSpot
                // fatal internal errors
                definition + "java.,org.apache.catalina.,org.apache.jasper.");
    }

    // Replace System.out and System.err with a custom PrintStream
    SystemLogHandler log = new SystemLogHandler(System.out);
    System.setOut(log);
    System.setErr(log);

    Thread shutdownHook = new CatalinaShutdownHook();

    // Start the new server
    if (server instanceof Lifecycle) {
        try {
            server.initialize();
            ((Lifecycle) server).start();
            try {
                // Register shutdown hook
                Runtime.getRuntime().addShutdownHook(shutdownHook);
            } catch (Throwable t) {
                // This will fail on JDK 1.2. Ignoring, as Tomcat can run
                // fine without the shutdown hook.
            }
            // Wait for the server to be told to shut down
            server.await();
        } catch (LifecycleException e) {
            System.out.println("Catalina.start: " + e);
            e.printStackTrace(System.out);
            if (e.getThrowable() != null) {
                System.out.println("----- Root Cause -----");
                e.getThrowable().printStackTrace(System.out);
            }
        }
    }

    // Shut down the server
    if (server instanceof Lifecycle) {
        try {
            try {
                // Remove the ShutdownHook first so that server.stop()
                // doesn't get invoked twice
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
            } catch (Throwable t) {
                // This will fail on JDK 1.2. Ignoring, as Tomcat can run
                // fine without the shutdown hook.
            }
            ((Lifecycle) server).stop();
        } catch (LifecycleException e) {
            System.out.println("Catalina.stop: " + e);
            e.printStackTrace(System.out);
            if (e.getThrowable() != null) {
                System.out.println("----- Root Cause -----");
                e.getThrowable().printStackTrace(System.out);
            }
        }
    }

}

From source file:eu.planets_project.pp.plato.xml.TreeLoader.java

/**
 *
 * @param file absolute file path to proper xml file conforming to
 * the old eu.planets_project.pp.plato.xml.legacy format used in the DELOS Testbed.
 * Note that the xml file structure is slightly adapted from the DELOS testbed, was easier
 * than getting the digester to work properly on the old one. Just the root is changed!
 * samples can be found in data/trees./* ww  w .j  a  v a 2  s.  c  om*/
 * @return {@link ObjectiveTree} created from the xml file,
 * or <code>null</code> if there was an error
 */
public ObjectiveTree load(String file) {
    ObjectiveTree tree = new ObjectiveTree();

    Digester digester = new Digester();
    digester.setValidating(false);
    digester.push(tree);

    digester.addObjectCreate("*/root", "eu.planets_project.pp.plato.model.Node");
    digester.addSetProperties("*/root");

    digester.addObjectCreate("*/node", "eu.planets_project.pp.plato.model.Node");
    digester.addSetProperties("*/node");

    digester.addObjectCreate("*/leaf", "eu.planets_project.pp.plato.model.Leaf");
    digester.addSetProperties("*/leaf");

    digester.addSetNext("*/leaf", "addChild");
    digester.addSetNext("*/node", "addChild");
    digester.addSetNext("*/root", "setRoot");

    try {
        InputStream s = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
        digester.setUseContextClassLoader(true);
        digester.parse(s);
    } catch (Exception e) {
        e.printStackTrace();
        tree = null;
    }

    return tree;
}

From source file:com.syrup.storage.xml.XmlFileConfigurationParser.java

public IStorage getMockServices(InputSource inputSource)
        throws org.xml.sax.SAXParseException, java.io.IOException, org.xml.sax.SAXException {

    Digester digester = new Digester();
    digester.setValidating(false);//from   w  w  w  .j av  a 2s . c  o  m
    digester.addObjectCreate(ROOT, InMemoryStorage.class);
    digester.addObjectCreate(PROJECT, Project.class);
    digester.addObjectCreate(PAGE, Page.class);
    digester.addObjectCreate(ASSET, Asset.class);

    digester.addSetNext(PROJECT, "saveOrUpdateProject");
    digester.addSetNext(PAGE, "saveOrUpdatePage");
    digester.addSetNext(ASSET, "saveOrUpdateAsset");

    digester.addSetProperties(PROJECT, "name", "name");
    digester.addSetProperties(PAGE, "name", "name");
    digester.addSetProperties(PAGE, "id", "id");

    digester.addSetProperties(ASSET, "id", "id");
    digester.addSetProperties(ASSET, "source", "source");
    digester.addSetProperties(ASSET, "left", "left");
    digester.addSetProperties(ASSET, "top", "top");

    IStorage c = (IStorage) digester.parse(inputSource);
    return c;
}

From source file:com.meidusa.venus.client.VenusServiceFactory.java

private void loadConfiguration(Map<String, Tuple<ObjectPool, BackendConnectionPool>> poolMap,
        Map<Class<?>, Tuple<Object, RemotingInvocationHandler>> servicesMap,
        Map<Class<?>, ServiceConfig> serviceConfig, Map<String, Object> realPools) throws Exception {
    VenusClient all = new VenusClient();
    for (String configFile : configFiles) {
        configFile = (String) ConfigUtil.filter(configFile);
        URL url = this.getClass().getResource("venusClientRule.xml");
        if (url == null) {
            throw new VenusConfigException("venusClientRule.xml not found!,pls rebuild venus!");
        }//from w w  w . ja  va  2  s  . c o  m
        RuleSet ruleSet = new FromXmlRuleSet(url, new DigesterRuleParser());
        Digester digester = new Digester();
        digester.setValidating(false);
        digester.addRuleSet(ruleSet);

        try {
            InputStream is = ResourceUtils.getURL(configFile.trim()).openStream();
            VenusClient venus = (VenusClient) digester.parse(is);
            for (ServiceConfig config : venus.getServiceConfigs()) {
                if (config.getType() == null) {
                    logger.error("Service type can not be null:" + configFile);
                    throw new ConfigurationException("Service type can not be null:" + configFile);
                }
            }
            all.getRemoteMap().putAll(venus.getRemoteMap());
            all.getServiceConfigs().addAll(venus.getServiceConfigs());
        } catch (Exception e) {
            throw new ConfigurationException("can not parser xml:" + configFile, e);
        }
    }

    // ? remotePool
    for (Map.Entry<String, Remote> entry : all.getRemoteMap().entrySet()) {
        RemoteContainer container = createRemoteContainer(entry.getValue(), realPools);
        Tuple<ObjectPool, BackendConnectionPool> tuple = new Tuple<ObjectPool, BackendConnectionPool>();
        tuple.left = container.getBioPool();
        tuple.right = container.getNioPool();
        poolMap.put(entry.getKey(), tuple);
    }

    for (ServiceConfig config : all.getServiceConfigs()) {

        Remote remote = all.getRemoteMap().get(config.getRemote());
        Tuple<ObjectPool, BackendConnectionPool> tuple = null;
        if (!StringUtil.isEmpty(config.getRemote())) {
            tuple = poolMap.get(config.getRemote());
            if (tuple == null) {
                throw new ConfigurationException("remote=" + config.getRemote() + " not found!!");
            }
        } else {
            String ipAddress = config.getIpAddressList();
            tuple = poolMap.get(ipAddress);
            if (ipAddress != null && tuple == null) {
                RemoteContainer container = createRemoteContainer(true, ipAddress, realPools);
                tuple = new Tuple<ObjectPool, BackendConnectionPool>();
                tuple.left = container.getBioPool();
                tuple.right = container.getNioPool();
                poolMap.put(ipAddress, tuple);
            }
        }

        if (tuple != null) {
            RemotingInvocationHandler invocationHandler = new RemotingInvocationHandler();
            invocationHandler.setBioConnPool(tuple.left);
            invocationHandler.setNioConnPool(tuple.right);
            invocationHandler.setServiceFactory(this);
            invocationHandler.setVenusExceptionFactory(this.getVenusExceptionFactory());
            if (remote != null && remote.getAuthenticator() != null) {
                invocationHandler.setSerializeType(remote.getAuthenticator().getSerializeType());
            }

            invocationHandler.setContainer(this.container);

            Object object = Proxy.newProxyInstance(this.getClass().getClassLoader(),
                    new Class[] { config.getType() }, invocationHandler);

            for (Method method : config.getType().getMethods()) {
                Endpoint endpoint = method.getAnnotation(Endpoint.class);
                if (endpoint != null) {
                    Class[] eclazz = method.getExceptionTypes();
                    for (Class clazz : eclazz) {
                        if (venusExceptionFactory != null && CodedException.class.isAssignableFrom(clazz)) {
                            venusExceptionFactory.addException(clazz);
                        }
                    }
                }
            }

            serviceConfig.put(config.getType(), config);
            Tuple<Object, RemotingInvocationHandler> serviceTuple = new Tuple<Object, RemotingInvocationHandler>(
                    object, invocationHandler);
            servicesMap.put(config.getType(), serviceTuple);
            if (config.getBeanName() != null) {
                serviceBeanMap.put(config.getBeanName(), serviceTuple);
            }
        } else {
            if (config.getInstance() != null) {
                Tuple<Object, RemotingInvocationHandler> serviceTuple = new Tuple<Object, RemotingInvocationHandler>(
                        config.getInstance(), null);
                servicesMap.put(config.getType(), serviceTuple);
                if (config.getBeanName() != null) {
                    serviceBeanMap.put(config.getBeanName(), serviceTuple);
                }
            } else {
                throw new ConfigurationException(
                        "Service instance or ipAddressList or remote can not be null:" + config.getType());
            }
        }

    }
}

From source file:fr.paris.lutece.portal.service.plugin.PluginFile.java

/**
 * Load plugin data from the XML file using Jakarta Commons Digester
 * @param strFilename The XML plugin filename
 * @throws fr.paris.lutece.portal.service.init.LuteceInitException If a problem occured during the loading
 *//*from  www  . j a v  a 2 s  .c o  m*/
public void load(String strFilename) throws LuteceInitException {
    // Configure Digester from XML ruleset
    URL rules = getClass().getResource(FILE_RULES);
    Digester digester = DigesterLoader.createDigester(rules);

    // Push empty List onto Digester's Stack
    digester.push(this);
    digester.setValidating(false);

    try {
        InputStream input = new FileInputStream(strFilename);
        digester.parse(input);
    } catch (FileNotFoundException e) {
        throw new LuteceInitException("Error loading plugin file : " + strFilename, e);
    } catch (SAXException e) {
        throw new LuteceInitException("Error loading plugin file : " + strFilename, e);
    } catch (IOException e) {
        throw new LuteceInitException("Error loading plugin file : " + strFilename, e);
    }
}

From source file:com.dianping.avatar.cache.configuration.CacheItemConfig.java

/**
 * Parse configuraiton file/*from   ww w . j  av  a2 s .  c om*/
 */
private void init(String file) {
    try {

        Digester digester = new Digester();

        digester.addCallMethod("dpcache/import", "addImport", 1, new Class[] { String.class });
        digester.addCallParam("dpcache/import", 0, "file");

        digester.addObjectCreate("dpcache/add", CacheKeyType.class);
        digester.addSetProperties("dpcache/add", "name", "category");
        digester.addSetProperties("dpcache/add", "index", "indexTemplate");
        digester.addSetProperties("dpcache/add", "duration", "duration");
        digester.addSetProperties("dpcache/add", "indexDesc", "indexParamDescs");
        digester.addSetProperties("dpcache/add", "type", "cacheType");

        digester.addSetNext("dpcache/add", "addCacheKeyType");

        InputStream in = resourceLoader.getResource(file).getInputStream();

        digester.push(this);
        digester.parse(in);

        in.close();

        for (String importFile : importFiles) {
            CacheItemConfig config = new CacheItemConfig();
            config.init(importFile);
            this.cacheKeyTypes.putAll(config.cacheKeyTypes);
        }
    } catch (Exception e) {
        throw new SystemException("Failed to initialize cache items config file", e);
    }
}

From source file:com.coroptis.coidi.core.services.impl.ConfigurationServiceImpl.java

/**
 * Creates {@link Properties} instance. Properties are read from the
 * specified XML file and XML elements./*www .j av a 2 s . c o m*/
 * 
 * @param configurationSection
 *            pattern that matches an element in configuration
 * @param resourceUrl
 *            specifies where configuration file is located
 * @return Map loaded from XML configuration file
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private HashMap<String, String> createProperties(String configurationSection, Resource configurationResource) {
    Digester digester = new Digester();
    digester.addObjectCreate("configuration/" + configurationSection, HashMap.class);
    // TODO refactor it, add test
    // call the put method on the top object on the digester stack
    // passing the key attribute as the 0th parameterw
    // and the element body text as the 1th parameter..
    digester.addCallMethod("configuration/" + configurationSection + "/property", "put", 2);
    digester.addCallParam("configuration/" + configurationSection + "/property", 0, "name");
    digester.addCallParam("configuration/" + configurationSection + "/property", 1);

    InputStream inputStream = null;
    HashMap properties = null;
    try {
        inputStream = configurationResource.openStream();
        properties = (HashMap) digester.parse(inputStream);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } catch (SAXException e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            logger.warn("Unable to close input stream after reading configuration file.");
        }
    }
    return properties;
}

From source file:com.salmonllc.ideTools.Tomcat50Engine.java

public void stopServer(String[] arguments, Tomcat50Bootstrap bootstrap) {

    if (_server == null) {
        // Create and execute our Digester
        Digester digester = createStopDigester();
        digester.setClassLoader(Thread.currentThread().getContextClassLoader());
        File file = configFile();
        try {//from   ww w .  ja v a2  s. c  o  m
            InputSource is = new InputSource("file://" + file.getAbsolutePath());
            FileInputStream fis = new FileInputStream(file);
            is.setByteStream(fis);
            digester.push(this);
            digester.parse(is);
            fis.close();
        } catch (Exception e) {
            System.out.println("Catalina.stop: " + e);
            e.printStackTrace(System.out);
            System.exit(1);
        }
    }

    // Stop the existing server
    try {
        String host = "127.0.0.1";
        int port = 8005;
        String shutdown = "SHUTDOWN";

        if (_shutdown != null) {
            port = _shutdown.getPort();
            shutdown = _shutdown.getShutdown();
        }

        Socket socket = new Socket(host, port);
        OutputStream stream = socket.getOutputStream();

        for (int i = 0; i < shutdown.length(); i++)
            stream.write(shutdown.charAt(i));
        stream.flush();
        stream.close();
        socket.close();
        Thread.sleep(500);
    } catch (Exception e) {
        //System.out.println("Catalina.stop: " + e);
        //e.printStackTrace(System.out);
        //System.exit(1);
    }

    bootstrap.notifyComplete();

}