package com.google.sps.servlets;

import com.google.sps.data.VolunteeringOpportunity;
import com.google.sps.utilities.CommonUtils;
import com.google.sps.utilities.DatabaseConstants;
import com.google.sps.utilities.DatabaseWrapper;
import java.io.IOException;
import java.util.Optional;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet to get volunteering opportunity given opportunityId */
@WebServlet("/volunteering-opportunity-data")
public class VolunteeringOpportunityDataServlet extends HttpServlet {
  private static final String OPPORTUNITY_ID = "opportunity-id";
  private static final DatabaseWrapper databaseWrapper =
      new DatabaseWrapper(DatabaseConstants.INSTANCE_ID, DatabaseConstants.DATABASE_ID);

  /**
   * Queries database for opportunity with opportunity ID given in the request parameter and writes
   * opportunity to the response.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws IOException if Input/Output error occurs
   */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String opportunityId = request.getParameter(OPPORTUNITY_ID);

    Optional<VolunteeringOpportunity> opportunity =
        databaseWrapper.getVolunteeringOpportunityByOppportunityId(opportunityId);

    if (!opportunity.isPresent()) {
      response.setContentType("text/html;");
      response
          .getWriter()
          .println(
              String.format("Error: No opportunity found for opportunityId %s", opportunityId));
    } else {
      response.setContentType("application/json;");
      response.getWriter().println(CommonUtils.convertToJson(opportunity.get()));
    }
  }
}

@@ -1455,9 +1455,8 @@
 if (
-!
 oppo
@@ -1513,17 +1513,24 @@
 pe(%22
-text/html
+application/json
 ;%22);
@@ -1544,27 +1544,16 @@
 response
-%0A          
 .getWrit
@@ -1560,109 +1560,43 @@
 er()
-%0A          .println(%0A              String.format(%22Error: No opportunity found for opportunityId %25s%22, 
+.println(CommonUtils.convertToJson(
 oppo
@@ -1602,18 +1602,22 @@
 ortunity
-Id
+.get()
 ));%0A    
@@ -1656,37 +1656,34 @@
 ntType(%22
-application/json
+text/html
 ;%22);%0A
+    
       re
@@ -1692,55 +1692,144 @@
 onse
-.getWriter().println(CommonUtils.convertToJson(
+%0A              .getWriter()%0A              .println(%0A                  String.format(%22Error: No opportunity found for opportunityId %25s%22, 
 oppo
@@ -1827,38 +1827,34 @@
 %25s%22, opportunity
-.get()
+Id
 ));%0A    %7D%0A  %7D%0A%7D%0A

Switch optional present checking