Changeset 116:07d87f9ad7d2 in iovar


Ignore:
Timestamp:
Mar 1, 2018, 7:26:02 PM (6 months ago)
Author:
Shawn Wilson <shawn@…>
Branch:
default
Phase:
public
Message:

saw_030118_1 - Introducing abstract Executable class for easier implementation of standard iovar

servlets. Beginning to support content-type tracking for shell variables.

Files:
1 added
10 edited
1 moved

Legend:

Unmodified
Added
Removed
  • CHANGELOG

    r113 r116  
    22Copyright (C) 2011-2015 Lannocc Technologies
    33@%@~LICENSE~@%@
     4
     5saw_030118_1 - Introducing abstract Executable class for easier implementation of standard iovar
     6               servlets. Beginning to support content-type tracking for shell variables.
    47
    58saw_022118_3 - Increment version to 1.1 for the next developments.
  • src/win/iovar/web/bin/Echo.java

    r67 r116  
    11/*
    2  * Copyright (C) 2016 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * Copyright (C) 2011-2014 Lannocc Technologies
    44 * @%@~LICENSE~@%@
     
    88// local imports:
    99import win.iovar.web.*;
    10 import win.iovar.web.dev.*;
    11 import win.iovar.web.bin.shell.*;
    1210
    1311// java imports:
    1412import java.io.*;
    1513import java.util.*;
    16 import java.util.List;
    17 import javax.servlet.*;
    18 import javax.servlet.http.*;
    1914
    2015// 3rd-party imports:
     
    2520 * @author  shawn@lannocc.com
    2621 */
    27 public class Echo extends HttpServlet
     22public class Echo extends Executable
    2823{
    29     protected void doHead (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     24    public static final Usage USAGE = new Usage (
     25            "[options] ...",
     26            new String[] {
     27                "Output the input stream followed by any arguments.",
     28                "A newline is automatically appended unless turned off in the options."
     29            },
     30            new Param[] {
     31                new Param ("noline", "do not output trailing newline")
     32            }
     33    );
     34   
     35    public Usage usage (final IO io)
    3036    {
    31         Utils.doHead (this, req, resp);
     37        return USAGE;
    3238    }
    3339   
    34     protected void doGet (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     40    public Accept prep (final IO io) throws IOException
    3541    {
    36         Utils.doGet (this, req, resp);
     42        return new Accept ("text/*");
    3743    }
    3844   
    39     protected void doPut (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     45    public void exec (final IO io) throws IOException
    4046    {
    41         Utils.doPut (this, req, resp);
    42     }
    43    
    44     public void usage (final HttpServletResponse resp) throws IOException
    45     {
    46         Log.debug ("displaying usage");
    47        
    48         resp.setContentType ("text/plain");
    49         final PrintWriter out = resp.getWriter ();
    50        
    51         out.println ("usage: echo [options] ...");
    52         out.println ();
    53         out.println ("Output the input stream followed by any arguments.");
    54         out.println ("A newline is automatically appended unless turned off in the options.");
    55         out.println ();
    56         out.println ("Options:");
    57         out.println ("   ?help      - display this help screen");
    58         out.println ("   ?noline    - do not output trailing newline");
    59     }
    60    
    61     protected void doPost (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    62     {
     47        final PrintWriter out = io.outP ("text/plain");
    6348        try
    6449        {
    65             final ServletContext context = getServletContext ();
    66             final String query = req.getQueryString ();
    67             final Map<String,List<String>> params = Utils.getParams (query);
    68 
    69             if (params.containsKey ("help"))
     50            //boolean space = in!=null && in.available ()>0; // FIXME: doesn't actually seem to work as expected
     51            if (Utils.pipe (io.in, out) > 0)
    7052            {
    71                 usage (resp);
    72                 Shell.exit (req, context, 0);
    73                 return;
    74             }
    75 
    76             final PrintWriter out = resp.getWriter ();
    77             final InputStream in = req.getInputStream (); try
    78             {
    79                 //boolean space = in!=null && in.available ()>0; // FIXME: doesn't actually seem to work as expected
    80                 if (Utils.pipe (in, out) > 0)
    81                 {
    82                     out.print (' ');
    83                     out.flush ();
    84                 }
    85             }
    86             finally
    87             {
    88                 in.close ();
    89             }
    90 
    91             final List<String> vals = params.get (null);
    92             if (vals!=null)
    93             {
    94                 String sep = "";
    95                 for (final String val : vals)
    96                 {
    97                     out.print (sep);
    98                     out.print (val);
    99                     out.flush ();
    100                     sep = " ";
    101                 }
    102             }
    103 
    104             if (! params.containsKey ("noline")) out.print ('\n');
    105             //out.println ();
    106             out.flush ();
    107         }
    108         catch (Exception e)
    109         {
    110             StackTraceElement[] elems = e.getStackTrace ();
    111             for (StackTraceElement elem : elems)
    112             {
    113                 Log.fatal (elem.toString ());
     53                out.print (' ');
     54                out.flush ();
    11455            }
    11556        }
     57        finally
     58        {
     59            io.in.close ();
     60        }
     61
     62        final List<String> vals = io.params.get (null);
     63        if (vals!=null)
     64        {
     65            String sep = "";
     66            for (final String val : vals)
     67            {
     68                out.print (sep);
     69                out.print (val);
     70                out.flush ();
     71                sep = " ";
     72            }
     73        }
     74
     75        if (! io.params.containsKey ("noline")) out.print ('\n');
     76        //out.flush ();
    11677    }
    11778}
  • src/win/iovar/web/bin/Listing.java

    r80 r116  
    11/*
    2  * Copyright (C) 2016-2017 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * @%@~LICENSE~@%@
    44 */
     
    2626 * @author  shawn@lannocc.com
    2727 */
    28 public class List extends HttpServlet
     28public class Listing extends HttpServlet
    2929{
    3030    protected void doHead (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
  • src/win/iovar/web/bin/shell/Export.java

    r76 r116  
    11/*
    2  * Copyright (C) 2016-2017 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * Copyright (C) 2012-2015 Lannocc Technologies
    44 * @%@~LICENSE~@%@
     
    88// local imports:
    99import win.iovar.web.*;
    10 import win.iovar.web.dev.*;
    1110import win.iovar.web.lib.*;
    12 import win.iovar.web.proc.*;
    1311
    1412// java imports:
     
    1614import java.util.*;
    1715import javax.servlet.*;
    18 import javax.servlet.http.*;
    1916
    2017// 3rd-party imports:
     
    2522 * @author  shawn@lannocc.com
    2623 */
    27 public class Export extends HttpServlet
     24public class Export extends Executable
    2825{
    29     protected void doHead (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     26    public static final Usage USAGE = new Usage (
     27            "<name>[=[<val>]] ...",
     28            new String[] {
     29                "Defines a variable <name> and exports it to the parent environment.",
     30                "When called with a name and without equals sign then standard input is used for value."
     31            },
     32            new Param[] {
     33                new Param ("master", "export to the master session")
     34            }
     35    );
     36   
     37    public Usage usage (final IO io)
    3038    {
    31         Utils.doHead (this, req, resp);
     39        return USAGE;
    3240    }
    3341   
    34     protected void doGet (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    35     {
    36         Utils.doGet (this, req, resp);
    37     }
    38    
    39     protected void doPut (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    40     {
    41         Utils.doPut (this, req, resp);
    42     }
    43    
    44     public void usage (final HttpServletResponse resp) throws IOException
    45     {
    46         Log.debug ("displaying usage");
    47        
    48         resp.setContentType ("text/plain");
    49         final PrintWriter out = resp.getWriter ();
    50        
    51         out.println ("usage: export <name>[=[<val>]]...");
    52         out.println ();
    53         out.println ("Defines a variable <name> and exports it to the parent environment.");
    54         out.println ("When called with a name and without equals sign then standard input is used for value");
    55         out.println ();
    56         out.println ("Options:");
    57         out.println ("   ?help          - display this help screen");
    58         out.println ("   ?master        - export to the master session");
    59     }
    60    
    61     /**
    62      * Execute.
    63      */
    64     public void doPost (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     42    public void exec (final IO io) throws IOException
    6543    {
    6644        final ServletContext context = getServletContext ();
    67         final String query = req.getQueryString ();
    68         final Map<String,List<String>> params = Utils.getParams (query);
     45        final Map<String,List<String>> params = io.params;
    6946       
    70         if (params.containsKey ("help"))
    71         {
    72             usage (resp);
    73             Shell.exit (req, context, 0);
    74             return;
    75         }
    76 
    7747        final List<String> exports = params.get (null);
    7848        if (exports==null || exports.isEmpty ())
    7949        {
    80             usage (resp);
    81             Shell.exit (req, context, 1);
    82             return;
     50            throw new ExitUsage (1);
    8351        }
    8452       
    85         final Session session = Sessions.get (req);
    86         if (session==null)
    87         {
    88             Log.error ("unable to retrieve session");
    89             throw new IllegalArgumentException ("need a session to export to");
    90         }
    91        
     53        final Session shell = io.shell (true);
    9254        final boolean master = params.containsKey ("master");
    9355       
    9456        final StringBuffer s = new StringBuffer ();
    95         final InputStream in = req.getInputStream ();
     57        final InputStream in = io.in;
    9658        if (in!=null)
    9759        {
     
    10769            if (val==null) val = s.toString ();
    10870
    109             session.export (context, req.getSession (), key, val, master);
     71            shell.export (context, io.req.getSession (), key, val, master);
    11072        }
    11173
    11274        // FIXME: probably shouldn't automatically save here
    113         session.saveUp (context, req.getSession ());
    114        
    115         // FIXME: is this necessary?
    116         //Sessions.put (req, context, session);
     75        shell.saveUp (context, io.req.getSession ());
    11776    }
    11877}
  • src/win/iovar/web/bin/shell/Interactive.java

    r113 r116  
    212212                        "</shell>";
    213213               
     214                final Executable.IO io = new Executable.IO (req, null, resp);
     215               
    214216                XSLT.transform (context, Transport.handler (style, context, req.getSession ()).get (),
    215                         new ByteArrayInputStream (xml.getBytes ()), resp, req.getSession ());
     217                        new ByteArrayInputStream (xml.getBytes ()), io, req.getSession ());
    216218               
    217219                styled = true;
     
    243245            out.println ("      <form target=\"output\" method=\"GET\">");
    244246            out.println ("          <input type=\"hidden\" name=\""+Shell.PARAM_SESSION+"\" value=\""+shell.getPath ()+"\">");
     247            out.println ("          <input type=\"hidden\" name=\"ioframe\" value=\"partial\">");
    245248            out.println ("          <input id=\"cmd_exec\" type=\"submit\" value=\"exec\">");
    246249            out.println ("          <label id=\"cmd\">$ <input type=\"text\" id=\"cmd_in\" name=\""+Shell.PARAM_CMD+"\" size=\"60\"></label>");
    247250            out.println ("      </form>");
     251           
    248252            out.println ("      <iframe name=\"output\" width=\"800\" height=\"300\"> </iframe>");
     253           
    249254            out.println ("      <script language=\"javascript\"> document.getElementById ('cmd_in').focus (); </script>");
    250255            out.println ("  </body>");
     
    272277        }
    273278       
     279        /*
     280        if (params.containsKey ("ioframe") && shell.get ("ioframe")==null) {
     281            //params.put ("ioframe", Arrays.asList (new String[] { "partial" }));
     282            shell.set ("ioframe", "partial");
     283        }
     284        */
     285       
    274286        // FIXME: content-disposition, allow-origin not yet utilized here
    275287        final Return r = Shell.exec (path, params, new TaskData (shell, context, req.getRemoteUser (), req.getSession (), in, req.getContentType (), null, null));
  • src/win/iovar/web/bin/shell/Print.java

    r75 r116  
    11/*
    2  * Copyright (C) 2016-2017 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * @%@~LICENSE~@%@
    44 */
     
    77// local imports:
    88import win.iovar.web.*;
    9 import win.iovar.web.dev.*;
    109import win.iovar.web.lib.*;
    11 import win.iovar.web.proc.*;
    1210
    1311// java imports:
    1412import java.io.*;
    1513import java.util.*;
    16 import java.util.List;
    17 import javax.servlet.*;
    18 import javax.servlet.http.*;
    1914
    2015// 3rd-party imports:
     
    2318 * Output shell variable contents.
    2419 *
    25  * FIXME: `set` and `print` should also preserve content-type and other headers.
     20 * FIXME: `set` and `print` should also preserve content-type (and other headers?).
    2621 *
    2722 * @author  shawn@lannocc.com
    2823 */
    29 public class Print extends HttpServlet
     24public class Print extends Executable
    3025{
    31     protected void doHead (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     26    public static final Usage USAGE = new Usage (
     27            "<name> [<name> ...]",
     28            new String[] {
     29                "Output the contents of shell variable(s) called <name>.",
     30                "Any variables that don't exist are silently skipped."
     31            }
     32    );
     33   
     34    public Usage usage (final IO io)
    3235    {
    33         Utils.doHead (this, req, resp);
     36        return USAGE;
    3437    }
    3538   
    36     protected void doGet (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     39    public Accept prep (final IO io)
    3740    {
    38         Utils.doGet (this, req, resp);
     41        return null;
    3942    }
    4043   
    41     protected void doPut (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     44    public void exec (final IO io) throws IOException
    4245    {
    43         Utils.doPut (this, req, resp);
    44     }
    45    
    46     public void usage (final HttpServletResponse resp) throws IOException
    47     {
    48         Log.debug ("displaying usage");
     46        final Session shell = io.shell (true);
     47
     48        final List<String> vals = io.params.get (null);
     49        if (vals==null || vals.size () < 1)
     50        {
     51            throw new ExitUsage (1);
     52        }
    4953       
    50         resp.setContentType ("text/plain");
    51         final PrintWriter out = resp.getWriter ();
     54        if (vals.size () > 1)
     55        {
     56            io.multipart ();
     57        }
    5258       
    53         out.println ("usage: print <name>");
    54         out.println ();
    55         out.println ("Output the contents of shell variable called <name>.");
    56         out.println ();
    57         out.println ("Options:");
    58         out.println ("   ?help      - display this help screen");
    59     }
    60    
    61     protected void doPost (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    62     {
    63         try
     59        for (final String name : vals)
    6460        {
    65             final ServletContext context = getServletContext ();
    66             final String query = req.getQueryString ();
    67             final Map<String,List<String>> params = Utils.getParams (query);
    68 
    69             if (params.containsKey ("help"))
    70             {
    71                 usage (resp);
    72                 Shell.exit (req, context, 0);
    73                 return;
    74             }
    75        
    76             final Session shell = Sessions.get (req);
    77             if (shell==null)
    78             {
    79                 Log.error ("unable to retrieve session");
    80                 throw new IllegalArgumentException ("need a session to print a variable");
    81             }
     61            final Session.Variable var = shell.get (name);
     62            if (var == null) continue;
    8263           
    83             final List<String> vals = params.get (null);
    84             if (vals==null || vals.size () != 1)
    85             {
    86                 usage (resp);
    87                 Shell.exit (req, context, 1);
    88                 return;
    89             }
    90            
    91             final String name = vals.get (0);
    92             final PrintWriter out = resp.getWriter ();
    93            
    94             final String val = shell.get (name);
    95             if (val!=null)
    96             {
    97                 out.print (val);
    98                 out.flush ();
    99             }
    100         }
    101         catch (final Exception e)
    102         {
    103             Log.fatal (e);
    104             StackTraceElement[] elems = e.getStackTrace ();
    105             for (StackTraceElement elem : elems)
    106             {
    107                 Log.fatal (elem.toString ());
    108             }
     64            final OutputStream out = io.out (var.type);
     65            var.out (out);
     66            out.close ();
    10967        }
    11068    }
  • src/win/iovar/web/bin/shell/Set.java

    r76 r116  
    11/*
    2  * Copyright (C) 2016-2017 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * Copyright (C) 2011-2015 Lannocc Technologies
    44 * @%@~LICENSE~@%@
     
    1010import win.iovar.web.dev.*;
    1111import win.iovar.web.lib.*;
    12 import win.iovar.web.proc.*;
    1312
    1413// java imports:
     
    1615import java.util.*;
    1716import javax.servlet.*;
    18 import javax.servlet.http.*;
    1917
    2018// 3rd-party imports:
     
    2523 * @author  shawn@lannocc.com
    2624 */
    27 public class Set extends HttpServlet
     25public class Set extends Executable
    2826{
    29     protected void doHead (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     27    public static final Usage USAGE = new Usage (
     28            "[<name>[=<val>]]",
     29            new String[] {
     30                "When invoked without arguments, displays currently assigned variables.",
     31                "Otherwise define a variable named <name> and assign it <val> or from standard input."
     32            }
     33    );
     34   
     35    public Usage usage (final IO io)
    3036    {
    31         Utils.doHead (this, req, resp);
     37        return USAGE;
    3238    }
    3339   
    34     protected void doGet (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    35     {
    36         Utils.doGet (this, req, resp);
    37     }
    38    
    39     protected void doPut (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    40     {
    41         Utils.doPut (this, req, resp);
    42     }
    43    
    44     public void usage (final HttpServletResponse resp) throws IOException
    45     {
    46         Log.debug ("displaying usage");
    47        
    48         resp.setContentType ("text/plain");
    49         final PrintWriter out = resp.getWriter ();
    50        
    51         out.println ("usage: set [<name>[=<val>]]");
    52         out.println ();
    53         out.println ("When invoked without arguments, displays currently assigned variables.");
    54         out.println ("Otherwise define a variable named <name> and assign it <val> or from standard input.");
    55         out.println ();
    56         out.println ("Options:");
    57         out.println ("   ?help          - display this help screen");
    58     }
    59    
    60     /**
    61      * Execute.
    62      */
    63     protected void doPost (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
     40    public void exec (final IO io) throws IOException
    6441    {
    6542        final ServletContext context = getServletContext ();
    66         final String query = req.getQueryString ();
    67         final Map<String,List<String>> params = Utils.getParams (query);
    68        
    69         if (params.containsKey ("help"))
    70         {
    71             usage (resp);
    72             Shell.exit (req, context, 0);
    73             return;
    74         }
    75        
    76         final Session shell = Sessions.get (req);
    77         if (shell==null)
    78         {
    79             Log.error ("unable to retrieve session");
    80             throw new IllegalArgumentException ("need a session to list environment");
    81         }
     43        final Map<String,List<String>> params = io.params;
     44        final Session shell = io.shell (true);
    8245       
    8346        final List<String> vals = params.get (null);
    8447        if (vals==null || vals.isEmpty ())
    8548        {
    86             environment (shell, resp);
    87             Shell.exit (req, context, 0);
     49            environment (shell, io);
    8850            return;
    8951        }
    9052       
    9153        final StringBuffer s = new StringBuffer ();
    92         final InputStream in = req.getInputStream ();
     54        final InputStream in = io.in;
    9355        if (in!=null)
    9456        {
     
    10567           
    10668            // FIXME: re-evaluate this...
    107             shell.export (1, context, req.getSession (), key, val);
     69            shell.export (1, context, io.req.getSession (), key, val);
    10870        }
    10971       
    11072        // FIXME: re-evaluate this...
    111         shell.saveUp (1, context, req.getSession ());
    112        
    113         Shell.exit (req, context, 0);
     73        shell.saveUp (1, context, io.req.getSession ());
    11474    }
    11575   
    116     void environment (final Session shell, final HttpServletResponse resp) throws IOException
     76    void environment (final Session shell, final IO io) throws IOException
    11777    {
    118         PrintWriter out = resp.getWriter ();
    11978        Log.debug ("printing current environment for "+shell);
    12079       
    121         for (final Map.Entry<String,String> entry: shell.getVariables ().entrySet ())
     80        PrintWriter out = io.outP ("text/plain"); try
    12281        {
    123             out.println (entry);
     82            for (final Map.Entry<String,Session.Variable> entry: shell.getVariables ().entrySet ())
     83            {
     84                out.println (entry);
     85            }
     86
     87            for (final Map.Entry<String,Session.Variable> entry : shell.getLocals ().entrySet ())
     88            {
     89                out.println ("local "+entry);
     90            }
    12491        }
    125        
    126         for (final Map.Entry<String,String> entry : shell.getLocals ().entrySet ())
     92        finally
    12793        {
    128             out.println ("local "+entry);
     94            out.close ();
    12995        }
    13096    }
  • src/win/iovar/web/bin/shell/Shell.java

    r113 r116  
    227227                   
    228228                    // save history
    229                     String history = session.get ("HISTORY");
    230                     if (history==null) history = line;
    231                     else history = line + '\n' + history;
     229                    final String history;
     230                    {
     231                        final Session.Variable var = session.get ("HISTORY");
     232                        if (var==null) history = line;
     233                        else history = line + '\n' + var.value;
     234                    }
    232235                    session.export (context, req.getSession (), "HISTORY", history);
    233236                    session.saveUp (context, req.getSession ());
  • src/win/iovar/web/bin/shell/task/Variable.java

    r76 r116  
    11/*
    2  * Copyright (C) 2016-2017 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * Copyright (C) 2013-2014 Lannocc Technologies
    44 * @%@~LICENSE~@%@
     
    104104    public String value (Session shell, final ServletContext context, final HttpSession htsession)
    105105    {
    106         if (shell!=null) return shell.get (name);
    107         else return "";
     106        if (shell==null)
     107        {
     108            return "";
     109        }
     110       
     111        final Session.Variable var = shell.get (name);
     112        if (var == null)
     113        {
     114            return "";
     115        }
     116        else
     117        {
     118            return var.value;
     119        }
    108120    }
    109121   
  • src/win/iovar/web/lib/Session.java

    r76 r116  
    11/*
    2  * Copyright (C) 2016-2017 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * Copyright (C) 2011-2015 Lannocc Technologies
    44 * @%@~LICENSE~@%@
     
    3737    final String parentPath;
    3838
    39     final HashMap<String,String> env;
    40     final HashMap<String,String> locals; // locals do not propagate to children
     39    final HashMap<String,Variable> env;
     40    final HashMap<String,Variable> locals; // locals do not propagate to children
    4141    Object user;
    4242    Integer exit;
     
    5353        this.parentPath = null;
    5454
    55         this.env = new HashMap<String,String> ();
    56 
    57         env.put (ENV_INSTANCE, id);
    58         env.put (ENV_VERSION, win.iovar.web.bin.shell.Shell.VERSION);
     55        this.env = new HashMap<String,Variable> ();
     56
     57        env.put (ENV_INSTANCE, new Variable (id));
     58        env.put (ENV_VERSION, new Variable (win.iovar.web.bin.shell.Shell.VERSION));
    5959        //env.put (ENV_ROOT, root);
    6060        //env.put (ENV_WORKING_URI_BASE, pwu);
     
    6464        //env.put (ENV_PATH, "/usr/local/bin:/usr/bin:/bin:/opt/bin");
    6565
    66         this.locals = new HashMap<String,String> ();
     66        this.locals = new HashMap<String,Variable> ();
    6767        this.exit = null;
    6868
     
    8686        this.parentPath = parent.path;
    8787
    88         this.env = (HashMap<String,String>) parent.env.clone ();
    89         this.env.put (ENV_INSTANCE, id);
    90 
    91         this.locals = new HashMap<String,String> ();
     88        this.env = (HashMap<String,Variable>) parent.env.clone ();
     89        this.env.put (ENV_INSTANCE, new Variable (id));
     90
     91        this.locals = new HashMap<String,Variable> ();
    9292        this.exit = parent.exit;
    9393
     
    127127    }
    128128
    129     public String get (final String key)
     129    public Variable get (final String key)
    130130    {
    131131        Log.debug ("get ["+id+"]: "+key);
    132132        if ("?".equals (key)) {
    133133            Log.debug ("returning exit value: "+exit);
    134             return String.valueOf (exit);
     134            return new Variable ("text/plain", String.valueOf (exit));
    135135        }
    136136        else if (locals.containsKey (key)) return locals.get (key);
     
    138138    }
    139139
    140     public String set (final String key, final String val)
     140    public Variable set (final String key, final String type, final String val)
    141141    {
    142142        Log.debug ("set ["+id+"]: "+key+"="+val);
    143         return env.put (key, val);
    144     }
    145 
    146     public String setLocal (final String key, final String val)
     143        return env.put (key, new Variable (type, val));
     144    }
     145
     146    public Variable set (final String key, final String val)
     147    {
     148        return set (key, "text/plain", val);
     149    }
     150
     151    public Variable setLocal (final String key, final String type, final String val)
    147152    {
    148153        Log.debug ("set local ["+id+"]: "+key+"="+val);
    149         return locals.put (key, val);
     154        return locals.put (key, new Variable (type, val));
     155    }
     156
     157    public Variable setLocal (final String key, final String val)
     158    {
     159        return setLocal (key, "text/plain", val);
    150160    }
    151161
     
    170180     * Non-local variables only.
    171181     */
    172     public Map<String,String> getVariables ()
    173     {
    174         final Map<String,String> env =  (Map<String,String>) this.env.clone ();
    175         if (exit!=null) env.put ("?", exit.toString ());
     182    public Map<String,Variable> getVariables ()
     183    {
     184        final Map<String,Variable> env =  (Map<String,Variable>) this.env.clone ();
     185        if (exit!=null) env.put ("?", new Variable ("text/plain", exit.toString ()));
    176186        else env.remove ("?");
    177187        return env;
     
    181191     * Local variables only.
    182192     */
    183     public Map<String,String> getLocals ()
    184     {
    185         return (Map<String,String>) locals.clone ();
     193    public Map<String,Variable> getLocals ()
     194    {
     195        return (Map<String,Variable>) locals.clone ();
    186196    }
    187197
     
    189199     * All variables.
    190200     */
    191     public Map<String,String> getEnvironment ()
    192     {
    193         final Map<String,String> env = getVariables ();
    194 
    195         for (final Map.Entry<String,String> local : locals.entrySet ())
     201    public Map<String,Variable> getEnvironment ()
     202    {
     203        final Map<String,Variable> env = getVariables ();
     204
     205        for (final Map.Entry<String,Variable> local : locals.entrySet ())
    196206        {
    197207            env.put (local.getKey (), local.getValue ());
     
    201211    }
    202212
    203     public String export (final ServletContext context, final HttpSession htsession, final String key, final String val) throws IOException
     213    public Variable export (final ServletContext context, final HttpSession htsession, final String key, final String val) throws IOException
    204214    {
    205215        return export (context, htsession, key, val, false);
    206216    }
    207217
    208     public String export (final ServletContext context, final HttpSession htsession, final String key, final String val, final boolean master) throws IOException
     218    public Variable export (final ServletContext context, final HttpSession htsession, final String key, final String val, final boolean master) throws IOException
    209219    {
    210220        if (master)
     
    223233     *                  Use -2 to go up to the master session.
    224234     */
    225     public String export (final int count, final ServletContext context, final HttpSession htsession, final String key, final String val) throws IOException
     235    public Variable export (final int count, final ServletContext context, final HttpSession htsession, final String key, final String val) throws IOException
    226236    {
    227237        final Session parent = getParent (context, htsession);
     
    287297    public List<String> getPathList ()
    288298    {
    289         final String path = get (ENV_PATH);
     299        final Variable path = get (ENV_PATH);
    290300        if (path==null) return null;
    291301
     
    293303
    294304        // using comma as separator because colon is so prevalent in URIs
    295         for (final StringTokenizer st = new StringTokenizer (path, ","); st.hasMoreTokens (); )
     305        for (final StringTokenizer st = new StringTokenizer (path.value, ","); st.hasMoreTokens (); )
    296306        {
    297307            list.add (st.nextToken ());
     
    411421        return super.toString () + "{ "+id+" }";
    412422    }
     423   
     424    public static class Variable
     425    {
     426        public final String type;
     427        public final String value;
     428       
     429        public Variable (final String type, final String value)
     430        {
     431            this.type = type;
     432            this.value = value;
     433        }
     434       
     435        public Variable (final String value)
     436        {
     437            this ("text/plain", value);
     438        }
     439       
     440        public void out (final OutputStream out) throws IOException
     441        {
     442            out.write (value.getBytes ());
     443        }
     444       
     445        public String toString ()
     446        {
     447            return "["+type+"]"+value;
     448        }
     449    }
    413450}
  • src/win/iovar/web/usr/bin/XSLT.java

    r76 r116  
    11/*
    2  * Copyright (C) 2016-2017 Virgo Venture, Inc.
     2 * Copyright (C) 2016-2018 Virgo Venture, Inc.
    33 * Copyright (C) 2013-2015 Lannocc Technologies
    44 * @%@~LICENSE~@%@
     
    2828 * @author  shawn@lannocc.com
    2929 */
    30 public class XSLT extends HttpServlet
     30public class XSLT extends Executable
    3131{
    32     protected void doHead (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    33     {
    34         Utils.doHead (this, req, resp);
    35     }
    36    
    37     protected void doGet (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    38     {
    39         Utils.doGet (this, req, resp);
    40     }
    41    
    42     protected void doPut (final HttpServletRequest req, final HttpServletResponse resp) throws IOException
    43     {
    44         Utils.doPut (this, req, resp);
    45     }
    46    
    47     public void usage (final HttpServletResponse resp) throws IOException
    48     {
    49         Log.debug ("displaying usage");
    50        
    51         resp.setContentType ("text/plain");
    52         final PrintWriter out = resp.getWriter ();
    53        
    54         out.println ("usage: xslt <stylesheet> [<xml-document>] [--] [<arguments>]");
    55         out.println ("   - when <xml-document> is ommitted stdin is used");
    56         out.println ("   - any named parameters are passed to the stylesheet as xsl param variables");
    57         out.println ("   - unless ?variables is used, any additional arguments");
    58         out.println ("      (use '--' when xml-document is omitted)");
    59         out.println ("      are passed as parameters named arg1, arg2, etc.");
    60         out.println ();
    61         // FIXME: don't really want options here... this is temporary until useful buffer support
    62         //      (needed for cattamboo /bin/view)
    63         out.println ("Options:");
    64         out.println ("   ?help                     - display this help screen");
    65         out.println ("   ?variables                - the <arguments> are taken to be variable names");
    66         out.println ("                               and the value of these variables will be passed");
    67         out.println ("                               by name to the stylesheet as xsl param variables");
    68         out.println ("   ?preproc=<pre-stylesheet> - preprocess <stylesheet> using <pre-stylesheet> ");
    69         out.println ("                               and then use the result as stylesheet");
    70     }
    71    
    72     /**
    73      * Execute.
    74      */
    75     public void doPost (final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException
     32    public static final Usage USAGE = new Usage (
     33            "<stylesheet> [<xml-document>] [--] [<arguments>]",
     34            new String[] {
     35                "   - when <xml-document> is ommitted stdin is used",
     36                "   - any named parameters are passed to the stylesheet as xsl param variables",
     37                "   - unless ?variables is used, any additional arguments",
     38                "      (use '--' when xml-document is omitted)",
     39                "      are passed as parameters named arg1, arg2, etc."
     40            },
     41            // FIXME: don't really want options here... this is temporary until useful buffer support
     42            //      (needed for cattamboo /bin/view)
     43            new Param[] {
     44                new Param ("variables", "the <arguments> are taken to be variable names and the value of these variables will be passed by name to the stylesheet as xsl param variables"),
     45                new Param ("preproc=<pre-stylesheet>", "preprocess <stylesheet> using <pre-stylesheet> and then use the result as stylesheet")
     46            }
     47    );
     48   
     49    public Usage usage (final IO io)
     50    {
     51        return USAGE;
     52    }
     53   
     54    /*
     55    public Accept prep (final IO io)
     56    {
     57        return null;
     58    }
     59    */
     60   
     61    public void exec (final IO io) throws IOException
    7662    {
    7763        Log.debug ("begin xslt POST");
    7864       
    7965        final ServletContext context = getServletContext ();
    80         final String query = req.getQueryString ();
    81        
    82         if (query==null)
    83         {
    84             usage (resp);
    85             Shell.exit (req, context, 1);
    86             return;
    87         }
    88        
    89         final Map<String,List<String>> params = Utils.getParams (query);
     66        final Map<String,List<String>> params = io.params;
    9067        final List<String> resources = params.get (null);
    9168
    9269        if (resources==null || resources.size ()<1)
    9370        {
    94             usage (resp);
    95             Shell.exit (req, context, 2);
    96             return;
     71            throw new ExitUsage (1);
    9772        }
    9873       
     
    132107            params.remove ("variables");
    133108       
    134             final Session session = Sessions.get (req);
    135             if (session==null)
    136             {
    137                 Log.error ("unable to retrieve session");
    138                 throw new IllegalArgumentException ("need a session for variable substitution mode");
    139             }
     109            // a session is required for variable substitution mode
     110            final Session shell = io.shell (true);
    140111           
    141112            for (final String arg : resources)
    142113            {
    143                 params.put (arg, Arrays.asList (new String[] { session.get (arg) }));
     114                final Session.Variable var = shell.get (arg);
     115                if (var != null)
     116                {
     117                    params.put (arg, Arrays.asList (new String[] { var.value }));
     118                }
    144119            }
    145120        }
     
    152127        {
    153128            final TransformerFactory tf = TransformerFactory.newInstance();
    154             tf.setURIResolver (new TransportResolver (context, req.getSession ()));
     129            tf.setURIResolver (new TransportResolver (context, io.req.getSession ()));
    155130
    156131            final ByteArrayOutputStream bytes; // FIXME: #11
    157132            if (prestyle!=null)
    158133            {
    159                 final StreamSource xsl = new StreamSource (Transport.handler (prestyle, context, req.getSession ()).get ());
     134                final StreamSource xsl = new StreamSource (Transport.handler (prestyle, context, io.req.getSession ()).get ());
    160135                final Transformer trx = tf.newTransformer (xsl);
    161136                trx.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    162137
    163                 final StreamSource xml = new StreamSource (Transport.handler (stylesheet, context, req.getSession ()).get ());
     138                final StreamSource xml = new StreamSource (Transport.handler (stylesheet, context, io.req.getSession ()).get ());
    164139                bytes = new ByteArrayOutputStream ();
    165140                trx.transform (xml, new StreamResult (bytes));
     
    173148            {
    174149                if (bytes!=null) xsl = new StreamSource (new ByteArrayInputStream (bytes.toByteArray ()));
    175                 else xsl = new StreamSource (Transport.handler (stylesheet, context, req.getSession ()).get ());
     150                else xsl = new StreamSource (Transport.handler (stylesheet, context, io.req.getSession ()).get ());
    176151            }
    177152
    178153            final StreamSource xml;
    179154            {
    180                 if (resource!=null) xml = new StreamSource (Transport.handler (resource, context, req.getSession ()).get ());
    181                 else xml = new StreamSource (req.getInputStream ());
    182             }
    183            
    184             transform (tf, context, xsl, xml, params, args, resp);
    185            
    186             Shell.exit (req, context, 0);
     155                if (resource!=null) xml = new StreamSource (Transport.handler (resource, context, io.req.getSession ()).get ());
     156                else xml = new StreamSource (io.in);
     157            }
     158           
     159            transform (tf, context, xsl, xml, params, args, io);
    187160        }
    188161        catch (final IOException e)
    189162        {
    190             Log.error (e);
    191             resp.getWriter ().print ("xslt: i/o error: "+e+"\n");
    192             Shell.exit (req, context, 3);
     163            throw new Exit (2, "xslt: i/o error", e);
    193164        }
    194165        catch (final TransformerConfigurationException e)
    195166        {
    196             Log.error (e);
    197             //throw new ServletException (e);
    198             resp.getWriter ().print ("xslt: xml transform config failure: "+e+"\n");
    199             Shell.exit (req, context, 4);
     167            throw new Exit (3, "xslt: xml transform config failure", e);
    200168        }
    201169        catch (final TransformerException e)
    202170        {
    203             Log.error (e);
    204             //throw new ServletException ("xml transform failed: ", e);
    205             resp.getWriter ().print ("xslt: xml transform failed: "+e+"\n");
    206             Shell.exit (req, context, 5);
     171            throw new Exit (4, "xslt: xml transform failed", e);
    207172        }
    208173    }
     
    212177     */
    213178    public static void transform (final ServletContext context, final InputStream xsl,
    214             final InputStream xml, final HttpServletResponse resp, final HttpSession htsession)
     179            final InputStream xml, final IO io, final HttpSession htsession)
    215180           
    216181            throws IOException, TransformerConfigurationException, TransformerException
     
    219184        tf.setURIResolver (new TransportResolver (context, htsession));
    220185       
    221         transform (tf, context, new StreamSource (xsl), new StreamSource (xml), null, null, resp);
     186        transform (tf, context, new StreamSource (xsl), new StreamSource (xml), null, null, io);
    222187    }
    223188   
     
    225190            final StreamSource xsl, final StreamSource xml,
    226191            final Map<String,List<String>> params, final List<String> args,
    227             final HttpServletResponse resp)
     192            final IO io)
    228193           
    229194            throws IOException, TransformerConfigurationException, TransformerException
     
    263228        final String type = trx.getOutputProperty (OutputKeys.MEDIA_TYPE);
    264229        Log.debug ("media type from XSL stylesheet: "+type);
    265         if (type!=null)
    266         {
    267             Log.info ("setting content type: "+type);
    268             resp.setContentType (type);
    269         }
    270230
    271231        Log.info ("applying xsl transformation");
    272         trx.transform (xml, new StreamResult (resp.getWriter ()));
     232        trx.transform (xml, new StreamResult (io.outP (type)));
    273233    }
    274234   
Note: See TracChangeset for help on using the changeset viewer.