You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by gi...@apache.org on 2001/12/20 17:41:44 UTC

cvs commit: xml-cocoon2/src/org/apache/cocoon Main.java

giacomo     01/12/20 08:41:44

  Modified:    src/org/apache/cocoon Main.java
  Log:
  added Javadocs
  fixed debug logging (wrapped with isDebugEnabled)
  
  Revision  Changes    Path
  1.33      +256 -57   xml-cocoon2/src/org/apache/cocoon/Main.java
  
  Index: Main.java
  ===================================================================
  RCS file: /home/cvs/xml-cocoon2/src/org/apache/cocoon/Main.java,v
  retrieving revision 1.32
  retrieving revision 1.33
  diff -u -r1.32 -r1.33
  --- Main.java	2001/12/13 18:26:23	1.32
  +++ Main.java	2001/12/20 16:41:44	1.33
  @@ -1,11 +1,57 @@
  -
  -/*****************************************************************************
  - * Copyright (C) The Apache Software Foundation. All rights reserved.        *
  - * ------------------------------------------------------------------------- *
  - * This software is published under the terms of the Apache Software License *
  - * version 1.1, a copy of which has been included  with this distribution in *
  - * the LICENSE file.                                                         *
  - *****************************************************************************/
  +/*
  + * The Apache Software License, Version 1.1
  + *
  + *
  + * Copyright (c) 2001 The Apache Software Foundation.  All rights
  + * reserved.
  + *
  + * Redistribution and use in source and binary forms, with or without
  + * modification, are permitted provided that the following conditions
  + * are met:
  + *
  + * 1. Redistributions of source code must retain the above copyright
  + *    notice, this list of conditions and the following disclaimer.
  + *
  + * 2. Redistributions in binary form must reproduce the above copyright
  + *    notice, this list of conditions and the following disclaimer in
  + *    the documentation and/or other materials provided with the
  + *    distribution.
  + *
  + * 3. The end-user documentation included with the redistribution,
  + *    if any, must include the following acknowledgment:
  + *       "This product includes software developed by the
  + *        Apache Software Foundation (http://www.apache.org/)."
  + *    Alternately, this acknowledgment may appear in the software itself,
  + *    if and wherever such third-party acknowledgments normally appear.
  + *
  + * 4. The names "Axis" and "Apache Software Foundation" must
  + *    not be used to endorse or promote products derived from this
  + *    software without prior written permission. For written
  + *    permission, please contact apache@apache.org.
  + *
  + * 5. Products derived from this software may not be called "Apache",
  + *    nor may "Apache" appear in their name, without prior written
  + *    permission of the Apache Software Foundation.
  + *
  + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  + * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  + * SUCH DAMAGE.
  + * ====================================================================
  + *
  + * This software consists of voluntary contributions made by many
  + * individuals on behalf of the Apache Software Foundation.  For more
  + * information on the Apache Software Foundation, please see
  + * <http://www.apache.org/>.
  + */
   
   package org.apache.cocoon;
   
  @@ -28,38 +74,54 @@
   import org.apache.log.Logger;
   import org.apache.log.Priority;
   
  -import java.io.*;
  -import java.util.*;
  +import java.io.BufferedReader;
  +import java.io.BufferedOutputStream;
  +import java.io.File;
  +import java.io.FileInputStream;
  +import java.io.FileNotFoundException;
  +import java.io.FileOutputStream;
  +import java.io.FileReader;
  +import java.io.IOException;
  +import java.io.OutputStream;
  +import java.io.PrintStream;
  +import java.util.ArrayList;
  +import java.util.Arrays;
  +import java.util.Collection;
  +import java.util.HashMap;
  +import java.util.Iterator;
  +import java.util.List;
  +import java.util.Map;
  +import java.util.TreeMap;
   
   /**
    * Command line entry point.
    *
    * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
  - * @version CVS $Revision: 1.32 $ $Date: 2001/12/13 18:26:23 $
  + * @version CVS $Revision: 1.33 $ $Date: 2001/12/20 16:41:44 $
    */
  -
   public class Main {
   
  -    protected static Logger log = null;
  +    /** The <code>Logger</code> */
  +    private static Logger log = null;
   
  -    protected static final int HELP_OPT =        'h';
  -    protected static final int VERSION_OPT =     'v';
  -    protected static final int LOG_KIT_OPT =     'k';
  -    protected static final int LOGGER_OPT =      'l';
  -    protected static final int LOG_LEVEL_OPT =   'u';
  -    protected static final int CONTEXT_DIR_OPT = 'c';
  -    protected static final int DEST_DIR_OPT =    'd';
  -    protected static final int WORK_DIR_OPT =    'w';
  -    protected static final int XSP_OPT =         'x';
  -    protected static final int AGENT_OPT =       'a';
  -    protected static final int ACCEPT_OPT =      'p';
  -    protected static final int URI_FILE =        'f';
  -    protected static final int FOLLOW_LINKS_OPT ='r';
  +    protected static final int HELP_OPT =         'h';
  +    protected static final int VERSION_OPT =      'v';
  +    protected static final int LOG_KIT_OPT =      'k';
  +    protected static final int LOGGER_OPT =       'l';
  +    protected static final int LOG_LEVEL_OPT =    'u';
  +    protected static final int CONTEXT_DIR_OPT =  'c';
  +    protected static final int DEST_DIR_OPT =     'd';
  +    protected static final int WORK_DIR_OPT =     'w';
  +    protected static final int XSP_OPT =          'x';
  +    protected static final int AGENT_OPT =        'a';
  +    protected static final int ACCEPT_OPT =       'p';
  +    protected static final int URI_FILE =         'f';
  +    protected static final int FOLLOW_LINKS_OPT = 'r';
   
       protected static final String DEFAULT_USER_AGENT = Constants.COMPLETE_NAME;
       protected static final String DEFAULT_ACCEPT = "text/html, */*";
   
  -    protected static final CLOptionDescriptor [] options = new CLOptionDescriptor [] {
  +    protected static final CLOptionDescriptor [] OPTIONS = new CLOptionDescriptor [] {
           new CLOptionDescriptor("uriFile",
                                  CLOptionDescriptor.ARGUMENT_REQUIRED,
                                  URI_FILE,
  @@ -115,12 +177,18 @@
                                  + " (boolean argument is expected, default is true)"),
       };
   
  +    /**
  +     * <code>processFile</code> method.
  +     *
  +     * @param filename a <code>String</code> value
  +     * @param uris a <code>List</code> of URIs
  +     */
       public static void processFile(String filename, List uris) {
           try {
               BufferedReader uriFile = new BufferedReader(new FileReader(filename));
               boolean eof = false;
   
  -            while (! eof) {
  +            while (!eof) {
                   String uri = uriFile.readLine();
   
                   if (null == uri) {
  @@ -137,13 +205,19 @@
       }
   
   
  +    /**
  +     * The <code>main</code> method.
  +     *
  +     * @param args a <code>String[]</code> of arguments
  +     * @exception Exception if an error occurs
  +     */
       public static void main(String[] args) throws Exception {
   
           String destDir = Constants.DEFAULT_DEST_DIR;
           String contextDir = Constants.DEFAULT_CONTEXT_DIR;
           String workDir = Constants.DEFAULT_WORK_DIR;
           List targets = new ArrayList();
  -        CLArgsParser parser = new CLArgsParser(args, options);
  +        CLArgsParser parser = new CLArgsParser(args, OPTIONS);
           String logKit = null;
           String logger = null;
           String logLevel = "DEBUG";
  @@ -251,8 +325,9 @@
   
           try {
               File dest = null;
  -            if(!xspOnly)
  +            if (!xspOnly) {
                   dest = getDir(destDir, "destination");
  +            }
               File work = getDir(workDir, "working");
               File context = getDir(contextDir, "context");
               File conf = getConfigurationFile(context);
  @@ -262,7 +337,7 @@
               clContext.setLogger(log);
               appContext.put(Constants.CONTEXT_ENVIRONMENT_CONTEXT, clContext);
               DefaultLogKitManager logKitManager = null;
  -            if(logKit != null) {
  +            if (logKit != null) {
                   final FileInputStream fis = new FileInputStream(logKit);
                   final DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
                   final Configuration logKitConf = builder.build(fis);
  @@ -295,8 +370,9 @@
               main.accept = accept;
               main.followLinks = followLinks;
               main.warmup();
  -            if(main.process(targets, xspOnly)==0)
  +            if (main.process(targets, xspOnly) == 0) {
                   main.recursivelyProcessXSP(context, context);
  +            }
               c.dispose();
               log.info("Done");
           } catch (Exception e) {
  @@ -306,11 +382,13 @@
           System.exit(0);
       }
   
  +    /** Print the version string and exit */
       private static void printVersion() {
           System.out.println(Constants.VERSION);
           System.exit(0);
       }
   
  +    /** Print the usage message and exit */
       private static void printUsage() {
           String lSep = System.getProperty("line.separator");
           StringBuffer msg = new StringBuffer();
  @@ -320,33 +398,62 @@
           msg.append("------------------------------------------------------------------------ ").append(lSep).append(lSep);
           msg.append("Usage: java org.apache.cocoon.Main [options] [targets]").append(lSep).append(lSep);
           msg.append("Options: ").append(lSep);
  -        msg.append(CLUtil.describeOptions(Main.options).toString());
  +        msg.append(CLUtil.describeOptions(Main.OPTIONS).toString());
           msg.append("Note: the context directory defaults to '").append(Constants.DEFAULT_CONTEXT_DIR + "'").append(lSep);
           System.out.println(msg.toString());
           System.exit(0);
       }
   
  +    /**
  +     * Check for a configuration file in a specific directory.
  +     *
  +     * @param dir a <code>File</code> where to look for configuration files
  +     * @return a <code>File</code> representing the configuration
  +     * @exception Exception if an error occurs
  +     */
       private static File getConfigurationFile(File dir) throws Exception {
   
  -        log.debug("Trying configuration file at: " + dir + File.separator + Constants.DEFAULT_CONF_FILE);
  +        if (log.isDebugEnabled()) {
  +            log.debug("Trying configuration file at: " + dir + File.separator + Constants.DEFAULT_CONF_FILE);
  +        }
           File f = new File(dir, Constants.DEFAULT_CONF_FILE);
  -        if (f.canRead()) return f;
  +        if (f.canRead()) {
  +            return f;
  +        }
   
  -        log.debug("Trying configuration file at: " + System.getProperty("user.dir") + File.separator + Constants.DEFAULT_CONF_FILE);
  +        if (log.isDebugEnabled()) {
  +            log.debug("Trying configuration file at: " + System.getProperty("user.dir") + File.separator + Constants.DEFAULT_CONF_FILE);
  +        }
           f = new File(System.getProperty("user.dir") + File.separator + Constants.DEFAULT_CONF_FILE);
  -        if (f.canRead()) return f;
  +        if (f.canRead()) {
  +            return f;
  +        }
   
  -        log.debug("Trying configuration file at: /usr/local/etc/" + Constants.DEFAULT_CONF_FILE);
  +        if (log.isDebugEnabled()) {
  +            log.debug("Trying configuration file at: /usr/local/etc/" + Constants.DEFAULT_CONF_FILE);
  +        }
           f = new File("/usr/local/etc/", Constants.DEFAULT_CONF_FILE);
  -        if (f.canRead()) return f;
  +        if (f.canRead()) {
  +            return f;
  +        }
   
           log.error("Could not find the configuration file.");
           throw new FileNotFoundException("The configuration file could not be found.");
       }
   
  +    /**
  +     * Get a <code>File</code> representing a directory.
  +     *
  +     * @param dir a <code>String</code> with a directory name
  +     * @param type a <code>String</code> describing the type of directory
  +     * @return a <code>File</code> value
  +     * @exception Exception if an error occurs
  +     */
       private static File getDir(String dir, String type) throws Exception {
   
  -        log.debug("Getting handle to " + type + " directory '" + dir + "'");
  +        if (log.isDebugEnabled()) {
  +            log.debug("Getting handle to " + type + " directory '" + dir + "'");
  +        }
           File d = new File(dir);
   
           if (!d.exists()) {
  @@ -384,6 +491,9 @@
   
       /**
        * Creates the Main class
  +     * @param cocoon a <code>Cocoon</code> instance
  +     * @param context a <code>File</code> for the context directory
  +     * @param destDir a <code>File</code> for the destination directory
        */
       public Main(Cocoon cocoon, File context, File destDir) {
           this.cocoon = cocoon;
  @@ -397,6 +507,7 @@
   
       /**
        * Warms up the engine by accessing the root.
  +     * @exception Exception if an error occurs
        */
       public void warmup() throws Exception {
           log.info("Warming up...");
  @@ -407,6 +518,10 @@
   
       /**
        * Process the URI list and process them all independently.
  +     * @param uris a <code>Collection</code> of URIs
  +     * @param xspOnly a <code>boolean</code> denoting to process XSP only
  +     * @return an <code>int</code> value with the number of links processed
  +     * @exception Exception if an error occurs
        */
       public int process(Collection uris, boolean xspOnly) throws Exception {
           int nCount = 0;
  @@ -417,20 +532,20 @@
           String next;
           while (i.hasNext() == true) {
               next = (String)i.next();
  -            if (links.contains(next)==false) {
  +            if (links.contains(next) == false) {
                   links.add(next);
               }
           }
           while (links.size() > 0) {
               String url = (String)links.get(0);
  -            if(allProcessedLinks.get(url) == null){
  +            if (allProcessedLinks.get(url) == null) {
                   if (xspOnly) {
                       this.processXSP(url);
                   } else if (this.followLinks) {
                       i = this.processURI(url).iterator();
                       while (i.hasNext() == true) {
                           next = (String)i.next();
  -                        if (links.contains(next)==false) {
  +                        if (links.contains(next) == false) {
                               links.add(next);
                           }
                       }
  @@ -441,14 +556,18 @@
               links.remove(url);
               nCount++;
   
  -            log.debug("  Memory used: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
  -            log.debug("  Processed, Translated & Left: " + allProcessedLinks.size() + ", "  + allTranslatedLinks.size() + ", " + links.size());
  +            if (log.isDebugEnabled()) {
  +                log.debug("  Memory used: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
  +                log.debug("  Processed, Translated & Left: " + allProcessedLinks.size() + ", "  + allTranslatedLinks.size() + ", " + links.size());
  +            }
           }
           return nCount;
       }
   
       /**
        * Recurse the directory hierarchy and process the XSP's.
  +     * @param contextDir a <code>File</code> value for the context directory
  +     * @param file a <code>File</code> value for a single XSP file or a directory to scan recursively
        */
       public void recursivelyProcessXSP(File contextDir, File file) {
           if (file.isDirectory()) {
  @@ -456,7 +575,7 @@
               for (int i = 0; i < entries.length; i++) {
                   recursivelyProcessXSP(contextDir, new File(file, entries[i]));
               }
  -        } else if(file.getName().toLowerCase().endsWith(".xsp")) {
  +        } else if (file.getName().toLowerCase().endsWith(".xsp")) {
               try {
                   this.processXSP(IOUtils.getContextFilePath(contextDir.getCanonicalPath(),file.getCanonicalPath()));
               } catch (Exception e){
  @@ -465,6 +584,12 @@
           }
       }
   
  +    /**
  +     * Process a single XSP file
  +     *
  +     * @param uri a <code>String</code> pointing to an xsp URI
  +     * @exception Exception if an error occurs
  +     */
       public void processXSP(String uri) throws Exception {
           Environment env = new LinkSamplingEnvironment("/", context, attributes, null, this.log);
           cocoon.generateXSP(uri, env);
  @@ -486,6 +611,9 @@
        *  <li>list of absolute URI is returned, for every URI which is not yet
        *      present in list of all translated URIs</li>
        * </ul>
  +     * @param uri a <code>String</code> URI to process
  +     * @return a <code>Collection</code> containing all links found
  +     * @exception Exception if an error occurs
        */
       public Collection processURI(String uri) throws Exception {
           log.info("Processing URI: " + uri);
  @@ -500,13 +628,15 @@
   
           // Get file name from URI (without path)
           String pageURI = deparameterizedURI;
  -        if(pageURI.indexOf("/") != -1){
  +        if (pageURI.indexOf("/") != -1) {
               pageURI = pageURI.substring(pageURI.lastIndexOf("/") + 1);
  -            if(pageURI.length() == 0) pageURI = "./";
  +            if (pageURI.length() == 0) {
  +                pageURI = "./";
  +            }
           }
   
           String filename = (String)allTranslatedLinks.get(suri);
  -        if(filename == null){
  +        if (filename == null) {
               filename = mangle(suri);
               final String type = getType(deparameterizedURI, parameters);
               final String ext = NetUtils.getExtension(filename);
  @@ -531,7 +661,7 @@
               String link = (String) i.next();
               // Fix relative links starting with "?"
               String relativeLink = link;
  -            if(relativeLink.startsWith("?")){
  +            if (relativeLink.startsWith("?")) {
                   relativeLink = pageURI + relativeLink;
               }
   
  @@ -541,7 +671,7 @@
                   absoluteLink = NetUtils.parameterize(NetUtils.deparameterize(absoluteLink, p), p);
               }
               String translatedAbsoluteLink = (String)allTranslatedLinks.get(absoluteLink);
  -            if(translatedAbsoluteLink == null){
  +            if (translatedAbsoluteLink == null) {
                   translatedAbsoluteLink = this.translateURI(absoluteLink);
                   log.info("  Link translated: " + absoluteLink);
                   allTranslatedLinks.put(absoluteLink, translatedAbsoluteLink);
  @@ -568,6 +698,13 @@
           return absoluteLinks;
       }
   
  +    /**
  +     * Translate an URI into a file name.
  +     *
  +     * @param uri a <code>String</code> value to map
  +     * @return a <code>String</code> vlaue for the file
  +     * @exception Exception if an error occurs
  +     */
       public String translateURI(String uri) throws Exception {
           if (null == uri || "".equals(uri)) {
               log.warn("translate empty uri");
  @@ -590,6 +727,12 @@
           return filename;
       }
   
  +    /**
  +     * Generate a <code>resourceUnavailable</code> message.
  +     *
  +     * @param file being unavailable
  +     * @exception IOException if an error occurs
  +     */
       private void resourceUnavailable(File file) throws IOException {
           PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(file)));
           out.println(
  @@ -602,21 +745,47 @@
           out.close();
       }
   
  +    /**
  +     * Mangle an URI.
  +     *
  +     * @param uri a URI to mangle
  +     * @return a mangled URI
  +     */
       private String mangle(String uri) {
  -        log.debug("mangle(\"" + uri + "\")");
  -        if (uri.charAt(uri.length() - 1) == '/') uri += Constants.INDEX_URI;
  +        if (log.isDebugEnabled()) {
  +            log.debug("mangle(\"" + uri + "\")");
  +        }
  +        if (uri.charAt(uri.length() - 1) == '/') {
  +            uri += Constants.INDEX_URI;
  +        }
           uri = uri.replace('"', '\'');
           uri = uri.replace('?', '_');
           uri = uri.replace(':', '_');
  -        log.debug(uri);
  +        if (log.isDebugEnabled()) {
  +            log.debug(uri);
  +        }
           return uri;
       }
   
  +    /**
  +     * Generate the string for a leaf in ascii art for a tree view log output.
  +     *
  +     * @param level of nesting
  +     * @return a <code>String</code> value to print the levels requested
  +     */
       private String leaf(int level) {
  -        if (level == 0) return "";
  +        if (level == 0) {
  +            return "";
  +        }
           return tree(level - 2) + "+--";
       }
   
  +    /**
  +     * Generate the string for a tree in ascii art for a tree view log output.
  +     *
  +     * @param level of nesting
  +     * @return a <code>String</code> value to print the levels requested
  +     */
       protected String tree(int level) {
           StringBuffer buffer = new StringBuffer();
           for (int i = 0; i <= level; i++) {
  @@ -625,6 +794,14 @@
           return buffer.toString();
       }
   
  +    /**
  +     * Samples an URI for its links.
  +     *
  +     * @param deparameterizedURI a <code>String</code> value of an URI to start sampling from
  +     * @param parameters a <code>Map</code> value containing request parameters
  +     * @return a <code>Collection</code> of links
  +     * @exception Exception if an error occurs
  +     */
       protected Collection getLinks(String deparameterizedURI, Map parameters) throws Exception {
           LinkSamplingEnvironment env = new LinkSamplingEnvironment(deparameterizedURI,
                     context,
  @@ -635,6 +812,16 @@
           return env.getLinks();
       }
   
  +    /**
  +     * Processes an URI for its content.
  +     *
  +     * @param deparameterizedURI a <code>String</code> value of an URI to start sampling from
  +     * @param parameters a <code>Map</code> value containing request parameters
  +     * @param links a <code>Map</code> value
  +     * @param stream an <code>OutputStream</code> to write the content to
  +     * @return a <code>String</code> value for the content
  +     * @exception Exception if an error occurs
  +     */
       protected String getPage(String deparameterizedURI, Map parameters, Map links, OutputStream stream) throws Exception {
           FileSavingEnvironment env = new FileSavingEnvironment(deparameterizedURI,
                           context,
  @@ -647,6 +834,7 @@
           return env.getContentType();
       }
   
  +    /** Class <code>NullOutputStream</code> here. */
       static class NullOutputStream extends OutputStream
       {
           public void write(int b) throws IOException { }
  @@ -654,6 +842,14 @@
           public void write(byte b[], int off, int len) throws IOException { }
       }
   
  +    /**
  +     * Analyze the type of content for an URI.
  +     *
  +     * @param deparameterizedURI a <code>String</code> value to analyze
  +     * @param parameters a <code>Map</code> value for the request
  +     * @return a <code>String</code> value denoting the type of content
  +     * @exception Exception if an error occurs
  +     */
       protected String getType(String deparameterizedURI, Map parameters) throws Exception {
           FileSavingEnvironment env = new FileSavingEnvironment(deparameterizedURI,
                        context,
  @@ -677,8 +873,9 @@
        * we need to work with a known one.
        *
        * @param context  The context path
  +     * @return a <code>String</code> value
        */
  -     protected static String getClassPath(final String context) {
  +    protected static String getClassPath(final String context) {
           StringBuffer buildClassPath = new StringBuffer();
           String classDir = context + "/WEB-INF/classes";
           File root = new File(context + "/WEB-INF/lib");
  @@ -700,7 +897,9 @@
   //        buildClassPath.append(File.pathSeparatorChar)
   //                      .append(getExtraClassPath(context));
   
  -        log.debug("Context classpath: " + buildClassPath.toString());
  +        if (log.isDebugEnabled()) {
  +            log.debug("Context classpath: " + buildClassPath.toString());
  +        }
           return buildClassPath.toString();
        }
   }
  
  
  

----------------------------------------------------------------------
In case of troubles, e-mail:     webmaster@xml.apache.org
To unsubscribe, e-mail:          cocoon-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: cocoon-cvs-help@xml.apache.org