Exemplo n.º 1
0
 public String toJson(ObjectMapper mapper) {
   ObjectNode rootNode = mapper.createObjectNode();
   ArrayNode keysNode = rootNode.putArray("keys");
   for (Object key : keys) {
     keysNode.addPOJO(key);
   }
   try {
     return mapper.writeValueAsString(rootNode);
   } catch (Exception e) {
     throw Exceptions.propagate(e);
   }
 }
  @Override
  public void execute() {
    Connection dbConn = null;
    CallableStatement proc = null;
    ResultSet set = null;
    try {
      dbConn = PostgresConnection.getDataSource().getConnection();
      dbConn.setAutoCommit(false);
      proc = dbConn.prepareCall("{? = call get_user_favorites(?)}");
      proc.setPoolable(true);
      proc.registerOutParameter(1, Types.OTHER);
      proc.setInt(2, Integer.parseInt(map.get("user_id")));
      proc.execute();

      set = (ResultSet) proc.getObject(1);

      MyObjectMapper mapper = new MyObjectMapper();
      JsonNodeFactory nf = JsonNodeFactory.instance;
      ObjectNode root = nf.objectNode();
      ArrayNode tweets = nf.arrayNode();
      root.put("app", map.get("app"));
      root.put("method", map.get("method"));
      root.put("status", "ok");
      root.put("code", "200");

      while (set.next()) {
        Integer id = set.getInt(1);
        String tweet = set.getString(2);
        String image_url = set.getString(3);
        Timestamp created_at = set.getTimestamp(4);
        String creator_name = set.getString(5);
        String creator_username = set.getString(6);
        String creator_avatar = set.getString(7);

        Tweet t = new Tweet();
        t.setId(id);
        t.setTweetText(tweet);
        t.setImageUrl(image_url);
        t.setCreatedAt(created_at);
        User creator = new User();
        creator.setName(creator_name);
        creator.setAvatarUrl(creator_avatar);
        creator.setUsername(creator_username);
        t.setCreator(creator);

        tweets.addPOJO(t);
      }

      root.put("favorites", tweets);
      try {
        CommandsHelp.submit(
            map.get("app"), mapper.writeValueAsString(root), map.get("correlation_id"), LOGGER);
      } catch (JsonGenerationException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
      } catch (JsonMappingException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
      } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
      }

      dbConn.commit();
    } catch (PSQLException e) {
      CommandsHelp.handleError(
          map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"), LOGGER);
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (SQLException e) {
      CommandsHelp.handleError(
          map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"), LOGGER);
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } finally {
      PostgresConnection.disconnect(set, proc, dbConn);
    }
  }