jspwiki-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From juanpa...@apache.org
Subject svn commit: r1551049 - in /jspwiki/trunk/jspwiki-war/src: main/java/org/apache/wiki/filters/ main/java/org/apache/wiki/plugin/ main/java/org/apache/wiki/ui/ main/java/org/apache/wiki/util/ test/java/org/apache/wiki/util/
Date Sun, 15 Dec 2013 20:34:13 GMT
Author: juanpablo
Date: Sun Dec 15 20:34:12 2013
New Revision: 1551049

URL: http://svn.apache.org/r1551049
Log:
introduced utility class to parse xml files

DefaultFilterManager closes stream on .initialize(Properties props) if needed

Added:
    jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/XmlUtil.java
    jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/XmlUtilTest.java
Modified:
    jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java
    jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java
    jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/ui/EditorManager.java
    jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/ClassUtil.java
    jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/AllTests.java

Modified: jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java
URL: http://svn.apache.org/viewvc/jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java?rev=1551049&r1=1551048&r2=1551049&view=diff
==============================================================================
--- jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java
(original)
+++ jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java
Sun Dec 15 20:34:12 2013
@@ -22,16 +22,15 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 
+import org.apache.commons.io.IOUtils;
 import org.apache.log4j.Logger;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
@@ -45,11 +44,8 @@ import org.apache.wiki.modules.ModuleMan
 import org.apache.wiki.modules.WikiModuleInfo;
 import org.apache.wiki.util.ClassUtil;
 import org.apache.wiki.util.PriorityList;
-import org.jdom2.Document;
+import org.apache.wiki.util.XmlUtil;
 import org.jdom2.Element;
-import org.jdom2.JDOMException;
-import org.jdom2.input.SAXBuilder;
-import org.jdom2.xpath.XPath;
 
 
 /**
@@ -195,105 +191,73 @@ public class DefaultFilterManager extend
      *  @param props The list of properties.  Typically jspwiki.properties
      *  @throws WikiException If something goes wrong.
      */
