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