You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lenya.apache.org by an...@apache.org on 2006/06/22 00:22:33 UTC

svn commit: r416136 - in /lenya/trunk: src/resources/build/ src/targets/ tools/anttasks/org/apache/lenya/cms/ant/ tools/anttasks/org/apache/lenya/xml/

Author: andreas
Date: Wed Jun 21 15:22:32 2006
New Revision: 416136

URL: http://svn.apache.org/viewvc?rev=416136&view=rev
Log:
Build process: Building modules separately, dependencies are resolved

Added:
    lenya/trunk/src/resources/build/
    lenya/trunk/src/resources/build/modules2build.xsl
    lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.class   (with props)
    lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.java
    lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.class   (with props)
    lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.java
    lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.class   (with props)
    lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.java
    lenya/trunk/tools/anttasks/org/apache/lenya/xml/
    lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.class   (with props)
    lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.java
Modified:
    lenya/trunk/src/targets/modules-build.xml
    lenya/trunk/src/targets/properties-build.xml
    lenya/trunk/src/targets/webapp-build.xml
    lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/CopyJavaSourcesTask.class

Added: lenya/trunk/src/resources/build/modules2build.xsl
URL: http://svn.apache.org/viewvc/lenya/trunk/src/resources/build/modules2build.xsl?rev=416136&view=auto
==============================================================================
--- lenya/trunk/src/resources/build/modules2build.xsl (added)
+++ lenya/trunk/src/resources/build/modules2build.xsl Wed Jun 21 15:22:32 2006
@@ -0,0 +1,123 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
+  xmlns:mod="http://apache.org/lenya/module/1.0"
+  xmlns:list="http://apache.org/lenya/module-list/1.0">
+  
+  <xsl:output indent="yes"/>
+
+  <xsl:template match="list:modules">
+    <project name="lenya-modules">
+      
+      <!-- Set up classpath -->
+      <path id="classpath">
+        <fileset>
+          <xsl:attribute name="dir">${lib.dir}</xsl:attribute>
+          <include name="*.jar"/>
+        </fileset>
+        <fileset>
+          <xsl:attribute name="dir">${build.dir}/lib</xsl:attribute>
+          <include name="*.jar"/>
+        </fileset>
+        <fileset>
+          <xsl:attribute name="dir">${cocoon.webapp.dir}/WEB-INF/lib</xsl:attribute>
+          <include name="*.jar"/>
+        </fileset>
+        <fileset dir="tools/jetty/lib">
+          <include name="servlet-*.jar"/>
+        </fileset>
+      </path>
+      
+      <target name="compile-modules">
+        <xsl:apply-templates select="list:module" mode="call"/>
+      </target>
+      
+      <xsl:apply-templates select="list:module" mode="target"/>
+      
+    </project>
+  </xsl:template>
+  
+  
+  <xsl:template match="list:module" mode="call">
+    <xsl:apply-templates select="document(concat(@src, '/module.xml'))/mod:module" mode="call"/>
+  </xsl:template>
+  
+  
+  <xsl:template match="mod:module" mode="call">
+    <antcall target="compile-module-{mod:id}"/>
+  </xsl:template>
+  
+
+  <xsl:template match="list:module" mode="target">
+    <xsl:apply-templates select="document(concat(@src, '/module.xml'))/mod:module" mode="target">
+      <xsl:with-param name="src" select="@src"/>
+    </xsl:apply-templates>
+  </xsl:template>
+  
+  
+  <xsl:template match="mod:module" mode="target">
+    <xsl:param name="src"/>
+    <xsl:variable name="id" select="mod:id"/>
+    
+    <xsl:text>
+      
+    </xsl:text>
+    <xsl:comment>Compile module <xsl:value-of select="$src"/> </xsl:comment>
+    <xsl:text>
+    </xsl:text>
+    
+    <xsl:variable name="srcDir"><xsl:value-of select="$src"/>/java/src</xsl:variable>
+    <available file="{$srcDir}" property="compile.module.{$id}"/>
+    
+    <target name="compile-module-{$id}" if="compile.module.{$id}">
+      <xsl:variable name="destDir">${build.dir}/modules/<xsl:value-of select="$id"/></xsl:variable>
+      <xsl:variable name="debug">${debug}</xsl:variable>
+      <xsl:variable name="optimize">${optimize}</xsl:variable>
+      <xsl:variable name="deprecation">${deprecation}</xsl:variable>
+      <xsl:variable name="target">${target.vm}</xsl:variable>
+      <xsl:variable name="nowarn">${nowarn}</xsl:variable>
+      
+      <path id="module.classpath">
+        <path refid="classpath"/>
+        <fileset includes="lenya-*-api.jar">
+          <xsl:attribute name="dir">${build.webapp}/WEB-INF/lib</xsl:attribute>
+        </fileset>
+        <xsl:for-each select="mod:depends">
+          <fileset includes="lenya-module-{@module}.jar">
+            <xsl:attribute name="dir">${build.webapp}/WEB-INF/lib</xsl:attribute>
+          </fileset>
+        </xsl:for-each>
+        <fileset dir="{$src}">
+          <include name="java/lib/*.jar"/>
+        </fileset>
+        <fileset>
+          <xsl:attribute name="dir">${lib.dir}</xsl:attribute>
+          <include name="*.jar"/>
+        </fileset>
+      </path>
+      
+      <mkdir dir="{$destDir}"/>
+      
+      <javac
+        destdir="{$destDir}"
+        debug="{$debug}"
+        optimize="{$optimize}"
+        deprecation="{$deprecation}"
+        target="{$target}"
+        nowarn="{$nowarn}"
+        source="1.4">
+        <src path="{$srcDir}"/>
+        <classpath refid="module.classpath"/>
+      </javac>
+      
+      <xsl:variable name="jarfile">${build.webapp}/WEB-INF/lib/lenya-module-<xsl:value-of select="$id"/>.jar</xsl:variable>
+      
+      <jar jarfile="{$jarfile}" index="true">
+        <fileset dir="{$destDir}">
+          <exclude name="**/Manifest.mf"/>
+        </fileset>
+      </jar>
+
+    </target>
+  </xsl:template>
+  
+</xsl:stylesheet>
\ No newline at end of file

