Ejemplo n.º 1
0
  @Test
  public void testLoadTwoRootObjectsWithNoType() throws JsonProcessingException {
    JsonNode data =
        mapper
            .createArrayNode()
            .add(
                mapper.createObjectNode().put("userId", "1").put("name", "Paul").put("sex", "MALE"))
            .add(
                mapper
                    .createObjectNode()
                    .put("userId", "2")
                    .put("name", "Anna")
                    .put("sex", "FEMALE"));

    Resource result =
        mapper
            .reader()
            .withAttribute(RESOURCE_SET, resourceSet)
            .withAttribute(ROOT_ELEMENT, ModelPackage.Literals.USER)
            .treeToValue(data, Resource.class);

    assertNotNull(result);
    assertEquals(2, result.getContents().size());

    User first = (User) result.getContents().get(0);
    User second = (User) result.getContents().get(1);

    assertEquals("1", first.getUserId());
    assertEquals("Paul", first.getName());
    assertEquals("MALE", first.getSex().getLiteral());

    assertEquals("2", second.getUserId());
    assertEquals("Anna", second.getName());
    assertEquals("FEMALE", second.getSex().getLiteral());
  }
Ejemplo n.º 2
0
  public void add(User u) {
    u.addMembership(this.key, this);

    // add addedStates and remove removedStates to/from this users permissionmap
    int pMap = u.getPermissionMap();
    pMap = pMap | addedStates;
    pMap = pMap - (pMap & removedStates);
    Server.log(
        "[" + this.key + "]",
        "setting user-state-map for user " + u.getName() + " to value " + pMap,
        Server.MSG_AUTH,
        Server.LVL_VERY_VERBOSE);
    u.setPermission(pMap);

    int dpMap = u.getDefaultMembershipPermissionMap();
    dpMap = dpMap | addedDefaultStates;
    dpMap = dpMap - (dpMap & removedDefaultStates);
    Server.log(
        "[" + this.key + "]",
        "setting user-defaultmembership-state-map for user " + u.getName() + " to value " + dpMap,
        Server.MSG_AUTH,
        Server.LVL_VERY_VERBOSE);
    u.setDefaultMembershipPermission(dpMap);

    if (dpMap > 0 && dpMap != pMap) {
      Server.log(
          "[" + this.key + "]",
          "setting user-defaultstate-map for user " + u.getName() + " to value " + dpMap,
          Server.MSG_AUTH,
          Server.LVL_VERY_VERBOSE);
      u.setDefaultPermissionMap(dpMap);
    }
    if (mayUseTemplateset != null) u.mayUseTemplateset(mayUseTemplateset);
  }
 String getThreadId(User user) {
   String id = myUser2Thread.get(user.getName());
   if (id == null) {
     id = myThreadIdPrefix + myCurrentThreadId++;
     myUser2Thread.put(user.getName(), id);
   }
   return id;
 }
Ejemplo n.º 4
0
  @Override
  public int compare(WritableComparable o1, WritableComparable o2) {

    User p1 = (User) o1;
    User p2 = (User) o2;

    return p1.getName().compareTo(p2.getName());
  }
Ejemplo n.º 5
0
 @Override
 public User modify(User user) {
   System.out.println("ԭ�û���:" + user.getName() + "������:" + user.getPassword());
   user.setName("admin");
   user.setPassword("111111");
   System.out.println("�޸ĺ���û���:" + user.getName() + "������:" + user.getPassword());
   return user;
 }
