java convert resultset to a list - java

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);
}

Related

Convert a Collection of Strings to a Collection of Users. Have a method userService.findById()

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;
}

How to add Users in a Remarketing UserList using Google Ads API?

I'm trying to create a remarketing userList add some users into it using the Java implementation for Google Ads Api.
The custom audience creation part looks fine, I can see it created in the Ads plataform, but looks like the users wasn't included into it.
Print screen: Empty custom audience inside google ads plataform
I'm sending a JsonArray with 2000 user as parameter and hashing it inside this function, and used this samples as reference.
I'm not sure if I misunderstood the documentation or if I'm including the userList in a wrong way or anything like that.
public JsonArray uploadJsonList(String customerId, JsonArray jsonUsers) throws Exception {
List<Member> members = new ArrayList<>();
JsonObject hashedObj = new JsonObject();
JsonArray arrayJsonHashed = new JsonArray();
for (JsonValue jsonValue : jsonUsers) {
JsonObject obj = jsonValue.asObject();
hashedObj = new JsonObject();
//Getting user data
String normalizedEmail = textUtils.toNormalizedString(obj.get("PESSOA_EMAIL1").toString());
String normalizedPhone = textUtils.toNormalizedString(obj.get("PESSOA_CELULAR").toString());
String normalizedId = obj.get("PESSOA_ID").toString();
normalizedId = removeFirstandLast(normalizedId);
//Hashing user data
hashedObj.add("pessoa_email1", textUtils.toSHA256String(normalizedEmail));
hashedObj.add("pessoa_celular", textUtils.toSHA256String(normalizedPhone));
hashedObj.add("pessoa_id",normalizedId);
arrayJsonHashed.add(hashedObj);
//Creating a member list
Member member = new Member();
member.setHashedEmail(textUtils.toSHA256String(normalizedEmail));
member.setHashedPhoneNumber(textUtils.toSHA256String(normalizedPhone));
members.add(member);
}
//starting ads services
AdWordsServices adWordsServices = new AdWordsServices();
Customer[] customers = getCustomers(adWordsServices, session);
session.setClientCustomerId(customerId);
AdwordsUserListServiceInterface userListService = adWordsServices.get(session, AdwordsUserListServiceInterface.class);
// Create a user list.
CrmBasedUserList userList = new CrmBasedUserList();
userList.setName("Test Remarketing Custom Audience - " + System.currentTimeMillis());
userList.setDescription("A list of customers that was readed from big query");
// CRM-based user lists can use a membershipLifeSpan of 10000 to indicate unlimited; otherwise
// normal values apply.
userList.setMembershipLifeSpan(100L);
userList.setUploadKeyType(CustomerMatchUploadKeyType.CONTACT_INFO);
// Create operation.
UserListOperation operation = new UserListOperation();
operation.setOperand(userList);
operation.setOperator(Operator.ADD);
// Add user list.
UserListReturnValue result = userListService.mutate(new UserListOperation[]{operation});
// Display user list.
UserList userListAdded = result.getValue(0);
System.out.printf(
"User list with name '%s' and ID %d was added.%n",
userListAdded.getName(), userListAdded.getId());
// Get user list ID.
Long userListId = userListAdded.getId();
// Create operation to add members to the user list based on email addresses.
MutateMembersOperation mutateMembersOperation = new MutateMembersOperation();
MutateMembersOperand operand = new MutateMembersOperand();
operand.setUserListId(userListId);
operand.setMembersList(members.toArray(new Member[members.size()]));
mutateMembersOperation.setOperand(operand);
mutateMembersOperation.setOperator(Operator.ADD);
// Add members to the user list based on email addresses.
MutateMembersReturnValue mutateMembersResult =
userListService.mutateMembers(new MutateMembersOperation[]{mutateMembersOperation});
// Display results.
// Reminder: it may take several hours for the list to be populated with members.
for (UserList userListResult : mutateMembersResult.getUserLists()) {
System.out.printf(
"%d email addresses were uploaded to user list with name '%s' and ID %d "
+ "and are scheduled for review.%n",
members.size(), userListResult.getName(), userListResult.getId());
}
return arrayJsonHashed;
}

Update objects in a list from another List

