changeset 1:0ff3ede32060

Initial revision
author robcast
date Thu, 17 Jan 2002 15:25:46 +0100
parents ffd2df307e81
children cbea17861f61 d407cb901df4
files servlet/doc/Scaler.html servlet/license.txt servlet/src/digilib/Utils.java servlet/src/digilib/auth/AuthOpException.java servlet/src/digilib/auth/AuthOps.java servlet/src/digilib/auth/AuthOpsImpl.java servlet/src/digilib/auth/DBAuthOpsImpl.java servlet/src/digilib/auth/HashTree.java servlet/src/digilib/auth/XMLAuthOps.java servlet/src/digilib/auth/dlDataModule.java servlet/src/digilib/image/DocuImage.java servlet/src/digilib/image/DocuImageImpl.java servlet/src/digilib/image/ImageLoaderDocuImage.java servlet/src/digilib/image/ImageOpException.java servlet/src/digilib/image/JAIDocuImage.java servlet/src/digilib/image/JIMIDocuImage.java servlet/src/digilib/io/FileOpException.java servlet/src/digilib/io/FileOps.java servlet/src/digilib/io/XMLListLoader.java servlet/src/digilib/servlet/DocumentBean.java servlet/src/digilib/servlet/Scaler.java servlet/src/digilib/servlet/ServletOps.java
diffstat 22 files changed, 2731 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/doc/Scaler.html	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,64 @@
+<HTML>
+<HEAD>
+<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
+<TITLE>JBuilder Project ScaleServlet2.jpx</TITLE>
+</HEAD>
+<BODY>
+<H1>Scaler</H1>
+
+<p>A Servlet for scaling images.</p>
+
+<p>Scaler takes parameters in the http request format:
+<code>Scaler/request_path/?param1=value1&param2=value2&...</code></p>
+
+<p>Recognised parameters:
+<ul>
+  <li><b>request_path</b> path to file or directory.
+
+  <li><b>fn</b> path to file or directory below <code>/docuserver/images</code>.
+    This path will be added to the <code>request_path</code> behind the servlet name.
+    Either parameter can be empty.
+
+  <li><b>pn</b> page number. Index into the (alphabetically sorted) directory
+    given by the path. Starts with 1. Ignored if the path points to a file.
+    Default: 1.
+
+  <li><b>dw</b> destination image width (pixels).
+  <li><b>dh</b> destination image height.
+
+  <li><b>wx</b> relative x offset of the image area to be sent (0 &lt;= wx &lt;= 1).
+    Default: 0.
+  <li><b>wy</b> relative y offset of the image area to be sent.
+    Default: 0.
+  <li><b>ww</b> relative width of the image area to be sent.
+    Default: 1.
+  <li><b>wh</b> relative height of the image area to be sent.
+    Default: 1.
+
+  <li><b>ws</b> additional scaling factor. The resulting image will have the size
+    <code>[ws*dw,ws*dh]</code>. Default: 1.
+
+  <li><b>mo</b> flags for the mode of operation separated by "+".
+    <ul>
+      <li><b>fit</b>: always scale the image to fit <code>[dw,dh]</code>.<br>
+        <b>file</b>: send the file as-is (may be very large and all sorts of image types!).<br>
+        If none of these flags is set heuristics is used (send unzoomed GIF as-is).
+
+      <li><b>errtxt</b>: send error response as HTML.<br>
+        <b>errimg</b>: response as image (default).
+
+      <li><b>q0</b>-<b>q2</b>: quality of interpolation in scaling
+        (<code>q0</code>: worst, default).
+
+      <li><b>lores</b>: try to use scaled image (default)<br>
+        <b>hires</b>: always use unscaled image.<br>
+        If the image is zoomed (ww, wh &lt; 1) the unscaled image is used in any case.
+    </ul>
+
+</ul>
+The image will be scaled equally in horizontal and vertical direction such that
+the resulting image does not exceed the rectangle <code>[ww,wh]</code>.
+</p>
+
+</BODY>
+</HTML>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/license.txt	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,340 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/Utils.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,48 @@
+/*  Utils -- general utility classes for scaler servlet
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib;
+
+public class Utils {
+
+  public Utils() {
+  }
+
+  public Utils(int dbg) {
+    debugLevel = dbg;
+  }
+
+  /**
+   *  Debugging help
+   *    dprintln(1, "blabla");
+   *    will be printed on stdout if debug >= 1
+   */
+  public static int debugLevel = 10;
+  public static void dprintln(int dbg, String s) {
+    if (debugLevel >= dbg) {
+      String ind = "";
+      // indent by debuglevel
+      for (int i = 0; i < dbg; i++) {
+        ind += "  ";
+      }
+      System.out.println(ind+s);
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/auth/AuthOpException.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,30 @@
+/*  AuthOpException -- Authentication exception class
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.auth;
+
+public class AuthOpException extends Exception {
+
+  public AuthOpException() {
+  }
+  public AuthOpException(String s) {
+    super(s);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/auth/AuthOps.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,52 @@
+/*  AuthOps -- Authentication interface class
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.auth;
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.http.*;
+
+public interface AuthOps {
+
+  /**
+   *  check if the request must be authorized to access filepath
+   */
+  public boolean isAuthRequired(String filepath, HttpServletRequest request) throws AuthOpException;
+
+  /**
+   *  check if the request is allowed to access filepath
+   */
+  public boolean isAuthorized(String filepath, HttpServletRequest request) throws AuthOpException;
+
+  /**
+   *  return a list of authorization roles needed for request
+   *  to access the specified path
+   *    (does not look at request address for now)
+   */
+  public List rolesForPath(String filepath, HttpServletRequest request) throws AuthOpException;
+
+  /**
+   * check request authorization against a list of roles
+   */
+  public boolean isRoleAuthorized(List roles, HttpServletRequest request);
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/auth/AuthOpsImpl.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,77 @@
+/*  AuthOps -- Authentication class implementation
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.auth;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.*;
+
+import digilib.*;
+
+public abstract class AuthOpsImpl implements AuthOps {
+
+  protected Utils util;
+
+  public AuthOpsImpl() {
+    util = new Utils();
+    try {
+      init();
+    } catch (AuthOpException e) {
+    }
+  }
+
+  public AuthOpsImpl(Utils u) {
+    util = u;
+    try {
+      init();
+    } catch (AuthOpException e) {
+    }
+  }
+
+  public boolean isAuthRequired(String filepath, HttpServletRequest request) throws AuthOpException {
+    // check permissions
+    List rolesRequired = rolesForPath(filepath, request);
+    return (rolesRequired != null);
+  }
+
+  public boolean isAuthorized(String filepath, HttpServletRequest request) throws AuthOpException {
+    List rolesAllowed = rolesForPath(filepath, request);
+    return isRoleAuthorized(rolesAllowed, request);
+  }
+
+  public boolean isRoleAuthorized(List roles, HttpServletRequest request) {
+    ListIterator r = roles.listIterator();
+    String s = "";
+    while (r.hasNext()) {
+      s = (String)r.next();
+      util.dprintln(5, "Testing role: "+s);
+      if (request.isUserInRole(s)) {
+        util.dprintln(5, "Role Authorized");
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public abstract void init() throws AuthOpException;
+
+  public abstract List rolesForPath(String filepath, HttpServletRequest request) throws AuthOpException;
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/auth/DBAuthOpsImpl.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,134 @@
+/*  DBAuthOpsImpl -- Authentication class using database
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.auth;
+
+import javax.servlet.http.*;
+import java.util.*;
+import com.borland.dx.dataset.*;
+
+import digilib.*;
+
+public class DBAuthOpsImpl implements AuthOps {
+
+  private Utils util = null;
+  private dlDataModule dlDataModule1;
+
+  public DBAuthOpsImpl() {
+    util = new Utils();
+    dbInit();
+  }
+
+  public DBAuthOpsImpl(Utils u) {
+    util = u;
+    dbInit();
+  }
+
+  void dbInit() {
+    try {
+      dlDataModule1 = new dlDataModule();
+      dlDataModule1.getAuthPathsQuery().open();
+    }
+    catch(Exception e) {
+      e.printStackTrace();
+    }
+  }
+
+  public void setUtils(Utils u) {
+    util = u;
+  }
+
+  public boolean isAuthRequired(String filepath, HttpServletRequest request) throws AuthOpException {
+    // check permissions
+    List rolesRequired = rolesForPath(filepath, request);
+    return (rolesRequired != null);
+  }
+
+  public boolean isAuthorized(String filepath, HttpServletRequest request) throws AuthOpException {
+    List rolesAllowed = rolesForPath(filepath, request);
+    return isRoleAuthorized(rolesAllowed, request);
+  };
+
+  public List rolesForPath(String filepath, HttpServletRequest request) throws AuthOpException {
+    util.dprintln(4, "rolesForPath ("+filepath+")");
+    String p = "";
+    List r;
+    LinkedList roles = new LinkedList();
+
+    // split path in directories
+    StringTokenizer path = new StringTokenizer(filepath, "/");
+    // walk directories and check with db
+    while (path.hasMoreTokens()) {
+      p += "/" + path.nextToken();
+      r = dbRolesForPath(p);
+      if (r != null) {
+         roles.addAll(r);
+      }
+    }
+    if (roles.size() > 0) {
+      return roles;
+    } else {
+      return null;
+    }
+  }
+
+  public boolean isRoleAuthorized(List roles, HttpServletRequest request) {
+    ListIterator r = roles.listIterator();
+    String s = "";
+    while (r.hasNext()) {
+      s = (String)r.next();
+      util.dprintln(5, "Testing role: "+s);
+      if (request.isUserInRole(s)) {
+        util.dprintln(5, "Role Authorized");
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private List dbRolesForPath(String filepath) throws AuthOpException {
+    util.dprintln(4, "dbRolesForPath ("+filepath+")");
+
+    LinkedList roles = new LinkedList();
+    DataSet query = dlDataModule1.getAuthPathsQuery();
+    if (query == null) {
+      throw new AuthOpException("Unable to access database!");
+    }
+    // search for PATH_NAME == filepath
+    DataRow lookupRow = new DataRow(query, "PATH_NAME");
+    lookupRow.setString("PATH_NAME", filepath);
+
+    if (query.locate(lookupRow, Locate.FIRST)) {
+      roles.add(query.getString("ROLE_NAME"));
+      util.dprintln(5, "role found: "+query.getString("ROLE_NAME"));
+      // any more matches?
+      while (query.locate(lookupRow, Locate.NEXT_FAST)) {
+        roles.add(query.getString("ROLE_NAME"));
+        util.dprintln(5, "role found: "+query.getString("ROLE_NAME"));
+      }
+    }
+    if (roles.size() > 0) {
+      return roles;
+    } else {
+      return null;
+    }
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/auth/HashTree.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,80 @@
+/*  HashTree -- Tree in a Hashtable
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.auth;
+
+import java.util.*;
+
+public class HashTree {
+
+  private Hashtable table;
+  private String twigSep = "/";
+  private String leafSep = ",";
+
+  public HashTree() {
+    table = new Hashtable();
+  }
+
+  public HashTree(Hashtable t, String twig_separator, String leaf_separator) {
+    table = t;
+    twigSep = twig_separator;
+    leafSep = leaf_separator;
+    optimizeTable();
+  }
+
+  void optimizeTable() {
+  }
+
+  List match(String branch) {
+    String b = "";
+    String m;
+    LinkedList matches = new LinkedList();
+
+    // split branch
+    StringTokenizer twig = new StringTokenizer(branch, twigSep);
+    // walk branch and check with tree
+    while (twig.hasMoreTokens()) {
+      if (b.length() == 0) {
+        b = twig.nextToken();
+      } else {
+        b += twigSep + twig.nextToken();
+      }
+      m = (String)table.get(b);
+      //System.out.println("CHECK: "+b+" = "+m);
+      if (m != null) {
+        if (m.indexOf(leafSep) < 0) {
+          // single leaf
+          matches.add(m);
+        } else {
+          // split leaves
+          StringTokenizer leaf = new StringTokenizer(m, leafSep);
+          while (leaf.hasMoreTokens()) {
+            matches.add(leaf.nextToken());
+          }
+        }
+      }
+    }
+    if (matches.size() > 0) {
+      return matches;
+    } else {
+      return null;
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/auth/XMLAuthOps.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,97 @@
+/* XMLAuthOps -- Authentication class implementation using XML files
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.auth;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.*;
+import java.io.*;
+
+import digilib.*;
+import digilib.io.*;
+
+
+public class XMLAuthOps extends AuthOpsImpl {
+
+  private String configFile = "/docuserver/www/digitallibrary/WEB-INF/digilib-auth.xml";
+  private HashTree authPaths;
+  private HashTree authIPs;
+
+  public XMLAuthOps(Utils u, String confFile) throws AuthOpException {
+    util = u;
+    configFile = confFile;
+    init();
+  }
+
+  public void setConfig(String confFile) throws AuthOpException {
+    configFile = confFile;
+    init();
+  }
+
+  public void init() throws AuthOpException {
+    util.dprintln(10, "xmlauthops.init ("+configFile+")");
+    Hashtable pathList = null;
+    Hashtable ipList = null;
+    try {
+      // create data loader for auth-path file
+      File confFile = new File(configFile);
+      // load authPaths
+      XMLListLoader pathLoader = new XMLListLoader("digilib-paths", "path", "name", "role");
+      pathList = pathLoader.loadURL(confFile.toURL().toString());
+      // load authIPs
+      XMLListLoader ipLoader = new XMLListLoader("digilib-addresses", "address", "ip", "role");
+      ipList = ipLoader.loadURL(confFile.toURL().toString());
+    }
+    catch (Exception e) {
+      throw new AuthOpException("ERROR loading authorization config file: "+e);
+    }
+    if ((pathList == null)||(ipList == null)) {
+      throw new AuthOpException("ERROR unable to load authorization config file!");
+    }
+    // setup path tree
+    authPaths = new HashTree(pathList, "/", ",");
+    // setup ip tree
+    authIPs = new HashTree(ipList, ".", ",");
+  }
+
+  public List rolesForPath(String filepath, HttpServletRequest request) throws digilib.auth.AuthOpException {
+    util.dprintln(4, "rolesForPath ("+filepath+") by ["+request.getRemoteAddr()+"]");
+
+    // check if the requests address provides a role
+    List provided = authIPs.match(request.getRemoteAddr());
+    if ((provided != null)&&(provided.contains("ALL"))) {
+      // ALL switches off checking;
+      return null;
+    }
+    // which roles are required?
+    List required = authPaths.match(filepath);
+    // do any provided roles match?
+    if ((provided != null)&&(required != null)) {
+      for (int i = 0; i < provided.size(); i++) {
+        if (required.contains(provided.get(i))) {
+          // satisfied
+          return null;
+        }
+      }
+    }
+    return required;
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/auth/dlDataModule.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,58 @@
+/* dlDataModule -- Database access helper class
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.auth;
+
+import com.borland.dx.dataset.*;
+import com.borland.dx.sql.dataset.*;
+
+
+public class dlDataModule implements DataModule {
+  private static dlDataModule myDM;
+  Database dlDatabase = new Database();
+  QueryDataSet authPathsQuery = new QueryDataSet();
+
+  public dlDataModule() {
+    try {
+      jbInit();
+    }
+    catch(Exception e) {
+      e.printStackTrace();
+    }
+  }
+  private void jbInit() throws Exception {
+    authPathsQuery.setReadOnly(true);
+    authPathsQuery.setEditable(false);
+    authPathsQuery.setQuery(new com.borland.dx.sql.dataset.QueryDescriptor(dlDatabase, "select * from digilib_paths", null, true, Load.ALL));
+    dlDatabase.setConnection(new com.borland.dx.sql.dataset.ConnectionDescriptor("jdbc:oracle:thin:@penelope.unibe.ch:1521:WTWG", "digilib_auth", "allesmainz", false, "oracle.jdbc.driver.OracleDriver"));
+  }
+  public static dlDataModule getDataModule() {
+    if (myDM == null) {
+      myDM = new dlDataModule();
+    }
+    return myDM;
+  }
+  public com.borland.dx.sql.dataset.Database getDlDatabase() {
+    return dlDatabase;
+  }
+  public com.borland.dx.sql.dataset.QueryDataSet getAuthPathsQuery() {
+    return authPathsQuery;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/image/DocuImage.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,68 @@
+/* DocuImage -- General image interface class
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.image;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+import java.awt.image.*;
+import java.awt.image.renderable.*;
+
+import digilib.*;
+import digilib.io.*;
+
+public interface DocuImage {
+
+  public String[] getKnownFileTypes();
+
+  /**
+   *  send an image file as-is
+   */
+  public void sendFile(File f, ServletResponse res) throws FileOpException;
+
+  /**
+   *  load image file
+   */
+  public void loadImage(File f) throws FileOpException;
+
+  /**
+   *  write image with mime type mt to Stream
+   */
+  public void writeImage(String mt, ServletResponse res) throws FileOpException;
+
+  /**
+   *  get the image height and width
+   */
+  public int getWidth();
+  public int getHeight();
+
+  /**
+   *  crop and scale image
+   *    take rectangle width,height at position x_off,y_off
+   *    and scale by scale with interpolation quality qual (0=worst)
+   */
+  public void cropAndScale(
+                int x_off, int y_off,
+                int width, int height,
+                float scale, int qual) throws ImageOpException;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/image/DocuImageImpl.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,84 @@
+/* DocuImage -- General image interface class implementation
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.image;
+
+import java.io.*;
+import javax.servlet.ServletResponse;
+
+import digilib.*;
+import digilib.io.*;
+
+public abstract class DocuImageImpl implements DocuImage {
+
+  protected Utils util = null;
+
+  public DocuImageImpl() {
+    util = new Utils();
+  }
+
+  public DocuImageImpl(Utils u) {
+    util = u;
+  }
+
+  public void setUtils(Utils u) {
+    util = u;
+  }
+
+  protected String[] knownFileTypes = {"jpg", "png", "gif", "tiff"};
+
+  public String[] getKnownFileTypes() {
+    return knownFileTypes;
+  }
+
+  /**
+   *  send an image file as-is
+   */
+  public void sendFile(File f, ServletResponse response) throws FileOpException {
+    util.dprintln(4, "sendFile("+f+")");
+    String mimeType = FileOps.mimeForFile(f);
+    if (mimeType == null) {
+      util.dprintln(2, "ERROR(sendFile): unknown file Type");
+      throw new FileOpException("Unknown file type.");
+    }
+    response.setContentType(mimeType);
+    // open file
+    try {
+      FileInputStream inFile = new FileInputStream(f);
+      OutputStream outStream = response.getOutputStream();
+      byte dataBuffer[] = new byte[1024];
+      int len;
+      while ((len = inFile.read(dataBuffer)) != -1) {
+        // copy out file
+        outStream.write(dataBuffer, 0, len);
+      }
+      inFile.close();
+    } catch (IOException e) {
+      util.dprintln(2, "ERROR(sendFile): unable to send file");
+      throw new FileOpException("Unable to send file.");
+    }
+  }
+
+  public abstract void loadImage(File f) throws FileOpException;
+  public abstract void writeImage(String mt, ServletResponse res) throws FileOpException;
+  public abstract int getWidth();
+  public abstract int getHeight();
+  public abstract void cropAndScale(int x_off, int y_off, int width, int height, float scale, int qual)  throws ImageOpException;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/image/ImageLoaderDocuImage.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,164 @@
+/* ImageLoaderDocuImage -- Image class implementation using JDK 1.4 ImageLoader
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.image;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+import java.awt.*;
+import java.awt.image.*;
+import java.awt.geom.*;
+import java.awt.image.renderable.*;
+
+import javax.imageio.*;
+
+import digilib.*;
+import digilib.io.*;
+
+public class ImageLoaderDocuImage extends DocuImageImpl {
+
+  private BufferedImage img;
+
+  public ImageLoaderDocuImage() {
+  }
+
+  public ImageLoaderDocuImage(Utils u) {
+    util = u;
+  }
+
+  /**
+   *  load image file
+   */
+  public void loadImage(File f) throws FileOpException {
+    util.dprintln(10, "loadImage!");
+    System.gc();
+    try {
+      for (int i = 0; i < ImageIO.getReaderFormatNames().length; i++) {
+    System.out.println("ImageLoader reader:"+ImageIO.getReaderFormatNames()[i]);
+      }
+      for (int i = 0; i < ImageIO.getWriterFormatNames().length; i++) {
+    System.out.println("ImageLoader writer:"+ImageIO.getWriterFormatNames()[i]);
+      }
+      img = ImageIO.read(f);
+      if (img == null) {
+        util.dprintln(3, "ERROR(loadImage): unable to load file");
+        throw new FileOpException("Unable to load File!");
+      }
+    }
+    catch (IOException e) {
+      throw new FileOpException("Error reading image.");
+    }
+  }
+
+  /**
+   *  write image of type mt to Stream
+   */
+  public void writeImage(String mt, ServletResponse res)
+         throws FileOpException {
+    util.dprintln(10, "writeImage!");
+    try {
+      // setup output
+      String type = "png";
+      if (mt == "image/jpeg") {
+        type = "jpeg";
+      } else if (mt == "image/png") {
+        type = "png";
+      } else {
+        // unknown mime type
+        util.dprintln(2, "ERROR(writeImage): Unknown mime type "+mt);
+        throw new FileOpException("Unknown mime type: "+mt);
+      }
+      res.setContentType(mt);
+      // render output
+      if (ImageIO.write(img, type, res.getOutputStream())) {
+        // writing was OK
+        return;
+      } else {
+        throw new FileOpException("Error writing image: Unknown image format!");
+      }
+    } catch (IOException e) {
+      // e.printStackTrace();
+      throw new FileOpException("Error writing image.");
+    }
+  }
+
+  public int getWidth() {
+    if (img != null) {
+      return img.getWidth();
+    }
+    return 0;
+  }
+
+  public int getHeight() {
+    if (img != null) {
+      return img.getHeight();
+    }
+    return 0;
+  }
+
+  /**
+   *  crop and scale image
+   *    take rectangle width,height at position x_off,y_off
+   *    and scale by scale
+   */
+   public void cropAndScale(int x_off, int y_off, int width, int height,
+         float scale, int qual) throws ImageOpException {
+    util.dprintln(10, "cropAndScale!");
+
+    int scaleInt = 0;
+    // setup interpolation quality
+    if (qual > 0) {
+      util.dprintln(4, "quality q1");
+      scaleInt = AffineTransformOp.TYPE_BILINEAR;
+    } else {
+      util.dprintln(4, "quality q0");
+      scaleInt = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
+    }
+
+    // setup Crop
+    BufferedImage croppedImg = img.getSubimage(x_off, y_off, width, height);
+
+    img = null; // free img
+    util.dprintln(3, "CROP:"+croppedImg.getWidth()+"x"+croppedImg.getHeight()); //DEBUG
+//    util.dprintln(2, "  time "+(System.currentTimeMillis()-startTime)+"ms");
+
+    if (croppedImg == null) {
+      util.dprintln(2, "ERROR(cropAndScale): error in crop");
+      throw new ImageOpException("Unable to crop");
+    }
+
+    // setup scale
+    AffineTransformOp scaleOp = new AffineTransformOp(
+                      AffineTransform.getScaleInstance(scale, scale),
+                      scaleInt);
+    BufferedImage scaledImg = scaleOp.filter(croppedImg, null);
+    croppedImg = null; // free opCrop
+
+    if (scaledImg == null) {
+      util.dprintln(2, "ERROR(cropAndScale): error in scale");
+      throw new ImageOpException("Unable to scale");
+    }
+    img = scaledImg;
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/image/ImageOpException.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,31 @@
+/* ImageOpException -- Exception class for image operations
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.image;
+
+
+public class ImageOpException extends Exception {
+
+  public ImageOpException() {
+  }
+  public ImageOpException(String s) {
+    super(s);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/image/JAIDocuImage.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,168 @@
+/* JAIDocuImage -- Image class implementation using JAI (Java Advanced Imaging)
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.image;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+import java.awt.*;
+import java.awt.image.*;
+import java.awt.image.renderable.*;
+import javax.media.jai.*;
+
+import digilib.*;
+import digilib.io.*;
+
+
+public class JAIDocuImage extends DocuImageImpl {
+
+  private RenderedImage img;
+
+  public JAIDocuImage() {
+  }
+
+  public JAIDocuImage(Utils u) {
+    util = u;
+  }
+
+  /**
+   *  load image file
+   */
+  public void loadImage(File f) throws FileOpException {
+    System.gc();
+    img = JAI.create("fileload", f.getAbsolutePath());
+    if (img == null) {
+      util.dprintln(3, "ERROR(loadImage): unable to load file");
+      throw new FileOpException("Unable to load File!");
+    }
+  }
+
+  /**
+   *  write image of type mt to Stream
+   */
+  public void writeImage(String mt, ServletResponse res)
+         throws FileOpException {
+    try {
+    // setup output
+    ParameterBlock pb3 = new ParameterBlock();
+    pb3.addSource(img);
+    pb3.add(res.getOutputStream());
+    if (mt == "image/jpeg") {
+      pb3.add("JPEG");
+    } else if (mt == "image/png") {
+      pb3.add("PNG");
+    } else {
+      // unknown mime type
+      util.dprintln(2, "ERROR(writeImage): Unknown mime type "+mt);
+      throw new FileOpException("Unknown mime type: "+mt);
+    }
+    res.setContentType(mt);
+    // render output
+    JAI.create("encode", pb3);
+
+    } catch (IOException e) {
+      throw new FileOpException("Error writing image.");
+    }
+  }
+
+  public int getWidth() {
+    if (img != null) {
+      return img.getWidth();
+    }
+    return 0;
+  }
+
+  public int getHeight() {
+    if (img != null) {
+      return img.getHeight();
+    }
+    return 0;
+  }
+
+
+  /**
+   *  crop and scale image
+   *    take rectangle width,height at position x_off,y_off
+   *    and scale by scale
+   */
+   public void cropAndScale(int x_off, int y_off, int width, int height,
+         float scale, int qual) throws ImageOpException {
+
+    Interpolation scaleInt = null;
+    // setup interpolation quality
+    if (qual > 1) {
+      util.dprintln(4, "quality q2");
+      scaleInt = Interpolation.getInstance(Interpolation.INTERP_BICUBIC);
+    } else if (qual == 1) {
+      util.dprintln(4, "quality q1");
+      scaleInt = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
+    } else {
+      util.dprintln(4, "quality q0");
+      scaleInt = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
+    }
+
+    // setup Crop
+    ParameterBlock pb1 = new ParameterBlock();
+    pb1.addSource(img);
+    pb1.add((float)x_off);
+    pb1.add((float)y_off);
+    pb1.add((float)width);
+    pb1.add((float)height);
+    RenderedImage croppedImg = JAI.create("crop", pb1);
+    img = null; // free img
+
+    util.dprintln(3, "CROP:"+croppedImg.getWidth()+"x"+croppedImg.getHeight()); //DEBUG
+
+    if (croppedImg == null) {
+      util.dprintln(2, "ERROR(cropAndScale): error in crop");
+      throw new ImageOpException("Unable to crop");
+    }
+
+    // setup scale
+    ParameterBlock pb2 = new ParameterBlock();
+    pb2.addSource(croppedImg);
+    pb2.add(scale);
+    pb2.add(scale);
+    pb2.add(0f);
+    pb2.add(0f);
+    pb2.add(scaleInt);
+    // the following is nice but way too slow...
+    //if (opCrop.getColorModel().getPixelSize() < 8) {
+    // change color model if necessary
+    //  util.dprintln("converting color model...");
+    //  BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY);
+    //  ImageLayout lay = new ImageLayout(bi);
+    //  rh = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, lay);
+    //}
+    RenderedImage scaledImg = JAI.create("scale", pb2);
+    croppedImg = null; // free opCrop
+
+    if (scaledImg == null) {
+      util.dprintln(2, "ERROR(cropAndScale): error in scale");
+      throw new ImageOpException("Unable to scale");
+    }
+
+    img = scaledImg;
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/image/JIMIDocuImage.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,143 @@
+/* JAIDocuImage -- Image class implementation using JIMI toolkit
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.image;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+import com.sun.jimi.core.*;
+import com.sun.jimi.core.raster.*;
+import com.sun.jimi.core.filters.*;
+
+import java.awt.*;
+import java.awt.image.*;
+
+import digilib.*;
+import digilib.io.*;
+
+
+public class JIMIDocuImage extends DocuImageImpl {
+
+  private JimiRasterImage img;
+  private ImageProducer imgp;
+
+  public JIMIDocuImage() {
+  }
+
+  public JIMIDocuImage(Utils u) {
+    util = u;
+  }
+
+  /**
+   *  load image file
+   */
+  public void loadImage(File f) throws FileOpException {
+    System.gc();
+    try {
+    img = Jimi.getRasterImage(f.toURL());
+    } catch (java.net.MalformedURLException e) {
+      util.dprintln(3, "ERROR(loadImage): MalformedURLException");
+    } catch (JimiException e) {
+      util.dprintln(3, "ERROR(loadImage): JIMIException");
+      throw new FileOpException("Unable to load File!"+e);
+    }
+    if (img == null) {
+      util.dprintln(3, "ERROR(loadImage): unable to load file");
+      throw new FileOpException("Unable to load File!");
+    }
+  }
+
+  /**
+   *  write image of type mt to Stream
+   */
+  public void writeImage(String mt, ServletResponse res)
+         throws FileOpException {
+    try {
+    // setup output
+    res.setContentType(mt);
+    // render output
+    Jimi.putImage(mt, imgp, res.getOutputStream());
+
+    } catch (JimiException e) {
+      throw new FileOpException("Error writing image!"+e);
+    } catch (IOException e) {
+      throw new FileOpException("Error writing image."+e);
+    }
+  }
+
+  public int getWidth() {
+    if (img != null) {
+      return img.getWidth();
+    }
+    return 0;
+  }
+
+  public int getHeight() {
+    if (img != null) {
+      return img.getHeight();
+    }
+    return 0;
+  }
+
+
+  /**
+   *  crop and scale image
+   *    take rectangle width,height at position x_off,y_off
+   *    and scale by scale
+   */
+   public void cropAndScale(int x_off, int y_off, int width, int height,
+         float scale, int qual) throws ImageOpException {
+
+    ImageFilter scaleFilter;
+    int destWidth = (int)(scale * (float)width);
+    int destHeight = (int)(scale * (float)height);
+
+    // setup Crop
+    ImageProducer croppedImg = img.getCroppedImageProducer(x_off, y_off, width, height);
+    //util.dprintln(3, "CROP:"+croppedImg.getWidth()+"x"+croppedImg.getHeight()); //DEBUG
+
+    if (croppedImg == null) {
+      util.dprintln(2, "ERROR(cropAndScale): error in crop");
+      throw new ImageOpException("Unable to crop");
+    }
+
+    // setup scale and interpolation quality
+    if (qual > 0) {
+      util.dprintln(4, "quality q1");
+      scaleFilter = new AreaAverageScaleFilter(destWidth, destHeight);
+    } else {
+      util.dprintln(4, "quality q0");
+      scaleFilter = new ReplicatingScaleFilter(destWidth, destHeight);
+    }
+
+    ImageProducer scaledImg = new FilteredImageSource(croppedImg, scaleFilter);
+
+    if (scaledImg == null) {
+      util.dprintln(2, "ERROR(cropAndScale): error in scale");
+      throw new ImageOpException("Unable to scale");
+    }
+
+    imgp = scaledImg;
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/io/FileOpException.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,33 @@
+/*  FileOpException -- Exception class for file operations
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.io;
+
+import java.io.IOException;
+
+
+public class FileOpException extends IOException {
+
+  public FileOpException() {
+  }
+  public FileOpException(String s) {
+    super(s);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/io/FileOps.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,188 @@
+/*  FileOps -- Utility class for file operations
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.io;
+
+import java.io.*;
+import java.util.*;
+
+import digilib.*;
+
+
+public class FileOps {
+
+  private Utils util = null;
+  public static String[] fileTypes = {
+            "jpg", "image/jpeg",
+            "jpeg", "image/jpeg",
+            "png", "image/png",
+            "gif", "image/gif",
+            "tif", "image/tiff",
+            "tiff", "image/tiff"};
+
+  public FileOps() {
+    util = new Utils();
+  }
+
+  public FileOps(Utils u) {
+    util = u;
+  }
+
+  public void setUtils(Utils u) {
+    util = u;
+  }
+
+
+  /**
+   *  get the mime type for a file format (by extension)
+   */
+  public static String mimeForFile(File f) {
+    String fn = f.getName();
+    for (int i = 0; i < fileTypes.length; i += 2) {
+      if (fn.toLowerCase().endsWith(fileTypes[i])) {
+        return fileTypes[i+1];
+      }
+    }
+    return null;
+  }
+
+  /**
+   *  get a filehandle for a file or directory name
+   *    returns File number n if fn is directory (starts with 1)
+   */
+  public File getFile(String fn, int n) throws FileOpException {
+    util.dprintln(4, "getFile ("+fn+", "+n+")");
+
+    File f = new File(fn);
+    // if fn is a file name then return file
+    if (f.isFile()) {
+      return f;
+    }
+    // if fn is a directory name then open directory
+    if (f.isDirectory()) {
+      File[] fl = f.listFiles(new ImgFileFilter());
+      Arrays.sort(fl);
+      if ((n > 0) && (n <= fl.length)) {
+         return fl[n - 1];
+      }
+    }
+    throw new FileOpException("Unable to find file: "+fn);
+  }
+
+  /**
+   *  get the number of files in a directory
+   *    (almost the same as getFile)
+   *  returns 0 in case of problems
+   */
+  public int getNumFiles(String fn) throws FileOpException {
+    util.dprintln(4, "getNumFiles ("+fn+")");
+
+    File f = new File(fn);
+    // if fn is a file name then return 1
+    if (f.isFile()) {
+      return 1;
+    }
+    // if fn is a directory name then return the number of files
+    if (f.isDirectory()) {
+      return f.listFiles(new ImgFileFilter()).length;
+    }
+    // then fn must be something strange...
+    return 0;
+  }
+
+
+  /**
+   *  get a filehandle for a file or directory name out of a list
+   *    dirs is a list of base directories, fn is the appended file/dirname
+   *    searches dirs until fn exists (backwards if fwd is false)
+   *    returns File number n if fn is directory (starts with 1)
+   */
+  public File getFileVariant(String[] dirs, String fn, int n, boolean fwd) throws FileOpException {
+    util.dprintln(4, "getVariantFile ("+dirs+", "+fn+", "+n+")");
+
+    File f = null;
+    int start = 0;
+    int inc = 1;
+    int end = dirs.length;
+    if (fwd == false) {
+      start = dirs.length - 1;
+      inc = -1;
+      end = 0;
+    }
+
+    for (int i = start; i != end; i += inc) {
+      try {
+        f = getFile(dirs[i]+fn, n);
+      } catch (FileOpException e) {
+        f = null;
+      }
+      if (f != null) {
+        return f;
+      }
+    }
+    throw new FileOpException("Unable to find file: "+fn);
+  }
+
+  /**
+   *  get the number of files in a directory
+   *    (almost the same as getFileVariant)
+   *  returns 0 in case of problems
+   */
+  public int getNumFilesVariant(String[] dirs, String fn, boolean fwd) throws FileOpException {
+    util.dprintln(4, "getNumFilesVariant ("+dirs+", "+fn+")");
+
+    int nf = 0;
+    int start = 0;
+    int inc = 1;
+    int end = dirs.length;
+    if (fwd == false) {
+      start = dirs.length - 1;
+      inc = -1;
+      end = 0;
+    }
+
+    for (int i = start; i != end; i += inc) {
+      try {
+        nf = getNumFiles(dirs[i]+fn);
+      } catch (FileOpException e) {
+        nf = 0;
+      }
+      if (nf > 0) {
+        return nf;
+      }
+    }
+    return 0;
+  }
+
+  /**
+   *  FileFilter for image types (helper class for getFile)
+   */
+  private class ImgFileFilter implements FileFilter {
+
+    public boolean accept(File f) {
+      if (f.isFile()) {
+        return (mimeForFile(f) != null);
+      } else {
+        return false;
+      }
+    }
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/io/XMLListLoader.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,141 @@
+/* XMLListLoader -- Load an XML list into a Hashtable
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.io;
+
+// JAXP packages
+import javax.xml.parsers.*;
+import org.xml.sax.*;
+import org.xml.sax.helpers.*;
+
+import java.util.*;
+import java.io.*;
+
+public class XMLListLoader {
+
+    private String listTag = "list";
+    private String entryTag = "entry";
+    private String keyAtt = "key";
+    private String valueAtt = "value";
+
+    public XMLListLoader() {
+    }
+
+    public XMLListLoader(String list_tag, String entry_tag, String key_att, String value_att) {
+      //System.out.println("xmlListLoader("+list_tag+","+entry_tag+","+key_att+","+value_att+")");
+      listTag = list_tag;
+      entryTag = entry_tag;
+      keyAtt = key_att;
+      valueAtt = value_att;
+    }
+
+    /**
+     *  inner class XMLListParser to be called by the parser
+     */
+    private class XMLListParser extends DefaultHandler {
+
+      private Hashtable listData;
+      private Stack nameSpace;
+
+      public Hashtable getData() {
+        return listData;
+      }
+
+      // Parser calls this once at the beginning of a document
+      public void startDocument() throws SAXException {
+          listData = new Hashtable();
+          nameSpace = new Stack();
+      }
+
+      // Parser calls this for each element in a document
+      public void startElement(String namespaceURI, String localName,
+                               String qName, Attributes atts)
+  	throws SAXException
+      {
+        //System.out.println("<"+qName);
+        // open a new namespace
+        nameSpace.push(qName);
+
+        // ist it an entry tag?
+        if (qName.equals(entryTag)) {
+          // is it inside a list tag?
+          if ((listTag.length() > 0)&&(nameSpace.search(listTag) < 0)) {
+            System.out.println("BOO: Entry "+entryTag+" not inside list "+listTag);
+            throw new SAXParseException("Entry "+entryTag+" not inside list "+listTag, null);
+          }
+          // get the attributes
+          String key = atts.getValue(keyAtt);
+          String val = atts.getValue(valueAtt);
+          if ((key == null)||(val == null)) {
+            System.out.println("BOO: Entry "+entryTag+" does not have Attributes "+keyAtt+", "+valueAtt);
+            throw new SAXParseException("Entry "+entryTag+" does not have Attributes "+keyAtt+", "+valueAtt, null);
+          }
+          // add the values
+          //System.out.println("DATA: "+key+" = "+val);
+          listData.put(key, val);
+        }
+    }
+
+    public void endElement(String namespaceURI, String localName,
+                             String qName)
+	throws SAXException
+    {
+      // exit the namespace
+      nameSpace.pop();
+    }
+
+    }
+
+
+    /**
+     *  load and parse a file (as URL)
+     *    returns Hashtable with list data
+     */
+    public Hashtable loadURL(String path) throws SAXException, IOException {
+        //System.out.println("loadurl ("+path+")");
+        // Create a JAXP SAXParserFactory and configure it
+        SAXParserFactory spf = SAXParserFactory.newInstance();
+        //spf.setNamespaceAware(true);
+
+        XMLReader xmlReader = null;
+        try {
+          // Create a JAXP SAXParser
+          SAXParser saxParser = spf.newSAXParser();
+
+          // Get the encapsulated SAX XMLReader
+          xmlReader = saxParser.getXMLReader();
+        }
+        catch (ParserConfigurationException e) {
+          throw new SAXException(e);
+        }
+
+        // create a list parser (keeps the data!)
+        XMLListParser listParser = new XMLListParser();
+
+        // Set the ContentHandler of the XMLReader
+        xmlReader.setContentHandler(listParser);
+
+        // Tell the XMLReader to parse the XML document
+        xmlReader.parse(path);
+
+        return listParser.getData();
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/servlet/DocumentBean.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,198 @@
+/* DocumentBean -- Access control bean for JSP
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.servlet;
+
+
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import digilib.*;
+import digilib.io.*;
+import digilib.auth.*;
+
+public class DocumentBean implements AuthOps {
+
+  // Utils object for logging
+  private Utils util = new Utils(5);
+  // AuthOps object to check authorization
+  private AuthOps authOp;
+  // FileOps object
+  private FileOps fileOp = new FileOps(util);
+
+  // base directories in order of preference (prescaled versions first)
+  private String[] baseDirs = {"/docuserver/scaled/small", "/docuserver/images", "/docuserver/scans/quellen"};
+  // part of URL path to prepend for authenticated access
+  private String authURLpath = "authenticated/";
+
+
+  public DocumentBean() {
+  }
+
+  public void setConfig(ServletConfig conf) throws ServletException {
+    util.dprintln(10, "setConfig");
+    // servletOps takes a ServletConfig to get the config file name
+    ServletOps servletOp = new ServletOps(util, conf);
+    /**
+     *  basedir-list : List of document directories
+     */
+    String bl = servletOp.tryToGetInitParam("basedir-list", null);
+    if ((bl != null)&&(bl.length() > 0)) {
+      // split list into directories
+      StringTokenizer dirs = new StringTokenizer(bl, ":");
+      int n = dirs.countTokens();
+      if (n > 0) {
+        // add directories into array
+        baseDirs = new String[n];
+        for (int i = 0; i < n; i++) {
+          baseDirs[i] = dirs.nextToken();
+        }
+      }
+      util.dprintln(3, "basedir-list: "+bl);
+    }
+    /**
+     *  auth-url-path : part of URL to indicate authenticated access
+     */
+    String au = servletOp.tryToGetInitParam("auth-url-path", null);
+    if ((au != null)&&(au.length() > 0)) {
+      authURLpath = au;
+      util.dprintln(3, "auth-url-path: "+au);
+    }
+    /**
+     *  authentication
+     */
+    try {
+      // DB version
+      //private AuthOps authOp = new DBAuthOpsImpl(util);
+      // XML version
+      String cp = servletOp.tryToGetInitParam("auth-file", "/docuserver/www/digitallibrary/WEB-INF/digilib-auth.xml");
+      util.dprintln(3, "auth-file: "+cp);
+      authOp = new XMLAuthOps(util, cp);
+    } catch (AuthOpException e) {
+      throw new ServletException(e);
+    }
+  }
+
+  public String getDocuPath(HttpServletRequest request) {
+    util.dprintln(10, "getDocuPath");
+    // fetch query string
+    String qs = request.getQueryString();
+    String fn = "";
+    if (qs != null && qs.length() > 0) {
+       // the file name is in the request before the first "+"
+       int endfn = qs.indexOf("+");
+       if (endfn > 0) {
+         fn = qs.substring(0, endfn);
+       } else {
+	 fn = qs;
+       }
+    }
+    util.dprintln(4, "docuPath: "+fn);
+    return fn;
+  }
+
+  /**
+   *  check if the request must be authorized to access filepath
+   */
+  public boolean isAuthRequired(HttpServletRequest request) throws AuthOpException {
+    util.dprintln(10, "isAuthRequired");
+    return authOp.isAuthRequired(getDocuPath(request), request);
+  }
+
+  public boolean isAuthRequired(String filepath, HttpServletRequest request) throws AuthOpException {
+    util.dprintln(10, "isAuthRequired");
+    return authOp.isAuthRequired(filepath, request);
+  }
+
+  /**
+   *  check if the request is allowed to access filepath
+   */
+  public boolean isAuthorized(HttpServletRequest request) throws AuthOpException {
+    util.dprintln(10, "isAuthorized");
+    return authOp.isAuthorized(getDocuPath(request), request);
+  }
+
+  public boolean isAuthorized(String filepath, HttpServletRequest request) throws AuthOpException {
+    util.dprintln(10, "isAuthorized");
+    return authOp.isAuthorized(filepath, request);
+  }
+
+  /**
+   *  return a list of authorization roles needed for request
+   *  to access the specified path
+   */
+  public List rolesForPath(String filepath, HttpServletRequest request) throws AuthOpException {
+    util.dprintln(10, "rolesForPath");
+    return authOp.rolesForPath(filepath, request);
+  }
+
+  /**
+   * check request authorization against a list of roles
+   */
+  public boolean isRoleAuthorized(List roles, HttpServletRequest request) {
+    util.dprintln(10, "isRoleAuthorized");
+    return authOp.isRoleAuthorized(roles, request);
+  }
+
+  /**
+   * check for authenticated access and redirect if necessary
+   */
+  public boolean doAuthentication(HttpServletRequest request, HttpServletResponse response) throws Exception {
+    util.dprintln(10, "doAuthentication");
+    // check if we are already authenticated
+    if (request.getRemoteUser() == null) {
+      util.dprintln(3, "unauthenticated so far");
+      // if not maybe we must?
+      if (isAuthRequired(request)) {
+        util.dprintln(3, "auth required, redirect");
+	// we are not yet authenticated -> redirect
+	response.sendRedirect(authURLpath+request.getServletPath()+"?"+request.getQueryString());
+      }
+    }
+    return true;
+  }
+
+  /**
+   *  get the first page number in the directory
+   *  (not yet functional)
+   */
+  public int getFirstPage(HttpServletRequest request) {
+    return getFirstPage(getDocuPath(request), request);
+  }
+
+  public int getFirstPage(String filepath, HttpServletRequest request) {
+    util.dprintln(10, "getFirstPage");
+    return 1;
+  }
+
+  /**
+   *  get the number of pages/files in the directory
+   */
+  public int getNumPages(HttpServletRequest request) throws Exception {
+    return getNumPages(getDocuPath(request), request);
+  }
+
+  public int getNumPages(String filepath, HttpServletRequest request) throws Exception {
+    util.dprintln(10, "getNumPages");
+    return fileOp.getNumFilesVariant(baseDirs, "/"+filepath, true);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/servlet/Scaler.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,377 @@
+/* Scaler -- Scaler servlet main class
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.servlet;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+import digilib.*;
+import digilib.io.*;
+import digilib.image.*;
+import digilib.auth.*;
+
+
+//public class Scaler extends HttpServlet implements SingleThreadModel {
+public class Scaler extends HttpServlet {
+
+  // Utils instance with debuglevel
+  Utils util;
+  // ServletOpss instance
+  ServletOps servletOp;
+  // FileOps instance
+  FileOps fileOp;
+  // AuthOps instance
+  AuthOps authOp;
+  // global DocuImage instance (don't reuse inside a request!)
+  DocuImage globalImage;
+
+  // use authorization database
+  boolean useAuthentication = true;
+  // image file to send in case of error
+  File errorImgFile = new File("/docuserver/images/icons/scalerror.gif");
+  // image file to send if access is denied
+  File denyImgFile = new File("/docuserver/images/icons/denied.gif");
+  // base directories in order of preference (prescaled versions first)
+  String[] baseDirs = {"/docuserver/scaled/small", "/docuserver/images", "/docuserver/scans/quellen"};
+
+
+  /*********************************************************
+   *             Initialize global variables
+   *********************************************************/
+  public void init(ServletConfig config) throws ServletException {
+    super.init(config);
+
+    // first we need an Utils to setup ServletOps UGLY!!
+    util = new Utils(5);
+    // servletOps takes a ServletConfig to get the config file name
+    servletOp = new ServletOps(util, config);
+    // then we can start reading parameters UGLY!!
+
+    // Utils instance with debuglevel
+    int debugLevel = servletOp.tryToGetInitParam("debug-level", 10);
+    util = new Utils(debugLevel);
+    // reset Util for ServletOps instance
+    servletOp.setUtils(util);
+    // image file to send in case of error
+    String errorImgFileName = servletOp.tryToGetInitParam("error-image", "/docuserver/images/icons/scalerror.gif");
+    errorImgFile = new File(errorImgFileName);
+    // image file to send if access is denied
+    String denyImgFileName = servletOp.tryToGetInitParam("denied-image", "/docuserver/images/icons/denied.gif");
+    denyImgFile = new File(denyImgFileName);
+    // base directories in order of preference (prescaled versions first)
+    String baseDirList = servletOp.tryToGetInitParam("basedir-list", "/docuserver/scaled/small:/docuserver/images:/docuserver/scans/quellen");
+    // split list into directories
+    StringTokenizer dirs = new StringTokenizer(baseDirList, ":");
+    int n = dirs.countTokens();
+    // add directories into array
+    baseDirs = new String[n];
+    for (int i = 0; i < n; i++) {
+      baseDirs[i] = dirs.nextToken();
+    }
+    // use authentication information
+    String useAuth = servletOp.tryToGetInitParam("use-authorization", "true");
+    if ((useAuth.indexOf("false") > 0)||(useAuth.indexOf("FALSE") > 0)) {
+      useAuthentication = false;
+    } else {
+      useAuthentication = true;
+      try {
+        // DB version
+        //authOp = new DBAuthOpsImpl(util);
+        // XML version
+        String cnfPath = servletOp.tryToGetInitParam("auth-file", "/docuserver/www/digitallibrary/WEB-INF/digilib-auth.xml");
+        authOp = new XMLAuthOps(util, cnfPath);
+      } catch (AuthOpException e) {
+        throw new ServletException(e);
+      }
+    }
+    // FileOps instance
+    fileOp = new FileOps(util);
+    // global DocuImage instance (don't reuse inside a request!)
+    globalImage = new JAIDocuImage(util);
+//    globalImage = new JIMIDocuImage(util);
+    //globalImage = new ImageLoaderDocuImage(util);
+
+  }
+
+  /**Process the HTTP Get request*/
+  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+    util.dprintln(1, "The servlet has received a GET!");
+    processRequest(request, response);
+  }
+
+  /**Process the HTTP Post request*/
+  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+    util.dprintln(1, "The servlet has received a POST!");
+    processRequest(request, response);
+  }
+
+  /**Clean up resources*/
+  public void destroy() {
+  }
+
+/**********************************************************************
+ *                       main request handler
+ **********************************************************************/
+
+  void processRequest(HttpServletRequest request, HttpServletResponse response)
+    throws ServletException, IOException {
+
+    // time for benchmarking
+    long startTime = System.currentTimeMillis();
+    // output mime/type
+    String mimeType = "image/png";
+
+    /**
+     * parameters for a session
+     */
+
+    // scale the image file to fit window size
+    boolean scaleToFit = true;
+    // use heuristics (GIF?) to scale or not
+    boolean forcedScale = false;
+    // try prescaled images first
+    boolean preScaledFirst = true;
+    // interpolation to use for scaling
+    int scaleQual = 0;
+    // send html error message (or image file)
+    boolean errorMsgHtml = false;
+
+    /**
+     *  request parameter
+     */
+
+    // file/dir to load
+    String param_fn = servletOp.tryToGetParam("fn", "", request);
+    // page number
+    int param_pn = servletOp.tryToGetParam("pn", 1, request);
+    // destination image width
+    int param_dw = servletOp.tryToGetParam("dw", 300, request);
+    // destination image height
+    int param_dh = servletOp.tryToGetParam("dh", 400, request);
+    // relative area x_offset (0..1)
+    float param_wx = servletOp.tryToGetParam("wx", 0f, request);
+    // relative area y_offset
+    float param_wy = servletOp.tryToGetParam("wy", 0f, request);
+    // relative area width (0..1)
+    float param_ww = servletOp.tryToGetParam("ww", 1f, request);
+    // relative area height
+    float param_wh = servletOp.tryToGetParam("wh", 1f, request);
+    // scale factor (additional to dw/width, dh/height)
+    float param_ws = servletOp.tryToGetParam("ws", 1f, request);
+    // operation mode: flags separated by "+"
+    String param_mo = servletOp.tryToGetParam("mo", "", request);
+    // operation mode: "fit": always fit to page, "file": send as-is
+    if (param_mo.indexOf("fit") >= 0) {
+      scaleToFit = true;
+      forcedScale = true;
+    } else if (param_mo.indexOf("file") >= 0) {
+      scaleToFit = false;
+      forcedScale = true;
+    }
+    // operation mode: "errtxt": error message in html, "errimg": error image
+    if (param_mo.indexOf("errtxt") >= 0) {
+      errorMsgHtml = true;
+    } else if (param_mo.indexOf("errimg") >= 0) {
+      errorMsgHtml = false;
+    }
+    // operation mode: "q0" - "q2": interpolation quality
+    if (param_mo.indexOf("q0") >= 0) {
+      scaleQual = 0;
+    } else if (param_mo.indexOf("q1") >= 0) {
+      scaleQual = 1;
+    } else if (param_mo.indexOf("q2") >= 0) {
+      scaleQual = 2;
+    }
+    // operation mode: "lores": try to use scaled image, "hires": unscaled image
+    if (param_mo.indexOf("lores") >= 0) {
+      preScaledFirst = true;
+    } else if (param_mo.indexOf("hires") >= 0) {
+      preScaledFirst = false;
+    }
+
+    Utils.dprintln(1, "Parameter values: fn:"+param_fn+" pn:"+param_pn+" dw:"+param_dw+" dh:"+param_dh+" wx:"+param_wx+" wy:"+param_wy+" ww:"+param_ww+" wh:"+param_wh+" ws:"+param_ws+" mo:"+param_mo);
+
+    //"big" try for all file/image actions
+    try {
+
+    // DocuImage instance
+    DocuImage docuImage = new JAIDocuImage(util);
+//    DocuImage docuImage = new JIMIDocuImage(util);
+    //DocuImage docuImage = new ImageLoaderDocuImage(util);
+
+
+    /**
+     *  find the file to load/send
+     */
+
+    String loadPathName = "";
+    // if there's PathInfo, append
+    if (request.getPathInfo() != null) {
+      loadPathName += request.getPathInfo();
+    }
+    // append fn parameter
+    loadPathName += param_fn;
+    // if it's zoomed, try hires version (to be optimized...)
+    if ((param_ww < 1f) || (param_wh < 1f)) {
+      preScaledFirst = false;
+    }
+
+    if (useAuthentication) {
+      // check permissions
+      List rolesRequired = authOp.rolesForPath(loadPathName, request);
+      if (rolesRequired != null) {
+        Utils.dprintln(1, "Role required: "+rolesRequired);
+        Utils.dprintln(2, "User: "+request.getRemoteUser());
+        if (! authOp.isRoleAuthorized(rolesRequired, request)) {
+          Utils.dprintln(1, "ERROR: access denied!");
+          if (errorMsgHtml) {
+            servletOp.htmlMessage("ERROR: Unauthorized access!", response);
+          } else {
+            docuImage.sendFile(denyImgFile, response);
+          }
+          return;
+        }
+      }
+    }
+
+    // find the file
+    File fileToLoad = fileOp.getFileVariant(baseDirs, loadPathName, param_pn, preScaledFirst);
+
+    Utils.dprintln(1, "Loading: "+fileToLoad);
+
+    // get the source image type (if it's known)
+    mimeType = fileOp.mimeForFile(fileToLoad);
+
+    // if not forced and source is GIF/PNG then send-as-is if not zoomed
+    if((!forcedScale && (mimeType == "image/gif" || mimeType == "image/png")
+        && (param_ww == 1f) && (param_wh == 1f)) || (forcedScale && !scaleToFit)) {
+
+      Utils.dprintln(1, "Sending File as is.");
+
+      docuImage.sendFile(fileToLoad, response);
+
+      Utils.dprintln(1, "Done in "+(System.currentTimeMillis()-startTime)+"ms");
+      return;
+    }
+
+    // load file
+    docuImage.loadImage(fileToLoad);
+
+    /**
+     *  crop and scale the image
+     */
+
+    // get size
+    int imgWidth = docuImage.getWidth();
+    int imgHeight = docuImage.getHeight();
+
+    util.dprintln(2, "IMG: "+imgWidth+"x"+imgHeight);
+    util.dprintln(2, "time "+(System.currentTimeMillis()-startTime)+"ms");
+
+    // calculate absolute from relative coordinates
+    float areaXoff = param_wx * imgWidth;
+    float areaYoff = param_wy * imgHeight;
+    float areaWidth = param_ww * imgWidth;
+    float areaHeight = param_wh * imgHeight;
+    // calculate scaling factors
+    float scaleX = param_dw / areaWidth * param_ws;
+    float scaleY = param_dh / areaHeight * param_ws;
+    float scaleXY = (scaleX > scaleY) ? scaleY : scaleX;
+
+    util.dprintln(1, "Scale "+scaleXY+"("+scaleX+","+scaleY+") on "+areaXoff+","+areaYoff+" "+areaWidth+"x"+areaHeight);
+
+    // fit area to image
+    areaWidth = (areaXoff + areaWidth > imgWidth) ? imgWidth - areaXoff : areaWidth;
+    areaHeight = (areaYoff + areaHeight > imgHeight) ? imgHeight - areaYoff : areaHeight;
+
+    util.dprintln(2, "cropped: "+areaXoff+","+areaYoff+" "+areaWidth+"x"+areaHeight);
+
+    // check image parameters
+    if ((areaWidth < 1)||(areaHeight < 1)
+       ||(scaleXY * areaWidth < 2)||(scaleXY * areaHeight < 2)) {
+      Utils.dprintln(1, "ERROR: invalid scale parameter set!");
+      throw new ImageOpException("Invalid scale parameter set!");
+    }
+
+    // crop and scale image
+    docuImage.cropAndScale((int)areaXoff, (int)areaYoff, (int)areaWidth, (int)areaHeight,
+                            scaleXY, scaleQual);
+
+    util.dprintln(2, "time "+(System.currentTimeMillis()-startTime)+"ms");
+
+    /**
+     *  write the resulting image
+     */
+
+    // setup output -- if source is JPG then dest will be JPG else it's PNG
+    if (mimeType != "image/jpeg") {
+      mimeType="image/png";
+    }
+
+    // write the image
+    docuImage.writeImage(mimeType, response);
+
+    util.dprintln(1, "Done in "+(System.currentTimeMillis()-startTime)+"ms");
+
+    /**
+     *  error handling
+     */
+
+    }//"big" try
+    catch (FileOpException e) {
+      util.dprintln(1, "ERROR: File IO Error: "+e);
+      try {
+        if (errorMsgHtml) {
+          servletOp.htmlMessage("ERROR: File IO Error: "+e, response);
+        } else {
+          globalImage.sendFile(errorImgFile, response);
+        }
+      } catch (FileOpException ex) {} // so we don't get a loop
+      return;
+    }
+    catch (AuthOpException e) {
+      Utils.dprintln(1, "ERROR: Authorization error: "+e);
+      try {
+        if (errorMsgHtml) {
+          servletOp.htmlMessage("ERROR: Authorization error: "+e, response);
+        } else {
+          globalImage.sendFile(errorImgFile, response);
+        }
+      } catch (FileOpException ex) {} // so we don't get a loop
+      return;
+    }
+    catch (ImageOpException e) {
+      Utils.dprintln(1, "ERROR: Image Error: "+e);
+      try {
+        if (errorMsgHtml) {
+          servletOp.htmlMessage("ERROR: Image Operation Error: "+e, response);
+        } else {
+          globalImage.sendFile(errorImgFile, response);
+        }
+      } catch (FileOpException ex) {} // so we don't get a loop
+      return;
+    }
+
+  }
+
+}//Scaler class
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servlet/src/digilib/servlet/ServletOps.java	Thu Jan 17 15:25:46 2002 +0100
@@ -0,0 +1,156 @@
+/* ServletOps -- Servlet utility class
+
+  Digital Image Library servlet components
+
+  Copyright (C) 2001, 2002 Robert Casties (robcast@mail.berlios.de)
+
+  This program is free software; you can redistribute  it and/or modify it
+  under  the terms of  the GNU General  Public License as published by the
+  Free Software Foundation;  either version 2 of the  License, or (at your
+  option) any later version.
+   
+  Please read license.txt for the full details. A copy of the GPL
+  may be found at http://www.gnu.org/copyleft/lgpl.html
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+package digilib.servlet;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+import digilib.*;
+import digilib.io.*;
+
+
+public class ServletOps {
+
+  private Utils util = null;
+  private Hashtable confTable = null;
+
+  public ServletOps() {
+    util = new Utils();
+  }
+
+  public ServletOps(Utils u) {
+    util = u;
+  }
+
+  public ServletOps(Utils u, ServletConfig sc) throws ServletException {
+    util = u;
+    setConfig(sc);
+  }
+
+  public void setUtils(Utils u) {
+    util = u;
+  }
+
+  /**
+   * read parameter list from the XML file in init parameter "config-file"
+   */
+  public void setConfig(ServletConfig c) throws ServletException {
+    // reset parameter table
+    confTable = null;
+    if (c == null) {
+      return;
+    }
+    // get config file name
+    String fn = c.getInitParameter("config-file");
+    if (fn == null) {
+      util.dprintln(4, "setConfig: no param config-file");
+      return;
+    }
+    File f = new File(fn);
+    // setup config file list reader
+    XMLListLoader lilo = new XMLListLoader("digilib-config", "parameter", "name", "value");
+    try {
+      confTable = lilo.loadURL(f.toURL().toString());
+    } catch (Exception e) {
+      util.dprintln(4, "setConfig: unable to read file "+fn);
+      throw new ServletException(e);
+    }
+  }
+
+  /**
+   *  print a servlet response and exit
+   */
+  public static void htmlMessage(String s, HttpServletResponse response) throws IOException {
+    response.setContentType("text/html; charset=iso-8859-1");
+    PrintWriter out = response.getWriter();
+    out.println("<html>");
+    out.println("<head><title>Scaler</title></head>");
+    out.println("<body>");
+    out.println("<p>"+s+"</p>");
+    out.println("</body></html>");
+  }
+
+  /**
+   *  get a parameter from request and return it if set, otherwise return default
+   */
+  public int tryToGetParam(String s, int i, HttpServletRequest r) {
+    try {
+      i = Integer.parseInt(r.getParameter(s));
+    } catch(Exception e) {
+      util.dprintln(4, "trytoGetParam(int) failed on param "+s);
+      //e.printStackTrace();
+    }
+    return i;
+  }
+  public float tryToGetParam(String s, float f, HttpServletRequest r) {
+    try {
+      f = Float.parseFloat(r.getParameter(s));
+    } catch(Exception e) {
+      util.dprintln(4, "trytoGetParam(float) failed on param "+s);
+      //e.printStackTrace();
+    }
+    return f;
+  }
+  public String tryToGetParam(String s, String x, HttpServletRequest r) {
+    if (r.getParameter(s) != null) {
+      x = r.getParameter(s);
+    } else {
+      util.dprintln(4, "trytoGetParam(string) failed on param "+s);
+    }
+    return x;
+  }
+
+
+  /**
+   *  get an init parameter from config and return it if set, otherwise return default
+   */
+  public int tryToGetInitParam(String s, int i) {
+    //System.out.println("trytogetInitParam("+s+", "+i+")");
+    try {
+      //System.out.println("trytogetInitParam: "+(String)confTable.get(s));
+      i = Integer.parseInt((String)confTable.get(s));
+    } catch(Exception e) {
+      util.dprintln(4, "trytogetInitParam(int) failed on param "+s);
+      //e.printStackTrace();
+    }
+    return i;
+  }
+  public float tryToGetInitParam(String s, float f) {
+    try {
+      f = Float.parseFloat((String)confTable.get(s));
+    } catch(Exception e) {
+      util.dprintln(4, "trytoGetInitParam(float) failed on param "+s);
+      //e.printStackTrace();
+    }
+    return f;
+  }
+  public String tryToGetInitParam(String s, String x) {
+    if ((confTable != null)&&((String)confTable.get(s) != null)) {
+      x = (String)confTable.get(s);
+    } else {
+      util.dprintln(4, "trytoGetInitParam(string) failed on param "+s);
+    }
+    return x;
+  }
+
+}