Ejemplo n.º 6
0
  public static void main(String[] args) {
    List<User> userArrayList = new ArrayList<User>();
    userArrayList.add(new User("1", "First"));
    userArrayList.add(new User("2", "Second"));
    userArrayList.add(new User("3", "Third"));
    userArrayList.add(new User("1", "First"));

    List<User> userLinkedList = new LinkedList<User>();
    userLinkedList.add(new User("1", "First"));
    userLinkedList.add(new User("2", "Second"));
    userLinkedList.add(new User("3", "Third"));
    userLinkedList.add(new User("1", "First"));

    Set<User> userHashSet = new HashSet<User>();
    userHashSet.add(new User("1", "First"));
    userHashSet.add(new User("2", "Second"));
    userHashSet.add(new User("3", "Third"));
    userHashSet.add(new User("1", "First"));

    Map<String, User> userHashMap = new HashMap<String, User>();
    userHashMap.put("1", new User("1", "First"));
    userHashMap.put("2", new User("2", "Second"));
    userHashMap.put("3", new User("3", "Third"));
    userHashMap.put("1", new User("1", "First"));

    // ArrayList includes internal iterator
    System.out.println("=================ArrayList=================");
    for (User user : userArrayList) {
      System.out.println(user);
      System.out.println("User " + user.getName() + " HashCode = " + user.hashCode());
    }
    System.out.println("======================================================");

    System.out.println("====================LinkedList================");
    // ArrayList includes internal iterator
    for (User user : userLinkedList) {
      System.out.println(user);
      System.out.println("User " + user.getName() + " HashCode = " + user.hashCode());
    }
    System.out.println("======================================================");

    System.out.println("====================HashSet================");
    for (User user : userHashSet) {
      System.out.println(user);
      System.out.println("User " + user.getName() + " HashCode = " + user.hashCode());
    }
    System.out.println("======================================================");

    System.out.println("====================HashMap================");
    // HashMap doesn't include internal iterator. Should use EntrySet()
    for (Map.Entry<String, User> user : userHashMap.entrySet()) {
      System.out.println(user);
      System.out.println(
          "User " + user.getValue().getName() + " HashCode = " + user.getValue().hashCode());
    }

    System.out.println("======================================================");
  }
  public static void main(String[] args) {
    User person = new User();

    person.setName("Name: ");
    person.setAge("Age: 1 - 100", 1, 100);
    person.setHeight("Height: 36 - 92", 36, 92);
    person.setWeight("Weight: 80 - 400", 80, 400);
    person.setFavNumber("Favorite Numner: 0 - 1", 0, 1);

    System.out.println("Name:\t" + person.getName());
    System.out.println("Age:\t" + person.getAge());
    System.out.println("Height:\t" + person.getHeight());
    System.out.println("Weight:\t" + person.getWeight());
    System.out.println("Number:\t" + person.getFavNumber());

    // get a filename
    String filename = (System.getProperty("user.dir") + File.separatorChar + "file2015Oct.txt");
    // write to a file
    PrintWriter writer = null;
    try {
      writer = new PrintWriter(new File(filename));
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    writer.println(person.getName());
    writer.println(person.getAge());
    writer.println(person.getHeight());
    writer.println(person.getWeight());
    writer.println(person.getFavNumber());
    writer.close();

    // read a file
    // This will reference one line at a time
    String line = null;

    try {
      // FileReader reads text files in the default encoding.
      FileReader fileReader = new FileReader(filename);

      // Always wrap FileReader in BufferedReader.
      BufferedReader bufferedReader = new BufferedReader(fileReader);

      while ((line = bufferedReader.readLine()) != null) {
        System.out.println(line);
      }

      // Always close files.
      bufferedReader.close();
    } catch (FileNotFoundException ex) {
      System.out.println("Unable to open file '" + filename + "'");
    } catch (IOException ex) {
      System.out.println("Error reading file '" + filename + "'");
      // Or we could just do this:
      // ex.printStackTrace();
    }
  }
 private void updateIsIDEtalkClient(String jabberId, User user) {
   if (getResource(jabberId)
       .toLowerCase()
       .startsWith(JabberFacade.IDETALK_RESOURCE.toLowerCase())) {
     myIDEtalkUsers.add(user.getName());
   } else {
     myIDEtalkUsers.remove(user.getName());
   }
 }
Ejemplo n.º 9
0
 public Message process(User user) throws Exception {
   if (!StringUtils.hasText(user.getName())) {
     throw new RuntimeException("The user name is required!");
   }
   Message m = new Message();
   m.setUser(user);
   m.setContent("Hello " + user.getName() + ",please pay promptly at end of this month.");
   return m;
 }
Ejemplo n.º 10
0
 public static void testUpdateAndFind() {
   User user = new User();
   user = getSession().insert(user);
   user.setName("name12");
   getSession().update(user);
   User user1 = getSession().find(User.class, user.getId());
   System.out.println(user1.getId() == user.getId());
   System.out.println(user1.getName().equals(user.getName()));
   System.out.println(user1.getAge() == user.getAge());
   System.out.println(user.getId());
 }
Ejemplo n.º 11
0
  /** Save user data. Store the properties. */
  public synchronized void save(User usr) throws FtpException {
    lazyInit();

    // null value check
    if (usr.getName() == null) {
      throw new NullPointerException("User name is null.");
    }
    String thisPrefix = PREFIX + usr.getName() + '.';

    // set other properties
    userDataProp.setProperty(thisPrefix + ATTR_PASSWORD, getPassword(usr));

    String home = usr.getHomeDirectory();
    if (home == null) {
      home = "/";
    }
    userDataProp.setProperty(thisPrefix + ATTR_HOME, home);
    userDataProp.setProperty(thisPrefix + ATTR_ENABLE, usr.getEnabled());
    userDataProp.setProperty(
        thisPrefix + ATTR_WRITE_PERM, usr.authorize(new WriteRequest()) != null);
    userDataProp.setProperty(thisPrefix + ATTR_MAX_IDLE_TIME, usr.getMaxIdleTime());

    TransferRateRequest transferRateRequest = new TransferRateRequest();
    transferRateRequest = (TransferRateRequest) usr.authorize(transferRateRequest);

    if (transferRateRequest != null) {
      userDataProp.setProperty(
          thisPrefix + ATTR_MAX_UPLOAD_RATE, transferRateRequest.getMaxUploadRate());
      userDataProp.setProperty(
          thisPrefix + ATTR_MAX_DOWNLOAD_RATE, transferRateRequest.getMaxDownloadRate());
    } else {
      userDataProp.remove(thisPrefix + ATTR_MAX_UPLOAD_RATE);
      userDataProp.remove(thisPrefix + ATTR_MAX_DOWNLOAD_RATE);
    }

    // request that always will succeed
    ConcurrentLoginRequest concurrentLoginRequest = new ConcurrentLoginRequest(0, 0);
    concurrentLoginRequest = (ConcurrentLoginRequest) usr.authorize(concurrentLoginRequest);

    if (concurrentLoginRequest != null) {
      userDataProp.setProperty(
          thisPrefix + ATTR_MAX_LOGIN_NUMBER, concurrentLoginRequest.getMaxConcurrentLogins());
      userDataProp.setProperty(
          thisPrefix + ATTR_MAX_LOGIN_PER_IP, concurrentLoginRequest.getMaxConcurrentLoginsPerIP());
    } else {
      userDataProp.remove(thisPrefix + ATTR_MAX_LOGIN_NUMBER);
      userDataProp.remove(thisPrefix + ATTR_MAX_LOGIN_PER_IP);
    }

    saveUserData();
  }
  @Timeout
  public void replicateUsers() throws IOException {

    logger.info("replicating users from MySQL to CouchDB");
    List<SecuredUser> users = userService.list();

    List<User> usersView = userDb.getUsersView().<User>createDocQuery().asDocs();
    Map<String, User> couchUsers = User.toMap(usersView);

    List<User> newOrModifiedUsers = new ArrayList<>();

    // Add new users to couchdb
    for (SecuredUser user : users) {
      String id = user.getId().toString();
      if (!couchUsers.containsKey(id)) {
        String mmsi = getMmsi(user);
        String name = getName(user);
        newOrModifiedUsers.add(new User(id, user.getUserName(), name, mmsi));
        logger.info("Adding user with id={} and name={}", user.getId(), name);
      } else {
        User couchUser = couchUsers.get(id);
        String mmsi = getMmsi(user);
        String name = getName(user);
        if (!Objects.equals(couchUser.getName(), name)
            || !Objects.equals(couchUser.getMmsi(), mmsi)
            || !Objects.equals(couchUser.getUserName(), user.getUserName())) {
          couchUser.setMmsi(mmsi);
          couchUser.setName(name);
          couchUser.setUserName(user.getUserName());
          logger.info("Updating user with id={} and name={}", id, name);
          newOrModifiedUsers.add(couchUser);
        }
      }
    }
    userDb.bulk(newOrModifiedUsers);

    // remove deleted users from couchdb
    Map<Long, SecuredUser> securedUsers =
        users.stream().collect(Collectors.toMap(SecuredUser::getId, u -> u));
    List<User> toRemove = new ArrayList<>();
    for (User user : couchUsers.values()) {
      if (!securedUsers.containsKey(Long.parseLong(user.getDocId()))) {
        toRemove.add(user);
        user.setDeleted();
        logger.info("Removing user with id={} and name={}", user.getDocId(), user.getName());
      }
    }

    userDb.bulk(toRemove);
  }
Ejemplo n.º 13
0
  @Test
  public void TUnitCreateAndSet() throws ClassNotFoundException, SQLException {

    dao.deleteAll();
    assertThat(dao.getCount(), is(0));

    dao.add(user1);
    assertThat(dao.getCount(), is(1));

    User user2 = dao.get(user1.getId());

    assertThat(user2.getName(), is(user1.getName()));
    assertThat(user2.getPW(), is(user1.getPW()));
  }
Ejemplo n.º 14
0
  public void onMessage(PlineMessage m, List<Message> out) {
    int slot = m.getSlot();
    // no check for server messages
    if (slot < 1 || slot > 6) {
      out.add(m);
      return;
    }

    String text = m.getText();
    float charsByLine = 70;
    int lineCount = (int) Math.ceil(text.length() / charsByLine);

    long now = System.currentTimeMillis();
    boolean isRateExceeded = false;
    for (int i = 0; i < lineCount; i++) {
      isRateExceeded = isRateExceeded || isRateExceeded(slot - 1, now);
    }

    if (slot > 0 && isRateExceeded) {
      if ((now - lastWarning) > warningPeriod * 1000) {
        User user = getChannel().getPlayer(slot);
        out.add(new PlineMessage("filter.flood.blocked", user.getName()));
        lastWarning = now;
      }
    } else {
      out.add(m);
    }
  }
Ejemplo n.º 15
0
  @Test
  public void testJSONDeserializer() throws IOException, URISyntaxException {
    User user = new User(new RestClient(null, new URI("/123/asd")), getTestJSON());
    assertEquals(user.getName(), username);
    assertEquals(user.getDisplayName(), displayName);
    assertEquals(user.getEmail(), email);
    assertEquals(user.getId(), userID);

    Map<String, String> avatars = user.getAvatarUrls();

    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=16",
        avatars.get("16x16"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=24",
        avatars.get("24x24"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=32",
        avatars.get("32x32"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=48",
        avatars.get("48x48"));

    assertTrue(user.isActive());
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    if (req.getParameter(PARAM_NAME) == null
        || req.getParameter(PARAM_NAME).trim().isEmpty()
        || req.getParameter(PARAM_PASSWORD) == null
        || req.getParameter(PARAM_PASSWORD).trim().isEmpty()) {
      req.setAttribute(PARAM_ERR_MESS, "login/pass can't be empty!");
      getServletContext().getRequestDispatcher("/login.jsp").forward(req, resp);
    } else {

      User user = new User(req.getParameter(PARAM_NAME), req.getParameter(PARAM_PASSWORD));

      String userId = UserHandler.getUserId(user);
      System.out.println(userId);
      if (userId != null) {
        req.setAttribute(PARAM_USERNAME, user.getName());
        Cookie userIdCookie = new Cookie(COOKIE_USER_ID, userId);
        userIdCookie.setMaxAge(cookieLifeTime);
        resp.addCookie(userIdCookie);
        getServletContext().getRequestDispatcher("/homepage").forward(req, resp);
      } else {
        System.out.println("Incorrect password!");
        req.setAttribute(PARAM_ERR_MESS, "Incorrect login or password");
        getServletContext().getRequestDispatcher("/login.jsp").forward(req, resp);
      }
    }
  }
Ejemplo n.º 17
0
  @Test
  public void getReporter() {
    Issue issue = new Issue(null, Utils.getTestIssue());
    assertNotNull(issue.getReporter());

    User reporter = issue.getReporter();

    assertEquals(reporter.getDisplayName(), "Joseph McCarthy");
    assertEquals(reporter.getName(), "joseph");
    assertTrue(reporter.isActive());
    assertEquals(reporter.getEmail(), "*****@*****.**");

    Map<String, String> avatars = reporter.getAvatarUrls();

    assertNotNull(avatars);
    assertEquals(avatars.size(), 4);

    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=16",
        avatars.get("16x16"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=24",
        avatars.get("24x24"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=32",
        avatars.get("32x32"));
    assertEquals(
        "https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=48",
        avatars.get("48x48"));
  }
Ejemplo n.º 18
0
  private Tweet getTweetObjectFromStatus(Status status) {

    Tweet tweet = new Tweet();
    tweet.setId(Long.toString(status.getId()));
    tweet.setText(status.getText());
    tweet.setCreatedAt(status.getCreatedAt());

    tweet.setFavCount(status.getFavoriteCount());

    User user = status.getUser();

    tweet.setUserId(user.getId());
    tweet.setUserName(user.getName());
    tweet.setUserScreenName(user.getScreenName());

    HashtagEntity[] hashtagEntities = status.getHashtagEntities();
    List<String> hashtags = new ArrayList<String>();

    for (HashtagEntity hashtagEntity : hashtagEntities) {
      hashtags.add(hashtagEntity.getText());
    }

    tweet.setHashTags(hashtags.toArray(new String[hashtags.size()]));

    GeoLocation geoLocation = status.getGeoLocation();
    if (geoLocation != null) {
      double[] coordinates = {geoLocation.getLongitude(), geoLocation.getLatitude()};
      tweet.setCoordinates(coordinates);
    }

    return tweet;
  }
Ejemplo n.º 19
0
    public ActionResult execute(User user, String[] args) {
      ActionResult res = new ActionResult();
      if (!user.isAdmin()) {
        res.setMess(new String[] {prefix + ErrorMessages.E101.Mess(null, null)});
        return res;
      }

      if (args[0].equals("")) {
        res.setMess(new String[] {prefix + ErrorMessages.E103.Mess(null, null)});
        return res;
      }

      String theUser = match(user.getMisc(), args[0]);

      if (!DCoProperties.getDS().AccountExists(AccountType.BANK, theUser)) {
        res.setMess(new String[] {prefix + ErrorMessages.E104.Mess(theUser, "Bank")});
        return res;
      }

      DCoProperties.getDS().setBalance(AccountType.BANK, theUser, 0);

      res.setMess(new String[] {prefix + AdminMessages.A301.Mess(theUser, "Account", 0)});
      log(LoggingMessages.L622.Mess(user.getName(), theUser, 0, null));
      return res;
    }
Ejemplo n.º 20
0
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String thisUsersId = req.getParameter("userId");
    if ("true".equals(req.getParameter("pingAlive"))) {
      updateLastAliveTime(thisUsersId);
    } else {
      ObjectMapper mapper = new ObjectMapper();

      ArrayNode usersArray = mapper.createArrayNode();

      for (Map.Entry<String, User> userEntry : users.entrySet()) {
        if (!thisUsersId.equals(userEntry.getKey())) {
          User user = userEntry.getValue();
          Date now = new Date();
          if ((now.getTime() - user.getLastAliveTime().getTime()) / 1000 <= 10) {
            ObjectNode userJson = mapper.createObjectNode();
            userJson.put("user_id", userEntry.getKey());
            userJson.put("user_name", user.getName());
            usersArray.add(userJson);
          }
        }
      }

      ObjectNode usersJson = mapper.createObjectNode();
      usersJson.put("opponents", usersArray);

      resp.setContentType("application/json; charset=UTF-8");
      mapper.writeValue(resp.getWriter(), usersJson);
    }
  }
Ejemplo n.º 21
0
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_test);
   view = (TextView) findViewById(R.id.textView2);
   Button button = (Button) findViewById(R.id.button2);
   editText = (EditText) findViewById(R.id.editText);
   // 获取传递的数据并显示出来
   Intent i = getIntent();
   //        Bundle bundle = i.getBundleExtra("date");
   // 设置显示数据,显示数据key,默认无数据是显示的参数
   /*view.setText(String.format("data=%s,age=%d,name=%s", bundle.getString("data"),
   bundle.getInt("age"), bundle.getString("name","name")));*/
   //
   // view.setText(bundle.getString("data")+"\n"+bundle.getInt("age")+"\n"+bundle.getString("name",
   // "name"));
   User user = i.getParcelableExtra("user");
   // 使用Parcelable传递对象,自定义序列化
   view.setText(String.format("Usrt info(name=%s,age=%d) ", user.getName(), user.getAge()));
   button.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           Intent i = new Intent();
           i.putExtra("date", editText.getText().toString());
           setResult(1, i);
           finish();
         }
       });
 }
