Getting all users with a Role in Liferay - java

I'm new to Liferay development in general, so feel free to point out if I'm going about stuff totally the wrong way.
I'm trying to get a DynamicQuery object of all users within a certain group (I'll use this object to further filter another query I'll do against the message board). The User interface seems to have a roleIds property that I might be able to use, since I already know the roleId I'm interested in. But I can't find the proper way to query if roleIds contains a certain value.
Any ideas on what I want to do?
PS: I would have the exact SQL query I could ask directly, but I'd rather use Liferay's own connection pool, without needing to do some weird ext project thingy.

You don't need a DynamicQuery. These are the methods you are looking for in the classes that Dirk points out:
long[] UserServiceUtil.getRoleUserIds(long roleId)
or
long[] UserLocalServiceUtil.getRoleUserIds(long roleId)
List<User> UserLocalServiceUtil.getRoleUsers(long roleId)
Remember that the methods in the classes XXXLocalServiceUtil are not checking the permissions of the current user.
EDIT: If you are looking for all users with a given role within a given community:
long companyId= _X_; //Perhaps CompanyThreadLocal.getCompanyId() if you don't have it anywhere else?
Role role=RoleLocalServiceUtil.getRole(companyId, "Example Role");
Group group=GroupLocalServiceUtil.getGroup(companyId, "Example Community");
List<UserGroupRole> userGroupRoles = UserGroupRoleLocalServiceUtil.
getUserGroupRolesByGroupAndRole(groupId, role.getRoleId());
for(UserGroupRole userGroupRole:userGroupRoles){
User oneUser=userGroupRole.getUser();
}

The easiest way to access liferays own objects is by using the XXXServiceUtil classes (e.g. RoleServiceUtil.getUserRoles(userId)). Thus you rarely have to deal with any SQL directly. Either the RoleServiceUtil or UserServiceUtil might have what you need.

The roles of an Organizations are stored in the table UserGroupRole, so if you want to get the owner of an Organization you must use the following code:
boolean isOrgOwner =
UserGroupRoleLocalServiceUtil.hasUserGroupRole(
usr.getUserId(),
this.currentOrganization.getGroupId(),
RoleConstants.ORGANIZATION_OWNER);
If you want to retrieve all the Organization Owners of an organization:
List<User> administrators = new LinkedList<>();
List<UserGroupRole> allOrganizationAdministrators =
UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(
this.currentOrganization.getGroupId(), roleId);
for (UserGroupRole userGroupRoleTemp : allOrganizationAdministrators) {
administrators.add(userGroupRoleTemp.getUser());
}
Cheers!

Related

How can I delete rows in a database using a query?

There is a user with the attribute Role, by default TENANT, using a query we set him LANDLORD and in theHOUSE table he adds an apartment with various attributes: description, price, city_id and others. But suddenly this user wanted to remove himself from the status of LANDLORD, delete his apartments from our database and again become justTENANT, how in this case can I delete the information that he has apartments? How to do it, if he has apartments, then they need to be deleted, if not, then just change the user's status to TENANT?
At first there was an idea to assign a zero value, but it seemed strange to me if we just zeroed it out, because then the table will start to get cluttered. There is also a status option: ACTIVE or BANNED, but I don't like this option, because his apartment is still not needed.
The code looks like this:
#PutMapping ("/ {id}")
#PreAuthorize ("hasAuthority ('landlord: write')")
public void TenantPostAdd (#PathVariable (value = "id") Long id) {
User user = userRepository.findById (id) .orElseThrow ();
Role role = Role.TENANT;
user.setRole (role);
House house = houseRepository.findById (id) .orElseThrow ();
house ... // what's here
}
Full Code
To build this level of infrastructure, there are a lot of questions I would have to ask to recommend something. I'd want to see the current database schema as well. Your also requesting the ability to delete which can become problematic. You may want to consider leaving data if you believe that the customer may change roles again. That kind of information is based off of the terms of agreement.
Have you considered building something like this?
Absolute(Numeric) Mode
0 No Permission --- etc...
https://www.guru99.com/file-permissions.html
This could be a prepared statement issue with not the appropriate joins occurring in the statement. I believe you should take another look over your database schema.

