rogerrut    2005/03/21 09:31:11

  Modified:    portals-bridges/perl/src/java/org/apache/portals/bridges/perl
                        PerlPortlet.java
  Added:       portals-bridges/perl/src/java/org/apache/portals/bridges/perl
                        PerlContentRewriter.java
  Log:
  Use rewriter component instead of ScriptPostProcess class.
  
  Revision  Changes    Path
  1.7       +144 -13   
jakarta-jetspeed-2/portals-bridges/perl/src/java/org/apache/portals/bridges/perl/PerlPortlet.java
  
  Index: PerlPortlet.java
  ===================================================================
  RCS file: 
/home/cvs/jakarta-jetspeed-2/portals-bridges/perl/src/java/org/apache/portals/bridges/perl/PerlPortlet.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- PerlPortlet.java  27 Feb 2005 21:59:28 -0000      1.6
  +++ PerlPortlet.java  21 Mar 2005 17:31:11 -0000      1.7
  @@ -18,12 +18,20 @@
   import javax.portlet.GenericPortlet;
   
   import java.io.BufferedReader;
  +import java.io.ByteArrayInputStream;
  +import java.io.ByteArrayOutputStream;
   import java.io.FileNotFoundException;
   import java.io.FileReader;
   import java.io.IOException;
   import java.io.InputStream;
   import java.io.InputStreamReader;
  +import java.io.OutputStream;
  +import java.io.OutputStreamWriter;
   import java.io.PrintWriter;
  +import java.io.StringReader;
  +import java.io.UnsupportedEncodingException;
  +import java.io.Writer;
  +import java.util.Arrays;
   import java.util.Enumeration;
   
   import javax.servlet.http.HttpServletRequestWrapper;
  @@ -44,11 +52,22 @@
   
   import org.apache.commons.logging.Log;
   import org.apache.commons.logging.LogFactory;
  -import org.apache.portals.bridges.common.ScriptPostProcess;
  +import org.apache.jetspeed.rewriter.JetspeedRewriterController;
  +import org.apache.jetspeed.rewriter.RewriterController;
  +import org.apache.jetspeed.rewriter.RewriterException;
  +import org.apache.jetspeed.rewriter.RulesetRewriter;
  +import org.apache.jetspeed.rewriter.html.SwingParserAdaptor;
  +import org.apache.jetspeed.rewriter.rules.Ruleset;
  +import org.apache.jetspeed.rewriter.xml.SaxParserAdaptor;
   
   
   /**
   * This portlet is executes a Perl/cgi files in a portlet.
  +* 
  +* Note:
  +* The Perl Portlet uses the rewriter component that requires config xml 
files.
  +* Make sre that the portlet application using the Perl Portlet has the 
following files included
  +* in WEB-INF/conf: rewriter-rules-mapping.xml and default-rewriter-rules.xml
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Roger Ruttimann</a>
   * @version $Id$
  @@ -102,6 +121,13 @@
       // Cache the last generated page
       String lastPage = null;
       
  +    /* PerlContent rewriter */
  +    RulesetRewriter          rewriter = null;
  +    RewriterController       rewriteController = null;
  +    
  +    /** Default encoding */
  +    public String defaultEncoding = "iso-8859-1";
  +    
       
       public void init(PortletConfig config) throws PortletException
       {
  @@ -273,12 +299,12 @@
           String path = portletApplication.getRealPath("/WEB-INF");
           String contextPath = path + "/";
    
  -        contextPath += scriptPath;
  +        String fullScriptPath = contextPath + scriptPath;
       
        // Build full path to scripts
        if (perlScript.startsWith("/") == false )
  -             contextPath += "/";
  -     contextPath += perlScript;
  +         fullScriptPath += "/";
  +     fullScriptPath += perlScript;
        
        // command to execute
        String command = null;
  @@ -286,7 +312,7 @@
        // Open the script and read the first line to get the executable 
!/usr/bin/perl OR !c:\bin\perl\perl.exe
        try
                {
  -             BufferedReader in= new BufferedReader(new 
FileReader(contextPath));
  +             BufferedReader in= new BufferedReader(new 
FileReader(fullScriptPath));
                String lnExecutable = in.readLine();
                
                if (lnExecutable != null )
  @@ -313,16 +339,16 @@
                
                StringBuffer commandBuffer = new StringBuffer();
                if (perlExecutable == null)
  -                     commandBuffer.append(contextPath);
  +                     commandBuffer.append(fullScriptPath);
                else
  -                     commandBuffer.append(perlExecutable).append(' 
').append(contextPath);
  +                     commandBuffer.append(perlExecutable).append(' 
').append(fullScriptPath);
                
                command = new String(commandBuffer.toString());
                
                }
        catch(FileNotFoundException e)
                {
  -             writer.println("<P><B>File doesn't exist (" + contextPath + 
")</B></P>");
  +             writer.println("<P><B>File doesn't exist (" + fullScriptPath + 
")</B></P>");
                }
        catch(IOException e)
                {
  @@ -343,7 +369,7 @@
                        // Script info. This is for the Demo only
                        writer.println("<P>The portlet executes the perl script 
defined by the init-params. If you don't get an output make sure that the perl 
executable defined in the script is valid.");
                        writer.println("The executable is defined on the first 
line of your 
script.</P>Examples<ul><li><B>UNIX/Linux:</B>!/usr/bin/perl</li><li><B>Windows:</B>!c:\\bin\\perl\\perl.exe</li></ul>");
  -                     writer.println("<B><P>Perl Script:</B>" + contextPath + 
"<BR>");
  +                     writer.println("<B><P>Perl Script:</B>" + 
fullScriptPath + "<BR>");
                        writer.println("<B>Perl executable:</B>" + 
perlExecutable + "<BR>");
                        writer.println("<B>Query String:</B>" + query + "</P>");
                }       
  @@ -397,11 +423,56 @@
                                }
                                // Close stream
                                perlResult.close();     
  -                             
  -                             // Post Process for generated page
  -                             // Any HREFs and Form actions should be 
extended with the ActionURL
  +                                     
  +                             /*
  +                              * Use rewriter for replacing all URL's with 
portlet actions
  +                              */
  +                     if (rewriteController == null)
  +                     {
  +                         try
  +                         {
  +                             // Create rewriter adaptor
  +                             rewriteController = getController(contextPath);
  +                         }
  +                         catch (Exception e)
  +                         {
  +                             // Failed to create rewriter controller
  +                             throw new PortletException("WebContentProtlet 
failed to create rewriter controller. Error:"
  +                                     + e.getMessage());
  +                         }
  +                     }
  +                     
  +                     //      Any HREFs and Form actions should be extended 
with the ActionURL
                                PortletURL actionURL = 
response.createActionURL();
  +                             byte[] content = this.doWebContent(page, 
actionURL, PerlParameters.ACTION_PARAMETER_PERL);
  +                             ByteArrayInputStream bais = new 
ByteArrayInputStream(content);
  +                             OutputStream oswriter = 
response.getPortletOutputStream();
  +                             
  +                             int BLOCK_SIZE = 4096;
  +                             byte[] bytes = new byte[BLOCK_SIZE];
  +                     try
  +                     {
  +                         int length = bais.read(bytes);
  +                         while (length != -1)
  +                         {
  +                             if (length != 0)
  +                             {
  +                                 oswriter.write(bytes, 0, length);
  +                             }
  +                             length = bais.read(bytes);
  +                         }
  +                     }
  +                     finally
  +                     {
  +                         bytes = null;
  +                     }
                                
  +                             //      Cache page
  +                             lastPage = new String(content);
  +                             
  +                             
  +                             /*
  +                             // Post Process for generated page              
                
                                ScriptPostProcess processor = new 
ScriptPostProcess();
                                processor.setInitalPage(page);
                                processor.postProcessPage(actionURL, 
PerlParameters.ACTION_PARAMETER_PERL);
  @@ -410,8 +481,10 @@
                                // Write the page
                                writer.println(finalPage);
                                
  +                             
                                // Cache page
                                lastPage = new String(finalPage);
  +                             */
                        }
                        catch(IOException ioe)
                        {
  @@ -419,5 +492,63 @@
                        }
                }       
        } 
  +    
  +    /*
  +     * Generate a rewrite controller using the basic rules file
  +     */
  +    private RewriterController getController(String contextPath) throws 
Exception
  +    {
  +        Class[] rewriterClasses = new Class[]
  +        { PerlContentRewriter.class, PerlContentRewriter.class};
  +        
  +        Class[] adaptorClasses = new Class[]
  +        { SwingParserAdaptor.class, SaxParserAdaptor.class};
  +        RewriterController rwc = new JetspeedRewriterController(contextPath 
+ "conf/rewriter-rules-mapping.xml", Arrays
  +                .asList(rewriterClasses), Arrays.asList(adaptorClasses));
  +
  +        FileReader reader = new FileReader(contextPath + 
"conf/default-rewriter-rules.xml");
  +
  +        Ruleset ruleset = rwc.loadRuleset(reader);
  +        reader.close();
  +        rewriter = rwc.createRewriter(ruleset);
  +        return rwc;
  +    }
  +    
  +    protected byte[] doWebContent(StringBuffer perlRenderedPage, PortletURL 
actionURL, String actionParameterName)
  +    throws PortletException
  +     {
  +             // Initialization
  +             Writer htmlWriter = null;
  +             
  +             ByteArrayOutputStream byteOutputStream = new 
ByteArrayOutputStream();
  +             
  +             try
  +             {
  +                 htmlWriter = new OutputStreamWriter(byteOutputStream, 
this.defaultEncoding);
  +             
  +                 // Set the action URL in the rewriter
  +                
  +                ((PerlContentRewriter) rewriter).setActionURL(actionURL);
  +                ((PerlContentRewriter) 
rewriter).setActionParameterName(actionParameterName);
  +                
  +                 StringReader perlReader = new 
StringReader(perlRenderedPage.toString());
  +                 
rewriter.rewrite(rewriteController.createParserAdaptor("text/html"), 
perlReader, htmlWriter);
  +                 htmlWriter.flush();
  +             }
  +             catch (UnsupportedEncodingException ueex)
  +             {
  +                 throw new PortletException("Encoding " + defaultEncoding + 
" not supported. Error: " + ueex.getMessage());
  +             }
  +             catch (RewriterException rwe)
  +             {
  +                 throw new PortletException("Failed to rewrite Perl ouput. 
Error: " + rwe.getMessage());
  +             }
  +             catch (Exception e)
  +             {
  +                 throw new PortletException("Exception while rewritting Perl 
output. Error: " + e.getMessage());
  +             }
  +             
  +             return byteOutputStream.toByteArray();
  +     }
   }
        
  
  
  
  1.1                  
jakarta-jetspeed-2/portals-bridges/perl/src/java/org/apache/portals/bridges/perl/PerlContentRewriter.java
  
  Index: PerlContentRewriter.java
  ===================================================================
  /* Copyright 2004 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.portals.bridges.perl;
  
  
  import javax.portlet.PortletURL;
  
  import org.apache.jetspeed.rewriter.Rewriter;
  import org.apache.jetspeed.rewriter.RulesetRewriterImpl;
  
  /**
   * PerlContentRewriter
   * 
   * @author <a href="mailto:[EMAIL PROTECTED]">Roger Ruttimann </a>
   * @version $Id: PerlContentRewriter.java,v 1.1 2005/03/21 17:31:11 rogerrut 
Exp $
   */
  public class PerlContentRewriter extends RulesetRewriterImpl implements
          Rewriter {
  
      /** WebContentURL */
      public static final String ACTION_PARAMETER_URL = "WCURL";
  
      /* Portlet URL will be used to replace all URL's */
      private PortletURL actionURL = null;
  
      /* Parameter name attached to action */
      private String actionParameterName = null;
  
      /*
       * LocalhostIP Some perl script refer to localhost which doesn't work for
       * remote connections. The rewriter will replace any localhost references
       * with the IP address
       */
      private String localHostIP = null;
  
      /**
       * Setters/getters for members
       */
      public void setActionURL(PortletURL action) {
          this.actionURL = action;
      }
  
      public PortletURL getActionURL() {
          return this.actionURL;
      }
  
      /**
       * @return Returns the localHostIP.
       */
      public String getLocalHostIP() {
          return localHostIP;
      }
  
      /**
       * @param localHostIP
       *                    The localHostIP to set.
       */
      public void setLocalHostIP(String localHostIP) {
          this.localHostIP = localHostIP;
      }
  
      /**
       * @return Returns the actionParameterName.
       */
      public String getActionParameterName() {
          return actionParameterName;
      }
  
      /**
       * @param actionParameterName
       *                    The actionParameterName to set.
       */
      public void setActionParameterName(String actionParameterName) {
          this.actionParameterName = actionParameterName;
      }
  
      /**
       * rewriteURL
       * 
       * @param url
       * @param tag
       * @param attribute
       * @return the modified url which is a portlet action
       * 
       * Rewrites all URL's in the perl script with portlet actions. Tags 
include
       * A (AREA) and FORM and replaces any localhost with the real IP address 
if
       * provided
       */
      public String rewriteUrl(String url, String tag, String attribute) {
          String modifiedURL = url;
          // TODO: Remove debug
          System.out.println("Perl HTML output TAG = " + tag + " Attribute = " 
+ attribute);
  
          // For now only add PortletActions to URL's which are anchors (tag=a) 
or
          // FORMS and HREF's (attribute= HREF) -- ignore all others links
          if ((         tag.compareToIgnoreCase("A") == 0
                  ||  tag.compareToIgnoreCase("FORM") == 0)
                  && attribute.compareToIgnoreCase("HREF") == 0) {
              // Regular URL just add a portlet action
              if (this.actionURL != null) {
                  // create Action URL
                  actionURL.setParameter(actionParameterName, modifiedURL);
                  modifiedURL = actionURL.toString();
              }
          }
  
          return modifiedURL;
      }
  
      /*
       * (non-Javadoc)
       * 
       * @see 
org.apache.jetspeed.rewriter.Rewriter#shouldRemoveTag(java.lang.String)
       */
      /*
       * public boolean shouldRemoveTag(String tag) { if
       * (tag.equalsIgnoreCase("html")) { return true; } return false; }
       */
  
      /*
       * (non-Javadoc)
       * 
       * @see 
org.apache.jetspeed.rewriter.Rewriter#shouldStripTag(java.lang.String)
       */
      /*
       * public boolean shouldStripTag(String tag) { if
       * (tag.equalsIgnoreCase("head")) { return true; } return false; }
       */
  
      /*
       * (non-Javadoc)
       * 
       * @see org.apache.jetspeed.rewriter.Rewriter#shouldRemoveComments()
       */
      /*
       * public boolean shouldRemoveComments() { return true; }
       */
  
  }
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to