<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.neighborgood.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;
import com.google.neighborgood.helper.RewardingPoints;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that creates new task entity and fetch saved tasks. */
@WebServlet("/tasks")
public class TaskServlet extends HttpServlet {
  @Override
  // doGet method retrieves tasks from datastore and responds with the HTML for each task fetched
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    boolean userLoggedIn = userService.isUserLoggedIn();
    String userId = userLoggedIn ? userService.getCurrentUser().getUserId() : "null";
    String zipcode = "";
    String country = "";

    if (request.getParameterMap().containsKey("zipcode")
        && request.getParameterMap().containsKey("country")) {
      zipcode = request.getParameter("zipcode");
      country = request.getParameter("country");
    } else {
      System.err.println("Zipcode and Country details are missing");
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST, "Zipcode and Country details are missing");
    }

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    Query query = new Query("Task").addSort("timestamp", SortDirection.DESCENDING);

    // Creates list of filters
    List<Query.Filter> filters = new ArrayList<Query.Filter>();
    filters.add(new Query.FilterPredicate("zipcode", Query.FilterOperator.EQUAL, zipcode));
    filters.add(new Query.FilterPredicate("country", Query.FilterOperator.EQUAL, country));
    filters.add(new Query.FilterPredicate("status", Query.FilterOperator.EQUAL, "OPEN"));

    // Applies a category filter, if any
    if (request.getParameterMap().containsKey("category")) {
      String category = request.getParameter("category");
      filters.add(new Query.FilterPredicate("category", Query.FilterOperator.EQUAL, category));
    }

    // Applies filters to query
    query.setFilter(new Query.CompositeFilter(Query.CompositeFilterOperator.AND, filters));

    // limits results to the 20 most recent tasks
    List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(20));

    StringBuilder out = new StringBuilder();

    // Builds and stores HTML for each task
    for (Entity entity : results) {
      out.append("<div class='task' data-key='")
          .append(KeyFactory.keyToString(entity.getKey()))
          .append("'>");
      if (userLoggedIn) {
        out.append("<div class='help-overlay'>");
        out.append("<div class='exit-help'><a>&times</a></div>");
        out.append("<a class='confirm-help'>CONFIRM</a>");
        out.append("</div>");
      }
      out.append("<div class='task-container'>");
      out.append("<div class='task-header'>");

      // Retrieves task's user to get user's nickname
      String taskOwner = (String) entity.getProperty("Owner");
      Query userQuery =
          new Query("UserInfo")
              .setFilter(new FilterPredicate("userId", FilterOperator.EQUAL, taskOwner));
      PreparedQuery userResults = datastore.prepare(userQuery);
      Entity userEntity = userResults.asSingleEntity();

      if (userEntity == null) {
        System.err.println("Unable to find the user entity based on the current user id");
        response.sendError(
            HttpServletResponse.SC_NOT_FOUND, "The requested user could not be found");
        return;
      }

      out.append("<div class='user-nickname'>")
          .append((String) userEntity.getProperty("nickname"))
          .append("</div>");
      if (userLoggedIn) {
        // changes the Help Button div if the current user is the owner of the task
        if (!userId.equals((String) entity.getProperty("userId"))) {
          out.append("<div class='help-out'>HELP OUT</div>");
        } else {
          out.append(
              "<div class='help-out disable-help' title='This is your own task'>HELP OUT</div>");
        }
      }
      out.append("</div>");
      out.append("<div class='task-content'>")
          .append((String) entity.getProperty("detail"))
          .append("</div>");
      out.append("<div class='task-footer'><div class='task-category'>#")
          .append((String) entity.getProperty("category"))
          .append("</div></div>");
      out.append("</div></div>");
    }

    Gson gson = new Gson();
    String json = gson.toJson(out.toString());
    response.setContentType("application/json;");
    response.getWriter().println(json);
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // First check whether the user is logged in<commit_msg>modify doGet TaskServlet method to assign a fallback nickname if task's owner's entity cannot be retrieved<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.neighborgood.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;
import com.google.neighborgood.helper.RewardingPoints;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that creates new task entity and fetch saved tasks. */
@WebServlet("/tasks")
public class TaskServlet extends HttpServlet {
  @Override
  // doGet method retrieves tasks from datastore and responds with the HTML for each task fetched
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    boolean userLoggedIn = userService.isUserLoggedIn();
    String userId = userLoggedIn ? userService.getCurrentUser().getUserId() : "null";
    String zipcode = "";
    String country = "";

