@@ -0,0 +1,2621 @@
+// Copyright 2019 Google LLC%0A//%0A// Licensed under the Apache License, Version 2.0 (the %22License%22);%0A// you may not use this file except in compliance with the License.%0A// You may obtain a copy of the License at%0A//%0A//     https://www.apache.org/licenses/LICENSE-2.0%0A//%0A// Unless required by applicable law or agreed to in writing, software%0A// distributed under the License is distributed on an %22AS IS%22 BASIS,%0A// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A// See the License for the specific language governing permissions and%0A// limitations under the License.%0A%0Apackage com.google.sps.servlets;%0A%0Aimport com.google.appengine.api.datastore.DatastoreService;%0Aimport com.google.appengine.api.datastore.DatastoreServiceFactory;%0Aimport com.google.appengine.api.datastore.Entity;%0Aimport com.google.appengine.api.datastore.FetchOptions;%0Aimport com.google.appengine.api.datastore.Query;%0Aimport com.google.common.collect.ImmutableSet;%0Aimport com.google.gson.Gson;%0Aimport com.google.sps.data.SpendingAnalytics;%0Aimport java.io.IOException;%0Aimport java.util.HashMap;%0Aimport java.util.stream.Stream;%0Aimport javax.servlet.annotation.WebServlet;%0Aimport javax.servlet.http.HttpServlet;%0Aimport javax.servlet.http.HttpServletRequest;%0Aimport javax.servlet.http.HttpServletResponse;%0A%0A/** Servlet that computes user spending analytics from datastore data. */%0A@WebServlet(%22/compute-analytics%22)%0Apublic class SpendingAnalyticsServlet extends HttpServlet %7B%0A  private final DatastoreService datastore;%0A%0A  public SpendingAnalyticsServlet() %7B%0A    datastore = DatastoreServiceFactory.getDatastoreService();%0A  %7D%0A%0A  public SpendingAnalyticsServlet(DatastoreService datastore) %7B%0A    this.datastore = datastore;%0A  %7D%0A%0A  @Override%0A  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException %7B%0A    HashMap%3CString, Double%3E storeAnalytics = getStoreAnalytics();%0A%0A    Gson gson = new Gson();%0A    response.setContentType(%22application/json;%22);%0A    response.getWriter().println(gson.toJson(storeAnalytics));%0A  %7D%0A%0A  /** Returns analytics HashMap mapping a store to the total amount spent there. */%0A  private HashMap%3CString, Double%3E getStoreAnalytics() %7B%0A    Query query = new Query(%22Receipt%22);%0A    ImmutableSet%3CEntity%3E allReceipts = datastore.prepare(query)%0A                                           .asList(FetchOptions.Builder.withDefaults())%0A                                           .stream()%0A                                           .collect(ImmutableSet.toImmutableSet());%0A%0A    SpendingAnalytics analytics = new SpendingAnalytics(allReceipts);%0A    return analytics.getStoreAnalytics();%0A  %7D%0A%7D

Create spending analytics servlet