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.ContentTypeUtil;
40  import com.liferay.portal.util.PortalUtil;
41  import com.liferay.portlet.imagegallery.model.IGImage;
42  import com.liferay.portlet.imagegallery.service.IGImageLocalServiceUtil;
43  import com.liferay.util.servlet.ServletResponseUtil;
44  
45  import java.io.IOException;
46  
47  import java.util.Date;
48  
49  import javax.servlet.ServletConfig;
50  import javax.servlet.ServletException;
51  import javax.servlet.http.HttpServlet;
52  import javax.servlet.http.HttpServletRequest;
53  import javax.servlet.http.HttpServletResponse;
54  
55  /**
56   * <a href="ImageServlet.java.html"><b><i>View Source</i></b></a>
57   *
58   * @author Brian Wing Shun Chan
59   * @author Brett Randall
60   *
61   */
62  public class ImageServlet extends HttpServlet {
63  
64      public void init(ServletConfig servletConfig) throws ServletException {
65          super.init(servletConfig);
66  
67          _lastModified = GetterUtil.getBoolean(
68              servletConfig.getInitParameter("last_modified"), true);
69      }
70  
71      public void service(
72              HttpServletRequest request, HttpServletResponse response)
73          throws IOException, ServletException {
74  
75          if (_lastModified) {
76              long lastModified = getLastModified(request);
77  
78              if (lastModified > 0) {
79                  long ifModifiedSince = request.getDateHeader(
80                      HttpHeaders.IF_MODIFIED_SINCE);
81  
82                  if ((ifModifiedSince > 0) &&
83                      (ifModifiedSince == lastModified)) {
84  
85                      response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
86  
87                      return;
88                  }
89              }
90  
91              if (lastModified > 0) {
92                  response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
93              }
94          }
95  
96          try {
97              writeImage(request, response);
98          }
99          catch (Exception e) {
100             PortalUtil.sendError(
101                 HttpServletResponse.SC_NOT_FOUND, e, request, response);
102         }
103     }
104 
105     protected Image getDefaultImage(HttpServletRequest request, long imageId)
106         throws NoSuchImageException {
107 
108         String path = GetterUtil.getString(request.getPathInfo());
109 
110         if (path.startsWith("/company_logo")) {
111             return ImageLocalServiceUtil.getDefaultCompanyLogo();
112         }
113         else if (path.startsWith("/organization_logo")) {
114             return ImageLocalServiceUtil.getDefaultOrganizationLogo();
115         }
116         else if (path.startsWith("/user_female_portrait")) {
117             return ImageLocalServiceUtil.getDefaultUserFemalePortrait();
118         }
119         else if (path.startsWith("/user_male_portrait")) {
120             return ImageLocalServiceUtil.getDefaultUserMalePortrait();
121         }
122         else if (path.startsWith("/user_portrait")) {
123             return ImageLocalServiceUtil.getDefaultUserMalePortrait();
124         }
125         else {
126             throw new NoSuchImageException(
127                 "No default image exists for " + imageId);
128         }
129     }
130 
131     protected Image getImage(HttpServletRequest request, boolean getDefault)
132         throws PortalException, SystemException {
133 
134         long imageId = getImageId(request);
135 
136         Image image = null;
137 
138         if (imageId > 0) {
139             image = ImageLocalServiceUtil.getImage(imageId);
140         }
141         else {
142             String uuid = ParamUtil.getString(request, "uuid");
143             long groupId = ParamUtil.getLong(request, "groupId");
144 
145             try {
146                 if (Validator.isNotNull(uuid) && (groupId > 0)) {
147                     IGImage igImage =
148                         IGImageLocalServiceUtil.getImageByUuidAndGroupId(
149                             uuid, groupId);
150 
151                     image = ImageLocalServiceUtil.getImage(
152                         igImage.getLargeImageId());
153                 }
154             }
155             catch (Exception e) {
156             }
157         }
158 
159         if (getDefault) {
160             if (image == null) {
161                 if (_log.isWarnEnabled()) {
162                     _log.warn("Get a default image for " + imageId);
163                 }
164 
165                 image = getDefaultImage(request, imageId);
166             }
167         }
168 
169         return image;
170     }
171 
172     protected long getImageId(HttpServletRequest request) {
173 
174         // The image id may be passed in as image_id, img_id, or i_id
175 
176         long imageId = ParamUtil.getLong(request, "image_id");
177 
178         if (imageId <= 0) {
179             imageId = ParamUtil.getLong(request, "img_id");
180         }
181 
182         if (imageId <= 0) {
183             imageId = ParamUtil.getLong(request, "i_id");
184         }
185 
186         if (imageId <= 0) {
187             long companyId = ParamUtil.getLong(request, "companyId");
188             String screenName = ParamUtil.getString(request, "screenName");
189 
190             try {
191                 if ((companyId > 0) && Validator.isNotNull(screenName)) {
192                     User user = UserLocalServiceUtil.getUserByScreenName(
193                         companyId, screenName);
194 
195                     imageId = user.getPortraitId();
196                 }
197             }
198             catch (Exception e) {
199             }
200         }
201 
202         return imageId;
203     }
204 
205     protected long getLastModified(HttpServletRequest request) {
206         try {
207             Image image = getImage(request, false);
208 
209             if (image == null) {
210                 return -1;
211             }
212 
213             Date modifiedDate = image.getModifiedDate();
214 
215             if (modifiedDate == null) {
216                 modifiedDate = PortalUtil.getUptime();
217             }
218 
219             // Round down and remove milliseconds
220 
221             return (modifiedDate.getTime() / 1000) * 1000;
222         }
223         catch (Exception e) {
224             _log.error(e, e);
225 
226             return -1;
227         }
228     }
229 
230     protected void writeImage(
231             HttpServletRequest request, HttpServletResponse response)
232         throws PortalException, SystemException {
233 
234         Image image = getImage(request, true);
235 
236         if (image == null) {
237             throw new NoSuchImageException("Image is null");
238         }
239         else {
240             if (!image.getType().equals(ImageImpl.TYPE_NOT_AVAILABLE)) {
241                 String contentType = ContentTypeUtil.getContentType(
242                     image.getType());
243 
244                 response.setContentType(contentType);
245             }
246 
247             try {
248                 ServletResponseUtil.write(response, image.getTextObj());
249             }
250             catch (Exception e) {
251                 if (_log.isWarnEnabled()) {
252                     _log.warn(e, e);
253                 }
254             }
255         }
256     }
257 
258     private static Log _log = LogFactoryUtil.getLog(ImageServlet.class);
259 
260     private boolean _lastModified = true;
261 
262 }