jakarta-taglibs-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From a...@apache.org
Subject cvs commit: jakarta-taglibs-sandbox/image/src/org/apache/taglibs/image ImageServlet.java ImageTag.java
Date Thu, 10 Jun 2004 13:58:21 GMT
abey        2004/06/10 06:58:21

  Modified:    image/xml image.xml
               image/examples/conf web.xml
               image/src/org/apache/taglibs/image ImageTag.java
  Added:       image/src/org/apache/taglibs/image ImageServlet.java
  Log:
  Added support to function using the servlet context temp dir and stream the image using
a servlet - Abey
  
  Revision  Changes    Path
  1.7       +16 -10    jakarta-taglibs-sandbox/image/xml/image.xml
  
  Index: image.xml
  ===================================================================
  RCS file: /home/cvs/jakarta-taglibs-sandbox/image/xml/image.xml,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- image.xml	6 Jun 2004 03:41:48 -0000	1.6
  +++ image.xml	10 Jun 2004 13:58:21 -0000	1.7
  @@ -112,10 +112,14 @@
   		  (saving a lot of processing and memory). If the <code>refresh</code> is
set 
   		  to "<code>true</code>" the image is re-generated for each request. The
default 
   		  for the <code>refresh</code> attribute is "<code>false</code>".
The <code>dir</code> 
  -		  attribute lets you specify a directory to save the generated images. The generated

  -		  images are saved into a default "<code>gen-images</code>" directory or
the one 
  -		  specified by the <code>dir</code> attribute. The quality of the final image
can be specified
  -		  as a float (0.0 to 1.0 - default 0.6) by the <code>quality</code> attribute.</blockquote>
  +		  attribute lets you specify a directory to save the generated images within the context.
  +		  The generated images are saved into this directory and the img url is set appropriately.
  +		  If the dir attribute is not set, the images are saved to the context temp directory
and 
  +		  a servlet is used to serve them later. The servlet name/ mapping can be specified as
a 
  +		  context parameter in the web.xml (see the web.xml in the image-examples.war). The context

  +		  param to be set is "<code>ImageServletMapping</code>". The quality of the
final image can 
  +		  be specified as a float (0.0 to 1.0 - default 0.6) by the <code>quality</code>