I have a user list
List<User> usrList1 = new ArrayList<User>();
userList.add(new User("usr1",11,""));
userList.add(new User("usr2",22,""));
userList.add(new User("usr3",33,""));
another User List contains
List<User> usrList2 = new ArrayList<User>();
userList2.add(new User("",11,"add1"));
userList2.add(new User("",22,"add2"));
now how can I merge these two List and get a single list of User using id, considering performance. Consider the size of userList1 and userList2 are around 50.
List<User> usrList = new ArrayList<User>();
userList.add(new User("usr1",11,"add1"));
userList.add(new User("usr2",22,"add2"));
userList.add(new User("usr3",33,""));
This is pretty straight forward for a small list, without considering performance issues and assuming a merge strategy of appending Name and Data fields:
Copy (shallow) list1 into a new list merged
Iterate over list2
For each item in merged check if item in list2 already exists
If the item exists, just update its fields
If it does not exist, append it to the end of merged
Code:
public static List<User> Merge(List<User> list1, List<User> list2) {
List<User> merged = new ArrayList<User>(list1);
for (User user : list2) {
boolean found = false;
for (User u : merged) {
if (u.Id == user.Id) {
found = true;
u.Name += user.Name;
u.Data += user.Data;
break;
}
}
if (!found) {
merged.add(user);
}
}
return merged;
}
You can user HashMap as helper data structure
For key is needed to use user id (integer value in list)
public static void main(String[] args) {
List<User> userList1 = new ArrayList<User>();
userList1.add(new User("usr1", 11, ""));
userList1.add(new User("usr2", 22, ""));
userList1.add(new User("usr3", 33, ""));
List<User> userList2 = new ArrayList<User>();
userList2.add(new User("", 11, "add1"));
userList2.add(new User("", 22, "add2"));
// Insert all elements from first list to hash map
HashMap<Integer, User> userMap = new HashMap<>();
for (User user : userList1) {
userMap.put(user.getId(), user);
}
// Update user elements
for (User user : userList2) {
User update = userMap.get(user.getId());
update.setAddres(user.getAddress());
}
// convert hash map to list
List<User> merge = new ArrayList<>();
merge.addAll(userMap.values());
System.out.println(merge);
}
Note:
HashMap will not preserve the order of elements. If it is needed to merge list be in the same order as userList1 then use LinkedHashMap.

Retrieve Object Value from Java Map using Map Key

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

Friends list of a friend using Twitter4J

How can I obtain the friends list of a friend or follower using Twitter4J?
Using getFriendsId(), I'm only able to retrieve the friend's/follower's list of that current user which is authenticated. What I want is to obtain the list of friends of a follower or friend of the authenticated user.
This will show the name of your friend's followers.
User u1 = null ;
long cursor = -1;
IDs ids;
System.out.println("Listing followers's ids.");
do {
ids = twitter.getFollowersIDs("username", cursor);
for (long id : ids.getIDs()) {
System.out.println(id);
User user = twitter.showUser(id);
System.out.println(user.getName());
}
} while ((cursor = ids.getNextCursor()) != 0);
You only need to do this:
Twitter twitter = mTwitterApp.getTwitterInstance();
long cursor = -1;
List<User> users=twitter.getFriendsList(mTwitterApp.getUserID(), cursor);
Here users is a list users who are your friends(you are following them).
mTwitterApp.getUserID() is your login useris which is a long value.
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(userID, lCursor);
System.out.println(twitter.showUser(userID).getName());
System.out.println("==========================");
do
{
for (long i : friendsIDs.getIDs())
{
System.out.println("follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
}
}while(friendsIDs.hasNext());
This code works! (without exceeding rate limits). Referred twitter4j documentation and other answers on StackOverflow.
try {
// get friends
long cursor = -1;
PagableResponseList<User> pagableFollowings;
do {
pagableFollowings = twitter.getFriendsList(twitter.getId(), cursor);
for (User user : pagableFollowings) {
listFriends.add(user); // ArrayList<User>
}
} while ((cursor = pagableFollowings.getNextCursor()) != 0);
// get followers
cursor = -1;
PagableResponseList<User> pagableFollowers;
do {
pagableFollowers = twitter.getFollowersList(twitter.getId(), cursor);
for (User user : pagableFollowers) {
listFollowers.add(user); // ArrayList<User>
}
} while ((cursor = pagableFollowers.getNextCursor()) != 0);
} catch (TwitterException e) {
printError(e);
}
You can use
twitter.getFollowersIDs("username", cursor);
http://twitter4j.org/javadoc/twitter4j/api/FriendsFollowersResources.html#getFollowersIDs-java.lang.String-long-
which returns only 5000 user not all users. Also it is limited 15 times in 15 minutes.(https://dev.twitter.com/rest/reference/get/friends/ids)
Also, you can use,
twitter.getFollowersList("username", cursor);
http://twitter4j.org/javadoc/twitter4j/api/FriendsFollowersResources.html#getFollowersList-java.lang.String-long- which is also limited with 20 user. Also it is limited 15 times in 15 minutes for user auth, 30 times in 15 minutes for app auth (https://dev.twitter.com/rest/reference/get/friends/list)
For unlimited access, you can look at https://gnip.com/ or whitelisted user access of twitter.
PagableResponseList<User> friendlist= twitter.getFriendsList(user.getScreenName(), -1);
int sizeoffreindlist= friendlist.size();
for(int i=0;i<sizeoffreindlist;i++)
{
System.out.println(friendlist.get(i));
}
It will provide you a list of 20 friends as the default limit is 20
What about something like get Friends List? https://dev.twitter.com/docs/api/1.1/get/friends/list
According to the docs:
Returns a cursored collection of user objects for every user the
specified user is following (otherwise known as their "friends").
There is an interface for this in twitter4j.api, but I can't figure out how to use it:
PagableResponseList<User> getFriendsList(String screenName, long cursor) throws TwitterException;

Categories

Resources