    if (request.getParameterMap().containsKey("zipcode")
        && request.getParameterMap().containsKey("country")) {
      zipcode = request.getParameter("zipcode");
      country = request.getParameter("country");
    } else {
      System.err.println("Zipcode and Country details are missing");
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST, "Zipcode and Country details are missing");
    }

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    Query query = new Query("Task").addSort("timestamp", SortDirection.DESCENDING);

    // Creates list of filters
    List<Query.Filter> filters = new ArrayList<Query.Filter>();
    filters.add(new Query.FilterPredicate("zipcode", Query.FilterOperator.EQUAL, zipcode));
    filters.add(new Query.FilterPredicate("country", Query.FilterOperator.EQUAL, country));
    filters.add(new Query.FilterPredicate("status", Query.FilterOperator.EQUAL, "OPEN"));

    // Applies a category filter, if any
    if (request.getParameterMap().containsKey("category")) {
      String category = request.getParameter("category");
      filters.add(new Query.FilterPredicate("category", Query.FilterOperator.EQUAL, category));
    }

    // Applies filters to query
    query.setFilter(new Query.CompositeFilter(Query.CompositeFilterOperator.AND, filters));

    // limits results to the 20 most recent tasks
    List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(20));

    StringBuilder out = new StringBuilder();

    // Builds and stores HTML for each task
    for (Entity entity : results) {
      out.append("<div class='task' data-key='")
          .append(KeyFactory.keyToString(entity.getKey()))
          .append("'>");
      if (userLoggedIn) {
        out.append("<div class='help-overlay'>");
        out.append("<div class='exit-help'><a>&times</a></div>");
        out.append("<a class='confirm-help'>CONFIRM</a>");
        out.append("</div>");
      }
      out.append("<div class='task-container'>");
      out.append("<div class='task-header'>");

      // Retrieves task's user to get user's nickname
      String taskOwner = (String) entity.getProperty("Owner");
      Query userQuery =
          new Query("UserInfo")
              .setFilter(new FilterPredicate("userId", FilterOperator.EQUAL, taskOwner));
      PreparedQuery userResults = datastore.prepare(userQuery);
      Entity userEntity = userResults.asSingleEntity();

      out.append("<div class='user-nickname'>");

      if (userEntity == null) {
        System.err.println(
            "Unable to find the user entity based on the current user id. Setting a default nickname.");
        out.append("Neighbor");
      } else out.append((String) userEntity.getProperty("nickname"));

      out.append("</div>");
      if (userLoggedIn) {
        // changes the Help Button div if the current user is the owner of the task
        if (!userId.equals((String) entity.getProperty("userId"))) {
          out.append("<div class='help-out'>HELP OUT</div>");
        } else {
          out.append(
              "<div class='help-out disable-help' title='This is your own task'>HELP OUT</div>");
        }
      }
      out.append("</div>");
      out.append("<div class='task-content'>")
          .append((String) entity.getProperty("detail"))
          .append("</div>");
      out.append("<div class='task-footer'><div class='task-category'>#")
          .append((String) entity.getProperty("category"))
          .append("</div></div>");
      out.append("</div></div>");
    }

    Gson gson = new Gson();
    String json = gson.toJson(out.toString());
    response.setContentType("application/json;");
    response.getWriter().println(json);
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // First check whether the user is logged in
{'fraction_non_alphanumeric': 0.12773175542406312, 'fraction_numerical': 0.001893491124260355, 'mean_word_length': 3.76720571643475, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 61, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2652347', 'n_tokens_mistral': 3497, 'n_tokens_neox': 3470, 'n_words': 868}