// inform researchers that have logged an interest with the encounter or marked individual
  public static void informInterestedIndividualParties(
      HttpServletRequest request, String shark, String message, String context) {
    Shepherd myShepherd = new Shepherd(context);
    myShepherd.beginDBTransaction();

    if (myShepherd.isMarkedIndividual(shark)) {
      MarkedIndividual sharkie = myShepherd.getMarkedIndividual(shark);
      if (sharkie.getInterestedResearchers() != null) {
        Vector notifyMe = sharkie.getInterestedResearchers();
        int size = notifyMe.size();
        String[] interested = new String[size];
        for (int i = 0; i < size; i++) {
          interested[i] = (String) notifyMe.get(i);
        }
        myShepherd.rollbackDBTransaction();
        myShepherd.closeDBTransaction();
        if (size > 0) {

          ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService();

          Vector e_images = new Vector();
          String mailMe = interested[0];
          String email =
              getText("dataUpdate.txt")
                  .replaceAll(
                      "INSERTTEXT",
                      ("Tag "
                          + shark
                          + ": "
                          + message
                          + "\n\nLink to individual: http://"
                          + CommonConfiguration.getURLLocation(request)
                          + "/individuals.jsp?number="
                          + shark));
          email +=
              ("\n\nWant to stop tracking this set of this individual's data? Use this link.\n\nhttp://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/dontTrack?shark="
                  + shark
                  + "&email=");

          es.execute(
              new NotificationMailer(
                  CommonConfiguration.getMailHost(context),
                  CommonConfiguration.getAutoEmailAddress(context),
                  mailMe,
                  ("Marked individual data update: " + shark),
                  (email + mailMe),
                  e_images,
                  context));
          for (int j = 1; j < size; j++) {
            mailMe = interested[j];
            es.execute(
                new NotificationMailer(
                    CommonConfiguration.getMailHost(context),
                    CommonConfiguration.getAutoEmailAddress(context),
                    mailMe,
                    ("Individual data update: " + shark),
                    (email + mailMe),
                    e_images,
                    context));
          }
        }
      } else {
        myShepherd.rollbackDBTransaction();
        myShepherd.closeDBTransaction();
      }
    } else {
      myShepherd.rollbackDBTransaction();
      myShepherd.closeDBTransaction();
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Shepherd myShepherd = new Shepherd();
    // set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;

    String email = "None", encounterNumber = "None", shark = "None";

    email = request.getParameter("email");
    encounterNumber = request.getParameter("number");
    myShepherd.beginDBTransaction();
    if ((request.getParameter("number") != null)
        && (myShepherd.isEncounter(request.getParameter("number")))
        && (email != null)
        && (!email.equals(""))
        && (email.indexOf("@") != -1)) {
      Encounter enc = myShepherd.getEncounter(encounterNumber);

      // int positionInList=0;
      try {

        Vector interested = enc.getInterestedResearchers();
        interested.add(email);

      } catch (Exception le) {
        locked = true;
        myShepherd.rollbackDBTransaction();
      }

      if (!locked) {
        myShepherd.commitDBTransaction();
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<strong>Success!</strong> I have successfully added the tracking of encounter#"
                + encounterNumber
                + " for e-mail address "
                + email
                + ".");

        out.println(
            "<p><a href=\"http://"
                + CommonConfiguration.getURLLocation(request)
                + "/encounters/encounter.jsp?number="
                + encounterNumber
                + "\">Return to encounter "
                + encounterNumber
                + "</a></p>\n");
        out.println(ServletUtilities.getFooter());
        Vector e_images = new Vector();
        String message =
            "This is a confirmation that e-mail tracking of data changes to encounter "
                + encounterNumber
                + " has now started. You should receive e-mail updates any time changes to this encounter are made.";
        NotificationMailer mailer =
            new NotificationMailer(
                CommonConfiguration.getMailHost(),
                CommonConfiguration.getAutoEmailAddress(),
                email,
                ("Encounter data tracking started for encounter: " + encounterNumber),
                message,
                e_images);
      } else {

        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<strong>Failure!</strong> This encounter is currently being modified by another user, or the database is locked. Please wait a few seconds before trying to add this e-mail address for tracking again.");
        out.println(
            "<p><a href=\"http://"
                + CommonConfiguration.getURLLocation(request)
                + "/encounters/encounter.jsp?number="
                + encounterNumber
                + "\">Return to encounter "
                + encounterNumber
                + "</a></p>\n");
        out.println(ServletUtilities.getFooter());
      }
    } else if ((request.getParameter("individual") != null)
        && (myShepherd.isMarkedIndividual(request.getParameter("individual")))
        && (email != null)
        && (!email.equals(""))
        && (email.indexOf("@") != -1)) {

      shark = request.getParameter("individual");
      MarkedIndividual sharkie = myShepherd.getMarkedIndividual(shark);

      // myShepherd.beginDBTransaction();
      // int positionInList=0;
      try {

        Vector interested = sharkie.getInterestedResearchers();
        interested.add(email);

      } catch (Exception le) {
        locked = true;
        myShepherd.rollbackDBTransaction();
      }

      if (!locked) {
        myShepherd.commitDBTransaction();
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<strong>Success!</strong> I have successfully added the tracking of "
                + shark
                + " for e-mail address "
                + email
                + ".");

        out.println(
            "<p><a href=\"http://"
                + CommonConfiguration.getURLLocation(request)
                + "/individuals.jsp?number="
                + shark
                + "\">Return to "
                + shark
                + "</a></p>\n");
        out.println(ServletUtilities.getFooter());
        Vector e_images = new Vector();
        String message =
            "This is a confirmation that e-mail tracking of data changes to "
                + shark
                + " has now started. You should receive e-mail updates any time changes to this record are made.";
        NotificationMailer mailer =
            new NotificationMailer(
                CommonConfiguration.getMailHost(),
                CommonConfiguration.getAutoEmailAddress(),
                email,
                ("Data tracking started for encounter: " + shark),
                message,
                e_images);
      } else {

        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<strong>Failure!</strong> This record is currently being modified by another user, or the database is locked. Please wait a few seconds before trying to add this e-mail address for tracking again.");
        out.println(
            "<p><a href=\"http://"
                + CommonConfiguration.getURLLocation(request)
                + "/individuals.jsp?number="
                + shark
                + "\">Return to "
                + shark
                + "</a></p>\n");
        out.println(ServletUtilities.getFooter());
      }

    } else {
      myShepherd.rollbackDBTransaction();
      out.println(ServletUtilities.getHeader(request));
      out.println(
          "<strong>Error:</strong> I was unable to add your e-mail address to the tracking list. I cannot find the record that you indicated in the database, or your e-mail address is invalid.");
      out.println(ServletUtilities.getFooter());
    }
    out.close();
    myShepherd.closeDBTransaction();
  }
  public static void informInterestedParties(
      HttpServletRequest request, String number, String message, String context) {
    // String context="context0";
    // context=ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    myShepherd.beginDBTransaction();

    if (myShepherd.isEncounter(number)) {

      Encounter enc = myShepherd.getEncounter(number);
      if (enc.getInterestedResearchers() != null) {
        Vector notifyMe = enc.getInterestedResearchers();
        int size = notifyMe.size();
        String[] interested = new String[size];
        for (int i = 0; i < size; i++) {
          interested[i] = (String) notifyMe.get(i);
        }
        myShepherd.rollbackDBTransaction();
        myShepherd.closeDBTransaction();
        if (size > 0) {
          Vector e_images = new Vector();
          String mailMe = interested[0];
          String email =
              getText("dataUpdate.txt")
                  .replaceAll(
                      "INSERTTEXT",
                      ("Encounter "
                          + number
                          + ": "
                          + message
                          + "\n\nLink to encounter: http://"
                          + CommonConfiguration.getURLLocation(request)
                          + "/encounters/encounter.jsp?number="
                          + number));
          email +=
              ("\n\nWant to stop tracking this set of encounter data? Use this link.\nhttp://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/dontTrack?number="
                  + number
                  + "&email=");
          ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService();
          es.execute(
              new NotificationMailer(
                  CommonConfiguration.getMailHost(context),
                  CommonConfiguration.getAutoEmailAddress(context),
                  mailMe,
                  ("Encounter data update: " + number),
                  (email + mailMe),
                  e_images,
                  context));

          // NotificationMailer mailer=new NotificationMailer(CommonConfiguration.getMailHost(),
          // CommonConfiguration.getAutoEmailAddress(), mailMe, ("Encounter data update: "+number),
          // (email+mailMe), e_images);
          for (int j = 1; j < size; j++) {
            mailMe = interested[j];
            es.execute(
                new NotificationMailer(
                    CommonConfiguration.getMailHost(context),
                    CommonConfiguration.getAutoEmailAddress(context),
                    mailMe,
                    ("Encounter data update: " + number),
                    (email + mailMe),
                    e_images,
                    context));
          }
        }
      } else {
        myShepherd.rollbackDBTransaction();
        myShepherd.closeDBTransaction();
      }

    } else {
      myShepherd.rollbackDBTransaction();
      myShepherd.closeDBTransaction();
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String context = "context0";
    context = ServletUtilities.getContext(request);
    String langCode = ServletUtilities.getLanguageCode(request);
    Shepherd myShepherd = new Shepherd(context);
    // set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;
    boolean isOwner = true;

    if (request.getParameter("number") != null) {
      myShepherd.beginDBTransaction();
      Encounter enc2reject = myShepherd.getEncounter(request.getParameter("number"));
      setDateLastModified(enc2reject);
      boolean isOK = enc2reject.isAssignedToMarkedIndividual().equals("Unassigned");
      myShepherd.rollbackDBTransaction();
      if (isOK) {

        myShepherd.beginDBTransaction();
        try {

          // enc2reject.reject();
          enc2reject.setState("unidentifiable");
          enc2reject.addComments(
              "<p><em>"
                  + request.getRemoteUser()
                  + " on "
                  + (new java.util.Date()).toString()
                  + "</em><br>Set this encounter as unidentifiable in the database.</p>");
          // enc2reject.approved = false;
          enc2reject.setState("unidentifiable");
        } catch (Exception le) {
          locked = true;
          le.printStackTrace();
          myShepherd.rollbackDBTransaction();
        }

        if (!locked) {
          String submitterEmail = enc2reject.getSubmitterEmail();
          myShepherd.commitDBTransaction();
          out.println(ServletUtilities.getHeader(request));
          out.println(
              "<strong>Success:</strong> I have set encounter "
                  + request.getParameter("number")
                  + " as unidentifiable in the database.");
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/encounters/encounter.jsp?number="
                  + request.getParameter("number")
                  + "\">View unidentifiable encounter #"
                  + request.getParameter("number")
                  + "</a></p>\n");
          ArrayList<String> allStates =
              CommonConfiguration.getSequentialPropertyValues("encounterState", context);
          int allStatesSize = allStates.size();
          if (allStatesSize > 0) {
            for (int i = 0; i < allStatesSize; i++) {
              String stateName = allStates.get(i);
              out.println(
                  "<p><a href=\"encounters/searchResults.jsp?state="
                      + stateName
                      + "\">View all "
                      + stateName
                      + " encounters</a></font></p>");
            }
          }
          out.println(ServletUtilities.getFooter(context));
          String message =
              "Encounter "
                  + request.getParameter("number")
                  + " was set as unidentifiable in the database.";
          ServletUtilities.informInterestedParties(
              request, request.getParameter("number"), message, context);

          // Email submitter about change
          Map<String, String> tagMap = NotificationMailer.createBasicTagMap(request, enc2reject);
          tagMap.put("@TEXT_CONTENT@", message);
          ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService();
          NotificationMailer mailer =
              new NotificationMailer(context, null, submitterEmail, "encounterDataUpdate", tagMap);
          es.execute(mailer);
          es.shutdown();

        } else {
          out.println(ServletUtilities.getHeader(request));
          out.println(
              "<strong>Failure:</strong> I have NOT modified encounter "
                  + request.getParameter("number")
                  + " in the database because another user is currently modifying its entry. Please try this operation again in a few seconds.");
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/encounters/encounter.jsp?number="
                  + request.getParameter("number")
                  + "\">View unidentifiable encounter #"
                  + request.getParameter("number")
                  + "</a></p>\n");
          ArrayList<String> allStates =
              CommonConfiguration.getSequentialPropertyValues("encounterState", context);
          int allStatesSize = allStates.size();
          if (allStatesSize > 0) {
            for (int i = 0; i < allStatesSize; i++) {
              String stateName = allStates.get(i);
              out.println(
                  "<p><a href=\"encounters/searchResults.jsp?state="
                      + stateName
                      + "\">View all "
                      + stateName
                      + " encounters</a></font></p>");
            }
          }
          out.println(ServletUtilities.getFooter(context));
        }

      } else {
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "Encounter# "
                + request.getParameter("number")
                + " is assigned to an individual and cannot be set as unidentifiable until it has been removed from that individual.");
        out.println(ServletUtilities.getFooter(context));
      }
    } else {
      out.println(ServletUtilities.getHeader(request));
      out.println(
          "<strong>Error:</strong> I do not know which encounter you are trying to remove.");
      out.println(ServletUtilities.getFooter(context));
    }

    out.close();
    myShepherd.closeDBTransaction();
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // set the response

    Shepherd myShepherd = new Shepherd();

    Vector rEncounters = new Vector();

    // setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName());
    // if(!shepherdDataDir.exists()){shepherdDataDir.mkdir();}
    File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters");
    // if(!encountersDir.exists()){encountersDir.mkdir();}

    // set up the files
    String gisFilename = "geneGIS_export_" + request.getRemoteUser() + ".csv";
    File gisFile = new File(encountersDir.getAbsolutePath() + "/" + gisFilename);

    myShepherd.beginDBTransaction();

    try {

      // set up the output stream
      FileOutputStream fos = new FileOutputStream(gisFile);
      OutputStreamWriter outp = new OutputStreamWriter(fos);

      try {

        EncounterQueryResult queryResult =
            EncounterQueryProcessor.processQuery(
                myShepherd, request, "year descending, month descending, day descending");
        rEncounters = queryResult.getResult();

        int numMatchingEncounters = rEncounters.size();

        // build the CSV file header
        StringBuffer locusString = new StringBuffer("");
        int numLoci = 2; // most covered species will be loci
        try {
          numLoci = (new Integer(CommonConfiguration.getProperty("numLoci"))).intValue();
        } catch (Exception e) {
          System.out.println("numPloids configuration value did not resolve to an integer.");
          e.printStackTrace();
        }

        for (int j = 0; j < numLoci; j++) {
          locusString.append(",Locus" + (j + 1) + " A1,Locus" + (j + 1) + " A2");
        }
        // out.println("<html><body>");
        // out.println("Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub
        // Area,Sex,Haplotype"+locusString.toString());

        outp.write(
            "Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub Area,Sex,Haplotype"
                + locusString.toString()
                + "\n");

        for (int i = 0; i < numMatchingEncounters; i++) {

          Encounter enc = (Encounter) rEncounters.get(i);
          String assembledString = "";
          if (enc.getIndividualID() != null) {
            assembledString += enc.getIndividualID();
          }
          if (enc.getAlternateID() != null) {
            assembledString += "," + enc.getAlternateID();
          } else {
            assembledString += ",";
          }

          String dateString = ",";
          if (enc.getYear() > 0) {
            dateString += enc.getYear();
            if (enc.getMonth() > 0) {
              dateString += ("-" + enc.getMonth());
              if (enc.getDay() > 0) {
                dateString += ("-" + enc.getDay());
              }
            }
          }
          assembledString += dateString;

          String timeString = ",";
          if (enc.getHour() > -1) {
            timeString += enc.getHour() + ":" + enc.getMinutes();
          }
          assembledString += timeString;

          if ((enc.getDecimalLatitude() != null) && (enc.getDecimalLongitude() != null)) {
            assembledString += "," + enc.getDecimalLatitude();
            assembledString += "," + enc.getDecimalLongitude();
          } else {
            assembledString += ",,";
          }

          assembledString += "," + enc.getVerbatimLocality();
          assembledString += "," + enc.getLocationID();
          assembledString += "," + enc.getSex();

          // find and print the haplotype
          String haplotypeString = ",";
          if (enc.getHaplotype() != null) {
            haplotypeString += enc.getHaplotype();
          }

          // find and print the ms markers
          String msMarkerString = "";
          List<TissueSample> samples = enc.getTissueSamples();
          int numSamples = samples.size();
          boolean foundMsMarkers = false;
          for (int k = 0; k < numSamples; k++) {
            if (!foundMsMarkers) {
              TissueSample t = samples.get(k);
              List<GeneticAnalysis> analyses = t.getGeneticAnalyses();
              int aSize = analyses.size();
              for (int l = 0; l < aSize; l++) {
                GeneticAnalysis ga = analyses.get(l);
                if (ga.getAnalysisType().equals("MicrosatelliteMarkers")) {
                  foundMsMarkers = true;
                  MicrosatelliteMarkersAnalysis ga2 = (MicrosatelliteMarkersAnalysis) ga;
                  List<Locus> loci = ga2.getLoci();
                  int localLoci = loci.size();
                  for (int m = 0; m < localLoci; m++) {
                    Locus locus = loci.get(m);
                    if (locus.getAllele0() != null) {
                      msMarkerString += "," + locus.getAllele0();
                    } else {
                      msMarkerString += ",";
                    }
                    if (locus.getAllele1() != null) {
                      msMarkerString += "," + locus.getAllele1();
                    } else {
                      msMarkerString += ",";
                    }
                  }
                }
              }
            }
          }

          // out.println("<p>"+assembledString+haplotypeString+msMarkerString+"</p>");
          outp.write(assembledString + haplotypeString + msMarkerString + "\n");
        }
        outp.close();
        outp = null;

        // now write out the file
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment;filename=" + gisFilename);
        ServletContext ctx = getServletContext();
        // InputStream is = ctx.getResourceAsStream("/encounters/"+gisFilename);
        InputStream is = new FileInputStream(gisFile);

        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();

        while ((read = is.read(bytes)) != -1) {
          os.write(bytes, 0, read);
        }
        os.flush();
        os.close();

      } catch (Exception ioe) {
        ioe.printStackTrace();
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<html><body><p><strong>Error encountered</strong> with file writing. Check the relevant log.</p>");
        out.println(
            "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
        out.println(ServletUtilities.getFooter());
        out.close();
        outp.close();
        outp = null;
      }

    } catch (Exception e) {
      e.printStackTrace();
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println(ServletUtilities.getHeader(request));
      out.println("<html><body><p><strong>Error encountered</strong></p>");
      out.println(
          "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
      out.println(ServletUtilities.getFooter());
      out.close();
    }
    myShepherd.rollbackDBTransaction();
    myShepherd.closeDBTransaction();
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String context = "context0";
    context = ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    GridManager gm = GridManagerFactory.getGridManager();
    // set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String action = request.getParameter("action");
    System.out.println("scanTaskHandler action is: " + action);
    if (action != null) {

      if ((action.equals("removeTask")) && (request.getParameter("taskID") != null)) {
        myShepherd.beginDBTransaction();
        boolean locked = false;
        // gotta check if it's a valid scanTask to begin with!

        // check for permissions to delete this scanTask
        boolean deletePermission = false;
        deletePermission = true;

        if ((myShepherd.isScanTask(request.getParameter("taskID"))) && (deletePermission)) {
          try {

            // change
            ThreadPoolExecutor es = SharkGridThreadExecutorService.getExecutorService();

            ScanTask st = myShepherd.getScanTask(request.getParameter("taskID"));
            myShepherd.getPM().deletePersistent(st);

            myShepherd.commitDBTransaction();

            // scanTaskCleanupThread swiThread=new
            // scanTaskCleanupThread(request.getParameter("taskID"));
            es.execute(new ScanTaskCleanupThread(request.getParameter("taskID")));

          } catch (Exception e) {
            locked = true;
            System.out.println("I encounter the following error while deleting a scanTask:");
            e.printStackTrace();

            myShepherd.rollbackDBTransaction();
          }
          if (!locked) {
            // confirm success
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Success:</strong> The scanTask <i>"
                    + request.getParameter("taskID")
                    + "</i> has been removed.");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp\">Return to scanTask administration page.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          } else {
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Error:</strong> The scanTask <i>"
                    + request.getParameter("taskID")
                    + "</i> was not removed. The task may be locked by another user or in process. Check the logs for more information.");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp\">Return to scanTask administration page.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          }
        } else {
          myShepherd.rollbackDBTransaction();
          out.println(ServletUtilities.getHeader(request));
          out.println(
              "<strong>Error:</strong> The scanTask <i>"
                  + request.getParameter("taskID")
                  + "</i> was not identified in the database.");
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/appadmin/scanTaskAdmin.jsp\">Return to scanTask administration page.</a></p>\n");
          out.println(ServletUtilities.getFooter(context));
        }
      } else if ((action.equals("addTask")) && (request.getParameter("encounterNumber") != null)) {

        myShepherd.getPM().setIgnoreCache(true);

        boolean locked = false;
        // String readableName="";
        boolean successfulStore = false;

        // set up our properties
        java.util.Properties props2 = new java.util.Properties();
        String secondRun = "true";
        String rightScan = "false";
        boolean isRightScan = false;
        boolean writeThis = true;
        // String uniqueNum="";
        if (request.getParameter("writeThis") == null) {
          writeThis = false;
        }
        if ((request.getParameter("rightSide") != null)
            && (request.getParameter("rightSide").equals("true"))) {
          rightScan = "true";
          isRightScan = true;
        }
        props2.setProperty("epsilon", "0.01");
        props2.setProperty("R", "8");
        props2.setProperty("Sizelim", "0.85");
        props2.setProperty("maxTriangleRotation", "10");
        props2.setProperty("C", "0.99");
        props2.setProperty("secondRun", secondRun);
        props2.setProperty("rightScan", rightScan);

        // let's check if a scanTask for this exists
        System.out.println("scanTaskHandler: Checking whether this is a new scanTask...");

        myShepherd.beginDBTransaction();

        String sideIdentifier = "L";

        if (rightScan.equals("true")) {
          sideIdentifier = "R";
          // numComparisons=myShepherd.getNumEncountersWithSpotData(true);
        } else {
          // numComparisons=myShepherd.getNumEncountersWithSpotData(false);
        }
        String taskIdentifier = "scan" + sideIdentifier + request.getParameter("encounterNumber");
        ScanTask st = new ScanTask();

        // let's do a check to see if too many scanTasks are in the queue
        int taskLimit = gm.getScanTaskLimit();
        int currentNumScanTasks = myShepherd.getNumUnfinishedScanTasks();
        myShepherd.getPM().getFetchPlan().setGroup(FetchPlan.DEFAULT);
        System.out.println("currentNumScanTasks is: " + currentNumScanTasks);
        // int currentNumScanTasks=0;
        if (currentNumScanTasks < taskLimit) {

          int numComparisons = 0;
          if (rightScan.equals("true")) {
            // sideIdentifier="R";
            numComparisons = myShepherd.getNumEncountersWithSpotData(true);
          } else {
            numComparisons = myShepherd.getNumEncountersWithSpotData(false);
          }
          myShepherd.getPM().getFetchPlan().setGroup(FetchPlan.DEFAULT);

          System.out.println(
              "scanTaskHandler: Under the limit, so proceeding to check for condiions for creating a new scanTask...");
          if ((!myShepherd.isScanTask(taskIdentifier))) {
            System.out.println("scanTaskHandler: This scanTask does not exist, so go create it...");

            // check if this encounter has the needed spots to create the task
            boolean hasNeededSpots = false;
            Encounter enc = myShepherd.getEncounter(request.getParameter("encounterNumber"));
            if ((rightScan.equals("true")) && (enc.getRightSpots() != null)) {
              hasNeededSpots = true;
            } else if (enc.getSpots() != null) {
              hasNeededSpots = true;
            }

            if (hasNeededSpots) {

              System.out.println("scanTaskHandler: I have needed spots...proceeding...");

              st =
                  new ScanTask(
                      myShepherd,
                      taskIdentifier,
                      props2,
                      request.getParameter("encounterNumber"),
                      writeThis);
              st.setNumComparisons(numComparisons - 1);
              if (request.getRemoteUser() != null) {
                st.setSubmitter(request.getRemoteUser());
              }
              System.out.println("scanTaskHandler: About to create a scanTask...");
              successfulStore = myShepherd.storeNewTask(st);
              if (!successfulStore) {

                System.out.println("scanTaskHandler: Unsuccessful store...");

                myShepherd.rollbackDBTransaction();
                myShepherd.closeDBTransaction();
                locked = true;
              } else {
                System.out.println("scanTaskHandler: Successful store...");

                myShepherd.commitDBTransaction();
                myShepherd.closeDBTransaction();
                myShepherd = new Shepherd(context);
              }
            } else {
              myShepherd.rollbackDBTransaction();
              myShepherd.closeDBTransaction();
              locked = true;
            }

          } else if (myShepherd.isScanTask(taskIdentifier)) {

            System.out.println("scanTaskHandler: This is an existing scanTask...");

            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;

            String rightFilter = "";
            if ((request.getParameter("rightSide") != null)
                && (request.getParameter("rightSide").equals("true"))) {
              rightFilter = "&rightSide=true";
            }

            // if it exists already, advance to the scanTask administration page to await its
            // completion
            response.sendRedirect(
                "http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp");
          } else {
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;
          }
        }

        if (!locked && successfulStore) {

          try {

            ThreadPoolExecutor es = SharkGridThreadExecutorService.getExecutorService();
            es.execute(
                new ScanWorkItemCreationThread(
                    taskIdentifier,
                    isRightScan,
                    request.getParameter("encounterNumber"),
                    writeThis,
                    context));

          } catch (Exception e) {
            System.out.println("I failed while constructing the workItems for a new scanTask.");
            e.printStackTrace();
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;
          }
          if (!locked) {
            System.out.println("Trying to commit the add of the scanWorkItems");

            // myShepherd.commitDBTransaction();
            // myShepherd.closeDBTransaction();
            System.out.println("I committed the workItems!");

            String rightFilter = "L";
            String rightURL = "";
            if ((request.getParameter("rightSide") != null)
                && (request.getParameter("rightSide").equals("true"))) {
              rightFilter = "R";
              rightURL = "&rightSide=true";
            }

            // confirm success
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Success:</strong> Your scan was successfully added to the sharkGrid!");
            // out.println("<p><a
            // href=\"http://"+CommonConfiguration.getURLLocation()+"/encounters/workAppletScan.jsp?number=scan"+rightFilter+request.getParameter("encounterNumber")+rightURL+"\">Start scanning for a match.</a></p>\n");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/encounters/encounter.jsp?number="
                    + request.getParameter("encounterNumber")
                    + "\">Return to encounter "
                    + request.getParameter("encounterNumber")
                    + ".</a></p>\n");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp"
                    + "\">Go to sharkGrid administration to monitor for completion.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          } else {
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Failure:</strong> The scan could not be created or was not fully created!");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          }
        } else {
          out.println(ServletUtilities.getHeader(request));
          out.println("<strong>Failure:</strong> I have NOT added this scanTask to the queue.");
          if (currentNumScanTasks < taskLimit) {
            out.println(
                "The unfinished task limit of "
                    + taskLimit
                    + " has been filled. Please try adding the task to the queue again after existing tasks have finished.");
          }
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
          out.println(ServletUtilities.getFooter(context));
        }
      } else if (action.equals("addTuningTask")) {

        // myShepherd.getPM().setIgnoreCache(true);

        boolean locked = false;
        // String readableName="";
        boolean successfulStore = false;

        int maxNumWorkItems = 99999999;
        if ((request.getParameter("maxNumWorkItems") != null)
            && (!request.getParameter("maxNumWorkItems").equals(""))) {
          maxNumWorkItems = Integer.parseInt(request.getParameter("maxNumWorkItems"));
        }

        // set up our properties
        java.util.Properties props2 = new java.util.Properties();
        String secondRun = "true";
        String rightScan = "false";
        boolean isRightScan = false;
        boolean writeThis = true;
        // String uniqueNum="";
        if (request.getParameter("writeThis") == null) {
          writeThis = false;
        }
        if ((request.getParameter("rightSide") != null)
            && (request.getParameter("rightSide").equals("true"))) {
          rightScan = "true";
          isRightScan = true;
        }
        props2.setProperty("epsilon", "0.01");
        props2.setProperty("R", "8");
        props2.setProperty("Sizelim", "0.85");
        props2.setProperty("maxTriangleRotation", "10");
        props2.setProperty("C", "0.99");
        props2.setProperty("secondRun", secondRun);
        props2.setProperty("rightScan", rightScan);

        // let's check if a scanTask for this exists
        System.out.println("scanTaskHandler: Checking whether this is a new scanTask...");

        myShepherd.beginDBTransaction();

        String sideIdentifier = "L";

        if (rightScan.equals("true")) {
          sideIdentifier = "R";
          // numComparisons=myShepherd.getNumEncountersWithSpotData(true);
        } else {
          // numComparisons=myShepherd.getNumEncountersWithSpotData(false);
        }
        String taskIdentifier = "TuningTask";
        ScanTask st = new ScanTask();

        // let's do a check to see if too many scanTasks are in the queue
        int taskLimit = gm.getScanTaskLimit();
        int currentNumScanTasks = myShepherd.getNumUnfinishedScanTasks();
        myShepherd.getPM().getFetchPlan().setGroup(FetchPlan.DEFAULT);
        System.out.println("currentNumScanTasks is: " + currentNumScanTasks);
        // int currentNumScanTasks=0;
        if (currentNumScanTasks < taskLimit) {

          Vector leftSharks = myShepherd.getPossibleTrainingIndividuals();
          Vector rightSharks = myShepherd.getRightPossibleTrainingIndividuals();

          int numComparisons = 0;

          // calculate the number of comparisons that can be made
          int numLeftSharks = leftSharks.size();
          for (int i = 0; i < numLeftSharks; i++) {
            MarkedIndividual s = (MarkedIndividual) leftSharks.get(i);
            int numTrainable = s.getNumberTrainableEncounters();
            // int numCompareEncounters=s.getNumberTrainableEncounters();
            // for(int j=(numCompareEncounters-1);j>1;j--){
            //  numCompareEncounters=numCompareEncounters*j;
            // }
            // numCompareEncounters=numCompareEncounters/(2*(numTrainable-2));
            // numComparisons=numComparisons+numCompareEncounters;
            numComparisons = numComparisons + combinations(numTrainable, 2);
          }
          int numRightSharks = rightSharks.size();
          for (int i = 0; i < numRightSharks; i++) {
            MarkedIndividual s = (MarkedIndividual) rightSharks.get(i);
            int numCompareEncounters = s.getNumberRightTrainableEncounters();
            // for(int j=(numCompareEncounters-1);j>1;j--){
            // numCompareEncounters=numCompareEncounters*j;
            // }
            // numComparisons=numComparisons+numCompareEncounters;
            numComparisons = numComparisons + combinations(numCompareEncounters, 2);
          }

          System.out.println(
              "scanTaskHandler: Under the limit, so proceeding to check for condiions for creating a new scanTask...");
          if ((!myShepherd.isScanTask(taskIdentifier))) {
            // System.out.println("scanTaskHandler: This scanTask does not exist, so go create
            // it...");

            st = new ScanTask(myShepherd, taskIdentifier, props2, "TuningTask", writeThis);

            if (numComparisons < (2 * maxNumWorkItems)) {
              st.setNumComparisons(numComparisons);
            } else {
              st.setNumComparisons((2 * maxNumWorkItems));
            }

            if (request.getRemoteUser() != null) {
              st.setSubmitter(request.getRemoteUser());
            }
            System.out.println("scanTaskHandler: About to create a TuningTask...");
            successfulStore = myShepherd.storeNewTask(st);
            if (!successfulStore) {

              System.out.println("scanTaskHandler: Unsuccessful TuningTask store...");

              myShepherd.rollbackDBTransaction();
              myShepherd.closeDBTransaction();
              locked = true;
            } else {
              System.out.println("scanTaskHandler: Successful TuningTask store...");

              myShepherd.commitDBTransaction();
              myShepherd.closeDBTransaction();
              myShepherd = new Shepherd(context);
            }

          } else if (myShepherd.isScanTask(taskIdentifier)) {

            System.out.println("scanTaskHandler: This is an existing scanTask...");

            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;

            String rightFilter = "";
            if ((request.getParameter("rightSide") != null)
                && (request.getParameter("rightSide").equals("true"))) {
              rightFilter = "&rightSide=true";
            }

            // if it exists already, advance to the scan page to assist it
            response.sendRedirect(
                "http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/encounters/workAppletScan.jsp?writeThis=true&number="
                    + taskIdentifier
                    + rightFilter);
          } else {
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;
          }
        }

        if (!locked && successfulStore) {

          try {

            ThreadPoolExecutor es = SharkGridThreadExecutorService.getExecutorService();
            es.execute(
                new TuningTaskCreationThread(taskIdentifier, writeThis, maxNumWorkItems, context));

          } catch (Exception e) {
            System.out.println("I failed while constructing the workItems for a new scanTask.");
            e.printStackTrace();
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;
          }
          if (!locked) {
            System.out.println("Trying to commit the add of the scanWorkItems");

            // myShepherd.commitDBTransaction();
            // myShepherd.closeDBTransaction();
            System.out.println("I committed the workItems!");

            String rightFilter = "L";
            String rightURL = "";
            if ((request.getParameter("rightSide") != null)
                && (request.getParameter("rightSide").equals("true"))) {
              rightFilter = "R";
              rightURL = "&rightSide=true";
            }

            // confirm success
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Success:</strong> Your scan was successfully added to the sharkGrid!");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp"
                    + "\">Return to sharkGrid administration.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          } else {
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Failure:</strong> The scan could not be created or was not fully created!");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          }
        } else {
          out.println(ServletUtilities.getHeader(request));
          out.println("<strong>Failure:</strong> I have NOT added this scanTask to the queue.");
          if (currentNumScanTasks < taskLimit) {
            out.println(
                "The unfinished task limit of "
                    + taskLimit
                    + " has been filled. Please try adding the task to the queue again after existing tasks have finished.");
          }
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
          out.println(ServletUtilities.getFooter(context));
        }
      } else if (action.equals("addFalseMatchTask")) {

        boolean locked = false;
        boolean successfulStore = false;

        int maxNumWorkItems = 99999999;
        if ((request.getParameter("maxNumWorkItems") != null)
            && (!request.getParameter("maxNumWorkItems").equals(""))) {
          maxNumWorkItems = Integer.parseInt(request.getParameter("maxNumWorkItems"));
        }

        // set up our properties
        java.util.Properties props2 = new java.util.Properties();
        String secondRun = "true";
        String rightScan = "false";
        boolean isRightScan = false;
        boolean writeThis = true;
        if (request.getParameter("writeThis") == null) {
          writeThis = false;
        }
        if ((request.getParameter("rightSide") != null)
            && (request.getParameter("rightSide").equals("true"))) {
          rightScan = "true";
          isRightScan = true;
        }
        props2.setProperty("epsilon", "0.01");
        props2.setProperty("R", "8");
        props2.setProperty("Sizelim", "0.85");
        props2.setProperty("maxTriangleRotation", "10");
        props2.setProperty("C", "0.99");
        props2.setProperty("secondRun", secondRun);
        props2.setProperty("rightScan", rightScan);

        // let's check if a scanTask for this exists
        System.out.println(
            "scanTaskHandler: Checking whether this is a new False Match scanTask...");

        myShepherd.beginDBTransaction();

        String sideIdentifier = "L";

        if (rightScan.equals("true")) {
          sideIdentifier = "R";
        }

        String taskIdentifier = "FalseMatchTask";
        ScanTask st = new ScanTask();

        // let's do a check to see if too many scanTasks are in the queue
        int taskLimit = gm.getScanTaskLimit();
        int currentNumScanTasks = myShepherd.getNumUnfinishedScanTasks();
        myShepherd.getPM().getFetchPlan().setGroup(FetchPlan.DEFAULT);
        System.out.println("currentNumScanTasks is: " + currentNumScanTasks);
        // int currentNumScanTasks=0;
        if (currentNumScanTasks < taskLimit) {

          // Vector leftSharks=myShepherd.getPossibleTrainingSharks();
          // Vector rightSharks=myShepherd.getRightPossibleTrainingSharks();

          int numComparisons = maxNumWorkItems * 2;

          System.out.println(
              "scanTaskHandler: Under the limit, so proceeding to check for condiions for creating a new scanTask...");
          if ((!myShepherd.isScanTask(taskIdentifier))) {
            // System.out.println("scanTaskHandler: This scanTask does not exist, so go create
            // it...");

            st = new ScanTask(myShepherd, taskIdentifier, props2, "FalseMatchTask", writeThis);
            st.setNumComparisons(numComparisons);
            if (request.getRemoteUser() != null) {
              st.setSubmitter(request.getRemoteUser());
            }
            System.out.println("scanTaskHandler: About to create a TuningTask...");
            successfulStore = myShepherd.storeNewTask(st);
            if (!successfulStore) {

              System.out.println("scanTaskHandler: Unsuccessful FalseMatchTask store...");

              myShepherd.rollbackDBTransaction();
              myShepherd.closeDBTransaction();
              locked = true;
            } else {
              System.out.println("scanTaskHandler: Successful FalseMatchTask store...");

              myShepherd.commitDBTransaction();
              myShepherd.closeDBTransaction();
              myShepherd = new Shepherd(context);
            }

          } else if (myShepherd.isScanTask(taskIdentifier)) {

            System.out.println("scanTaskHandler: This is an existing scanTask...");

            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;

            String rightFilter = "";
            if ((request.getParameter("rightSide") != null)
                && (request.getParameter("rightSide").equals("true"))) {
              rightFilter = "&rightSide=true";
            }

            // if it exists already, advance to the scan page to assist it
            response.sendRedirect(
                "http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/encounters/workAppletScan.jsp?writeThis=true&number="
                    + taskIdentifier
                    + rightFilter);
          } else {
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;
          }
        }

        if (!locked && successfulStore) {

          try {

            ThreadPoolExecutor es = SharkGridThreadExecutorService.getExecutorService();
            es.execute(new FalseMatchCreationThread(maxNumWorkItems, taskIdentifier, context));

          } catch (Exception e) {
            System.out.println("I failed while constructing the workItems for a new scanTask.");
            e.printStackTrace();
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            locked = true;
          }
          if (!locked) {
            System.out.println("Trying to commit the add of the scanWorkItems");

            // myShepherd.commitDBTransaction();
            // myShepherd.closeDBTransaction();
            System.out.println("I committed the workItems!");

            String rightFilter = "L";
            String rightURL = "";
            if ((request.getParameter("rightSide") != null)
                && (request.getParameter("rightSide").equals("true"))) {
              rightFilter = "R";
              rightURL = "&rightSide=true";
            }

            // confirm success
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Success:</strong> Your scan was successfully added to the sharkGrid!");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp"
                    + "\">Return to sharkGrid administration.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          } else {
            out.println(ServletUtilities.getHeader(request));
            out.println(
                "<strong>Failure:</strong> The scan could not be created or was not fully created!");
            out.println(
                "<p><a href=\"http://"
                    + CommonConfiguration.getURLLocation(request)
                    + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
            out.println(ServletUtilities.getFooter(context));
          }
        } else {
          out.println(ServletUtilities.getHeader(request));
          out.println("<strong>Failure:</strong> I have NOT added this scanTask to the queue.");
          if (currentNumScanTasks < taskLimit) {
            out.println(
                "The unfinished task limit of "
                    + taskLimit
                    + " has been filled. Please try adding the task to the queue again after existing tasks have finished.");
          }
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
          out.println(ServletUtilities.getFooter(context));
        }
      }

      // delete all scan-related items
      else if (action.equals("removeAllWorkItems")) {
        try {

          GridCleanupThread swiThread = new GridCleanupThread(context);
          gm.removeAllWorkItems();

          // confirm success
          out.println(ServletUtilities.getHeader(request));
          out.println(
              "<strong>Success:</strong> I removed all outstanding scanWorkItems from the database.<br>/<strong>Warning!</strong> <em>This may cause any outstanding scanTasks to fail!</em>");
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
          out.println(ServletUtilities.getFooter(context));
        } catch (Exception e) {
          e.printStackTrace();
          myShepherd.rollbackDBTransaction();
          out.println(ServletUtilities.getHeader(request));
          out.println(
              "<strong>Failure:</strong> I failed to remove all outstanding scanWorkItems from the database. Check the log for more information.");
          out.println(
              "<p><a href=\"http://"
                  + CommonConfiguration.getURLLocation(request)
                  + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
          out.println(ServletUtilities.getFooter(context));
        }
      } else {

        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<p>I did not receive enough data to process your command, or you do not have the necessary permissions to perform this operation.</p>");
        out.println(
            "<p><a href=\"http://"
                + CommonConfiguration.getURLLocation(request)
                + "/appadmin/scanTaskAdmin.jsp\">Go to sharkGrid administration.</a></p>\n");
        out.println(ServletUtilities.getFooter(context));
      }

    } else {
      out.println(ServletUtilities.getHeader(request));
      out.println(
          "<p>I did not receive enough data to process your command, or you do not have the necessary permissions to perform this operation. </p>");
      out.println("<p>Please try again or <a href=\"welcome.jsp\">login here</a>.");
      out.println(ServletUtilities.getFooter(context));
    }
    myShepherd.closeDBTransaction();
    myShepherd = null;
    out.flush();
    out.close();
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String context = "context0";
    context = ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    // set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;
    boolean isOwner = true;

    if ((request.getParameter("number") != null) && (request.getParameter("state") != null)) {
      myShepherd.beginDBTransaction();
      Encounter changeMe = myShepherd.getEncounter(request.getParameter("number"));
      setDateLastModified(changeMe);
      String state = request.getParameter("state");

      String oldScar = "None";

      try {
        if (changeMe.getState() != null) {
          oldScar = changeMe.getState();
        }
        changeMe.setState(state);
        changeMe.addComments(
            "<p><em>"
                + request.getRemoteUser()
                + " on "
                + (new java.util.Date()).toString()
                + "</em><br>Changed state from "
                + oldScar
                + " to "
                + state
                + ".</p>");
      } catch (Exception le) {
        locked = true;
        le.printStackTrace();
        myShepherd.rollbackDBTransaction();
      }

      if (!locked) {
        myShepherd.commitDBTransaction();
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<strong>Success:</strong> Encounter state has been updated from "
                + oldScar
                + " to "
                + state
                + ".");
        out.println(
            "<p><a href=\"http://"
                + CommonConfiguration.getURLLocation(request)
                + "/encounters/encounter.jsp?number="
                + request.getParameter("number")
                + "\">Return to encounter #"
                + request.getParameter("number")
                + "</a></p>\n");
        List<String> allStates =
            CommonConfiguration.getIndexedPropertyValues("encounterState", context);
        int allStatesSize = allStates.size();
        if (allStatesSize > 0) {
          for (int i = 0; i < allStatesSize; i++) {
            String stateName = allStates.get(i);
            out.println(
                "<p><a href=\"encounters/searchResults.jsp?state="
                    + stateName
                    + "\">View all "
                    + stateName
                    + " encounters</a></font></p>");
          }
        }
        out.println(
            "<p><a href=\"individualSearchResults.jsp\">View all individuals</a></font></p>");
        out.println(ServletUtilities.getFooter(context));
        String message =
            "Encounter "
                + request.getParameter("number")
                + " state has been updated from "
                + oldScar
                + " to "
                + state
                + ".";
        ServletUtilities.informInterestedParties(
            request, request.getParameter("number"), message, context);
      } else {
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<strong>Failure:</strong> Encounter state was NOT updated because another user is currently modifying this reconrd. Please try to reset the scarring again in a few seconds.");
        out.println(
            "<p><a href=\"http://"
                + CommonConfiguration.getURLLocation(request)
                + "/encounters/encounter.jsp?number="
                + request.getParameter("number")
                + "\">Return to encounter #"
                + request.getParameter("number")
                + "</a></p>\n");
        List<String> allStates =
            CommonConfiguration.getIndexedPropertyValues("encounterState", context);
        int allStatesSize = allStates.size();
        if (allStatesSize > 0) {
          for (int i = 0; i < allStatesSize; i++) {
            String stateName = allStates.get(i);
            out.println(
                "<p><a href=\"encounters/searchResults.jsp?state="
                    + stateName
                    + "\">View all "
                    + stateName
                    + " encounters</a></font></p>");
          }
        }
        out.println(
            "<p><a href=\"individualSearchResults.jsp\">View all individuals</a></font></p>");
        out.println(ServletUtilities.getFooter(context));
      }
    } else {
      out.println(ServletUtilities.getHeader(request));
      out.println(
          "<strong>Error:</strong> I don't have enough information to complete your request.");
      out.println(
          "<p><a href=\"http://"
              + CommonConfiguration.getURLLocation(request)
              + "/encounters/encounter.jsp?number="
              + request.getParameter("number")
              + "\">Return to encounter #"
              + request.getParameter("number")
              + "</a></p>\n");
      List<String> allStates =
          CommonConfiguration.getIndexedPropertyValues("encounterState", context);
      int allStatesSize = allStates.size();
      if (allStatesSize > 0) {
        for (int i = 0; i < allStatesSize; i++) {
          String stateName = allStates.get(i);
          out.println(
              "<p><a href=\"encounters/searchResults.jsp?state="
                  + stateName
                  + "\">View all "
                  + stateName
                  + " encounters</a></font></p>");
        }
      }
      out.println("<p><a href=\"individualSearchResults.jsp\">View all individuals</a></font></p>");
      out.println(ServletUtilities.getFooter(context));
    }

    out.close();
    myShepherd.closeDBTransaction();
  }