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("/organization_logo")) {
113             return ImageLocalServiceUtil.getDefaultOrganizationLogo();
114         }
115         else if (path.startsWith("/user_female_portrait")) {
116             return ImageLocalServiceUtil.getDefaultUserFemalePortrait();
117         }
118         else if (path.startsWith("/user_male_portrait")) {
119             return ImageLocalServiceUtil.getDefaultUserMalePortrait();
120         }
121         else if (path.startsWith("/user_portrait")) {
122             return ImageLocalServiceUtil.getDefaultUserMalePortrait();
123         }
124         else {
125             throw new NoSuchImageException(
126                 "No default image exists for " + imageId);
127         }
128     }
129 
130     protected Image getImage(HttpServletRequest request, boolean getDefault)
131         throws PortalException, SystemException {
132 
133         long imageId = getImageId(request);
134 
135         Image image = null;
136 
137         if (imageId > 0) {
138             image = ImageLocalServiceUtil.getImage(imageId);
139         }
140         else {
141             String uuid = ParamUtil.getString(request, "uuid");
142             long groupId = ParamUtil.getLong(request, "groupId");
143 
144             try {
145                 if (Validator.isNotNull(uuid) && (groupId > 0)) {
146                     IGImage igImage =
147                         IGImageLocalServiceUtil.getImageByUuidAndGroupId(
148                             uuid, groupId);
149 
150                     image = ImageLocalServiceUtil.getImage(
151                         igImage.getLargeImageId());
152                 }
153             }
154             catch (Exception e) {
155             }
156         }
157 
158         if (getDefault) {
159             if (image == null) {
160                 if (_log.isWarnEnabled()) {
161                     _log.warn("Get a default image for " + imageId);
162                 }
163 
164                 image = getDefaultImage(request, imageId);
165             }
166         }
167 
168         return image;
169     }
170 
171     protected long getImageId(HttpServletRequest request) {
172 
173         // The image id may be passed in as image_id, img_id, or i_id
174 
175         long imageId = ParamUtil.getLong(request, "image_id");
176 
177         if (imageId <= 0) {
178             imageId = ParamUtil.getLong(request, "img_id");
179         }
180 
181         if (imageId <= 0) {
182             imageId = ParamUtil.getLong(request, "i_id");
183         }
184 
185         if (imageId <= 0) {
186             long companyId = ParamUtil.getLong(request, "companyId");
187             String screenName = ParamUtil.getString(request, "screenName");
188 
189             try {
190                 if ((companyId > 0) && Validator.isNotNull(screenName)) {
191                     User user = UserLocalServiceUtil.getUserByScreenName(
192                         companyId, screenName);
193 
194                     imageId = user.getPortraitId();
195                 }
196             }
197             catch (Exception e) {
198             }
199         }
200 
201         return imageId;
202     }
203 
204     protected long getLastModified(HttpServletRequest request) {
205         try {
206             Image image = getImage(request, false);
207 
208             if (image == null) {
209                 return -1;
210             }
211 
212             Date modifiedDate = image.getModifiedDate();
213 
214             if (modifiedDate == null) {
215                 modifiedDate = PortalUtil.getUptime();
216             }
217 
218             // Round down and remove milliseconds
219 
220             return (modifiedDate.getTime() / 1000) * 1000;
221         }
222         catch (Exception e) {
223             _log.error(e, e);
224 
225             return -1;
226         }
227     }
228 
229     protected void writeImage(
230             HttpServletRequest request, HttpServletResponse response)
231         throws PortalException, SystemException {
232 
233         Image image = getImage(request, true);
234 
235         if (image == null) {
236             throw new NoSuchImageException("Image is null");
237         }
238         else {
239             if (!image.getType().equals(ImageImpl.TYPE_NOT_AVAILABLE)) {
240                 response.setContentType("image/" + image.getType());
241             }
242 
243             try {
244                 ServletResponseUtil.write(response, image.getTextObj());
245             }
246             catch (Exception e) {
247                 if (_log.isWarnEnabled()) {
248                     _log.warn(e, e);
249                 }
250             }
251         }
252     }
253 
254     private static Log _log = LogFactoryUtil.getLog(ImageServlet.class);
255 
256     private boolean _lastModified = true;
257 
258 }