Modified: lenya/trunk/src/targets/modules-build.xml
URL: http://svn.apache.org/viewvc/lenya/trunk/src/targets/modules-build.xml?rev=416136&r1=416135&r2=416136&view=diff
==============================================================================
--- lenya/trunk/src/targets/modules-build.xml (original)
+++ lenya/trunk/src/targets/modules-build.xml Wed Jun 21 15:22:32 2006
@@ -26,6 +26,21 @@
   <property name="modules.root.dirs" value=""/>
   <property name="build.modules" value="${build.webapp}/lenya/modules"/>
   
+  <target name="compile-modules" depends="init-tasks">
+    <generateModuleList
+      moduleDirs="${modules.root.dirs}"
+      moduleFile="${build.dir}/temp/modules.xml"/>
+    <xslt
+      in="${build.dir}/temp/modules.xml"
+      out="${build.dir}/temp/modules-build.xml"
+      style="${src.resource.dir}/build/modules2build.xsl"/>
+
+    <ant antfile="${build.dir}/temp/modules-build.xml"
+      inheritall="true"
+      inheritrefs="true"
+      target="compile-modules"/>
+  </target>
+  
   <target name="copy-modules">
     <!--
     <copyPubs todir="${build.webapp}/lenya/modules"

Modified: lenya/trunk/src/targets/properties-build.xml
URL: http://svn.apache.org/viewvc/lenya/trunk/src/targets/properties-build.xml?rev=416136&r1=416135&r2=416136&view=diff
==============================================================================
--- lenya/trunk/src/targets/properties-build.xml (original)
+++ lenya/trunk/src/targets/properties-build.xml Wed Jun 21 15:22:32 2006
@@ -156,6 +156,7 @@
     <taskdef name="bulkCopy"        classpath="${tools.tasks.dest}" classname="org.apache.lenya.cms.ant.BulkCopyTask"/>
     <taskdef name="copyPubs"        classpath="${tools.tasks.dest}" classname="org.apache.lenya.cms.ant.CopyPublicationsTask"/>
     <taskdef name="xpatch"          classpath="${cocoon.src.dir}/tools/anttasks" classname="XConfToolTask" />
