1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portlet.ratings.action;
16  
17  import com.liferay.portal.kernel.json.JSONFactoryUtil;
18  import com.liferay.portal.kernel.json.JSONObject;
19  import com.liferay.portal.kernel.util.MathUtil;
20  import com.liferay.portal.kernel.util.ParamUtil;
21  import com.liferay.portal.struts.JSONAction;
22  import com.liferay.portlet.ratings.model.RatingsStats;
23  import com.liferay.portlet.ratings.service.RatingsEntryServiceUtil;
24  import com.liferay.portlet.ratings.service.RatingsStatsLocalServiceUtil;
25  
26  import javax.servlet.http.HttpServletRequest;
27  import javax.servlet.http.HttpServletResponse;
28  
29  import org.apache.struts.action.ActionForm;
30  import org.apache.struts.action.ActionMapping;
31  
32  /**
33   * <a href="RateEntryAction.java.html"><b><i>View Source</i></b></a>
34   *
35   * @author Brian Wing Shun Chan
36   */
37  public class RateEntryAction extends JSONAction {
38  
39      public String getJSON(
40              ActionMapping mapping, ActionForm form, HttpServletRequest request,
41              HttpServletResponse response)
42          throws Exception {
43  
44          String className = getClassName(request);
45          long classPK = getClassPK(request);
46          double score = ParamUtil.getDouble(request, "score");
47  
48          if (score == 0) {
49              RatingsEntryServiceUtil.deleteEntry(className, classPK);
50          }
51          else {
52              RatingsEntryServiceUtil.updateEntry(className, classPK, score);
53          }
54  
55          RatingsStats stats = RatingsStatsLocalServiceUtil.getStats(
56              className, classPK);
57  
58          double averageScore = MathUtil.format(stats.getAverageScore(), 1, 1);
59  
60          JSONObject jsonObj = JSONFactoryUtil.createJSONObject();
61  
62          jsonObj.put("totalEntries", stats.getTotalEntries());
63          jsonObj.put("totalScore", stats.getTotalScore());
64          jsonObj.put("averageScore", averageScore);
65  
66          return jsonObj.toString();
67      }
68  
69      protected String getClassName(HttpServletRequest request) {
70          return ParamUtil.getString(request, "className");
71      }
72  
73      protected long getClassPK(HttpServletRequest request) {
74          return ParamUtil.getLong(request, "classPK");
75      }
76  
77  }