Esempio n. 1
0
 private void printObj(JSONObject jObj, PrintWriter writer) {
   try {
     // System.out.println(jObj.toString(3));
     writer.print(jObj.toString(3));
   } catch (JSONException e) {
     System.out.println("could to to string json object");
   }
 }
 private void getServices(HttpServletResponse res) {
   InputStream is = null;
   try {
     URL url = ctx.getResource(resourcesDir + XHP_CONFIG);
     // use classpath if not found locally.
     if (url == null)
       url = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + XHP_CONFIG);
     is = url.openStream();
   } catch (Exception ex) {
     try {
       getLogger().severe("XmlHttpProxyServlet error loading xhp.json : " + ex);
       PrintWriter writer = res.getWriter();
       writer.write(
           "XmlHttpProxyServlet Error: Error loading xhp.json. Make sure it is available in the /resources directory of your applicaton.");
       writer.flush();
     } catch (Exception iox) {
     }
   }
   services = xhp.loadServices(is);
 }
Esempio n. 3
0
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   response.setContentType("text/plain");
   PrintWriter writer = response.getWriter();
   String q = request.getParameter("q");
   if (q == null) {
     writer.println("ERROR: q has no value.");
     writer.close();
     return;
   }
   ResultBundle[] results = Map.getResults(q.toLowerCase());
   writer.println("STATUS: " + results.length + " results for the query " + q + "!");
   for (ResultBundle rb : results) {
     JSONObject j = new JSONObject();
     j.put("thumbnail", rb.getThumbnail());
     j.put("title", rb.getTitle());
     j.put("description", rb.getDescription());
     j.put("url", rb.getUrl());
     writer.println(j.toString());
   }
   writer.close();
 }
  public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
Esempio n. 5
0
  private void createData(int size, String outputFilename) {
    int command;
    int userId;
    int gameCount = 1;
    Random randomNum = new Random();
    File outputFile = new File(outputFilename);
    PrintWriter writer = null;
    JSONObject jObj = null;
    userIds = new boolean[max_users + 1];
    gameRecord = new Hashtable<Integer, GameInfo>();

    try {
      writer = new PrintWriter(new FileWriter(outputFile));
    } catch (IOException e) {
      System.out.println("Could not create file " + outputFilename);
    }

    writer.write("[\n");

    for (int i = 0; i < size; i++) {
      if (gameRecord.isEmpty()) {
        jObj = createNewUser(gameCount++);
      } else if (gameRecord.size() == max_users) {
        jObj = endGame(gameCount);
      } else {
        command = randomNum.nextInt(14);
        switch (command) {
          case 0:
            jObj = createNewUser(gameCount++);
            break;
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
          case 8:
            jObj = moveUser(gameCount);
            break;
          case 9:
          case 10:
          case 11:
          case 12:
            jObj = specialMove(gameCount);
            break;
          case 13:
            jObj = endGame(gameCount);
            break;
        }
      }
      printObj(jObj, writer);
      if (i != (size - 1)) {
        writer.write(",\n");
      } else {
        writer.write("\n");
      }
    }
    writer.write("]");
    writer.close();
  }
