public String getPrimaryDisplay() { StringBuilder sb = new StringBuilder(); sb.append(""); sb.append( (user.getPrimaryDisplay().toString() == null ? " " : user.getPrimaryDisplay().toString())); return sb.toString(); }
@Test public void testFind() throws Exception { User foundUser = h2User.find(user.getId()); assertEquals(email, foundUser.getEmail()); assertEquals(password, foundUser.getPassword()); assertEquals(type, foundUser.getType()); }
@Test(expected = InsufientPermissionException.class) public void testNoPermission() { User u = new User(); u.setPermission(Permission.EXECUTE | Permission.READ); pt.needsWrite(u); }
@Test public void getByEmailTest() { User user = getUser(UserRole.ROLE_ORG_USER, UserRole.ROLE_GROUP_USER); user = userService.getByEmail(user.getEmail()); assertNotNull(user); }
public User viewHelper() throws DataAccessException { User user = new User(); Map<String, Object> resultMap = null; String sql = QueryUtil.getStringQuery( "admin_sql", "admin.usergroup.viewhelper"); // 쿼리 프로퍼티파일의 키값에 해당되는 sql문을 읽어온다. // 넘겨받은 파라미터를 세팅한다. Map<String, Object> param = new HashMap<String, Object>(); // SQL문이 실행된다. try { resultMap = getSimpleJdbcTemplate().queryForMap(sql, param); } catch (EmptyResultDataAccessException e1) { } if (resultMap != null) { user.setUserID((String) (resultMap.get("userID"))); } else { user.setUserID(""); } return user; }
public static ArrayList<String> getNames() { ArrayList<String> ret = new ArrayList<String>(); for (User user : _users) { ret.add(user.getName()); } return ret; }
@Test public void testShowBulk() { { // a small bulk! Twitter tw = TwitterTest.newTestTwitter(); List<User> users = tw.users().show(Arrays.asList("mcfc", "winterstein")); for (User user : users) { System.out.println( user.getScreenName() + "\t" + user.getLocation() + "\t" + user.getPlace() + "\t" + user.getId()); } } { // anonymous -- only in version 1 Twitter tw = new Twitter(); tw.setAPIRootUrl("http://api.twitter.com/1"); List<User> users = tw.users().show(Arrays.asList("joehalliwell", "winterstein")); for (User user : users) { System.out.println( user.getScreenName() + "\t" + user.getLocation() + "\t" + user.getPlace() + "\t" + user.getId()); } } }
// test valid User, but invalid ip @Test public void testAuthenticateValidAuthButInvalidIp() throws Exception { UserObjectifyDAOImpl userDAO = new UserObjectifyDAOImpl(); User dbuser = new User(); dbuser.setLogin("bob"); dbuser.setToken("smith"); dbuser.setPermissions(Permission.LIST_ALL_JOBS); ArrayList<String> allowedIps = new ArrayList<String>(); allowedIps.add("192.168.1.2"); dbuser.setAllowedIpAddresses(allowedIps); dbuser = userDAO.insert(dbuser); AuthenticatorImpl auth = new AuthenticatorImpl(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRemoteAddr()).thenReturn("192.168.1.1"); when(request.getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER)) .thenReturn("Basic " + encodeString("bob:smith")); User u = auth.authenticate(request); assertTrue(u.getLogin() == null); assertTrue(u.getToken() == null); assertTrue(u.getPermissions() == Permission.NONE); assertTrue(u.getIpAddress().equals("192.168.1.1")); verify(request).getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER); }
private synchronized void notifyUsers(Integer floor) { for (User user : users) { if (user.traveling()) { user.setCurrentFloor(floor); } } }
private synchronized Set<User> applyCommand(Command command) throws ElevatorIsBrokenException { Set<User> doneUsers = emptySet(); notifyUsers(); switch (command) { case CLOSE: door = CLOSE; break; case OPEN: door = OPEN; doneUsers = new HashSet<>(); for (User user : users) { user.elevatorIsOpen(floor); if (user.done()) { doneUsers.add(user); } } users.removeAll(doneUsers); break; case UP: floor++; notifyUsers(floor); break; case DOWN: floor--; notifyUsers(floor); break; case NOTHING: break; } return doneUsers; }
public String[] getInitialSchemaSQL() { HsqlArrayList list = new HsqlArrayList(userList.size()); for (int i = 0; i < userList.size(); i++) { User user = (User) userList.get(i); if (user.isSystem) { continue; } HsqlName name = user.getInitialSchema(); if (name == null) { continue; } list.add(user.getInitialSchemaSQL()); } String[] array = new String[list.size()]; list.toArray(array); return array; }
/** * 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; }
public HttpServletRequest addurl(HttpServletRequest req, HttpServletResponse response) { int idUser = Integer.parseInt(req.getParameter("id")); String siteUrl = req.getParameter("url"); String nomUrl = req.getParameter("nomUrl"); Url url = new Url(idUser, siteUrl, nomUrl, 0); User userInstance = User.getInstance(); Url oldurl = userInstance.getUrlByUri(siteUrl); if (oldurl == null) { try { url.addUrlToDBB(); url.setuId(url.getIdFromBDD()); User user = (User) this.parent.user(); user.addOneUrl(url); response.setStatus(200); } catch (MySQLIntegrityConstraintViolationException e) { // URL existe d�j� dans la BDD System.out.println("URL duppliquee"); response.setStatus(201); } catch (SQLException e) { // erreur dans l'insertion a la BDD e.printStackTrace(); response.setStatus(400); } } else { System.out.println("URL duppliquee"); response.setStatus(201); } return req; }
/** * Fonction tableauBord Gere la page tableau de bord de l'application * * @param req : HttpServletRequest */ public HttpServletRequest tableaubord(HttpServletRequest req, HttpServletResponse response) { User user = User.getInstance(); if (user == null) { this.parent.redirect("login", true); return req; } else { List<Tag> tags = user.getAllTag(); int nbTags = tags.size(); List<Url> urls = user.getAllUrl(); int nbUrls = urls.size(); List<Url> untaggedUrls = user.getUntaggedUrl(); int nbUntaggedUrls = untaggedUrls.size(); Map<Tag, List<Url>> mapTagUrls = new HashMap<Tag, List<Url>>(); if (tags != null) { Iterator<Tag> it = tags.iterator(); while (it.hasNext()) { Tag tag = it.next(); mapTagUrls.put(tag, tag.getUrls()); } } req.setAttribute("tags", tags); req.setAttribute("urls", urls); req.setAttribute("untaggedurls", untaggedUrls); req.setAttribute("mapTagUrls", mapTagUrls); req.setAttribute("nbTags", nbTags); req.setAttribute("nbUrls", nbUrls); req.setAttribute("nbUntaggedUrls", nbUntaggedUrls); return req; } }
/** * Generate a new universally unique ID for a user. * * @return the uuid */ public String getNewUserUUID() { // inits String uuid; Random rng = new Random(); int len = 6; boolean nonUnique; // continue looping until we get a unique ID do { // generate the number uuid = ""; for (int c = 0; c < len; c++) { uuid += ((Integer) rng.nextInt(10)).toString(); } // check to make sure it's unique nonUnique = false; for (User u : this.users) { if (uuid.compareTo(u.getUUID()) == 0) { nonUnique = true; break; } } } while (nonUnique); return uuid; }
private void doDeleteComment(int msgid, String reason, User user, int scoreBonus) throws SQLException, ScriptErrorException { if (!getReplys(msgid).isEmpty()) { throw new ScriptErrorException("Нельзя удалить комментарий с ответами"); } deleteComment.clearParameters(); insertDelinfo.clearParameters(); deleteComment.setInt(1, msgid); insertDelinfo.setInt(1, msgid); insertDelinfo.setInt(2, user.getId()); insertDelinfo.setString(3, reason + " (" + scoreBonus + ')'); updateScore.setInt(1, scoreBonus); updateScore.setInt(2, msgid); deleteComment.executeUpdate(); insertDelinfo.executeUpdate(); updateScore.executeUpdate(); logger.info( "Удалено сообщение " + msgid + " пользователем " + user.getNick() + " по причине `" + reason + '\''); }
@Test public void testAuthenticateValidAuthInHeaderAndUserInDataStoreButNotAuthorizedToRunAsAnotherUser() throws Exception { UserObjectifyDAOImpl userDAO = new UserObjectifyDAOImpl(); User dbuser = new User(); dbuser.setLogin("bob"); dbuser.setToken("smith"); dbuser.setPermissions(Permission.LIST_ALL_JOBS); dbuser = userDAO.insert(dbuser); AuthenticatorImpl auth = new AuthenticatorImpl(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRemoteAddr()).thenReturn("192.168.1.1"); when(request.getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER)) .thenReturn("Basic " + encodeString("bob:smith")); when(request.getParameter(Constants.USER_LOGIN_TO_RUN_AS_PARAM)).thenReturn("joe"); try { auth.authenticate(request); } catch (Exception ex) { assertTrue(ex.getMessage().equals("User does not have permission to run as another user")); } }
public synchronized void updateNick(int cid, int bid, String old_nick, String new_nick) { User u = getUser(cid, bid, old_nick); if (u != null) { u.nick = new_nick; u.old_nick = old_nick; } }
@Override public Representation put(Representation entity) throws ResourceException { this.userId = UmlgURLDecoder.decode((String) getRequestAttributes().get("userId")); User c = UMLG.get().getEntity(this.userId); try { String entityText = entity.getText(); c.fromJson(entityText); String lookupUri = UmlgURLDecoder.decode(getReference().getQueryAsForm(false).getFirstValue("lookupUri")); lookupUri = "riap://host" + lookupUri; int fakeIdIndex = lookupUri.indexOf("fake"); if (fakeIdIndex != -1) { int indexOfForwardSlash = lookupUri.indexOf("/", fakeIdIndex); String fakeId = lookupUri.substring(fakeIdIndex, indexOfForwardSlash); Object id = UmlgTmpIdManager.INSTANCE.get(fakeId); lookupUri = lookupUri.replace(fakeId, UmlgURLDecoder.encode(id.toString())); } ClientResource cr = new ClientResource(lookupUri); Representation result = cr.get(); return result; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } finally { UmlgTmpIdManager.INSTANCE.remove(); UMLG.get().rollback(); } }
@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); } }
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); } }
/* get/create device list entry */ public static GroupList getGroupList(User user, String groupID, boolean createOK) throws DBException { // does not return null, if 'createOK' is true /* User specified? */ if (user == null) { throw new DBException("User not specified."); } String accountID = user.getAccountID(); String userID = user.getUserID(); /* group exists? */ if (StringTools.isBlank(groupID)) { throw new DBException("DeviceGroup ID not specified."); } else if (!DeviceGroup.exists(accountID, groupID)) { throw new DBException("DeviceGroup does not exist: " + accountID + "/" + groupID); } /* create/save record */ GroupList.Key grpListKey = new GroupList.Key(accountID, userID, groupID); if (grpListKey.exists()) { // may throw DBException // already exists GroupList listItem = grpListKey.getDBRecord(true); listItem.setUser(user); return listItem; } else if (createOK) { GroupList listItem = grpListKey.getDBRecord(); listItem.setCreationDefaultValues(); listItem.setUser(user); return listItem; } else { // record doesn't exist, and caller doesn't want us to create it return null; } }
@RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST) public String formSubmit(@ModelAttribute User user, Model model) throws MalformedURLException, IOException { model.addAttribute("user", user); HttpPost post = new HttpPost( "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/"); BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName())); nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName())); nameValuePairs.add(new BasicNameValuePair("email", user.getEmail())); nameValuePairs.add(new BasicNameValuePair("password", user.getPassword())); nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation())); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(post); response = httpclient.execute(post); System.out.println("Status code is " + response.getStatusLine().getStatusCode()); System.out.println(response.toString()); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(response.getFirstHeader("Location")); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); EntityUtils.consume(response.getEntity()); /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html"); FileWriter fileWriter = new FileWriter(newTextFile); fileWriter.write(response.toString()); fileWriter.close();*/ return "result"; }
@Test public void testExecute_WithSecondState() throws Exception { User user = TestUtil.createUser(); user.setActiveted(null); Site parentSite = TestUtil.createSite(); DraftChildSiteRegistration registration = TestUtil.createChildSiteRegistration(parentSite); ChildSiteSettings settings = TestUtil.createChildSiteSettings(registration, parentSite); settings.setCreatedDate(new Date()); settings.setUserId(user.getUserId()); settings.setConfirmCode("confirm"); action.setSettingsId(settings.getChildSiteSettingsId()); action.setConfirmCode("confirm"); DraftChildSiteRegistration childSiteRegistration = TestUtil.createChildSiteRegistration("name", "comment"); childSiteRegistration.setBlueprintsId(Arrays.asList(1, 2)); settings.setRequiredToUseSiteBlueprint(true); settings.setSitePaymentSettings(new SitePaymentSettings()); settings.setChildSiteRegistration(childSiteRegistration); Assert.assertNull(user.getActiveted()); Assert.assertNull(new UsersManager().getLoginedUser()); ForwardResolution resolutionMock = (ForwardResolution) action.show(); Assert.assertNotNull(new UsersManager().getLoginedUser()); Assert.assertEquals(user, new UsersManager().getLoginedUser()); Assert.assertEquals( "/account/registration/childSiteRigistrationConfirmationSecondState.jsp", resolutionMock.getPath()); Assert.assertNotNull(user.getActiveted()); Assert.assertNotNull(new UsersManager().getLoginedUser()); Assert.assertEquals(user, new UsersManager().getLoginedUser()); Assert.assertNull(action.getTellFriendHtml()); }
@Before(UserInterceptor.class) public void setting() throws InterruptedException { String method = getRequest().getMethod(); if (method.equalsIgnoreCase(Constants.GET)) { setAttr("save", getPara("save")); render("front/user/setting.ftl"); } else if (method.equalsIgnoreCase(Constants.POST)) { User user = getSessionAttr(Constants.USER_SESSION); String url = getPara("url"); String nickname = getPara("nickname"); if (!user.getStr("nickname").equalsIgnoreCase(nickname) && User.me.findByNickname(nickname) != null) { error("此昵称已被注册,请更换昵称"); } else { if (!StrUtil.isBlank(url)) { if (!url.substring(0, 7).equalsIgnoreCase("http://")) { url = "http://" + url; } } user.set("url", StrUtil.transHtml(url)) .set("nickname", StrUtil.noHtml(nickname).trim()) .set("signature", StrUtil.transHtml(getPara("signature"))) .update(); // 保存成功 setSessionAttr(Constants.USER_SESSION, user); success(); } } }
private List<User> parseUsers(JSONArray array) { List<User> usersToInsert = new ArrayList<User>(); if (array != null) { for (int i = 0; i < array.length(); ++i) { JSONObject object = array.optJSONObject(i); if (object != null) { User user = AsyncUsersFetcher.fromJson(object); String remoteId = user.getDailymotionId(); if (!mLocalUsers.containsKey(remoteId)) { user.setNew(mLocalUsers.size() > 0); // considered // new if // existing // vids. usersToInsert.add(user); // need insertion, not // present locally. } else { if (!user.equals(mLocalUsers.get(remoteId))) { usersToInsert.add(user); // need insertion, been // updated } mLocalUsers.remove(remoteId); } mFetchedUsers.add(user); } } } return usersToInsert; }
public static boolean isSpam(User poster, String body, String ip) { Date lastPost = poster.getLastPost(); Date curTime = new Date(); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US); Date joinDate; if (poster.getIsMod()) return false; try { joinDate = formatter.parse(poster.getJoinDate()); } catch (Exception e) { joinDate = new Date(); } if (lastPost != null) { long diff = curTime.getTime() - lastPost.getTime(); long userLen = curTime.getTime() - joinDate.getTime(); long minInterval = (userLen < (Config.spamProbationPeriodDays * 1000 * 60 * 60 * 24)) ? Config.spamPostIntervalMinsProbation : Config.spamPostIntervalMinsStandard; minInterval *= 1000 * 60; if (diff < minInterval) { Log.log("Filtered post from " + poster.getUsername(), Log.DEBUG); return true; } } poster.setLastPost(curTime); return false; }
private boolean hasJabberContacts() { User[] users = myUserModel.getAllUsers(); for (User user : users) { if (user.getTransportCode().equals(getName())) return true; } return false; }
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; }
@Test public void testUpdate() throws Exception { user.setEmail("*****@*****.**"); user.setPassword("changedPassword"); user.setType(UserType.STUDENT); assertTrue(h2User.update(user)); }