package main; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import mining.TwitterApi; import mining.TwitterApi.Builder; import org.json.JSONException; import org.json.JSONObject; /** * Basic contained class for a Pair, because Java doesn't provide this. * * @author Maurice Laveaux */ class Parameter { public Parameter(String variable, String value) { this.variable = variable; this.value = value; } public String variable; public String value; } /** * A single request/response command that executes once. * * @author Maurice Laveaux */ public class RequestCommand implements ICommand { /** * The api to execute requests on */ private final TwitterApi m_api; private final String m_command; /** * The list of parameters that are executed */ private final ArrayList m_parameters; /** * Contruct a RequestCommand that executes the request and writes the * results into a file. * * @param api the main twitter api. * @param command the command of the twitter api f.e. users/show. * @param parameters the parameters for the executed command. */ public RequestCommand(TwitterApi api, String command, String[] parameters) { m_api = api; m_command = command; m_parameters = new ArrayList(); if (parameters.length < 1) { throw new IllegalArgumentException("Not enough parameters specified."); } for (String param : parameters) { // parse the parameter to a variable with a value. m_parameters.add(parseParam(param)); } } @Override public void execute() { try { // create the building object with the command. Builder builder = m_api.build(m_command); // add every parameter to the builder. for (Parameter param : m_parameters) { builder = builder.param(param.variable, param.value); } JSONObject result = builder.request(); // TODO: add the results to the main database. // For now write to a file File file = new File("database.txt"); FileWriter writer = new FileWriter(file, true); writer.write("\n\r" + result.toString()); writer.flush(); System.out.println(result.toString(4)); } catch (JSONException ex) { /* cannot happen */ throw new RuntimeException(ex); } catch (IOException ex) { // TODO: when ratelimit reached, add event back to queue. throw new RuntimeException(ex); } } /** * Parses the input string to a parameter. * * @param input A single line in the form variable=value. * @return A pair of strings for variable and value. */ private Parameter parseParam(final String input) { String[] seperated = input.split("="); if (seperated.length < 2) { throw new IllegalArgumentException("parameter did not contain =."); } return new Parameter(seperated[0], seperated[1]); } }