2 * Sone - GetLikesAjaxPage.java - Copyright © 2010 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.web.ajax;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.List;
25 import net.pterodactylus.sone.data.Post;
26 import net.pterodactylus.sone.data.Reply;
27 import net.pterodactylus.sone.data.Sone;
28 import net.pterodactylus.sone.template.SoneAccessor;
29 import net.pterodactylus.sone.web.WebInterface;
30 import net.pterodactylus.util.json.JsonArray;
31 import net.pterodactylus.util.json.JsonObject;
34 * AJAX page that retrieves the number of “likes” a {@link Post} has.
36 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
38 public class GetLikesAjaxPage extends JsonPage {
41 * Creates a new “get post likes” AJAX page.
44 * The Sone web interface
46 public GetLikesAjaxPage(WebInterface webInterface) {
47 super("getLikes.ajax", webInterface);
58 protected JsonObject createJsonObject(Request request) {
59 String type = request.getHttpRequest().getParam("type", null);
60 String id = request.getHttpRequest().getParam(type, null);
61 if ((id == null) || (id.length() == 0)) {
62 return createErrorJsonObject("invalid-" + type + "-id");
64 if ("post".equals(type)) {
65 Post post = webInterface.getCore().getPost(id);
66 Set<Sone> sones = webInterface.getCore().getLikes(post);
67 return createSuccessJsonObject().put("likes", sones.size()).put("sones", getSones(sones));
68 } else if ("reply".equals(type)) {
69 Reply reply = webInterface.getCore().getReply(id);
70 Set<Sone> sones = webInterface.getCore().getLikes(reply);
71 return createSuccessJsonObject().put("likes", sones.size()).put("sones", getSones(sones));
73 return createErrorJsonObject("invalid-type");
80 protected boolean needsFormPassword() {
89 * Creates a JSON array (containing the IDs and the nice names) from the
90 * given Sones, after sorting them by name.
93 * The Sones to convert to an array
94 * @return The Sones, sorted by name
96 private JsonArray getSones(Set<Sone> sones) {
97 JsonArray soneArray = new JsonArray();
98 List<Sone> sortedSones = new ArrayList<Sone>(sones);
99 Collections.sort(sortedSones, Sone.NICE_NAME_COMPARATOR);
100 for (Sone sone : sortedSones) {
101 soneArray.add(new JsonObject().put("id", sone.getId()).put("name", SoneAccessor.getNiceName(sone)));