I'm trying to sync to user list by building a map that contains a username as a key and an user object as the value. Once the map has been built, I'm having difficulties retrieving the object values. Below is the code I'm using.
private Map<String, User> map = new HashMap<String, User>();
I'm populating the map key and object as followed.
List<User> users = session.createCriteria(User.class).list();
for(ApplicationUser user : users) {
map.put(user.getUserName(), user);
}
I'm trying to retrieve the data as followed,
List<Person> persons = session.createCriteria(Person.class).list();
for (Person p : persons) {
User user = map.containsKey(p.getUsername()) ? map.get(p.getUsername()) : new User();
//Email is always null.
System.out.println(user.getEmail());
}
Could someone help point me in the right direction on how to retrieve the object values from my map. Thanks
First, you should change your loop to this:
for (Person p : persons) {
String username = p.getUsername();
User user = map.get(username);
if (user != null) {
System.out.println(user.getEmail());
} else {
System.out.println("User " + username + " is unknown");
}
}
Then set a breakpoint in the loop and debug your code. It looks correct so far. Maybe you are just not setting email in User or the users from persons are not in your map.
It seems like email is null because you are not initialising email in the default constructor of User() which gets executed here :
User user = map.containsKey(p.getUsername()) ? map.get(p.getUsername()) : new User();
Here , i think the usernames that you put in the map does not match with those you try to retrieve in the second part of the code . i.e . map.containsKey(p.getUsername()) seems to return false and default constructor gets called with email as null .
Try printing out the(or debug inspect) the map keyset() and the person usernames and check if they match exactly .
#George I think you will get a nullpointer exception if the user doesn't belong to person.
System.out.println(user.getEmail());
when condition is false User user = new User(); user.getEmail() is null
Related
I have an application in which I pass conferenceDto object with User Ids to my conferenceService where it needs to be added to a Conference Model. The problem is that the conferenceDto list of user ids is a string (ex. "2,4"). I am trying to find the best way of turning this collection of strings to a list of objects of type User
My conferenceService method:
#Override
public Conference updateConference(#Valid ConferenceDto conferenceDto){
Authentication user1 = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findByUsername(user1.getName());
Optional<Conference> conferenceTemp = findById(conferenceDto.getConference_id());
if (nameExist(conferenceDto.getName()) && !conferenceDto.getName().equals(conferenceTemp.get().getName())) {
throw new ConferenceAlreadyExistException(
"There is a conference with that name: "
+ conferenceDto.getName());
}
Conference conference = new Conference();
conference.setConference_id(conferenceDto.getConference_id());
conference.setCreator(user);
conference.setName(conferenceDto.getName());
conference.setDescription(conferenceDto.getDescription());
conference.setStartConference(conferenceDto.getStartConference());
conference.setEndConference(conferenceDto.getEndConference());
conference.setStudents(Collections.singletonList(userService.findById(conferenceDto.getStudents()))); // doesnt work this way because findById requires type long but here I am using Collection<Strings>
return conferenceRepository.save(conference);
}
I am quite new to Java and Spring so Im not sure if this needs a for loop to fill a new list and then pass it to conference.setStudents or it can be done another way. Any tips is very appreciated!
p.s. Type Conference's students is a Collection<User>
I found a solution. I did create a for loop and it turns the collection of strings into a collection of users like I want to. Although, it does not save to my attendance_table for some reason
Changed conferenceService method to:
#Override
public Conference updateConference(#Valid ConferenceDto conferenceDto){
Authentication user1 = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findByUsername(user1.getName());
Optional<Conference> conferenceTemp = findById(conferenceDto.getConference_id());
if (nameExist(conferenceDto.getName()) && !conferenceDto.getName().equals(conferenceTemp.get().getName())) {
throw new ConferenceAlreadyExistException(
"There is a conference with that name: "
+ conferenceDto.getName());
}
Conference conference = new Conference();
conference.setConference_id(conferenceDto.getConference_id());
conference.setCreator(user);
conference.setName(conferenceDto.getName());
conference.setDescription(conferenceDto.getDescription());
conference.setStartConference(conferenceDto.getStartConference());
conference.setEndConference(conferenceDto.getEndConference());
Collection<User> userCollection = new ArrayList<>();
for (String s: conferenceDto.getStudents()){
System.out.println(s);
userCollection.add(userService.findById((long) Integer.parseInt(s)).get());
}
conference.setStudents(userCollection);
return conferenceRepository.save(conference);
}
private boolean nameExist(String name) {
return conferenceRepository.findByName(name) != null;
}
I want to convert my Resultset to List of object . This is my query:
String querystring1= "SELECT userID, privilege"
+ "FROM dbo.User order by userID, privilege";
userID privilege
------------------
1001 read
1001 write
1001 execute
1001 delete
1006 execute
1006 read
1006 write
1007 read
1007 write
I have a class User defined like :
public class User {
private int userID;
private List<String> userPrivelege;
}
I want to have as an output to a list of Users, and this is my implemented code:
String previousId = null;
List<String> PrivList= new ArrayList<String>();
List<User> allUserList= new ArrayList<User>();
while(result_set.next()) {
String userID = result_set.getString("userID");
String privilege = result_set.getString("privilege");
if (previousId == null) { // first time
User user = new User();
PrivList.add(privilege);
previousId=userID;
} else if (previousId.equals(userID) {
PrivList.add(privilege);
} else {
user.setUserPrivilege(PrivList);
allUserList.add(user);
PrivList.clear();
previousId=null;
}
}
The problem is, other than the first user object created, all the next one are always missing the first value which means user 1006 will have 2 privileges other than 3.
Any idea?
All User objects refer the same object List of privileges as you don't create a new instance for each User. Instead you clear only the List.
Consequently, all Users are set with 2 privileges as the last User that you handle has 2 privileges.
So replace :
PrivList.clear();
by :
PrivList = new ArrayList<>();
That's because You Miss the First privilege of the New User here,
else {
user.setUserPrivilege(PrivList);
allUserList.add(user);
PrivList.clear();
previousId=null;
}
Do the privilege initialization for the next user here.
PrivList = new ArrayList<>();
PrivList.add(privilege);
As far as I can see, you are never assigning the user ID to the User object?
PrivList.clear(); clears the list that you have just assigned to a user. Instead create a new list, as davidxxx also said.
As anchreg said, after you have created a user and added it to the list, you need to initialize the next user in the same way as you did the first time.
After your loop terminates, if previousId is not null (that is, any user previlege was processed at all), you need to assign values to the last user and add it to the list in the same way as in the last else case in the loop.
All of this said a more elegant solution could be coded using streams.
You need to create a new instance of PrivList for each user.
Additionnaly, you need to add a privilege for the next user, otherwise you lose that information on the loop.
Edits shown by the <-- comments.
while(result_set.next()) {
String userID = result_set.getString("userID");
String privilege = result_set.getString("privilege");
if (previousId == null) { // first time
User user = new User();
PrivList.add(privilege);
previousId=userID;
} else if (previousId.equals(userID) {
PrivList.add(privilege);
} else {
// nex user
user.setUserPrivilege(PrivList);
allUserList.add(user);
PrivList = new ArrayList<>(); // <--
PrivList.add(privilege); // <--
previousId=null;
}
}
In m y opinion, I think that is not a good model. You should have a second table with privileges related with an user. But to solve your question:
List<String> privList= new ArrayList<String>();
Map<Integer, List<String>> hmUserPrivileges = HashMap<Integer, String>();
while(result_set.next()) {
int userID = result_set.getInt("userID");
String privilege = result_set.getString("privilege");
if (!hmUserPrivileges.contains(userID)) {
privList= new ArrayList<String>();
}
privList.add(privilege);
hmUserPrivileges.put(userID, privList);
}
List<User> allUserList = new ArrayList<User>();
Iterator<Entry<Integer, List<String>>> iterator = hmUserPrivileges.entrySet().iterator();
while(iterator.hasNext()) {
Entry<Integer, List<String>> entry = iterator.next();
User user = new User()
user.setUserID(entry.getKey());
user.setUserPrivelege(entry.getValue());
allUserList.add(user);
}
Can any one explain, how can I fetch the property of individual row in google datastore, this is my code
public Entity useravailable(String name, String pass) {
DatastoreService entityStore = DatastoreServiceFactory.getDatastoreService();
Key k = KeyFactory.createKey("databasecont", name);
try {
Entity user = entityStore.get(k);
System.out.println("password of user in db"+userHaveAccount);
if ("password".equals(password)) // Here check the database password with the password("passed as argument to this function")
return userHaveAccount;
else
return null;
}
catch (EntityNotFoundException e1) {
return null;
}
}
in if condition I need to check the value get from the database(password) with the argument passed(pass), how can retrieve the password from the database?
Kind(table name) -> databasecont,
properities(columns) -> name, password,
key(primary key) -> name
You would do something like -
String password = (String) entity.getProperty("password");
//The above assumes that the name of the property in the Datastore is "password".
You can refer to the API Documentation here.
I'm trying to get all the users of a DL using below code.The code is working as expected. However, I'm not able to get AD usernames for some users. Ex. First row of the o/p has username rkama but not the second row. Is this LDAP data issue or is there a different way to get user name/email address in a DL.
O/p
Entry is : CN=Ay\,Ram(rkama),OU=Site-SJN,OU=Accounts_User,DC=corp,DC=XXX,DC=com
Entry is : CN=Wang\,Peter(),OU=Site-SJN,OU=Accounts_User,DC=corp,DC=XXX,DC=com
public ArrayList<String> getAllDLs(String dlname) throws NamingException {
ArrayList<String> dls = new ArrayList<String>();
String attributes[] = { "member", "displayName" };
createDLContext();
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctrl.setReturningAttributes(attributes);
String search = "(&(objectClass=group)((sAMAccountName="+dlname+"*)))";
NamingEnumeration enumeration = dlContext.search("", search, ctrl);
while (enumeration.hasMoreElements()) {
SearchResult result = (SearchResult) enumeration.next();
System.out.println("Found match & result is : " + result);
NamingEnumeration<?> n2 = result.getAttributes().get("member").getAll();
while (n2 != null && n2.hasMore()) {
String dlList = (String) n2.next();
System.out.println("Entry is : " + dlList);
}
}
dlContext.close();
return dls;
}
I think you need to escape the \ character. Have a look at http://www.rlmueller.net/CharactersEscaped.htm
The member element only contains a DN for the user, this is not the username or password of the account, but a value that can be put back into the search to get the user information (including cn - the name of the user, and sAMAccountName - the userid of the user).
So you need to feed the dlList value into a second search (cleanly) e.g.
NamingEnumeration searchResult = dlContext.search("", "(dn={1})", new Object[]{ dlList }, ctrl);
Trying to construct the search with a simple string like "(&(objectClass=group)((sAMAccountName="+dlname+"*)))" will yield problems because the elements of the returned string will need to be escaped before putting it into the search (the \ for example).
I am using instgarm java api to find the user by using first and last name.
in that api i have to use the first name and last name of a user to find
public UserFeed searchUser(String query, int count) throws InstagramException {
Preconditions.checkNotNull(query, "search query cannot be null.");
Map<String, String> params = new HashMap<String, String>();
params.put(QueryParam.SEARCH_QUERY, query);
if(count > 0) {
params.put(QueryParam.COUNT, String.valueOf(count));
}
UserFeed userFeed = createInstagramObject(Verbs.GET, UserFeed.class, Methods.USERS_SEARCH, params);
return userFeed;
}
in that api i have the above method. How would i construct a query to find an user based on first and last name.
when i pass any name means it returns lot of users i want the exact search using first and last name.
Any one can help me?