+    <taskdef name="generateModuleList" classpath="${tools.tasks.dest}" classname="org.apache.lenya.cms.ant.GenerateModuleList" />
   </target>
 
   <!-- Compile tasks -->

Modified: lenya/trunk/src/targets/webapp-build.xml
URL: http://svn.apache.org/viewvc/lenya/trunk/src/targets/webapp-build.xml?rev=416136&r1=416135&r2=416136&view=diff
==============================================================================
--- lenya/trunk/src/targets/webapp-build.xml (original)
+++ lenya/trunk/src/targets/webapp-build.xml Wed Jun 21 15:22:32 2006
@@ -157,24 +157,13 @@
       includes="**/*.xconf"
       excludes="prepare/*.xconf"
       addComments="false"/>
+    
+    <antcall target="compile-modules"/>
       
-    <path id="classpath.modules">
-      <path refid="classpath"/>
-      <fileset dir="${build.webapp}/WEB-INF/lib" includes="lenya-*-api.jar"/>
-    </path>
-
-    <!-- compile and package modules -->
-    <antcall target="compile-src">
-      <param name="compile.src.dir" value="${build.dir}/java/modules"/>
-      <param name="compile.dest.dir" value="${build.dir}/modules"/>
-      <param name="compile.classpath" value="classpath.modules"/>
-      <param name="jar.name" value="modules"/>
-    </antcall>
-
     <path id="classpath.pubs">
       <path refid="classpath"/>
       <fileset dir="${build.webapp}/WEB-INF/lib" includes="lenya-*-api.jar"/>
-      <fileset dir="${build.webapp}/WEB-INF/lib" includes="lenya-*-modules.jar"/>
+      <fileset dir="${build.webapp}/WEB-INF/lib" includes="lenya-module-*.jar"/>
     </path>
     
     <!-- compile and package publications -->

Modified: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/CopyJavaSourcesTask.class
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/CopyJavaSourcesTask.class?rev=416136&r1=416135&r2=416136&view=diff
==============================================================================
Binary files - no diff available.

Added: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.class
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.class?rev=416136&view=auto
==============================================================================
Binary file - no diff available.

Propchange: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.class
------------------------------------------------------------------------------
    svn:mime-type = application/octet-stream

Added: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.java
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.java?rev=416136&view=auto
==============================================================================
--- lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.java (added)
+++ lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/GenerateModuleList.java Wed Jun 21 15:22:32 2006
@@ -0,0 +1,115 @@
+/*
+ * Copyright  1999-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.
+ *
+ */
+
+/* $Id: BulkCopyTask.java 383219 2006-03-04 23:04:55Z michi $  */
+package org.apache.lenya.cms.ant;
+
+import java.io.File;
+import java.util.StringTokenizer;
+
+import org.apache.lenya.xml.AntDocumentHelper;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.Task;
+import org.apache.tools.ant.types.Path;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Generate an XML containing modules.
+ */
+public class GenerateModuleList extends Task {
+
+    private Path moduleDirectories;
+    private String moduleFile;
+
+    /**
+     * @see org.apache.tools.ant.Task#execute()
+     */
+    public void execute() throws BuildException {
+
+        ModuleDescriptorList descriptors = new ModuleDescriptorList();
+
+        StringTokenizer st = new StringTokenizer(this.moduleDirectories.toString(),
+                File.pathSeparator);
+
+        while (st.hasMoreTokens()) {
+            String moduleDir = st.nextToken();
+            File path = new File(moduleDir);
+
+            if (path.isDirectory()) {
+                if (isModuleDirectory(path)) {
+                    descriptors.add(path);
+                } else {
+                    String[] dirs = path.list();
+                    boolean matched = false;
+                    for (int i = 0; i < dirs.length; i++) {
+                        File moduleSubDir = new File(path, dirs[i]);
+                        if (isModuleDirectory(moduleSubDir)) {
+                            descriptors.add(moduleSubDir);
+                            matched = true;
+                        }
+                    }
+                    if (!matched) {
+                        log("No module(s) found in directory [" + path + "]");
+                    }
+                }
+            } else {
+                throw new BuildException("No such directory: " + path);
+            }
+        }
+
+        try {
+            Document doc = AntDocumentHelper.createDocument(NAMESPACE, "modules", null);
+            ModuleDescriptor[] modules = descriptors.getSortedDescriptors();
+            for (int i = 0; i < modules.length; i++) {
+                File path = modules[i].getSourceDir();
+                Element element = doc.createElementNS(NAMESPACE, "module");
+                element.setAttribute("src", path.getAbsolutePath());
+                doc.getDocumentElement().appendChild(element);
+            }
+            File file = new File(this.moduleFile.replace('/', File.separatorChar));
+            AntDocumentHelper.writeDocument(doc, file);
+        } catch (Exception e) {
+            throw new BuildException(e);
+        }
+
+    }
+
+    protected static final String NAMESPACE = "http://apache.org/lenya/module-list/1.0";
+
+    protected boolean isModuleDirectory(File path) {
+        File moduleFile = new File(path, "module.xml");
+        return moduleFile.isFile();
+    }
+
+    /**
+     * Set the module source directories.
+     * @param dirs The module directories.
+     */
+    public void setModuleDirs(Path dirs) {
+        this.moduleDirectories = dirs;
+    }
+
+    /**
+     * Set the file to generate.
+     * @param file The file.
+     */
+    public void setModuleFile(String file) {
+        this.moduleFile = file;
+    }
+
+}