attribute.
  +		  </blockquote>
   
   		<b>Encoding, HTML generation and access of the images</b>
   		  <blockquote>
  @@ -299,9 +303,13 @@
               <rtexprvalue>true</rtexprvalue>
               <type>String</type>
           	<description>
  -        		The output file is generated in and reloaded from this directory. 
  -        		This is expected relative to the context path. The default value 
  -        		is &quot;gen-images&quot;.
  +        		The output file is generated in and reloaded from this directory. If 
  +				specified it is expected to be relative to the context path. The generated 
  +				images are saved into this directory and the img url is set appropriately. 
  +				If the dir attribute is not set, the images are saved to the context temp 
  +				directory and a servlet is used to serve them later. The servlet name/ mapping 
  +				can be specified as a context parameter in the web.xml (see the web.xml in 
  +				the image-examples.war)
           	</description>
           	<availability>1.0</availability>            
           </attribute>
  @@ -1097,9 +1105,7 @@
       </item>    
     </section>
     <section name="Bugs Fixed">
  -    <item>
  -      ARGB images are used for PNG and GIF (a typo error fixed)
  -    </item>
  +	<item> ARGB images are used for PNG and GIF (a typo error fixed) </item>
     </section>  
     
   </revision>
  
  
  
  1.3       +15 -0     jakarta-taglibs-sandbox/image/examples/conf/web.xml
  
  Index: web.xml
  ===================================================================
  RCS file: /home/cvs/jakarta-taglibs-sandbox/image/examples/conf/web.xml,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- web.xml	3 May 2004 15:47:42 -0000	1.2
  +++ web.xml	10 Jun 2004 13:58:21 -0000	1.3
  @@ -10,6 +10,21 @@
       from the JAKARTA-TAGLIBS project.
     </description>
   
  +  <context-param>
  +    <param-name>ImageServletMapping</param-name>
  +    <param-value>/gen-image</param-value>
  +  </context-param>
  +
  +  <servlet>
  +    <servlet-name>ImageServlet</servlet-name>
  +    <servlet-class>org.apache.taglibs.image.ImageServlet</servlet-class>
  +  </servlet>
  +
  +  <servlet-mapping>
  +    <servlet-name>ImageServlet</servlet-name>
  +    <url-pattern>/gen-image/*</url-pattern>
  +  </servlet-mapping>
  +
     <mime-mapping>
       <extension>txt</extension>
       <mime-type>text/plain</mime-type>
  
  
  
  1.8       +70 -12    jakarta-taglibs-sandbox/image/src/org/apache/taglibs/image/ImageTag.java
  
  Index: ImageTag.java
  ===================================================================
  RCS file: /home/cvs/jakarta-taglibs-sandbox/image/src/org/apache/taglibs/image/ImageTag.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- ImageTag.java	6 Jun 2004 03:41:48 -0000	1.7
  +++ ImageTag.java	10 Jun 2004 13:58:21 -0000	1.8
  @@ -54,7 +54,15 @@
    */
   public class ImageTag extends BodyTagSupport implements ImageHolder {
   
  -    public static final String GEN_IMAGES_DIR = "gen-images";
  +    private static final String DEFAULT_SERVLET_MAPPING = "/servlet/org.apache.taglibs.image.ImageServlet";
  +
  +    public static final String IMAGING_TYPE = "ImageTag.imagingType";
  +
  +    private static final String AUTHORIZATION = "Authorization";
  +
  +    private static final String CONTEXT_TEMPDIR = "javax.servlet.context.tempdir";
  +
  +    public static final String IMAGE_SERVLET_MAPPING = "ImageServletMapping";
   
       protected String src;
   
  @@ -68,7 +76,7 @@
   
       protected boolean display = true;
   
  -    protected String dir = GEN_IMAGES_DIR;
  +    protected String dir;
   
       protected BufferedImage image;
   
  @@ -89,6 +97,12 @@
       protected String imagingType;
   
       protected ImageHolder par;
  +    
  +    protected boolean usingContextTempDir;
  +
  +    protected String servletMapping;
  +    
  +    protected String servletMappingContextParameter = IMAGE_SERVLET_MAPPING;
   
       public int doStartTag() throws JspException {
           initialize();
  @@ -152,6 +166,10 @@
           hreq = (HttpServletRequest) (pageContext.getRequest());
           hres = (HttpServletResponse) (pageContext.getResponse());
           String reqUrl = hreq.getRequestURL().toString();
  +        if (dir == null) {
  +            usingContextTempDir = true;
  +        }
  +        
           URL base;
           try {
               base = new URL(hreq.getScheme(), hreq.getServerName(), hreq
  @@ -188,7 +206,7 @@
           String imgFile = null;
           //if the name is not specified the src will be specified
           if (name == null) {
  -            URL url = getUrl(src);
  +            URL url = getCorrectedUrl(src);
               name = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);
               imgFile = Util.extractFileName(name);
               // The genrated file may be jpeg due to lack of GIF encoding support
  @@ -213,7 +231,14 @@
           } else {
               imgFile = Util.extractFileName(name);
           }
  -        img = new File(context.getRealPath("/") + dir, imgFile);
  +        
  +        if (usingContextTempDir) {
  +            File imageDir = (File) context
  +                    .getAttribute(CONTEXT_TEMPDIR);
  +            img = new File(imageDir, imgFile);            
  +        } else {
  +            img = new File(context.getRealPath("/") + dir, imgFile);
  +        }
       }
   
       private void fetchImage() throws JspException, IOException {
  @@ -226,11 +251,11 @@
       }
   
       protected InputStream getImageStream() throws JspException, IOException {
  -        URLConnection connection = getUrl(src).openConnection();
  +        URLConnection connection = getCorrectedUrl(src).openConnection();
           //TODO: Auth only if it is the same server
  -        String auth = hreq.getHeader("Authorization");
  +        String auth = hreq.getHeader(AUTHORIZATION);
           if (auth != null && auth.length() > 0) {
  -            connection.setRequestProperty("Authorization", auth);
  +            connection.setRequestProperty(AUTHORIZATION, auth);
           }
           return connection.getInputStream();
       }
  @@ -239,7 +264,7 @@
           //use init variables to select JAI, Java2D, SWT, etc.
           if (imagingType == null || imagingType.length() == 0) {
               imagingType = (String) pageContext
  -                    .findAttribute("ImageTag.imagingType");
  +                    .findAttribute(IMAGING_TYPE);
           }
           if (imagingType != null && imagingType.length() > 0) {
               if (imagingType.equalsIgnoreCase("JAI")) {
  @@ -269,8 +294,14 @@
           //checking if the user has already specified the attributes.
           String al = attributes.toLowerCase();
           if (al.indexOf(" src") == -1) {
  -            html.append(" src=" + '"' + getUrl('/' + dir + '/' + img.getName())
  -                    + '"');
  +            if (usingContextTempDir) {
  +                html.append(" src=" + '"' + hreq.getContextPath()
  +                        + getServletUrlString() + "?image=" + img.getName()
  +                        + '"');
  +            } else {
  +                html.append(" src=" + '"' + hreq.getContextPath() + '/' + dir
  +                        + '/' + img.getName() + '"');
  +            }
           }
           if (al.indexOf("width") == -1 && al.indexOf("height") == -1) {
               html.append(" width=\"" + image.getWidth() + "\" height=\""
  @@ -281,7 +312,7 @@
       }
   
       //TODO: Add quality setting to the save
  -    public void saveImageIfRequired() {
  +    private void saveImageIfRequired() {
           if (!refresh) return;
   
           File f = img.getParentFile();
  @@ -300,7 +331,29 @@
           }
       }
   
  -    public URL getUrl(String srcStr) throws JspException {
  +    private String getServletUrlString() {
  +        String sName = servletMapping;
  +        if (sName == null) {
  +            sName = context.getInitParameter(servletMappingContextParameter);
  +            if (sName == null) {
  +                sName = DEFAULT_SERVLET_MAPPING;
  +            }
  +        }
  +        if (!sName.startsWith("/")) {
  +            sName += '/' + sName;
  +        }
  +        if (sName.endsWith("/")) {
  +            sName = sName.substring(0, sName.length() - 1);
  +        }
  +        return sName;
  +    }
  +    
  +    private URL getCorrectedUrl(String srcStr) throws JspException {
  +        return getUrl(correctUrlString(srcStr));
  +
  +    }
  +    
  +    private String correctUrlString(String srcStr) throws JspException {
           if (srcStr.startsWith("./")) //will just act like one without it
                   srcStr = srcStr.substring(2);
           String contextUrl = baseUrl + hreq.getContextPath();
  @@ -330,6 +383,11 @@
                   srcStr = parUrl + '/' + srcStr;
               }
           }
  +        return srcStr;
  +        
  +    }
  +    
  +    private URL getUrl(String srcStr) throws JspException {        
           URL url = null;
           try {
               url = new URL(srcStr);
  
  
  
  1.1                  jakarta-taglibs-sandbox/image/src/org/apache/taglibs/image/ImageServlet.java
  
  Index: ImageServlet.java
  ===================================================================
  /*
   * Created on Jun 10, 2004
   *  
   */
  package org.apache.taglibs.image;
  
  import java.io.BufferedInputStream;
  import java.io.BufferedOutputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.IOException;
  import java.io.OutputStream;
  import java.util.zip.GZIPOutputStream;
  
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  import com.mullassery.imaging.util.Util;
  
  /**
   *  
   */
  public class ImageServlet extends HttpServlet {
  
      protected void doGet(HttpServletRequest req, HttpServletResponse res)
              throws ServletException, IOException {
          File imageDir = (File) getServletContext().getAttribute(
                  "javax.servlet.context.tempdir");
          if (imageDir == null || !imageDir.exists() || !imageDir.isDirectory()) {
                  res.sendError(HttpServletResponse.SC_NOT_FOUND,
                          "Image temp directory " + imageDir + " not found");
                  return;
          }
          
          String imageName = req.getParameter("image");
  
          File image = new File(imageDir, imageName);
          if (image == null || !image.exists() || !image.isFile()) {
                  res.sendError(HttpServletResponse.SC_NOT_FOUND, "Image "
                          + image + " not found");
                  return;
          }
  
          String type = Util.correctImageType(Util.getExtentionType(image))
                  .toLowerCase();
          if (type == null || type.length() == 0) {
              //just guessing for files without extentions
              //TODO: Scan image to find the format??
              type = "jpeg";
          }
          res.setContentType("image/" + type);
  
          
          //stream image file
          OutputStream stream = res.getOutputStream();
          //accepts compressed data?
          String encoding = req.getHeader("Accept-Encoding");
          if(encoding != null && encoding.indexOf("gzip") >= 0){
              res.setHeader("Content-Encoding", "gzip");
              stream = new GZIPOutputStream(stream);
          }
          BufferedOutputStream bout = null;
          BufferedInputStream bin = null;
          try {
              bin = new BufferedInputStream(new FileInputStream(image));          
              bout = new BufferedOutputStream(stream);
              byte[] data = new byte[1024];
              int length = 0;
              while ((length = bin.read(data)) > 0) {
                  bout.write(data, 0, length);
              }
          } catch (Exception e) {
              throw new ServletException(e);
          } finally {
              if (bin != null) {
                  try {
                      bin.close();
                  } catch (Exception e) {
                      //ignoring exceptions while closing
                  }
              }
              if (bout != null) {
                  try {
                      bout.close();
                  } catch (Exception e) {
                      //ignoring exceptions while closing
                  }
              }
          }
      }
  }
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: taglibs-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: taglibs-dev-help@jakarta.apache.org


Mime
View raw message