1   /**
2    * Copyright (c) 2000-2010 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   *
12   *
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  }