com.controller.SearchController.java Source code

Java tutorial

Introduction

Here is the source code for com.controller.SearchController.java

Source

/*
 * The MIT License
 *
 * Copyright 2015 Jian.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.controller;

import com.fms.FMSCaller;
import com.googlesearch.GoogleSearch;
import com.twitter.TwitterSearch;
import com.youtube.YouTubeAPI;
import com.youtube.YouTubeInfo;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import twitter4j.Status;

/**
 * This search controller is just to parse all the JSON files and display them
 * at the intended location.
 *
 * @author Jian
 */
public class SearchController {

    public static String displayGoogleSearch(String query) throws JSONException {
        StringBuilder sb = new StringBuilder();
        try {
            sb.append("<h3 class=\"text-center\"><i class=\"fa fa-google\">&nbsp;</i>Google Custom Search</h3>");
            JSONObject json = GoogleSearch.configure(query);
            if (json.isNull("items")) {
                sb.append("<div class=\"label label-info\">");
                sb.append("No search results found.");
                sb.append("</div>");
                return sb.toString();
            }
            JSONArray items = json.getJSONArray("items");
            JSONObject result = items.getJSONObject(0);
            JSONObject ihateJson = result.getJSONObject("pagemap");
            JSONArray movie = ihateJson.getJSONArray("movie");
            JSONObject movieResult = movie.getJSONObject(0);
            String imgUrl = "<img class=\"img-responsive center-block\" src=" + movieResult.getString("image")
                    + "><br />";
            sb.append("<div class=\"row\"><div class=\" col-md-4\">");
            sb.append(imgUrl);
            sb.append("</div><div class=\" col-md-8\">");
            sb.append(movieResult.getString("description"));
            sb.append("<br /><strong>Movie Genre: &nbsp;</strong>");
            sb.append(movieResult.getString("genre"));
            sb.append("<br /><strong>Date Published: &nbsp;</strong>");
            sb.append(movieResult.getString("datepublished"));
            sb.append("</div></div>");
        } catch (JSONException ex) {
            //Logger.getLogger(SearchController.class.getName()).log(Level.SEVERE, null, ex);
            return "No results found!";
        }
        return sb.toString();
    }

    //Get JSON from own restful service
    public static String displayYouTube(String query) {
        ArrayList<YouTubeInfo> results = YouTubeAPI.configure(query);
        String str = " <h3 class=\"text-center\"><i class=\"fa fa-youtube-square\">&nbsp;</i>Youtube Video</h3>";

        if (results.isEmpty()) {
            str += "<div class=\"label label-info\">";
            str += "No search results found.";
            str += "</div>";
            return str;
        }
        for (YouTubeInfo status : results) {
            str += "<div class=\"embed-responsive embed-responsive-16by9\">";
            str += "<iframe class=\"embed-responsive-item\" src=https://www.youtube.com/embed/" + status.getId()
                    + "></iframe>";
            str += "</div>";
            str += "<div class=\"text-center\">";
            str += "<strong>" + status.getTitle() + "&nbsp;</strong><br /><br />";
            str += "</div>";
        }
        return str;
    }

    /**
     * This function will call various API and determine the movie rating.
     *
     * @return
     */
    public static String getFilmRating() {

        return "";
    }

    /**
     * This function queries the REST service and returns the results.
     *
     * Star rating CSS/Jquery to generate stars.
     * http://stackoverflow.com/questions/1987524/turn-a-number-into-star-rating-display-using-jquery-and-css
     *
     * @param query
     * @return
     */
    public static String displayFMSInfo(String query) {
        //String str = new String();
        StringBuilder sb = new StringBuilder();
        sb.append(
                "<h3 class=\"text-center\"><i class=\"fa fa-server\"></i>&nbsp;Results from own RESTful service</h3>");
        try {
            JSONObject json = FMSCaller.summary(query);
            JSONObject movie = json.getJSONObject("movie");
            if (json.isNull("movie")) {
                sb.append("No results found!");
                return sb.toString();
            }
            JSONArray reviewArr = json.getJSONArray("reviews");
            int noOfReviews = reviewArr.length();

            sb.append("<h5>Movie information</h5>");
            sb.append("<div class=\"table-responsive\">");
            sb.append("<table class=\"table table-striped\">");
            sb.append("<tr><td>Movie Name</td><td>");
            sb.append(movie.get("moviename"));
            sb.append("</td></tr>");
            sb.append("<tr><td>Movie Year</td><td>").append(movie.get("movieyear")).append("</td></tr>");
            sb.append("<tr><td>Movie Genre</td><td>").append(movie.get("moviegenre")).append("</td></tr>");
            sb.append("<tr><td>Average Score</td><td><span class=\"stars\">");
            sb.append(movie.get("averagescore"));
            sb.append("</span>").append(movie.get("averagescore")).append("&nbsp;from&nbsp;").append(noOfReviews)
                    .append(" users.</td></tr>");
            sb.append("<tr><td>Average Score</td><td>").append(movie.get("filmrating")).append("</td></tr>");
            sb.append("</table>");
            sb.append("</div>");

            sb.append("<h5>Reviews</h5>");
            //Display only 2 reviews.
            int length = 0;
            if (reviewArr.length() > 2) {
                length = 2;
            }
            for (int i = 0; i < length; i++) {
                sb.append("<div class='thumbnail row'>");
                sb.append(reviewArr.getJSONObject(i).get("firstname"));
                sb.append(" ");
                sb.append(reviewArr.getJSONObject(i).get("lastname"));
                sb.append("<br />");
                sb.append(reviewArr.getJSONObject(i).get("date"));
                sb.append("<br />");
                sb.append(reviewArr.getJSONObject(i).get("comment"));
                sb.append("<br />");
                sb.append("</div>");
            }

            return sb.toString();
        } catch (JSONException ex) {
            //Logger.getLogger(SearchController.class.getName()).log(Level.SEVERE, null, ex);
            //return "An error has occured.";
            sb.append("No results found");
        }

        return sb.toString();
    }

    //Get JSON from youtube service.
    public static String displayTweets(String query) {
        StringBuilder sb = new StringBuilder();
        sb.append(
                " <h3 class=\"text-center\"><i class=\"fa fa-twitter-square\"></i>&nbsp;Comments from Twitter</h3>");
        List<Status> tweet = TwitterSearch.configure(query);
        if (tweet.isEmpty()) {
            return "<span class=\"label label-info\">No Tweets results found.</span>";
        }

        if (tweet.size() > 5) {
            // Display a maximum of 5 tweets.
            tweet.subList(5, tweet.size()).clear();
        }

        for (Status status : tweet) {
            sb.append("<div class='thumbnail row'>");
            sb.append("<div class=\"text-center col-xs-2\">");
            sb.append("<img class=\"img-responsive\"' src=");
            sb.append(status.getUser().getBiggerProfileImageURL());
            sb.append(">");
            sb.append("</div>");
            sb.append("<div class=\"col-xs-10\">");
            sb.append(status.getCreatedAt());
            sb.append("<br />");
            sb.append("<strong>");
            sb.append(status.getUser().getScreenName());
            sb.append("&nbsp;</strong>said<br />");
            sb.append(status.getText());
            sb.append("</div>");
            sb.append("</div>");
        }

        return sb.toString();
    }

}