Added: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.class
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.class?rev=416136&view=auto
==============================================================================
Binary file - no diff available.

Propchange: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.class
------------------------------------------------------------------------------
    svn:mime-type = application/octet-stream

Added: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.java
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.java?rev=416136&view=auto
==============================================================================
--- lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.java (added)
+++ lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptor.java Wed Jun 21 15:22:32 2006
@@ -0,0 +1,94 @@
+/*
+ * Copyright  1999-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.
+ *
+ */
+
+/* $Id: BulkCopyTask.java 383219 2006-03-04 23:04:55Z michi $  */
+package org.apache.lenya.cms.ant;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.lenya.xml.AntDocumentHelper;
+import org.apache.tools.ant.BuildException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Module descriptor.
+ */
+public class ModuleDescriptor {
+
+    protected static final String NAMESPACE = "http://apache.org/lenya/module/1.0";
+
+    private String id;
+    private List dependencies = new ArrayList();
+    private File sourceDir;
+
+    /**
+     * Ctor.
+     * @param sourceDir The source dir.
+     * @throws BuildException if an error occurs.
+     */
+    public ModuleDescriptor(File sourceDir) throws BuildException {
+        this.sourceDir = sourceDir;
+        File moduleFile = new File(sourceDir, "module.xml");
+        try {
+            Document doc = AntDocumentHelper.readDocument(moduleFile);
+            Element idElement = AntDocumentHelper.getChildren(doc.getDocumentElement(),
+                    NAMESPACE,
+                    "id")[0];
+            this.id = AntDocumentHelper.getSimpleElementText(idElement).trim();
+            Element[] dependencyElements = AntDocumentHelper.getChildren(doc.getDocumentElement(),
+                    NAMESPACE,
+                    "depends");
+            for (int i = 0; i < dependencyElements.length; i++) {
+                String value = dependencyElements[i].getAttribute("module");
+                if (value == null || value.equals("")) {
+                    throw new BuildException("Invalid dependency for module [" + getId() + "]");
+                }
+                this.dependencies.add(value);
+            }
+        } catch (BuildException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new BuildException(e);
+        }
+    }
+
+    /**
+     * @return A list of the module IDs this module depends on.
+     */
+    public String[] getDependencies() {
+        return (String[]) dependencies.toArray(new String[dependencies.size()]);
+    }
+
+    /**
+     * @return The module ID.
+     */
+    public String getId() {
+        return id;
+    }
+
+    /**
+     * @return The source directory.
+     */
+    public File getSourceDir() {
+        return sourceDir;
+    }
+
+
+}

Added: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.class
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.class?rev=416136&view=auto
==============================================================================
Binary file - no diff available.