Ejemplo n.º 22
0
  /**
   * Retrieves the <code>User</code> objects representing the database users that are visible to the
   * <code>User</code> object represented by the <code>session</code> argument.
   *
   * <p>If the <code>session</code> argument's <code>User</code> object attribute has isAdmin() true
   * (directly or by virtue of a Role), then all of the <code>User</code> objects in this collection
   * are considered visible. Otherwise, only this object's special <code>PUBLIC</code> <code>User
   * </code> object attribute and the session <code>User</code> object, if it exists in this
   * collection, are considered visible.
   *
   * <p>
   *
   * @param session The <code>Session</code> object used to determine visibility
   * @return a list of <code>User</code> objects visible to the <code>User</code> object contained
   *     by the <code>session</code> argument.
   */
  public HsqlArrayList listVisibleUsers(Session session) {

    HsqlArrayList list;
    User user;
    boolean isAdmin;
    String sessionName;
    String userName;

    list = new HsqlArrayList();
    isAdmin = session.isAdmin();
    sessionName = session.getUsername();

    if (userList == null || userList.size() == 0) {
      return list;
    }

    for (int i = 0; i < userList.size(); i++) {
      user = (User) userList.get(i);

      if (user == null) {
        continue;
      }

      userName = user.getName().getNameString();

      if (isAdmin) {
        list.add(user);
      } else if (sessionName.equals(userName)) {
        list.add(user);
      }
    }

    return list;
  }