-    protected void initialize( Properties props )
-        throws WikiException
-    {
+    protected void initialize( Properties props ) throws WikiException {
         InputStream xmlStream = null;
         String      xmlFile   = props.getProperty( PROP_FILTERXML );
 
-        try
-        {
+        try {
             registerFilters();
             
-            if( m_engine.getServletContext() != null )
-            {
+            if( m_engine.getServletContext() != null ) {
                 log.debug( "Attempting to locate " + DEFAULT_XMLFILE + " from servlet context."
);
-                if( xmlFile == null )
-                {
+                if( xmlFile == null ) {
                     xmlStream = m_engine.getServletContext().getResourceAsStream( DEFAULT_XMLFILE
);
-                }
-                else
-                {
+                } else {
                     xmlStream = m_engine.getServletContext().getResourceAsStream( xmlFile
);
                 }
             }
 
-            if( xmlStream == null )
-            {
+            if( xmlStream == null ) {
                 // just a fallback element to the old behaviour prior to 2.5.8
                 log.debug( "Attempting to locate filters.xml from class path." );
 
-                if( xmlFile == null )
-                {
+                if( xmlFile == null ) {
                     xmlStream = getClass().getResourceAsStream( "/filters.xml" );
-                }
-                else
-                {
+                } else {
                     xmlStream = getClass().getResourceAsStream( xmlFile );
                 }
             }
 
-            if( (xmlStream == null) && (xmlFile != null) )
-            {
+            if( (xmlStream == null) && (xmlFile != null) ) {
                 log.debug("Attempting to load property file "+xmlFile);
                 xmlStream = new FileInputStream( new File(xmlFile) );
             }
 
-            if( xmlStream == null )
-            {
-                log.info("Cannot find property file for filters (this is okay, expected to
find it as: '"+ (xmlFile == null ? DEFAULT_XMLFILE : xmlFile ) +"')");
+            if( xmlStream == null ) {
+                log.info( "Cannot find property file for filters (this is okay, expected
to find it as: '" + 
+                           ( xmlFile == null ? DEFAULT_XMLFILE : xmlFile ) + 
+                          "')" );
                 return;
             }
             
             parseConfigFile( xmlStream );
-        }
-        catch( IOException e )
-        {
+        } catch( IOException e ) {
             log.error("Unable to read property file", e);
-        }
-        catch( JDOMException e )
-        {
-            log.error("Problem in the XML file",e);
+        } finally {
+        	IOUtils.closeQuietly( xmlStream );
         }
     }
 
     /**
      *  Parses the XML filters configuration file.
      *  
-     * @param xmlStream
-     * @throws JDOMException
-     * @throws IOException
-     */
-    private void parseConfigFile( InputStream xmlStream )
-        throws JDOMException,
-               IOException
-    {
-        Document doc = new SAXBuilder().build( xmlStream );
-        
-        XPath xpath = XPath.newInstance("/pagefilters/filter");
-    
-        List nodes = xpath.selectNodes( doc );
-        
-        for( Iterator i = nodes.iterator(); i.hasNext(); )
-        {
-            Element f = (Element) i.next();
-            
-            String filterClass = f.getChildText("class");
-
+     * @param xmlStream stream to parse
+     */
+    private void parseConfigFile( InputStream xmlStream ) {
+    	List< Element > pageFilters = XmlUtil.parse( xmlStream, "/pagefilters/filter"
);
+        for( Iterator< Element > i = pageFilters.iterator(); i.hasNext(); ) {
+            Element f = i.next();
+            String filterClass = f.getChildText( "class" );
             Properties props = new Properties();
             
-            List params = f.getChildren("param");
-            
-            for( Iterator par = params.iterator(); par.hasNext(); )
-            {
-                Element p = (Element) par.next();
-                
-                props.setProperty( p.getChildText("name"), p.getChildText("value") );
+            List< Element > params = f.getChildren( "param" );
+            for( Iterator< Element > par = params.iterator(); par.hasNext(); ) {
+                Element p = par.next();
+                props.setProperty( p.getChildText( "name" ), p.getChildText( "value" ) );
             }
 
             initPageFilter( filterClass, props );
         }
-        
     }
     
  
@@ -448,66 +412,26 @@ public class DefaultFilterManager extend
         return modules;
     }
 
-    private void registerFilters()
-    {
+    private void registerFilters() {
         log.info( "Registering filters" );
+        List< Element > filters = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/filter"
);
 
-        SAXBuilder builder = new SAXBuilder();
-
-        try
-        {
-            //
-            // Register all filters which have created a resource containing its properties.
-            //
-            // Get all resources of all plugins.
-            //
-
-            Enumeration resources = getClass().getClassLoader().getResources( PLUGIN_RESOURCE_LOCATION
);
-
-            while( resources.hasMoreElements() )
-            {
-                URL resource = (URL) resources.nextElement();
-
-                try
-                {
-                    log.debug( "Processing XML: " + resource );
-
-                    Document doc = builder.build( resource );
-
-                    List plugins = XPath.selectNodes( doc, "/modules/filter");
-
-                    for( Iterator i = plugins.iterator(); i.hasNext(); )
-                    {
-                        Element pluginEl = (Element) i.next();
-
-                        String className = pluginEl.getAttributeValue("class");
-
-                        PageFilterInfo pluginInfo = PageFilterInfo.newInstance( className,
pluginEl );
-
-                        if( pluginInfo != null )
-                        {
-                            registerPlugin( pluginInfo );
-                        }
-                    }
-                }
-                catch( java.io.IOException e )
-                {
-                    log.error( "Couldn't load " + PLUGIN_RESOURCE_LOCATION + " resources:
" + resource, e );
-                }
-                catch( JDOMException e )
-                {
-                    log.error( "Error parsing XML for filter: "+PLUGIN_RESOURCE_LOCATION
);
-                }
+        //
+        // Register all filters which have created a resource containing its properties.
+        //
+        // Get all resources of all plugins.
+        //
+        for( Iterator< Element > i = filters.iterator(); i.hasNext(); ) {
+            Element pluginEl = i.next();
+            String className = pluginEl.getAttributeValue( "class" );
+            PageFilterInfo filterInfo = PageFilterInfo.newInstance( className, pluginEl );
+            if( filterInfo != null ) {
+                registerFilter( filterInfo );
             }
         }
-        catch( java.io.IOException e )
-        {
-            log.error( "Couldn't load all " + PLUGIN_RESOURCE_LOCATION + " resources", e
);
-        }
     }
 
-    private void registerPlugin(PageFilterInfo pluginInfo)
-    {
+    private void registerFilter(PageFilterInfo pluginInfo) {
         m_filterClassMap.put( pluginInfo.getName(), pluginInfo );
     }
 

Modified: jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java
URL: http://svn.apache.org/viewvc/jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java?rev=1551049&r1=1551048&r2=1551049&view=diff
==============================================================================
--- jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java
(original)
+++ jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java
Sun Dec 15 20:34:12 2013
@@ -23,11 +23,9 @@ import java.io.PrintWriter;
 import java.io.StreamTokenizer;
 import java.io.StringReader;
 import java.io.StringWriter;
-import java.net.URL;
 import java.text.MessageFormat;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -66,11 +64,8 @@ import org.apache.wiki.preferences.Prefe
 import org.apache.wiki.util.ClassUtil;
 import org.apache.wiki.util.FileUtil;
 import org.apache.wiki.util.TextUtil;
-import org.jdom2.Document;
+import org.apache.wiki.util.XmlUtil;
 import org.jdom2.Element;
-import org.jdom2.JDOMException;
-import org.jdom2.input.SAXBuilder;
-import org.jdom2.xpath.XPath;
 
 /**
  *  Manages plugin classes.  There exists a single instance of PluginManager
@@ -541,41 +536,20 @@ public class DefaultPluginManager extend
 
     private void registerPlugins() {
         log.info( "Registering plugins" );
-        SAXBuilder builder = new SAXBuilder();
+        List< Element > plugins = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/plugin"
);
 
-        try {
-            //
-            // Register all plugins which have created a resource containing its properties.
-            //
-            // Get all resources of all plugins.
-            //
-
-            Enumeration< URL > resources = getClass().getClassLoader().getResources(
PLUGIN_RESOURCE_LOCATION );
-
-            while( resources.hasMoreElements() ) {
-                URL resource = resources.nextElement();
+        //
+        // Register all plugins which have created a resource containing its properties.
+        //
+        // Get all resources of all plugins.
+        //
+        for( Element pluginEl : plugins ) {
+            String className = pluginEl.getAttributeValue( "class" );
+            WikiPluginInfo pluginInfo = WikiPluginInfo.newInstance( className, pluginEl );
 
-                try {
-                    log.debug( "Processing XML: " + resource );
-                    Document doc = builder.build( resource );
-                    List< Element > plugins = ( List< Element > )XPath.selectNodes(
doc, "/modules/plugin" );
-
-                    for( Element pluginEl : plugins ) {
-                        String className = pluginEl.getAttributeValue( "class" );
-                        WikiPluginInfo pluginInfo = WikiPluginInfo.newInstance( className,
pluginEl );
-
-                        if( pluginInfo != null ) {
-                            registerPlugin( pluginInfo );
-                        }
-                    }
-                } catch( IOException e ) {
-                    log.error( "Couldn't load " + PLUGIN_RESOURCE_LOCATION + " resources:
" + resource, e );
-                } catch( JDOMException e ) {
-                    log.error( "Error parsing XML for plugin: "+PLUGIN_RESOURCE_LOCATION
);
-                }
+            if( pluginInfo != null ) {
+                registerPlugin( pluginInfo );
             }
-        } catch( IOException e ) {
-            log.error( "Couldn't load all " + PLUGIN_RESOURCE_LOCATION + " resources", e
);
         }
     }
 

Modified: jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/ui/EditorManager.java
URL: http://svn.apache.org/viewvc/jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/ui/EditorManager.java?rev=1551049&r1=1551048&r2=1551049&view=diff
==============================================================================
--- jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/ui/EditorManager.java (original)
+++ jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/ui/EditorManager.java Sun Dec
15 20:34:12 2013
@@ -18,10 +18,8 @@
  */
 package org.apache.wiki.ui;
 
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -38,11 +36,8 @@ import org.apache.wiki.api.exceptions.No
 import org.apache.wiki.modules.ModuleManager;
 import org.apache.wiki.modules.WikiModuleInfo;
 import org.apache.wiki.preferences.Preferences;
-import org.jdom2.Document;
+import org.apache.wiki.util.XmlUtil;
 import org.jdom2.Element;
-import org.jdom2.JDOMException;
-import org.jdom2.input.SAXBuilder;
-import org.jdom2.xpath.XPath;
 
 
 /**
@@ -110,69 +105,29 @@ public class EditorManager extends Modul
      *  Any editors found are put in the registry.
      *
      */
-    private void registerEditors()
-    {
+    private void registerEditors() {
         log.info( "Registering editor modules" );
-
         m_editors = new HashMap<String, WikiEditorInfo>();
-        SAXBuilder builder = new SAXBuilder();
-
-        try
-        {
-            //
-            // Register all editors which have created a resource containing its properties.
-            //
-            // Get all resources of all modules
-            //
-
-            Enumeration< URL > resources = getClass().getClassLoader().getResources(
PLUGIN_RESOURCE_LOCATION );
-
-            while( resources.hasMoreElements() )
-            {
-                URL resource = resources.nextElement();
-
-                try
-                {
-                    log.debug( "Processing XML: " + resource );
-
-                    Document doc = builder.build( resource );
-
-                    List plugins = XPath.selectNodes( doc, "/modules/editor");
 
-                    for( Iterator i = plugins.iterator(); i.hasNext(); )
-                    {
-                        Element pluginEl = (Element) i.next();
-
-                        String name = pluginEl.getAttributeValue("name");
-
-                        WikiEditorInfo info = WikiEditorInfo.newInstance(name, pluginEl);
-
-                        if( checkCompatibility(info) )
-                        {
-                            m_editors.put( name, info );
-
-                            log.debug("Registered editor "+name);
-                        }
-                        else
-                        {
-                            log.info("Editor '"+name+"' not compatible with this version
of JSPWiki.");
-                        }
-                    }
-                }
-                catch( java.io.IOException e )
-                {
-                    log.error( "Couldn't load " + ModuleManager.PLUGIN_RESOURCE_LOCATION
+ " resources: " + resource, e );
-                }
-                catch( JDOMException e )
-                {
-                    log.error( "Error parsing XML for plugin: "+ModuleManager.PLUGIN_RESOURCE_LOCATION
);
-                }
+        //
+        // Register all editors which have created a resource containing its properties.
+        //
+        // Get all resources of all modules
+        //
+        List< Element > editors = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/editor"
);
+
+        for( Iterator< Element > i = editors.iterator(); i.hasNext(); ) {
+            Element pluginEl = i.next();
+            String name = pluginEl.getAttributeValue( "name" );
+            WikiEditorInfo info = WikiEditorInfo.newInstance( name, pluginEl );
+
+            if( checkCompatibility(info) ) {
+                m_editors.put( name, info );
+                log.debug( "Registered editor " + name );
+            } else {
+                log.info( "Editor '" + name + "' not compatible with this version of JSPWiki."
);
             }
         }
-        catch( java.io.IOException e )
-        {
-            log.error( "Couldn't load all " + PLUGIN_RESOURCE_LOCATION + " resources", e
);
-        }
     }
 
     /**

Modified: jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/ClassUtil.java
URL: http://svn.apache.org/viewvc/jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/ClassUtil.java?rev=1551049&r1=1551048&r2=1551049&view=diff
==============================================================================
--- jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/ClassUtil.java (original)
+++ jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/ClassUtil.java Sun Dec 15
20:34:12 2013
@@ -20,7 +20,6 @@ package org.apache.wiki.util;
 
 import java.io.File;
 import java.io.IOException;
-import java.io.InputStream;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.net.JarURLConnection;
@@ -38,10 +37,7 @@ import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.apache.wiki.api.exceptions.WikiException;
-import org.jdom2.Document;
 import org.jdom2.Element;
-import org.jdom2.input.SAXBuilder;
-import org.jdom2.xpath.XPath;
 
 /**
  *  Contains useful utilities for class file manipulation.  This is a static class,
@@ -49,8 +45,8 @@ import org.jdom2.xpath.XPath;
  *
  *  @since 2.1.29.
  */
-public final class ClassUtil
-{
+public final class ClassUtil {
+
     private static final Logger log = Logger.getLogger(ClassUtil.class);
     /**
      *  The location of the classmappings.xml document. It will be searched for
@@ -63,49 +59,29 @@ public final class ClassUtil
     /**
      *  Initialize the class mappings document.
      */
-    static
-    {
-        try
-        {
-            InputStream is = ClassUtil.class.getResourceAsStream( MAPPINGS );
-    
-            if( is != null )
-            {
-                Document doc = new SAXBuilder().build( is );
-        
-                XPath xpath = XPath.newInstance("/classmappings/mapping");
-    
-                List nodes = xpath.selectNodes( doc );
+    static {
+    	List< Element > nodes = XmlUtil.parse( MAPPINGS, "/classmappings/mapping" );
+
+        if( nodes.size() > 0 ) {
+            for( Iterator< Element > i = nodes.iterator(); i.hasNext(); ) {
+                Element f = i.next();
             
-                for( Iterator i = nodes.iterator(); i.hasNext(); )
-                {
-                    Element f = (Element) i.next();
+                String key = f.getChildText("requestedClass");
+                String className = f.getChildText("mappedClass");
                 
-                    String key = f.getChildText("requestedClass");
-                    String className = f.getChildText("mappedClass");
-                    
-                    c_classMappings.put( key, className );
-                    
-                    log.debug("Mapped class '"+key+"' to class '"+className+"'");
-                }
-            }
-            else
-            {
-                log.info("Didn't find class mapping document in "+MAPPINGS);
+                c_classMappings.put( key, className );
+                
+                log.debug("Mapped class '"+key+"' to class '"+className+"'");
             }
-        }
-        catch( Exception ex )
-        {
-            log.error("Unable to parse mappings document!",ex);
+        } else {
+            log.info("Didn't find class mapping document in "+MAPPINGS);
         }
     }
 
     /**
      * Private constructor to prevent direct instantiation.
      */
-    private ClassUtil()
-    {
-    }
+    private ClassUtil() {}
     
     /**
      *  Attempts to find a class from a collection of packages.  This will first
@@ -120,45 +96,33 @@ public final class ClassUtil
      *  @throws ClassNotFoundException if this particular class cannot be found
      *          from the list.
      */
-    public static Class<?> findClass( List packages, String className )
-        throws ClassNotFoundException
-    {
+    public static Class<?> findClass( List< String > packages, String className
) throws ClassNotFoundException {
         ClassLoader loader = ClassUtil.class.getClassLoader();
 
-        try
-        {
+        try {
             return loader.loadClass( className );
-        }
-        catch( ClassNotFoundException e )
-        {
-            for( Iterator i = packages.iterator(); i.hasNext(); )
-            {
-                String packageName = (String)i.next();
+        } catch( ClassNotFoundException e ) {
+            for( Iterator< String > i = packages.iterator(); i.hasNext(); ) {
+                String packageName = i.next();
 
-                try
-                {
+                try {
                     return loader.loadClass( packageName + "." + className );
-                }
-                catch( ClassNotFoundException ex )
-                {
+                } catch( ClassNotFoundException ex ) {
                     // This is okay, we go to the next package.
                 }
             }
 
             // try the old (pre 2.9) package name for compatibility :
-            try
-            {
+            try {
                 className = className.replaceFirst( "com\\.ecyrd\\.jspwiki", "org.apache.wiki"
);
                 return loader.loadClass( className );
-            }
-            catch( ClassNotFoundException ex )
-            {
+            } catch( ClassNotFoundException ex ) {
                 // This is okay, if we fail we throw our own CNFE..
             }
 
         }
 
-        throw new ClassNotFoundException("Class '"+className+"' not found in search path!");
+        throw new ClassNotFoundException( "Class '" + className + "' not found in search
path!" );
     }
     
     /**
@@ -172,9 +136,7 @@ public final class ClassUtil
      *  @throws ClassNotFoundException if this particular class cannot be found.
      */
 
-    public static Class<?> findClass( String packageName, String className )
-        throws ClassNotFoundException
-    {
+    public static Class<?> findClass( String packageName, String className ) throws
ClassNotFoundException {
         ArrayList<String> list = new ArrayList<String>();
         list.add( packageName );
 

Added: jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/XmlUtil.java
URL: http://svn.apache.org/viewvc/jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/XmlUtil.java?rev=1551049&view=auto
==============================================================================
--- jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/XmlUtil.java (added)
+++ jspwiki/trunk/jspwiki-war/src/main/java/org/apache/wiki/util/XmlUtil.java Sun Dec 15 20:34:12
2013
@@ -0,0 +1,115 @@
+/* 
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.  
+ */
+package org.apache.wiki.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Logger;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.JDOMException;
+import org.jdom2.filter.Filters;
+import org.jdom2.input.SAXBuilder;
+import org.jdom2.xpath.XPathExpression;
+import org.jdom2.xpath.XPathFactory;
+
+
+/**
+ * Utility class to parse XML files.
+ *
+ * @since 2.10
+ */
+public final class XmlUtil {
+	
+	private static final Logger log = Logger.getLogger( XmlUtil.class );
+	
+	private XmlUtil() {}
+	
+	/**
+	 * Parses the given XML file and returns the requested nodes. If there's an error accessing
or parsing the file, an
+	 * empty list is returned.
+	 * 
+	 * @param xml file to parse; matches all resources from classpath, filters repeated items.
+	 * @param requestedNodes requestd nodes on the xml file
+	 * @return the requested nodes of the XML file.
+	 */
+	public static List< Element > parse( String xml, String requestedNodes ) {
+		if( StringUtils.isNotEmpty( xml ) && StringUtils.isNotEmpty( requestedNodes ) )
{
+			Set< Element > readed = new HashSet< Element >();
+			SAXBuilder builder = new SAXBuilder();
+			try {
+				Enumeration< URL > resources = XmlUtil.class.getClassLoader().getResources( xml
);
+				while( resources.hasMoreElements() ) {
+	                URL resource = resources.nextElement();
+	                
+	                log.debug( "reading " + resource.toString() );
+	                Document doc = builder.build( resource );
+	                XPathFactory xpfac = XPathFactory.instance();
+	                XPathExpression< Element > xp = xpfac.compile( requestedNodes, Filters.element()
);
+	                readed.addAll( xp.evaluate( doc ) ); // filter out repeated items
+	            }
+				return new ArrayList< Element >( readed );
+			} catch ( IOException ioe ) {
+				log.error( "Couldn't load all " + xml + " resources", ioe );
+			} catch ( JDOMException jdome ) {
+				log.error( "error parsing " + xml + " resources", jdome );
+			}
+		}
+		
+		return Collections.< Element >emptyList();
+	}
+	
+	/**
+	 * Parses the given stream and returns the requested nodes. If there's an error accessing
or parsing the stream, an
+	 * empty list is returned.
+	 * 
+	 * @param xmlStream stream to parse.
+	 * @param requestedNodes requestd nodes on the xml stream.
+	 * @return the requested nodes of the XML stream.
+	 */
+	public static List< Element > parse( InputStream xmlStream, String requestedNodes
) {
+		if( xmlStream != null && StringUtils.isNotEmpty( requestedNodes ) ) {
+			SAXBuilder builder = new SAXBuilder();
+			try {
+                Document doc = builder.build( xmlStream );
+                XPathFactory xpfac = XPathFactory.instance();
+                XPathExpression< Element > xp = xpfac.compile( requestedNodes, Filters.element()
);
+                
+				return xp.evaluate( doc );
+			} catch ( IOException ioe ) {
+				log.error( "Couldn't load all " + xmlStream + " resources", ioe );
+			} catch ( JDOMException jdome ) {
+				log.error( "error parsing " + xmlStream + " resources", jdome );
+			}
+		}
+		
+		return Collections.< Element >emptyList();
+	}
+
+}

Modified: jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/AllTests.java
URL: http://svn.apache.org/viewvc/jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/AllTests.java?rev=1551049&r1=1551048&r2=1551049&view=diff
==============================================================================
--- jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/AllTests.java (original)
+++ jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/AllTests.java Sun Dec 15
20:34:12 2013
@@ -16,7 +16,6 @@
     specific language governing permissions and limitations
     under the License.  
  */
-
 package org.apache.wiki.util;
 
 import junit.framework.Test;
@@ -24,15 +23,13 @@ import junit.framework.TestCase;
 import junit.framework.TestSuite;
 
 
-public class AllTests extends TestCase
-{
-    public AllTests( String s )
-    {
+public class AllTests extends TestCase {
+
+    public AllTests( String s ) {
         super( s );
     }
 
-    public static Test suite()
-    {
+    public static Test suite() {
         TestSuite suite = new TestSuite("Utility suite tests");
 
         suite.addTest( ClassUtilTest.suite() );
@@ -47,6 +44,7 @@ public class AllTests extends TestCase
         suite.addTest( TextUtilTest.suite() );
         suite.addTest( TimedCounterListTest.suite() );
         suite.addTest( UtilJ2eeCompatTest.suite() );
+        suite.addTest( XmlUtilTest.suite() );
         
         return suite;
     }

Added: jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/XmlUtilTest.java
URL: http://svn.apache.org/viewvc/jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/XmlUtilTest.java?rev=1551049&view=auto
==============================================================================
--- jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/XmlUtilTest.java (added)
+++ jspwiki/trunk/jspwiki-war/src/test/java/org/apache/wiki/util/XmlUtilTest.java Sun Dec
15 20:34:12 2013
@@ -0,0 +1,87 @@
+/* 
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.  
+ */
+package org.apache.wiki.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.List;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.wiki.modules.ModuleManager;
+import org.jdom2.Element;
+
+public class XmlUtilTest extends TestCase {
+
+    public static Test suite() {
+        return new TestSuite( XmlUtilTest.class );
+    }
+    
+    public void testParseFromClasspath() {
+    	List< Element > elements = XmlUtil.parse( ModuleManager.PLUGIN_RESOURCE_LOCATION,
"/modules/plugin" );
+    	assertEquals( 4, elements.size() ); // 2 on src/main/resources, another 2 on src/test/resources
+    	
+    	elements = XmlUtil.parse( ModuleManager.PLUGIN_RESOURCE_LOCATION, "/modules/filter"
);
+     	assertEquals( 1, elements.size() );
+     	
+     	elements = XmlUtil.parse( ModuleManager.PLUGIN_RESOURCE_LOCATION, "/modules/editor"
);
+     	assertEquals( 1, elements.size() );
+     	
+     	elements = XmlUtil.parse( ModuleManager.PLUGIN_RESOURCE_LOCATION, "/modules/heck" );
+     	assertEquals( 0, elements.size() );
+     	
+     	elements = XmlUtil.parse( "doesnt/exist.this", "/modules/editor" );
+     	assertEquals( 0, elements.size() );
+     	
+     	elements = XmlUtil.parse( ( String )null, "/modules/editor" );
+     	assertEquals( 0, elements.size() );
+     	
+     	elements = XmlUtil.parse( ModuleManager.PLUGIN_RESOURCE_LOCATION, null );
+     	assertEquals( 0, elements.size() );
+    }
+    
+    public void testParseFromStream() throws FileNotFoundException {
+    	InputStream is = new FileInputStream( new File ("./src/test/resources/ini/jspwiki_module.xml"
) );
+    	List< Element > elements = XmlUtil.parse( is, "/modules/plugin" );
+    	assertEquals( 2, elements.size() ); 
+    	
+    	elements = XmlUtil.parse( is, "/modules/filter" );
+     	assertEquals( 0, elements.size() );
+     	
+     	elements = XmlUtil.parse( is, "/modules/editor" );
+     	assertEquals( 0, elements.size() );
+     	
+     	elements = XmlUtil.parse( is, "/modules/heck" );
+     	assertEquals( 0, elements.size() );
+     	
+     	elements = XmlUtil.parse( ( InputStream )null, "/modules/editor" );
+     	assertEquals( 0, elements.size() );
+     	
+     	elements = XmlUtil.parse( is, null );
+     	assertEquals( 0, elements.size() );
+     	
+     	IOUtils.closeQuietly( is );
+    }
+
+}



Mime
View raw message