Package reddit.web

Source Code of reddit.web.RedditClient

package reddit.web;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import reddit.http.HttpAsynchronousRunnable;
import reddit.http.HttpSession;
import reddit.pojo.processing.RedditJSonProcessor;
import chatbot.client.Message;
import chatbot.client.MessageDispatcher;

public class RedditClient {

  private static final Logger logger = LoggerFactory.getLogger(RedditClient.class);
 
  private static final String redditUrl = "http://www.reddit.com/r/";
 
  private final MessageDispatcher dispatcher;
 
  public RedditClient(MessageDispatcher dispatcher) {
    this.dispatcher = dispatcher;
  }

  private String getSubredditName(Message message) {
    String payload = message.getPayload();
    String[] split = payload.split(" ");
    return split[1];
  }

  public void processMessage(Message message) {
    String subredditName = getSubredditName(message);
    HttpMethod httpMethod = new GetMethod(redditUrl + subredditName + ".json");
    RedditJSonProcessor responseProcessor = new RedditJSonProcessor(this.dispatcher);
    HttpSession httpSession = new HttpSession(httpMethod, responseProcessor);
   
    HttpAsynchronousRunnable runnable = new HttpAsynchronousRunnable(httpMethod, httpSession);
    ExecutorService executor = Executors.newSingleThreadExecutor();
   
    executeRunnable(executor, runnable, message);
  }
 
  private void executeRunnable(ExecutorService executor, Runnable runnable, Message message) {
    try {
      executor.execute(runnable);
    } catch (RuntimeException e) {
      dispatcher.dispatchMessage("An error occured processing input, get Cutnunt to look into it. \n Error message : " + e.getMessage());
      logger.info("An error occured processing message [{}] from user [{}]", message.getPayload(), message.getOriginatingUsername());
    }
  }
}
TOP

Related Classes of reddit.web.RedditClient

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.