Ejemplo n.º 23
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    Log.d(TAG, "getView");

    final User currUser = getUser(position);
    UserViewHolder holder;

    if (convertView == null) {
      Log.d(TAG, "getView: inflate view");
      convertView = mInflater.inflate(R.layout.user_item, null);

      holder = new UserViewHolder();

      holder.imgUserItem = (ImageView) convertView.findViewById(R.id.imgUserItem);

      holder.txtUserItemName = (TextView) convertView.findViewById(R.id.txtUserItemName);
      holder.txtUserItemLocation = (TextView) convertView.findViewById(R.id.txtUserItemLocation);
      holder.txtUserItemJoined = (TextView) convertView.findViewById(R.id.txtUserItemJoined);

      convertView.setTag(holder);
    } else {
      Log.d(TAG, "getView: reuse view");
      holder = (UserViewHolder) convertView.getTag();
    }

    holder.txtUserItemName.setText(currUser.getName());
    holder.txtUserItemLocation.setText(currUser.getLocation());
    holder.txtUserItemJoined.setText(currUser.getJoinedString());

    if (currUser.isPictureLoaded()) {
      holder.imgUserItem.setImageBitmap(currUser.getPicture());
    } else {
      BitmapDownloadTask task = mHolderMap.get(holder);

      if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
        Log.d(TAG, "cancel async task");
        task.cancel(false);
      }

      Log.d(TAG, "create async task");
      mHolderMap.put(
          holder,
          (BitmapDownloadTask) new BitmapDownloadTask(holder, currUser, mActivity).execute());
    }

    convertView.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent userActivityIntent = new Intent(mActivity, UserActivity.class);

            userActivityIntent.putExtras(UserActivity.getStartExtras(currUser));

            Log.d(TAG, "convertView onClick: start UserActivity");
            mActivity.startActivity(userActivityIntent);
          }
        });

    return convertView;
  }
