View Javadoc

1   /*
2    * Copyright 2007-2012 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springbyexample.web.servlet.image;
18  
19  import java.io.File;
20  import java.util.ArrayList;
21  import java.util.List;
22  
23  import javax.servlet.http.HttpServletRequest;
24  import javax.servlet.http.HttpServletResponse;
25  
26  import org.slf4j.Logger;
27  import org.slf4j.LoggerFactory;
28  import org.springbyexample.util.image.ImageProcessor;
29  import org.springframework.util.StringUtils;
30  import org.springframework.web.servlet.ModelAndView;
31  import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
32  
33  /**
34   * Intercepts a request and if the path to the view matches 
35   * a directory in the image directory, a list of images will be 
36   * created and thumbnails can optionally be generated.
37   * 
38   * @author David Winterfeldt
39   */
40  public class ImageInterceptor extends HandlerInterceptorAdapter {
41  
42  	final Logger logger = LoggerFactory.getLogger(ImageInterceptor.class);
43  	
44  	protected ImageProcessor imageProcessor = null;
45  	protected String rootImagePath = null;
46  	protected String imagesPath = "/images";
47  	protected String thumbnailSuffix = "-thumbnail";
48  	protected String fileSuffix = ".jpg";
49  	protected String imageViewName = null;	
50  	protected int rowWidth = 5;
51  	
52  	/**
53       * Sets image processor.
54       */
55      public void setImageProcessor(ImageProcessor imageProcessor) {
56          this.imageProcessor = imageProcessor;
57      }
58  
59  	/**
60  	 * Sets root image path.
61  	 */
62  	public void setRootImagePath(String rootImagePath) {
63  		this.rootImagePath = rootImagePath;
64  	}
65  
66  	/**
67  	 * Sets relative image path under root.
68  	 */
69  	public void setImagesPath(String imagesPath) {
70  		this.imagesPath = imagesPath;
71  	}
72  
73  	/**
74  	 * Sets thumbnail suffix.
75  	 */
76  	public void setThumbnailSuffix(String thumbnailSuffix) {
77  		this.thumbnailSuffix = thumbnailSuffix;
78  	}
79  
80  	/**
81  	 * A default image display view to have the interceptor 
82  	 * redirect to if an images directory is found 
83  	 * that matches the request.
84  	 */
85      public void setImageViewName(String imageViewName) {
86          this.imageViewName = imageViewName;
87      }
88  
89  	/**
90  	 * Sets file suffice.
91  	 */
92  	public void setFileSuffix(String fileSuffix) {
93  		this.fileSuffix = fileSuffix;
94  	}
95  
96  	/**
97  	 * Row width to expose to view for displaying image list.
98  	 */
99  	public void setRowWidth(int rowWidth) {
100         this.rowWidth = rowWidth;
101     }
102 
103 	/**
104 	 * Intercepts before request.
105 	 */
106 	@Override
107 	public void postHandle(HttpServletRequest request, HttpServletResponse response, 
108 						   Object handler, ModelAndView modelAndView)
109 			throws Exception {
110 		List<ThumbnailBean> lResults = new ArrayList<ThumbnailBean>();
111 
112 		if (!StringUtils.hasText(rootImagePath)) {
113 			rootImagePath = request.getSession().getServletContext().getRealPath("/");
114 		}
115     	
116     	String path = request.getServletPath();
117     	path = StringUtils.stripFilenameExtension(path);
118 		
119     	String imagePath = imagesPath + path;
120     	String absoluteImagePath = StringUtils.cleanPath(rootImagePath + "/" + imagePath);
121     	
122     	//logger.debug("imagePath={}", absoluteImagePath);
123     	
124     	File dir = new File(absoluteImagePath);
125     	
126 		if (dir.isDirectory()) {
127 			File fileList[] = dir.listFiles();
128 			
129 			for (int i = 0; i < fileList.length; i++) {
130 				File file = fileList[i];
131 				
132 				if (file.exists() && !file.isDirectory() && 
133 			        !file.getName().endsWith(thumbnailSuffix + fileSuffix)) {
134 					String name = StringUtils.stripFilenameExtension(file.getName());
135 					
136 					String thumbnailName = name + thumbnailSuffix + fileSuffix;
137 					
138 					String mainImagePath = imagePath + "/" + name + fileSuffix;
139 					String thumbnailPath = imagePath + "/" + thumbnailName;
140 					
141 					File newFile = new File(dir, thumbnailName);
142 					
143 					// if thumbnail file doesn't exist, create
144 					if  (!newFile.exists()) {
145 						imageProcessor.scaleImage(file, newFile);
146 					}
147 					
148 					lResults.add(new ThumbnailBean(mainImagePath, thumbnailPath));
149 				}
150 			}
151 
152 			modelAndView.setViewName(imageViewName);
153 		}
154 		
155 		modelAndView.addObject("rowWidth", rowWidth);
156     	modelAndView.addObject("imageList", lResults);
157     }
158     	   
159 }