1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.servlet;
24  
25  import com.liferay.portal.NoSuchImageException;
26  import com.liferay.portal.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.log.Log;
29  import com.liferay.portal.kernel.log.LogFactoryUtil;
30  import com.liferay.portal.kernel.servlet.HttpHeaders;
31  import com.liferay.portal.kernel.util.GetterUtil;
32  import com.liferay.portal.kernel.util.ParamUtil;
33  import com.liferay.portal.kernel.util.Validator;
34  import com.liferay.portal.model.Image;
35  import com.liferay.portal.model.User;
36  import com.liferay.portal.model.impl.ImageImpl;
37  import com.liferay.portal.service.ImageLocalServiceUtil;
38  import com.liferay.portal.service.UserLocalServiceUtil;
39  import com.liferay.portal.util.PortalUtil;
40  import com.liferay.portlet.imagegallery.model.IGImage;
41  import com.liferay.portlet.imagegallery.service.IGImageLocalServiceUtil;
42  import com.liferay.util.servlet.ServletResponseUtil;
43  
44  import java.io.IOException;
45  
46  import java.util.Date;
47  
48  import javax.servlet.ServletConfig;
49  import javax.servlet.ServletException;
50  import javax.servlet.http.HttpServlet;
51  import javax.servlet.http.HttpServletRequest;
52  import javax.servlet.http.HttpServletResponse;
53  
54  /**
55   * <a href="ImageServlet.java.html"><b><i>View Source</i></b></a>
56   *
57   * @author Brian Wing Shun Chan
58   * @author Brett Randall
59   *
60   */
61  public class ImageServlet extends HttpServlet {
62  
63      public void init(ServletConfig servletConfig) throws ServletException {
64          super.init(servletConfig);
65  
66          _lastModified = GetterUtil.getBoolean(
67              servletConfig.getInitParameter("last_modified"), true);
68      }
69  
70      public void service(
71              HttpServletRequest request, HttpServletResponse response)
72          throws IOException, ServletException {
73  
74          if (_lastModified) {
75              long lastModified = getLastModified(request);
76  
77              if (lastModified > 0) {
78                  long ifModifiedSince = request.getDateHeader(
79                      HttpHeaders.IF_MODIFIED_SINCE);
80  
81                  if ((ifModifiedSince > 0) &&
82                      (ifModifiedSince == lastModified)) {
83  
84                      response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
85  
86                      return;
87                  }
88              }
89  
90              if (lastModified > 0) {
91                  response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
92              }
93          }
94  
95          try {
96              writeImage(request, response);
97          }
98          catch (Exception e) {
99              PortalUtil.sendError(
100                 HttpServletResponse.SC_NOT_FOUND, e, request, response);
101         }
102     }
103 
104     protected Image getDefaultImage(HttpServletRequest request, long imageId)
105         throws NoSuchImageException {
106 
107         String path = GetterUtil.getString(request.getPathInfo());
108 
109         if (path.startsWith("/company_logo")) {
110             return ImageLocalServiceUtil.getDefaultCompanyLogo();
111         }
112         else if (path.startsWith("/user_female_portrait")) {
113             return ImageLocalServiceUtil.getDefaultUserFemalePortrait();
114         }
115         else if (path.startsWith("/user_male_portrait")) {
116             return ImageLocalServiceUtil.getDefaultUserMalePortrait();
117         }
118         else if (path.startsWith("/user_portrait")) {
119             return ImageLocalServiceUtil.getDefaultUserMalePortrait();
120         }
121         else {
122             throw new NoSuchImageException(
123                 "No default image exists for " + imageId);
124         }
125     }
126 
127     protected Image getImage(HttpServletRequest request, boolean getDefault)
128         throws PortalException, SystemException {
129 
130         long imageId = getImageId(request);
131 
132         Image image = null;
133 
134         if (imageId > 0) {
135             image = ImageLocalServiceUtil.getImage(imageId);
136         }
137         else {
138             String uuid = ParamUtil.getString(request, "uuid");
139             long groupId = ParamUtil.getLong(request, "groupId");
140 
141             try {
142                 if (Validator.isNotNull(uuid) && (groupId > 0)) {
143                     IGImage igImage =
144                         IGImageLocalServiceUtil.getImageByUuidAndGroupId(
145                             uuid, groupId);
146 
147                     image = ImageLocalServiceUtil.getImage(
148                         igImage.getLargeImageId());
149                 }
150             }
151             catch (Exception e) {
152             }
153         }
154 
155         if (getDefault) {
156             if (image == null) {
157                 if (_log.isWarnEnabled()) {
158                     _log.warn("Get a default image for " + imageId);
159                 }
160 
161                 image = getDefaultImage(request, imageId);
162             }
163         }
164 
165         return image;
166     }
167 
168     protected long getImageId(HttpServletRequest request) {
169 
170         // The image id may be passed in as image_id, img_id, or i_id
171 
172         long imageId = ParamUtil.getLong(request, "image_id");
173 
174         if (imageId <= 0) {
175             imageId = ParamUtil.getLong(request, "img_id");
176         }
177 
178         if (imageId <= 0) {
179             imageId = ParamUtil.getLong(request, "i_id");
180         }
181 
182         if (imageId <= 0) {
183             long companyId = ParamUtil.getLong(request, "companyId");
184             String screenName = ParamUtil.getString(request, "screenName");
185 
186             try {
187                 if ((companyId > 0) && Validator.isNotNull(screenName)) {
188                     User user = UserLocalServiceUtil.getUserByScreenName(
189                         companyId, screenName);
190 
191                     imageId = user.getPortraitId();
192                 }
193             }
194             catch (Exception e) {
195             }
196         }
197 
198         return imageId;
199     }
200 
201     protected long getLastModified(HttpServletRequest request) {
202         try {
203             Image image = getImage(request, false);
204 
205             if (image == null) {
206                 return -1;
207             }
208 
209             Date modifiedDate = image.getModifiedDate();
210 
211             if (modifiedDate == null) {
212                 modifiedDate = PortalUtil.getUptime();
213             }
214 
215             // Round down and remove milliseconds
216 
217             return (modifiedDate.getTime() / 1000) * 1000;
218         }
219         catch (Exception e) {
220             _log.error(e, e);
221 
222             return -1;
223         }
224     }
225 
226     protected void writeImage(
227             HttpServletRequest request, HttpServletResponse response)
228         throws PortalException, SystemException {
229 
230         Image image = getImage(request, true);
231 
232         if (image == null) {
233             throw new NoSuchImageException("Image is null");
234         }
235         else {
236             if (!image.getType().equals(ImageImpl.TYPE_NOT_AVAILABLE)) {
237                 response.setContentType("image/" + image.getType());
238             }
239 
240             try {
241                 ServletResponseUtil.write(response, image.getTextObj());
242             }
243             catch (Exception e) {
244                 if (_log.isWarnEnabled()) {
245                     _log.warn(e, e);
246                 }
247             }
248         }
249     }
250 
251     private static Log _log = LogFactoryUtil.getLog(ImageServlet.class);
252 
253     private boolean _lastModified = true;
254 
255 }