Ejemplo n.º 24
0
  // because different threads can activate this
  public void userLostConnection() {
    boolean lockSet = false;
    try {
      if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {
        lockSet = true;
        logger.debug("SESSION LOCK SET sessionId: " + sessionId);
      } else {
        logger.error("CAN'T GET LOCK - userId: " + userId);
      }
      User user = UserManager.getInstance().getUser(userId);
      if (user == null || !user.isConnected()) {
        return; // user was already disconnected by other thread
      }
      if (!user.getSessionId().equals(sessionId)) {
        // user already reconnected with another instance
        logger.info("OLD SESSION IGNORED - " + user.getName());
        return;
      }
      // logger.info("LOST CONNECTION - " + user.getName() + " id: " + userId);
      UserManager.getInstance().disconnect(userId, DisconnectReason.LostConnection);

    } catch (InterruptedException ex) {
      logger.error("SESSION LOCK lost connection - userId: " + userId, ex);
    } finally {
      if (lockSet) {
        lock.unlock();
        logger.trace("SESSION LOCK UNLOCK sessionId: " + sessionId);
      }
    }
  }
Ejemplo n.º 25
0
 public int create(User user) {
   try {
     Statement stat = conn.createStatement();
     ResultSet rs = stat.executeQuery("Select ID FROM USERS ");
     int i = user.getId();
     String n = user.getName();
     String pass = user.getPassword();
     Date d = user.getDate();
     System.out.println("i= " + i);
     stat.execute(
         "INSERT INTO USERS VALUES("
             + i
             + ",'"
             + n
             + "', '"
             + pass
             + "', TO_DATE('"
             + d
             + "','YYYY-MM-DD'))");
   } catch (SQLException e) {
     e.printStackTrace();
     System.out.println("Alarm in addUser");
   }
   return 1;
 }