Esempio n. 6
0
  /**
   * Parses a text file of JSONs into an array of tweets
   *
   * @param textFile The textfile containing the JSONs
   */
  public parseJSON() {

    // get folder paths
    String currentDir = System.getProperty("user.dir");
    String root = currentDir;
    String textFile = root + "/tweet_input/tweets.txt";
    String outputFolderF1 = root + "/tweet_output/f1.txt";
    String outputFolderF2 = root + "/tweet_output/f2.txt";

    int numTweets = 0;
    int numGoodTweets = 0;
    hashtagEdges hashEdges = new hashtagEdges();

    // try objects
    try {
      // create a reader object for tweet's textfile and read-in first line
      BufferedReader reader = new BufferedReader(new FileReader(textFile));
      String currentJSON = reader.readLine();
      // System.out.println(textFile);

      // initate a writer object with the outputFolder name
      PrintWriter writerF1 = new PrintWriter(outputFolderF1, "UTF-8");
      PrintWriter writerF2 = new PrintWriter(outputFolderF2, "UTF-8");

      // create an array list to save parsedTweets and declare problem variables
      List<parsedTweet> tweetList = new ArrayList<parsedTweet>();
      String tweetText, tweetTime;
      JSONObject objJSON;
      String[] hashArray;
      parsedTweet tweetObj;
      float currentAverage;

      while (currentJSON != null) {
        try {
          objJSON = new JSONObject(currentJSON);
          // if the JSON has a text and time stamp, process it
          numTweets = numTweets + 1;
          if (objJSON.has("created_at") && objJSON.has("text")) {

            // get timestamp and text from JSON object
            tweetTime = objJSON.getString("created_at");
            tweetText = objJSON.getString("text");

            // create a tweet object and add it to folder
            tweetObj = new parsedTweet(tweetTime, tweetText, currentJSON);
            tweetList.add(tweetObj);

            // update hashObjet
            hashArray = tweetObj.hashtags.toArray(new String[tweetObj.hashtags.size()]);
            currentAverage = hashEdges.updateEdges(hashArray, tweetTime);

            // write correctly-formated cleen-tweet to output folder
            writerF1.println(tweetObj.formatTweet());
            numGoodTweets = numGoodTweets + 1;
            writerF2.format("%.2f%n", currentAverage);
          }

        } catch (Exception e) {
          System.out.println("Error in parseJSON - 1");
          e.printStackTrace();
        }

        // read next line (which has the next JSON object)
        currentJSON = reader.readLine();
      }
      writerF1.close();
      writerF2.close();
    } catch (Exception e) {

      System.out.println("Error in parseJSON - 2");
      e.printStackTrace();
    }
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String id = request.getParameter("hashID");
    JSONObject result = new JSONObject();

    if (id != null && id.trim().isEmpty()) {
      response.setContentType("text/plain");
      response.setStatus(400);
      out.println("Empty hash ID");
      return;
    }

    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    String password;
    try {
      // Read the SQL password from a file
      BufferedReader reader = null;
      try {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("SQLpw.txt");
        reader = new BufferedReader(new InputStreamReader(inputStream));
        password = reader.readLine();
      } catch (NullPointerException e) {
        e.getStackTrace();
        password = "";
      }

      // create a mysql database connection
      String myDriver = "com.mysql.jdbc.Driver";
      String myUrl = "jdbc:mysql://localhost/lodstories";
      Class.forName(myDriver);
      conn = DriverManager.getConnection(myUrl, "root", password);
      st = conn.createStatement();
      rs = st.executeQuery("SELECT hash,title,author FROM hash_objects where id='" + id + "'");

      if (!rs.next()) {
        response.setContentType("text/plain");
        response.setStatus(400);
        out.println("Error retrieving hash object");
        return;
      }

      result.put("hash", rs.getString("hash"));
      result.put("title", rs.getString("title"));
      result.put("author", rs.getString("author"));
      // result.put("path", rs.getString("path"));
      // result.put("rating", rs.getInt("rating"));

      // Update the lastAccessed field
      st.executeUpdate(
          "UPDATE hash_objects SET lastAccessed=CURRENT_TIMESTAMP() WHERE id='" + id + "'");

      response.setContentType("application/json");

      response.setCharacterEncoding("UTF-8");
      out.println(result);
    } catch (ClassNotFoundException e) {
      System.err.println("Could not connect to driver!");
      System.err.println(e.getMessage());

    } catch (SQLException ex) {
      System.err.println(
          "SQLException: "
              + ex.getMessage()
              + ", SQLState: "
              + ex.getSQLState()
              + "VendorError: "
              + ex.getErrorCode());
    } catch (JSONException ex) {
      ex.printStackTrace();
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
      if (st != null) {
        try {
          st.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
    }
  }