private CouchDbConnector getCouch() throws IOException {
    final HttpClient httpClient = new StdHttpClient.Builder().url("http://localhost:5984").build();

    final CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
    final CouchDbConnector db = new StdCouchDbConnector("hybriddb", dbInstance);
    db.createDatabaseIfNotExists();
    return db;
  }
 @Override
 public void saveOrUpdatePlayer(IPlayer player) {
   if (containsPlayerById(player.getId())) {
     db.update(copyPlayer(player));
   } else {
     db.create(String.valueOf(player.getId()), copyPlayer(player));
   }
 }
 @RequestMapping("/admin-add-invitee")
 public String addInvitee(
     @RequestParam(required = false, value = "group") String groupId,
     @ModelAttribute Invitee invitee) {
   InvitationGroup group = db.get(InvitationGroup.class, groupId);
   group.addInvitee(invitee);
   db.update(group);
   return "redirect:admin?view=" + group.getId();
 }
  private void addComment(String itemNumber, String comment) {

    CouchDbConnector dbc = _db.createConnector(dbname, true);
    Map<String, String> doc = new HashMap<String, String>();
    doc.put("_id", UUID.randomUUID().toString());
    doc.put("itemNumber", itemNumber);
    doc.put("comment", comment);
    dbc.create(doc);
  }
  @RequestMapping("/bulk-invite")
  public String bulkInvite(@RequestParam("invitees") MultipartFile invitees) throws Exception {
    if (!invitees.isEmpty()) {
      Map<String, InvitationGroup> groupsByName = new HashMap<String, InvitationGroup>();
      ViewQuery query =
          new ViewQuery().designDocId("_design/groups").viewName("groups").includeDocs(true);
      for (InvitationGroup existing : db.queryView(query, InvitationGroup.class)) {
        groupsByName.put(standardizeName(existing.getGroupName()), existing);
      }

      BufferedReader r = new BufferedReader(new InputStreamReader(invitees.getInputStream()));
      for (String row = r.readLine(); row != null; row = r.readLine()) {
        String[] cells = row.split(",");
        if (cells[0].equals("Group Name")) continue;
        if (!(StringUtils.hasText(cells[0])
            && StringUtils.hasText(cells[1])
            && StringUtils.hasText(cells[2]))) throw new RuntimeException("Malformed row: " + row);
        if (cells[0].startsWith("\"") && cells[0].endsWith("\""))
          cells[0] = cells[0].substring(1, cells[0].length() - 1);
        InvitationGroup group = groupsByName.get(cells[0].trim());
        if (group == null) {
          group = new InvitationGroup();
          group.setGroupName(cells[0].trim());
          throw new RuntimeException("Only updates now! Couldn't find " + cells[0]);
        }
        group.setEmail(cells[1].trim());
        group.setLanguage(cells[2].trim());
        group.setInvitedTours(StringUtils.hasText(cells[3]));
        group.setInvitedRehearsal(StringUtils.hasText(cells[4]));
        if (group.getInvitees() != null) group.getInvitees().clear();
        for (int i = 5; i < cells.length; ++i) {
          if (StringUtils.hasText(cells[i].trim())) {
            Invitee invitee = new Invitee();
            invitee.setName(cells[i].trim());
            group.addInvitee(invitee);
          }
        }
        if (group.getInvitees().size() == 0)
          throw new RuntimeException("Group with no invitees: " + row);
        if (group.getId() == null) {
          group.setId(randomId());
          db.create(group);
          System.out.println("Created " + group.getGroupName());
        } else {
          db.update(group);
          System.out.println("Updated " + group.getId() + " " + group.getGroupName());
        }
      }
    }
    return "redirect:admin";
  }
 @Bean
 public CouchDbConnector createConnector() throws MalformedURLException {
   HttpClient httpClient =
       new StdHttpClient.Builder()
           .url(couchDBConfig.getUrl())
           .username(couchDBConfig.getUser())
           .password(couchDBConfig.getPassword())
           .build();
   CouchDbInstance couchDbInstance = new StdCouchDbInstance(httpClient);
   CouchDbConnector connector =
       new StdCouchDbConnector(couchDBConfig.getDataBase(), couchDbInstance);
   connector.createDatabaseIfNotExists();
   return connector;
 }
  @RequestMapping("/sendingmail")
  public String sendingMail(
      HttpSession session,
      Model model,
      @RequestParam(required = false, value = "sendNum") Integer sendNum)
      throws Exception {
    List<String> codesLeft = (List<String>) session.getAttribute("wedding-mail-to");
    String subject = (String) session.getAttribute("wedding-mail-subject");
    String body = (String) session.getAttribute("wedding-mail-body");
    if (sendNum != null) {
      for (int i = 0; i < sendNum; ++i) {
        if (codesLeft.size() == 0) break;
        String groupId = codesLeft.remove(0);
        InvitationGroup group = db.get(InvitationGroup.class, groupId);
        String msgBody = body.replaceAll("\\$code", group.getId());
        msgBody = msgBody.replaceAll("\\$name", group.getGroupName());
        sendEmail(group.getEmail(), subject, msgBody);
      }
    }

    if (codesLeft.size() == 0) {
      return "redirect:/admin";
    } else {
      model.addAttribute("subject", subject);
      model.addAttribute("body", body);
      model.addAttribute("numLeft", codesLeft.size());
      return null;
    }
  }
  private CouchDbPlayer copyPlayer(IPlayer player) {
    if (player == null) {
      return null;
    }

    int playerId = player.getId();
    CouchDbPlayer persistentPlayer;
    if (containsPlayerById(playerId)) {
      // The Object already exists within the session
      persistentPlayer = (CouchDbPlayer) db.find(CouchDbPlayer.class, String.valueOf(playerId));
    } else {
      // A new database entry
      persistentPlayer = new CouchDbPlayer();
    }

    persistentPlayer.setId(String.valueOf(playerId));
    persistentPlayer.setName(player.getName());
    persistentPlayer.setWinsTotal(player.getWinsTotal());
    persistentPlayer.setLossesTotal(player.getLossesTotal());

    //		System.out.println(player.getResults());

    List<IPersistentResult> list = new ArrayList<>();
    for (IResult r : player.getResults()) {
      list.add(new CouchDbResult(r.getEnemyId(), r.getWins(), r.getLosses()));
    }
    persistentPlayer.setResults(list);
    return persistentPlayer;
  }
 @Override
 public IPlayer getPlayerById(int id) {
   CouchDbPlayer p = db.find(CouchDbPlayer.class, String.valueOf(id));
   if (p == null) {
     return null;
   }
   return copyPlayer(p);
 }
 @GET
 @Produces(MediaType.TEXT_HTML)
 public Viewable get() {
   Map<String, String> model = new HashMap<String, String>();
   long docCount = connector.getDbInfo().getDocCount();
   // #statements = docCount - number of design-documents
   model.put("statementCount", Long.toString(docCount - 1));
   return new Viewable("/welcome.jsp", model);
 }
  private JSONArray getComments(String itemNumber) {
    JSONArray returnArray = new JSONArray();
    CouchDbConnector dbc = _db.createConnector(dbname, true);

    Map<String, String> doc = new HashMap<String, String>();

    ViewQuery query = new ViewQuery().allDocs().includeDocs(true);
    List<Map> result = dbc.queryView(query, Map.class);
    JSONArray jsonresult = new JSONArray();
    for (Map element : result) {
      JSONObject obj = new JSONObject();
      obj.putAll(element);
      if (itemNumber == null || obj.get("itemNumber").equals(itemNumber)) jsonresult.add(obj);
    }

    System.out.println(jsonresult.toString());

    return jsonresult;
  }
 @RequestMapping("/admin-add-group")
 public String addGroup(
     @ModelAttribute InvitationGroup group, @RequestParam("groupLanguage") String language) {
   if (StringUtils.hasText(group.getGroupName())) {
     group.setId(randomId());
     group.setLanguage(language);
     db.create(group);
   }
   return "redirect:admin";
 }
  @Override
  public List<IPlayer> listAllPlayers() {
    List<IPlayer> players = new ArrayList<>();
    ViewQuery query = new ViewQuery().allDocs();
    ViewResult vr = db.queryView(query);

    for (Row r : vr.getRows()) {
      players.add(getPlayerById(Integer.parseInt(r.getId())));
    }
    return players;
  }
 @RequestMapping("/saidNo")
 @ResponseBody
 public String saidNo(@RequestParam("codes") String codes) throws Exception {
   StringBuilder log = new StringBuilder();
   for (StringTokenizer st = new StringTokenizer(codes, ", "); st.hasMoreTokens(); ) {
     String groupId = st.nextToken();
     InvitationGroup group = db.get(InvitationGroup.class, groupId);
     for (Invitee inv : group.getInvitees()) {
       inv.setAttendingWednesday(false);
       inv.setAttendingThursday(false);
       inv.setAttendingFriday(false);
       inv.setAttendingRehearsal(false);
       inv.setAttendingCeremony(false);
       inv.setAttendingFiesta(false);
     }
     db.update(group);
     log.append("Updated " + group.getGroupName() + " \n<br/>");
   }
   return log.toString();
 }
 @RequestMapping("/fixRehearsal")
 public void fixRehearsal() throws Exception {
   ViewQuery query =
       new ViewQuery().designDocId("_design/groups").viewName("groups").includeDocs(true);
   List<InvitationGroup> groups = db.queryView(query, InvitationGroup.class);
   for (InvitationGroup group : groups) {
     boolean changed = false;
     for (Invitee inv : group.getInvitees()) {
       if (inv.getAttendingFriday() != null && inv.getAttendingFriday()) {
         if (inv.getAttendingRehearsal() == null || !inv.getAttendingRehearsal()) {
           inv.setAttendingRehearsal(true);
           changed = true;
         }
       }
     }
     if (group.isInvitedTours() && !group.isInvitedRehearsal()) {
       group.setInvitedRehearsal(true);
       changed = true;
     } else {
       System.out.println("Not invited to rehearsal: " + group.getGroupName());
     }
     if (changed) db.update(group);
   }
 }
 @SuppressWarnings("unchecked")
 @Test
 public void testSortingMessages() {
   OutboundVoiceMessageDao dao = new OutboundVoiceMessageDaoImpl(db);
   when(db.queryView(any(ViewQuery.class), any(Class.class))).thenReturn(messages);
   ArrayList<OutboundVoiceMessage> msgs =
       (ArrayList<OutboundVoiceMessage>) dao.getPendingMessages(PARTY_ID);
   for (int i = 1; i < msgs.size(); i++) {
     // check for creation date order
     assertTrue(msgs.get(i - 1).getCreationTime().compareTo(msgs.get(i).getCreationTime()) >= 0);
     // if creation date is the same, check for priority order
     assertTrue(
         (msgs.get(i - 1).getCreationTime().compareTo(msgs.get(i).getCreationTime()) != 0)
             || (msgs.get(i - 1)
                     .getVoiceMessageType()
                     .getPriority()
                     .compareTo(msgs.get(i).getVoiceMessageType().getPriority())
                 >= 0));
     //			System.out.println(msgs.get(i));
   }
 }
  @RequestMapping("/admin")
  public String admin(
      HttpSession session,
      @RequestParam(required = false, value = "password") String password,
      @RequestParam(required = false, value = "view") String groupId,
      @RequestParam(required = false, value = "item") String itemId,
      Model model)
      throws Exception {

    if (password != null) session.setAttribute("campodejazayeri-admin-password", password);
    if (!"PASSWORD".equals(session.getAttribute("campodejazayeri-admin-password"))) {
      return "admin-authenticate";
    }

    ViewQuery query =
        new ViewQuery().designDocId("_design/groups").viewName("groups").includeDocs(true);
    List<InvitationGroup> groups = db.queryView(query, InvitationGroup.class);
    model.addAttribute("groups", groups);

    List<String> attendees = new ArrayList<String>();
    List<String> notAttending = new ArrayList<String>();
    for (InvitationGroup g : groups) {
      for (Invitee inv : g.getAttending()) attendees.add(g.getGroupName() + ": " + inv.getName());
      for (Invitee inv : g.getSaidNo()) notAttending.add(g.getGroupName() + ": " + inv.getName());
    }
    model.addAttribute("numAttendees", attendees.size());
    model.addAttribute("attendees", attendees);
    model.addAttribute("numNotAttending", notAttending.size());
    model.addAttribute("notAttending", notAttending);

    List<String> attendingWednesday = new ArrayList<String>();
    List<String> attendingThursday = new ArrayList<String>();
    List<String> attendingFriday = new ArrayList<String>();
    List<String> attendingRehearsal = new ArrayList<String>();
    List<String> attendingCeremony = new ArrayList<String>();
    List<String> attendingFiesta = new ArrayList<String>();

    for (InvitationGroup g : groups) {
      for (Invitee i : g.getInvitees()) {
        if (test(i.getAttendingWednesday())) attendingWednesday.add(format(g, i));
        if (test(i.getAttendingThursday())) attendingThursday.add(format(g, i));
        if (test(i.getAttendingFriday())) attendingFriday.add(format(g, i));
        if (test(i.getAttendingRehearsal())) attendingRehearsal.add(format(g, i));
        if (test(i.getAttendingCeremony())) attendingCeremony.add(format(g, i));
        if (test(i.getAttendingFiesta())) attendingFiesta.add(format(g, i));
      }
    }

    model.addAttribute("attendingWednesday", attendingWednesday);
    model.addAttribute("attendingThursday", attendingThursday);
    model.addAttribute("attendingFriday", attendingFriday);
    model.addAttribute("attendingRehearsal", attendingRehearsal);
    model.addAttribute("attendingCeremony", attendingCeremony);
    model.addAttribute("attendingFiesta", attendingFiesta);

    List<String> englishGroups = new ArrayList<String>();
    List<String> spanishGroups = new ArrayList<String>();
    for (InvitationGroup g : groups) {
      if ("en".equals(g.getLanguage()) && g.getAttending().size() > 0) {
        englishGroups.add(g.getId() + " - " + g.getGroupName());
      } else if ("es".equals(g.getLanguage()) && g.getAttending().size() > 0) {
        spanishGroups.add(g.getId() + " - " + g.getGroupName());
      }
    }
    model.addAttribute("englishComing", englishGroups);
    model.addAttribute("spanishComing", spanishGroups);

    if (groupId != null) {
      InvitationGroup group = db.get(InvitationGroup.class, groupId);
      model.addAttribute("group", group);
    }

    return null;
  }
  @RequestMapping("/sendmail")
  public String sendMail(
      @RequestParam(value = "emailLanguage", required = false) String language,
      @RequestParam(value = "whichPeople", required = false) String whichPeople,
      @RequestParam(value = "codes", required = false) String whichCodes,
      @RequestParam("subject") String subject,
      @RequestParam("body") String body,
      HttpSession session) {
    if (!StringUtils.hasText(whichCodes)
        && !(StringUtils.hasText(language) && StringUtils.hasText(whichPeople))) {
      throw new RuntimeException("Must give codes or language & which");
    }
    if (!StringUtils.hasText(subject)) throw new RuntimeException("Missing Subject");
    if (!StringUtils.hasText(body)) throw new RuntimeException("Missing Body");
    if (body.indexOf("$code") < 0 || body.indexOf("$name") < 0)
      throw new RuntimeException("Must have $code and $name");

    if (!"en".equals(language) && !"es".equals(language))
      throw new RuntimeException("Must specify language");

    List<String> codes = new LinkedList<String>();

    if (StringUtils.hasText(whichCodes)) {
      for (StringTokenizer st = new StringTokenizer(whichCodes, ", "); st.hasMoreTokens(); ) {
        String groupId = st.nextToken();
        InvitationGroup group = db.get(InvitationGroup.class, groupId);
        if (group != null) codes.add(groupId);
      }

    } else {
      ViewQuery query =
          new ViewQuery().designDocId("_design/groups").viewName("groups").includeDocs(true);
      List<InvitationGroup> groups = db.queryView(query, InvitationGroup.class);
      for (InvitationGroup group : groups) {
        if (!whichPeople.equals("all")) {
          boolean anyYes = false;
          boolean anyNo = false;
          boolean anyNotYet = false;
          for (Invitee inv : group.getInvitees()) {
            Boolean coming = inv.getAttendingCeremony();
            if (coming == null) {
              anyNotYet = true;
            } else if (coming) {
              anyYes = true;
            } else {
              anyNo = true;
            }
          }
          boolean treatAsYes = anyYes && !anyNotYet;

          if (whichPeople.equals("notYet") && !anyNotYet) {
            continue;
          } else if (whichPeople.equals("yes") && !treatAsYes) {
            continue;
          }
        }
        if (group.getLanguage() == null)
          throw new RuntimeException(
              "Group " + group.getId() + " (" + group.getGroupName() + ") doesn't have a language");
        if (group.getLanguage().equals(language)) codes.add(group.getId());
      }

      // codes.add("4659");
    }

    session.setAttribute("wedding-mail-to", codes);
    session.setAttribute("wedding-mail-subject", subject);
    session.setAttribute("wedding-mail-body", body);

    return "redirect:sendingmail";
  }