Ejemplo n.º 26
0
  private Document buildUser(User user) {
    Element root = new Element(USER_REQUEST_ELEMENT);

    Document doc = new Document().setRootElement(root);

    Element data = new Element("data");

    root.addContent(data);

    data.addContent(new Element(USER_ID_ELEMENT).setText(user.getUserId()));
    data.addContent(new Element(USER_NAME_ELEMENT).setText(user.getName()));
    data.addContent(new Element(USER_STATUS_ELEMENT).setText(user.getStatus()));
    data.addContent(new Element(USER_EMAIL_ELEMENT).setText(user.getEmail()));

    Element roles = new Element(USER_ROLES_ELEMENT);

    for (String role : user.getRoles()) {
      roles.addContent(new Element(USER_ROLE_ELEMENT).setText(role));
    }

    data.addContent(roles);

    data.addContent(
        new Element(USER_USER_MANAGED_ELEMENT).setText(user.isUserManaged() ? "true" : "false"));

    return doc;
  }
Ejemplo n.º 27
0
 public static ArrayList<String> getNames() {
   ArrayList<String> ret = new ArrayList<String>();
   for (User user : _users) {
     ret.add(user.getName());
   }
   return ret;
 }
Ejemplo n.º 28
0
  public void add(final User user) throws ClassNotFoundException, SQLException {

    final String query = "insert into userinfo (id, name, password) values (?,?,?)";
    final String[] params = new String[] {user.getId(), user.getName(), user.getPassword()};

    getJdbcTemplate().update(query, params);
  }