Propchange: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.class
------------------------------------------------------------------------------
    svn:mime-type = application/octet-stream

Added: lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.java
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.java?rev=416136&view=auto
==============================================================================
--- lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.java (added)
+++ lenya/trunk/tools/anttasks/org/apache/lenya/cms/ant/ModuleDescriptorList.java Wed Jun 21 15:22:32 2006
@@ -0,0 +1,78 @@
+/*
+ * Copyright  1999-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.lenya.cms.ant;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Module descriptor list.
+ */
+public class ModuleDescriptorList {
+
+    private Map id2descriptor = new HashMap();
+
+    public void add(File srcDir) {
+        ModuleDescriptor descriptor = new ModuleDescriptor(srcDir);
+        if (!this.id2descriptor.containsKey(descriptor.getId())) {
+            this.id2descriptor.put(descriptor.getId(), descriptor);
+        }
+    }
+
+    public ModuleDescriptor get(String id) {
+        if (!this.id2descriptor.containsKey(id)) {
+            throw new IllegalArgumentException("Module [" + id + "] not found!");
+        }
+        return (ModuleDescriptor) this.id2descriptor.get(id);
+    }
+
+    public ModuleDescriptor[] getSortedDescriptors() {
+        Collection values = this.id2descriptor.values();
+        ModuleDescriptor[] descriptors = (ModuleDescriptor[]) values.toArray(new ModuleDescriptor[values.size()]);
+        sort(descriptors);
+        return descriptors;
+    }
+
+    public boolean dependsOn(ModuleDescriptor d1, ModuleDescriptor d2) {
+        boolean depends = false;
+        if (Arrays.asList(d1.getDependencies()).contains(d2.getId())) {
+            depends = true;
+        } else {
+            String[] dependencies = d1.getDependencies();
+            for (int i = 0; i < dependencies.length; i++) {
+                ModuleDescriptor dependency = ModuleDescriptorList.this.get(dependencies[i]);
+                depends = depends || dependsOn(dependency, d2);
+            }
+        }
+        return depends;
+    }
+
+    public void sort(ModuleDescriptor[] descriptors) {
+        for (int i = 0; i < descriptors.length; i++) {
+            for (int j = i + 1; j < descriptors.length; j++) {
+                if (dependsOn(descriptors[i], descriptors[j])) {
+                    ModuleDescriptor temp = descriptors[i];
+                    descriptors[i] = descriptors[j];
+                    descriptors[j] = temp;
+                }
+            }
+        }
+    }
+}

Added: lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.class
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.class?rev=416136&view=auto
==============================================================================
Binary file - no diff available.

Propchange: lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.class
------------------------------------------------------------------------------
    svn:mime-type = application/octet-stream

