/** This is where the user comes back to at the end of the OpenID redirect ping-pong. */
  public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {

    String code = request.getParameter("code");

    if (code == null || code.trim().length() == 0) {
      Log.info("doFinishLogin: missing code.");
      return HttpResponses.redirectToContextRoot();
    }

    Log.info("test");

    HttpPost httpost =
        new HttpPost(
            githubUri
                + "/login/oauth/access_token?"
                + "client_id="
                + clientID
                + "&"
                + "client_secret="
                + clientSecret
                + "&"
                + "code="
                + code);

    DefaultHttpClient httpclient = new DefaultHttpClient();

    org.apache.http.HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    String accessToken = extractToken(content);

    if (accessToken != null && accessToken.trim().length() > 0) {

      String githubServer = githubUri.replaceFirst("http.*\\/\\/", "");

      // only set the access token if it exists.
      GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, githubServer);
      SecurityContextHolder.getContext().setAuthentication(auth);

      GHUser self = auth.getGitHub().getMyself();
      User u = User.current();
      u.setFullName(self.getName());
      u.addProperty(new Mailer.UserProperty(self.getEmail()));
    } else {
      Log.info("Github did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) return HttpResponses.redirectTo(referer);
    return HttpResponses
        .redirectToContextRoot(); // referer should be always there, but be defensive
  }
  public List<Candidate> getCandidatesForResponse(MedicFormResponse response) {
    Log.info("Attempting to map response");
    // get the CHW that submitted the form
    CommunityHealthWorker chw = (CommunityHealthWorker) response.getSubmitter();
    // get the list of patients that the CHW cares for
    ArrayList<Patient> patients = (ArrayList<Patient>) patientDao.getPatientsForCHW(chw);
    ArrayList<Candidate> candidates = new ArrayList<Candidate>();
    // iterate through all fields on the form, seeing if they are mapped to patient identifying
    // fields
    // e.g. Birthdate, Name, and Patient ID
    for (Patient patient : patients) {
      candidates.add(new Candidate(patient));
    }
    List<MedicFormFieldResponse> responses = response.getResponses();
    try {
      responses.get(0).getDateSubmitted();
    } catch (Exception e) {
      responses = formFieldResponseDao.getResponsesForFormResponse(response);
    }

    for (MedicFormFieldResponse fieldResponse : responses) {
      // if it is mapped to a namefield, score it as a name
      if (fieldResponse.getField().getMapping() == PatientFieldMapping.NAMEFIELD) {
        for (Candidate c : candidates) {
          c.setNameScore(
              getNameDistance(c.getName().toLowerCase(), fieldResponse.getValue().toLowerCase()));
        }
        // if it is mapped to an id field, score it as an ID
      } else if (fieldResponse.getField().getMapping() == PatientFieldMapping.IDFIELD) {
        for (Candidate c : candidates) {
          c.setIdScore(getEditDistance(c.getStringID(), fieldResponse.getValue()));
        }
        // if it is mapped as a bday field, score it as a bday
      } else if (fieldResponse.getField().getMapping() == PatientFieldMapping.BIRTHDATEFIELD) {
        for (Candidate c : candidates) {
          if (fieldResponse.getValue().length() <= 8) {
            c.setBirthdateScore(
                getEditDistance(
                    shortFormatter.format(c.getPatient().getBirthdate()),
                    fieldResponse.getValue()));
          } else {
            c.setBirthdateScore(
                getEditDistance(
                    longFormatter.format(c.getPatient().getBirthdate()), fieldResponse.getValue()));
          }
        }
      }
    }
    Collections.sort(candidates);
    return candidates.subList(0, 5);
  }