Ejemplo n.º 29
0
 public void putAllDetails(User user) {
   SharedPreferences.Editor spEditor = sharedPreferences.edit();
   spEditor.putString("username", user.getUsername());
   spEditor.putString("name", user.getName());
   spEditor.putString("password", user.getPassword());
   spEditor.putString("age", user.getAge());
   spEditor.putString("email", user.getEmail());
   spEditor.putString("phone", user.getPhone());
   spEditor.putString("position", user.getPosition());
   spEditor.putString("experience", user.getExperience());
   spEditor.putString("curloc", user.getCurloc());
   spEditor.putString("desloc", user.getDesloc());
   spEditor.putString("imageuri", user.getImageUri());
   spEditor.putString("com1name", user.getCom1name());
   spEditor.putString("com1pos", user.getCom1pos());
   spEditor.putString("com1from", user.getCom1from());
   spEditor.putString("com1to", user.getCom1to());
   spEditor.putString("com1resp", user.getCom1resp());
   spEditor.putString("com2name", user.getCom2name());
   spEditor.putString("com2pos", user.getCom2pos());
   spEditor.putString("com2from", user.getCom2from());
   spEditor.putString("com2to", user.getCom2to());
   spEditor.putString("com2resp", user.getCom2resp());
   spEditor.putString("com3name", user.getCom3name());
   spEditor.putString("com3pos", user.getCom3pos());
   spEditor.putString("com3from", user.getCom3from());
   spEditor.putString("com3to", user.getCom3to());
   spEditor.putString("com3resp", user.getCom3resp());
   spEditor.apply();
 }
