@Test
  @Transactional
  public void testRemoveContactFromEventMultipleGroups() throws Exception {

    groupService.create(group);
    groupService.addAggregation(event, group);

    Group secondGroup = new Group();
    secondGroup.setGroupName("Second Group");
    groupService.create(secondGroup);
    groupService.addAggregation(event, secondGroup);

    Contact newContact = new Contact();
    newContact.setFirstName("Fresh Contact");
    newContact.setEmail("Fresh email");
    contactService.create(newContact);

    event = eventService.findById(event.getId());
    contactService.attendEvent(newContact, event);

    newContact = contactService.findById(newContact.getId());
    contactService.unattendEvent(newContact, event);

    event = eventService.findById(event.getId());
    assertFalse(event.getAttendees().contains(newContact));

    newContact = contactService.findById(newContact.getId());
    assertFalse(newContact.getAttendedEvents().contains(event));
  }
  /**
   * 사용자그룹(tm_usergroup)에서 보여준다
   *
   * @param groupID
   * @return
   * @throws DataAccessException
   */
  public Group viewGroup(String groupID) throws DataAccessException {

    Group group = new Group();
    Map<String, Object> resultMap = null;
    String sql =
        QueryUtil.getStringQuery(
            "admin_sql", "admin.usergroup.viewgroup"); // 쿼리 프로퍼티파일의 키값에 해당되는 sql문을 읽어온다.

    // 넘겨받은 파라미터를 세팅한다.
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("groupID", groupID);

    // SQL문이 실행된다.
    try {
      resultMap = getSimpleJdbcTemplate().queryForMap(sql, param);
    } catch (EmptyResultDataAccessException e1) {
    }
    if (resultMap != null) {
      group.setGroupID((String) (resultMap.get("groupID")));
      group.setGroupName((String) (resultMap.get("groupName")));
      group.setDescription((String) (resultMap.get("description")));

    } else {
      group.setGroupID("0");
    }
    return group;
  }
  @Before
  public void setup() throws ConstraintViolation, NullDomainReference {

    createContacts();

    committee = new Committee();
    committee.setName("Committee Name");
    committeeService.create(committee);
    contactService.addContactToCommittee(first, committee);
    contactService.addContactToCommittee(second, committee);

    organization = new Organization();
    organization.setName("Organization Name");
    organizationService.create(organization);
    contactService.addContactToOrganization(first, organization);
    contactService.addContactToOrganization(second, organization);

    event = new Event();
    event.setName("Event Name");
    event.setDateHeld("2015-01-01");
    eventService.create(event);
    contactService.attendEvent(first, event);
    contactService.attendEvent(second, event);

    group = new Group();
    group.setGroupName("New AlinskyGroup");
  }
  @Test
  @Transactional
  public void testAddContactToOrganizationMultipleGroups() throws Exception {

    groupService.create(group);
    groupService.addAggregation(organization, group);

    Group secondGroup = new Group();
    secondGroup.setGroupName("Second Group");
    groupService.create(secondGroup);
    groupService.addAggregation(organization, secondGroup);

    Contact newContact = new Contact();
    newContact.setFirstName("Fresh Contact");
    newContact.setEmail("Fresh email");
    contactService.create(newContact);

    contactService.addContactToOrganization(newContact, organization);

    newContact = contactService.findById(newContact.getId());
    assertTrue(newContact.getOrganizations().contains(organization));

    group = groupService.findById(group.getId());
    assertTrue(group.getAggregations().contains(organization));

    secondGroup = groupService.findById(secondGroup.getId());
    assertTrue(secondGroup.getAggregations().contains(organization));

    organization = organizationService.findById(organization.getId());
    assertTrue(organization.getMembers().contains(newContact));
  }
 private void addGroups() throws IOException {
   RandomAccessFile f = new RandomAccessFile("randomGroup.csv", "r");
   String dataString = null;
   while ((dataString = f.readLine()) != null) {
     String[] data = dataString.split(";");
     Group insert = new Group();
     if (data[0].length() < 45) {
       insert.setGroupName(data[0]);
     } else {
       insert.setGroupName(data[0].substring(0, 44));
     }
     System.out.println(insert);
     try {
       groupDAO.insertGroup(insert);
     } catch (GroupExistsException e) {
       e.printStackTrace();
     }
   }
   f.close();
 }
  @Test
  @Transactional
  public void testAddContactToMultipleGroupsMultipleConstituents() throws Exception {

    groupService.create(group);
    groupService.addAggregation(committee, group);
    groupService.addAggregation(event, group);

    Group secondGroup = new Group();
    secondGroup.setGroupName("Second Group");
    groupService.create(secondGroup);
    groupService.addAggregation(committee, secondGroup);
    groupService.addAggregation(event, secondGroup);

    Contact contact = new Contact();
    contact.setFirstName("Test Contact");
    contact.setEmail("*****@*****.**");
    contactService.create(contact);

    contactService.addContactToCommittee(contact, committee);
    contactService.attendEvent(contact, event);
    contactService.addToGroup(contact, group);
    contactService.addToGroup(contact, secondGroup);

    contact = contactService.findById(contact.getId());
    group = groupService.findById(group.getId());
    secondGroup = groupService.findById(secondGroup.getId());
    event = eventService.findById(event.getId());
    committee = committeeService.findById(committee.getId());

    assertTrue(contact.getGroups().contains(group));
    assertTrue(contact.getGroups().contains(secondGroup));
    assertTrue(contact.getCommittees().contains(committee));
    assertTrue(contact.getAttendedEvents().contains(event));

    assertTrue(event.getAttendees().contains(contact));
    assertTrue(event.getGroups().contains(group));
    assertTrue(event.getGroups().contains(secondGroup));

    assertTrue(committee.getMembers().contains(contact));
    assertTrue(committee.getGroups().contains(group));
    assertTrue(committee.getGroups().contains(secondGroup));

    assertTrue(group.getTopLevelMembers().contains(contact));
    assertTrue(group.getAggregations().contains(committee));
    assertTrue(group.getAggregations().contains(event));

    assertTrue(secondGroup.getTopLevelMembers().contains(contact));
    assertTrue(secondGroup.getAggregations().contains(committee));
    assertTrue(secondGroup.getAggregations().contains(event));
  }
  @Test
  @Transactional
  public void testAddEventMultipleGroups() throws Exception {

    groupService.create(group);
    groupService.addAggregation(event, group);
    groupService.addAggregation(committee, group);

    Group secondGroup = new Group();
    secondGroup.setGroupName("Second Group");
    groupService.create(secondGroup);
    groupService.addAggregation(event, secondGroup);
    groupService.addAggregation(organization, secondGroup);

    event = eventService.findById(event.getId());
    assertTrue(event.getGroups().contains(group));
    assertTrue(event.getGroups().contains(secondGroup));

    group = groupService.findById(group.getId());
    assertTrue(group.getAggregations().contains(event));

    secondGroup = groupService.findById(secondGroup.getId());
    assertTrue(secondGroup.getAggregations().contains(event));
  }
  /**
   * Displays a given Research Group page for a HTTP Get, or creates a new Group for a HTTP Post
   *
   * <p>- Requires a cookie for the session user - Requires a groupId request parameter for a GET -
   * Requires a groupName, description, createdByUserId request parameters for a POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void researchgroupAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<String, Object>();
    viewData.put("title", "Research Group");

    if (req.getMethod() == HttpMethod.Get) {
      // Load group data into Map
      GroupManager gm = new GroupManager();
      int groupId = Integer.parseInt(req.getParameter("groupId"));
      Group group = gm.get(groupId);

      if (group != null) {
        // Load Group into map
        viewData.put("group", group);

        // Load group members into Map
        List<String> groupMembers = gm.getGroupMembers(groupId);
        viewData.put("groupMembers", groupMembers);

        // Load meetings into map
        MeetingManager meetMan = new MeetingManager();
        List<Meeting> groupMeetings = meetMan.getGroupMeetings(groupId);
        viewData.put("groupMeetings", groupMeetings);

        // Load Document Data into Map
        DocumentManager docMan = new DocumentManager();
        List<Document> groupDocuments = docMan.getGroupDocuments(groupId);
        viewData.put("groupDocuments", groupDocuments);

        // Load discussion threads
        DiscussionManager dm = new DiscussionManager();
        viewData.put("groupDiscussions", dm.getThreads(groupId));

        // Check if the user is a member
        boolean isMember = false;
        HttpSession session = req.getSession();
        Session userSession = (Session) session.getAttribute("userSession");
        User user = userSession.getUser();

        for (Group g : gm.getAllGroups(user.getId())) {
          if (g.getId() == group.getId()) {
            isMember = true;
            break;
          }
        }

        viewData.put("notMember", !isMember);

        // View group page.
        view(req, res, "/views/group/ResearchGroup.jsp", viewData);

      } else {
        httpNotFound(req, res);
      }

    } else if (req.getMethod() == HttpMethod.Post) {
      // Create Group

      // Get data from parameters
      String groupName = req.getParameter("groupName");
      String description = req.getParameter("description");
      int adminId = Integer.parseInt(req.getParameter("createdByUserId"));

      // Create the Group
      GroupManager groupMan = new GroupManager();
      Group group = new Group();
      group.setGroupName(groupName);
      group.setDescription(description);
      group.setCoordinatorId(adminId);
      // Create the mapping
      groupMan.createGroup(group);
      int groupId = groupMan.getIdFor(group);
      groupMan.createMapping(groupId, adminId);

      group.setId(groupId);

      // Update the User Session to show new group
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      User admin = userSession.getUser();
      admin.getGroups().add(group);

      // Show the Group Page
      viewData.put("groupName", group.getGroupName());
      List<String> groupMembers = groupMan.getGroupMembers(groupId);
      viewData.put("groupMembers", groupMembers);

      view(req, res, "/views/group/ResearchGroup.jsp", viewData);
    }
  }
    @Override
    protected void onPostExecute(String[] result) {

      // initialize error boolean to pass through to calling method
      boolean taskSuccess = false;

      if (result != null && result[1].length() > 0) {
        switch (result[0]) {
          case USERREGISTER:
          case USERLOGIN:
            try {
              JSONArray jsonArray = new JSONArray(result[1]);

              // Debugging
              // Log.d("oma", "UserObject: " + result[1]);

              JSONObject jsonObject = jsonArray.getJSONObject(0);

              User user = new User();

              user.setUser_id(jsonObject.getInt("kayttaja_id"));
              user.setUserName(jsonObject.getString("nimimerkki"));
              user.setCreationTime(jsonObject.getString("perustamisaika"));
              user.setLastSeen(jsonObject.getString("viimeksi_nahty"));
              user.setGroup_id(0);

              // TODO Servertime needs implementation on the server side
              // How is this different from last seen?
              // user.setServerTime(jsonObject.getString("userservertime"));

              Log.d("oma", "Logged in as: " + user.getUserName());

              if (result[0].equals(USERLOGIN)) {
                updateUser(user);
              } else {
                addNewUser(user);
              }

              currentUser = user;
              taskSuccess = true;

            } catch (Exception e) {
              Log.d("oma", "onPostExecute USERREGISTER error: " + e);
            }
            break;
          case GROUPGETALL:
            try {
              JSONArray jsonArray = new JSONArray(result[1]);

              // Go through the JSONarray, extract the JSONobjects from it
              // and create Group objects from them and add them to group table
              for (int i = 0; i < jsonArray.length(); i++) {
                Group group = new Group();

                JSONObject jsonObject = jsonArray.getJSONObject(i);

                group.setGroup_id(jsonObject.getInt("ryhma_id"));
                group.setCreator(jsonObject.getInt("luoja"));
                group.setGroupName(jsonObject.getString("nimi"));
                group.setGroupPassword(jsonObject.getString("salasana"));
                group.setCreationTime(jsonObject.getString("perustamisaika"));

                addGroup(group);
                currentGroups.add(group);
                taskSuccess = true;

                Log.d("oma", "Added group: " + group.toString());
              } // for

            } // try
            catch (Exception e) {
              Log.d("oma", "tuli virhe " + e.toString());
            }
            break;
          case GROUPCREATE:
            try {
              JSONObject jsonObject = new JSONObject(result[1]);
              DatabaseHandler db = new DatabaseHandler(context);

              Group group = new Group();

              group.setGroup_id(jsonObject.getInt("groupid"));
              group.setGroupName(jsonObject.getString("groupname"));
              group.setCreator(jsonObject.getInt("creatorid"));
              group.setCreationTime(jsonObject.getString("groupcreationtime"));

              db.newGroup(group);
              currentUser.setGroup_id(group.getGroup_id());
              taskSuccess = true;

            } catch (Exception e) {
              Log.d("oma", "onPostExecute GROUPCREATE error: " + e);
            }
            break;
          case GROUPJOIN:
            break;
          case LOCATIONREPORT:
            // try to parse a JSONarray from the response
            try {
              JSONArray jsonArray = new JSONArray(result[1]);

              for (int i = 0; i < jsonArray.length(); i++) {
                User user = new User();
                Location location = new Location();
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                location.setLocation_id(jsonObject.getInt("sijainti_id"));
                location.setLat(jsonObject.getDouble("lat"));
                location.setLng(jsonObject.getDouble("lng"));
                location.setTimestamp(jsonObject.getString("aikaleima"));
                location.setUser_id(jsonObject.getInt("kayttaja_id"));
                location.setGroup_id(jsonObject.getInt("ryhma_id"));

                user.setUser_id(jsonObject.getInt("kayttaja_id"));
                user.setUserName(jsonObject.getString("nimimerkki"));
                user.setLastSeen(jsonObject.getString("viimeksi_nahty"));
                user.setGroup_id(jsonObject.getInt("ryhma_id"));
                user.setServerTime(jsonObject.getString("serveriaika"));
                taskSuccess = true;
              }
            } catch (Exception e) {
              Log.d("oma", "onPostExecute LOCATIONREPORT error: " + e);
            }
            break;
        } // switch for different connection descriptions
      } // if for checking if result length is 0 or it is null

      // Pass taskSuccess boolean to calling method in case some exception gets thrown
      local.onTaskComplete(taskSuccess);
    } // onPostExecute