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