Ejemplo n.º 30
0
  public void execute(User user, List<String> actions, CheckType type) {
    final String name = user.getName();
    for (String event : actions) {
      event =
          event
              .replaceAll("&player", name)
              .replaceAll("&world", user.getPlayer().getWorld().getName())
              .replaceAll("&check", type.name());

      if (event.startsWith("COMMAND[")) {
        for (String cmd : Utilities.getCommands(event)) {
          Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd);
        }
      } else if (event.equalsIgnoreCase("KICK")) {
        user.getPlayer().kickPlayer(RED + lang.getKickReason());
        String msg = RED + lang.getKickBroadcast().replaceAll("&player", name);
        if (!msg.equals("")) {
          Bukkit.broadcastMessage(msg);
        }
      } else if (event.equalsIgnoreCase("WARN")) {
        List<String> message = lang.getWarning();
        for (String string : message) {
          user.getPlayer().sendMessage(RED + string);
        }
      } else if (event.equalsIgnoreCase("BAN")) {
        user.getPlayer().setBanned(true);
        user.getPlayer().kickPlayer(RED + lang.getBanReason());
        String msg = RED + lang.getBanBroadcast().replaceAll("&player", name);
        if (!msg.equals("")) {
          Bukkit.broadcastMessage(msg);
        }
      }
    }
  }