What's an efficient way to retrieve chat messages from Realm?

I am using FCM to create a chat app, therefore both tokens and topics are being used. In my application I've created a POJO which extends RealmObject intended for storing the chat messages from different userIDs as well as the ones I've sent, both in private-chats and groups.
But what I can't understand is, how should I frame the Realm Query to retrieve the received messages and the messages I've sent to a UserID.
I'm thinking of trying:
RealmResults<ChatModel> results=mDatabase.where(TestChatModel.class)
.equalTo("sender",<Person with whom Im chatting's userID >)
.or()
.equalTo("receiver",<Person with whom Im chatting's userID >)
.and()
.equalTo("sender",<My userID >)
.or()
.equalTo("receiver",<My userID >
.sort("timestamp")
.findAll();
But that just seems very inefficient and messed up.
My POJO is:
public class TestChatModel {
private String chatMessage;
private String timestamp;
private String sender;
private String receiver;
private String topicName; // Set to NA is private-chat
private int isTopic; // Set to 0 for private-chat and Set to 1 for
// group
.
.
.
//Associated constructors and getters and setters
.
.
}
The community's help is much appreciated, thanks in advance !
Your query looks fine. All you can do is write down the query logic and then translate in into Realm query syntax. If your intention is to create a query with the criteria being that:
A specific person is either the sender or receiver, AND
The logged in user either the sender or receiver
Then that's probably the best way to do it. This assumes that you have ALL messages to and from everyone in the Realm; if you were to apply some other rule (e.g. that you only have messages including the logged in user in the Realm) then you could ditch clause 2, as this would be implied. An example of this would be if your API only provided messages for a logged in user (which seems like a reasonable scenario). That would improve efficiency and simplify the query.
In terms of other ways to improve efficiency, it's likely (although I have no direct evidence) that using a numerical ID for users rather than a string ID would allow for more efficient comparison and filtering in Realm. This would be preferable, but may depend on your API (again).
Finally, it's probably worth adding 'parentheses' to your query if it remains as above to ensure the operators are evaluated as you expect (i.e. the AND in the middle of the ORs). This can be accomplished with beginGroup and endGroup in the query (as described here).

Picketlink: finding users with given role

I configured a JPA store and see users and roles getting added correctly to the db when I call the related picketlink (2.7.1) API's
My questions is this: how does one get a list of all users that have a given role?
I tried doing this using the following RelationshipQuery
RelationshipQuery<Grant> rq = relationshipManager.createRelationshipQuery(Grant.class);
rq.setParameter(Grant.ROLE, role);
List<Grant> grants = rq.getResultList()
But the resulting grant list contains a single assignment grant, that refers to the last user in the database that has that role.
I checked the example queries in the documentation and tests but found nothing that does what I want. I know the project is no longer active but am hoping to find a solution to this.
Found out that role data wasn't imported correctly from the old db. Once I fixed that the above code worked as expected.

How to store all user activites in a website..?

I have a web application build in Django + Python that interact with web services (written in JAVA).
Now all the database management part is done by web-services i.e. all CRUD operations to actual database is done by web-services.
Now i have to track all User Activities done on my website in some log table.
Like If User posted a new article, then a new row is created into Articles table by web-services and side by side, i need to add a new row into log table , something like "User : Raman has posted a new article (with ID, title etc)"
I have to do this for all Objects in my database like "Article", "Media", "Comments" etc
Note : I am using PostgreSQL
So what is the best way to achieve this..?? (Should I do it in PostgreSQL OR JAVA ..??..And How..??)
So, you have UI <-> Web Services <-> DB
Since the web services talk to the DB, and the web services contain the business logic (i.e. I guess you validate stuff there, create your queries and execute them), then the best place to 'log' activities is in the services themselves.
IMO, logging PostgreSQL transactions is a different thing. It's not the same as logging 'user activities' anymore.
EDIT: This still means you create DB schema for 'logs' and write them to DB.
Second EDIT: Catching log worthy events in the UI and then logging them from there might not be the best idea either. You will have to rewrite logging if you ever decide to replace the UI, or for example, write an alternate UI for, say mobile devices, or something else.
For an audit table within the DB itself, have a look at the PL/pgSQL Trigger Audit Example
This logs every INSERT, UPDATE, DELETE into another table.
In your log table you can have various columns, including:
user_id (the user that did the action)
activity_type (the type of activity, such as view or commented_on)
object_id (the actual object that it concerns, such as the Article or Media)
object_type (the type of object; this can be used later, in combination with object_id to lookup the object in the database)
This way, you can keep track of all actions the users do. You'd need to update this table whenever something happens that you wish to track.
Whenever we had to do this, we overrode signals for every model and possible action.
https://docs.djangoproject.com/en/dev/topics/signals/
You can have the signal do whatever you want, from injecting some HTML into the page, to making an entry in the database. They're an excellent tool to learn to use.
I used django-audit-log and I am very satisfied.
Django-audit-log can track multiple models each in it's own additional table. All of these tables are pretty unified, so it should be fairly straightforward to create a SQL view that shows data for all models.
Here is what I've done to track a single model ("Pauza"):
class Pauza(models.Model):
started = models.TimeField(null=True, blank=False)
ended = models.TimeField(null=True, blank=True)
#... more fields ...
audit_log = AuditLog()
If you want changes to show in Django Admin, you can create an unmanaged model (but this is by no means required):
class PauzaAction(models.Model):
started = models.TimeField(null=True, blank=True)
ended = models.TimeField(null=True, blank=True)
#... more fields ...
# fields added by Audit Trail:
action_id = models.PositiveIntegerField(primary_key=True, default=1, blank=True)
action_user = models.ForeignKey(User, null=True, blank=True)
action_date = models.DateTimeField(null=True, blank=True)
action_type = models.CharField(max_length=31, choices=(('I', 'create'), ('U', 'update'), ('D', 'delete'),), null=True, blank=True)
pauza = models.ForeignKey(Pauza, db_column='id', on_delete=models.DO_NOTHING, default=0, null=True, blank=True)
class Meta:
db_table = 'testapp_pauzaauditlogentry'
managed = False
app_label = 'testapp'
Table testapp_pauzaauditlogentry is automatically created by django-audit-log, this merely creates a model for displaying data from it.
It may be a good idea to throw in some rude tamper protection:
class PauzaAction(models.Model):
# ... all like above, plus:
def save(self, *args, **kwargs):
raise Exception('Permission Denied')
def delete(self, *args, **kwargs):
raise Exception('Permission Denied')
As I said, I imagine you could create a SQL view with the four action_ fields and an additional 'action_model' field that could contain varchar references to model itself (maybe just the original table name).

JDO - List of Strings not being retrieved from database

On my User class I have a field that is a list of strings:
#Persistent
private List<String> openIds;
When I create a new user I do this:
User user = new User();
user.openIds.add(openid);
pm.makePersistent(user);
When I break after that last line and look, the openIds contains the openid I put in there.
But, when I later call User user = pm.getObjectById(User.class, id); with the correct id, the openIds field is an empty list.
Anyone know what could cause that?
EDIT: BTW I'm running on the Google App Engine
UPDATE: Looking at the datastore viewer, I can see the openid was correctly stored in the database. So its just not getting it out correctly...
UPDATE 2: Its working fine now. I'm pretty sure I didn't change anything. I think what must have happened is that there was an old version of the user object being pulled from the database. A user object that was put in before I had the code that saves the openid. Once I wiped the database things worked fine.
Not putting that field in the fetch plan ?
Accessing persistent fields directly, rather than going via setters ?

Categories

Resources