Added: lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.java
URL: http://svn.apache.org/viewvc/lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.java?rev=416136&view=auto
==============================================================================
--- lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.java (added)
+++ lenya/trunk/tools/anttasks/org/apache/lenya/xml/AntDocumentHelper.java Wed Jun 21 15:22:32 2006
@@ -0,0 +1,184 @@
+package org.apache.lenya.xml;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+import org.xml.sax.SAXException;
+
+/**
+ * Slightly modified version of Lenya's DocumentBuilder to be used in Ant tasks.
+ */
+public class AntDocumentHelper {
+
+    /**
+     * Creates a non-validating and namespace-aware DocumentBuilder.
+     * @return A new DocumentBuilder object.
+     * @throws ParserConfigurationException if an error occurs
+     */
+    public static DocumentBuilder createBuilder() throws ParserConfigurationException {
+        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        factory.setNamespaceAware(true);
+        DocumentBuilder builder = factory.newDocumentBuilder();
+        return builder;
+    }
+
+    /**
+     * Creates a document. A xmlns:prefix="namespaceUri" attribute is added to the document element.
+     * @param namespaceUri The namespace URL of the root element.
+     * @param qualifiedName The qualified name of the root element.
+     * @param documentType The type of document to be created or null. When doctype is not null, its
+     *            Node.ownerDocument attribute is set to the document being created.
+     * @return A new Document object.
+     * @throws DOMException if an error occurs
+     * @throws ParserConfigurationException if an error occurs
+     * @see org.w3c.dom.DOMImplementation#createDocument(String, String, DocumentType)
+     */
+    public static Document createDocument(String namespaceUri, String qualifiedName,
+            DocumentType documentType) throws DOMException, ParserConfigurationException {
+        DocumentBuilder builder = createBuilder();
+        Document document = builder.getDOMImplementation().createDocument(namespaceUri,
+                qualifiedName,
+                documentType);
+
+        // add xmlns:prefix attribute
+        String name = "xmlns";
+        int index = qualifiedName.indexOf(":");
+
+        if (index > -1) {
+            name += (":" + qualifiedName.substring(0, index));
+        }
+
+        document.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/",
+                name,
+                namespaceUri);
+
+        return document;
+    }
+
+    /**
+     * Writes a document to a file. A new file is created if it does not exist.
+     * @param document The document to save.
+     * @param file The file to save the document to.
+     * @throws IOException if an error occurs
+     * @throws TransformerConfigurationException if an error occurs
+     * @throws TransformerException if an error occurs
+     */
+    public static void writeDocument(Document document, File file)
+            throws TransformerConfigurationException, TransformerException, IOException {
+        // sanity checks
+        if (document == null)
+            throw new IllegalArgumentException("illegal usage, parameter document may not be null");
+        if (file == null)
+            throw new IllegalArgumentException("illegal usage, parameter file may not be null");
+
+        file.getParentFile().mkdirs();
+        file.createNewFile();
+
+        DOMSource source = new DOMSource(document);
+        FileOutputStream out = new FileOutputStream(file);
+        StreamResult result = new StreamResult(out);
+        getTransformer(document.getDoctype()).transform(source, result);
+        out.close();
+    }
+
+    /**
+     * Get the transformer.
+     * @param documentType the document type
+     * @return a transformer
+     * @throws TransformerConfigurationException if an error occurs
+     */
+    protected static Transformer getTransformer(DocumentType documentType)
+            throws TransformerConfigurationException {
+        TransformerFactory factory = TransformerFactory.newInstance();
+        Transformer transformer = factory.newTransformer();
+        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
+
+        if (documentType != null) {
+            if (documentType.getPublicId() != null)
+                transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, documentType.getPublicId());
+            if (documentType.getSystemId() != null)
+                transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId());
+        }
+
+        return transformer;
+    }
+
+    /**
+     * Reads a document from a file.
+     * @return A document.
+     * @param file The file to load the document from.
+     * @throws ParserConfigurationException if an error occurs
+     * @throws SAXException if an error occurs
+     * @throws IOException if an error occurs
+     */
+    public static Document readDocument(File file) throws ParserConfigurationException,
+            SAXException, IOException {
+        DocumentBuilder builder = createBuilder();
+        return builder.parse(file);
+    }
+
+    /**
+     * Returns all child elements of an element that belong to a certain
+     * namespace and have a certain local name.
+     * @param element The parent element.
+     * @param namespaceUri The namespace that the childen must belong to.
+     * @param localName The local name of the children.
+     * @return The child elements.
+     */
+    public static Element[] getChildren(Element element, String namespaceUri, String localName) {
+        List childElements = new ArrayList();
+        NodeList children = element.getElementsByTagNameNS(namespaceUri, localName);
+
+        for (int i = 0; i < children.getLength(); i++) {
+            if (children.item(i).getParentNode() == element) {
+                childElements.add(children.item(i));
+            }
+        }
+
+        return (Element[]) childElements.toArray(new Element[childElements.size()]);
+    }
+
+    /**
+     * Returns the text inside an element. Only the child text nodes of this
+     * element are collected.
+     * @param element The element.
+     * @return The text inside the element.
+     */
+    public static String getSimpleElementText(Element element) {
+        StringBuffer buffer = new StringBuffer();
+        NodeList children = element.getChildNodes();
+
+        for (int i = 0; i < children.getLength(); i++) {
+            Node child = children.item(i);
+
+            if (child instanceof Text) {
+                buffer.append(child.getNodeValue());
+            }
+        }
+
+        return buffer.toString();
+    }
+
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@lenya.apache.org
For additional commands, e-mail: commits-help@lenya.apache.org