I am trying to create multi user chat using XMPP(smack). After creation of room when i try to join to chat room then there is no entry of joined member in ofmucmember.
Creation of room code is as below :
public void createMultiUserChatRoom(String roomName, String nickName) {
MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat multiUserChat = multiUserChatManager.getMultiUserChat(roomName+"#conference.localhost");
try {
multiUserChat.create(nickName);
Form form = multiUserChat.getConfigurationForm();
Form submitForm = form.createAnswerForm();
List<FormField> formFieldList = submitForm.getFields();
for (FormField formField : formFieldList) {
if(!FormField.Type.hidden.equals(formField.getType()) && formField.getVariable() != null) {
submitForm.setDefaultAnswer(formField.getVariable());
}
}
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
submitForm.setAnswer("muc#roomconfig_publicroom", true);
submitForm.setAnswer("muc#roomconfig_enablelogging", true);
submitForm.setAnswer("x-muc#roomconfig_reservednick", false);
submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
submitForm.setAnswer("x-muc#roomconfig_registration", false);
submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", false);
submitForm.setAnswer("muc#roomconfig_roomname", roomName);
submitForm.setAnswer("muc#roomconfig_whois", Arrays.asList("none"));
multiUserChat.sendConfigurationForm(submitForm);
} catch (Exception e) {
e.printStackTrace();
}
}
Code for joining the created room is as below:
public void joinMultiUserChatRoom(String userName, String roomName) {
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat multiUserChat = manager.getMultiUserChat(roomName + "#conference.localhost");
DiscussionHistory history = new DiscussionHistory();
history.setMaxStanzas(0);
try {
multiUserChat.join(userName);
multiUserChat.sendMessage(userName +" : You have joined the group : " + roomName);
Presence presence = multiUserChat.getOccupantPresence(roomName + "#conference.localhost/" + userName);
presence.setMode(Presence.Mode.available);
connection.sendStanza(presence);
} catch (Exception e) {
e.printStackTrace();
}
}
Response from server :
<message to="admin#localhost/Smack" id="h7axM-14" type="groupchat" from="team6#conference.localhost/roy"><body>roy : You have joined the group : team6</body><x xmlns="jabber:x:delay" stamp="20160623T12:15:50" from="team6#conference.localhost/roy"/></message>
presence :<presence to='admin#localhost/Smack' id='WR9Dy-12'><x xmlns='http://jabber.org/protocol/muc#user'><item affiliation='owner' jid='admin#localhost/Smack' role='moderator'></item></x><c xmlns='http://jabber.org/protocol/caps' hash='sha-1' node='http://www.igniterealtime.org/projects/smack' ver='NfJ3flI83zSdUDzCEICtbypursw='/></presence>
I am not getting any error. Can anybody tell me where i am wrong here?
When you fill the configuration form, you need to fill following sections:
<field
label='Room Admins'
type='jid-multi'
var='muc#roomconfig_roomadmins'>
<value>wiccarocks#shakespeare.lit</value>
<value>hecate#shakespeare.lit</value>
</field>
<field
label='Room Owners'
type='jid-multi'
var='muc#roomconfig_roomowners'/>
Admins and Owner are saved in ofMucAffiliation table and if the configuration is updated and existing admin or owner is not mentioned then server assumes that it's affiliation has been changed to member, so it moves the entry to ofMucMember table.
You don't get a member just because you join a room. After you have joined a room, you are a Participant in the terminology of XEP-0045.
Related
Here is parent node
Inside I have clients
I'm trying to update the lastName of the first client.
I have the correct ID's, I've checked multiple times. I'm using JAVA, here is the code:
public void updateClient(ClientDto client) {
if(client.getUserId() == null){
throw new IllegalArgumentException("userId cannot be null when" +
" updating a client");
}
final ClientDto clientById = this.getClientById(client.getClientId(),client.getUserId());
Map<String, Object> data = new HashMap<>();
data.put("name", client.getName());
data.put("lastName", client.getLastName());
data.put("middleName", client.getMiddleName());
data.put("email", client.getEmail());
data.put("phone", client.getPhone());
data.put("lastUpdatedBy", client.getLastUpdatedBy());
data.put("lastUpdatedDate", client.getLastUpdatedDate());
this.fireDao.getDb()
.collection("users").document(client.getUserId())
.collection("clients")
.document(client.getClientId()).update(data);
}
this.fireDao.getDb() is an instance of firestore and I'm able to preform all other operations.
Here is what worked:
final ApiFuture<WriteResult> update = this.fireDao.getDb().collection("users").document(client.getUserId())
.collection("clients")
.document(client.getClientId()).update(data);
try {
log.info(format(
"Updating userId %s for customer id %s at time %s",
client.getUserId(),
client.getClientId(),
update.get().getUpdateTime()));
} catch (InterruptedException | ExecutionException e) {
log.error(format(
"Error updating userId %s for customer id %s",
client.getUserId(),
client.getClientId()), e);
}
I think this line did it but I'm not sure why I need it:
update.get().getUpdateTime()
Is it possible to create Group and User in AEM6.2 by using Jackrabbit User Manager API with permissions.
I have just followed below URL's but the code is throwing some exception :
https://helpx.adobe.com/experience-manager/using/jackrabbit-users.html
https://stackoverflow.com/questions/38259047/how-to-give-permission-all-in-aem-through-programatically
ResourceResolverFactory getServiceResourceResolver throws Exception in AEM 6.1
As getAdministrativeResourceResolver(Map) method is deprecated then how can we use getServiceResourceResolver(Map) method instead.
Sharing my solution which will be helpful for others.
Following is the code using getServiceResourceResolver(Map) method for creating Group first and then User and then add user into group with ACL privileges and permission:
public void createGroupUser(SlingHttpServletRequest request) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String groupName = request.getParameter("groupName");
Session session = null;
ResourceResolver resourceResolver = null;
try {
Map<String, Object> param = new HashMap<String, Object>();
param.put(ResourceResolverFactory.SUBSERVICE, "datawrite");
resourceResolver = resourceResolverFactory.getServiceResourceResolver(param);
session = resourceResolver.adaptTo(Session.class);
// Create UserManager Object
final UserManager userManager = AccessControlUtil.getUserManager(session);
// Create a Group
Group group = null;
if (userManager.getAuthorizable(groupName) == null) {
group = userManager.createGroup(groupName);
ValueFactory valueFactory = session.getValueFactory();
Value groupNameValue = valueFactory.createValue(groupName, PropertyType.STRING);
group.setProperty("./profile/givenName", groupNameValue);
session.save();
log.info("---> {} Group successfully created.", group.getID());
} else {
log.info("---> Group already exist..");
}
// Create a User
User user = null;
if (userManager.getAuthorizable(userName) == null) {
user = userManager.createUser(userName, password);
ValueFactory valueFactory = session.getValueFactory();
Value firstNameValue = valueFactory.createValue("Arpit", PropertyType.STRING);
user.setProperty("./profile/givenName", firstNameValue);
Value lastNameValue = valueFactory.createValue("Bora", PropertyType.STRING);
user.setProperty("./profile/familyName", lastNameValue);
Value emailValue = valueFactory.createValue("arpit.p.bora#gmail.com", PropertyType.STRING);
user.setProperty("./profile/email", emailValue);
session.save();
// Add User to Group
Group addUserToGroup = (Group) (userManager.getAuthorizable(groupName));
addUserToGroup.addMember(userManager.getAuthorizable(userName));
session.save();
// set Resource-based ACLs
String nodePath = user.getPath();
setAclPrivileges(nodePath, session);
log.info("---> {} User successfully created and added into group.", user.getID());
} else {
log.info("---> User already exist..");
}
} catch (Exception e) {
log.info("---> Not able to perform User Management..");
log.info("---> Exception.." + e.getMessage());
} finally {
if (session != null && session.isLive()) {
session.logout();
}
if (resourceResolver != null)
resourceResolver.close();
}
}
public static void setAclPrivileges(String path, Session session) {
try {
AccessControlManager aMgr = session.getAccessControlManager();
// create a privilege set
Privilege[] privileges = new Privilege[] {
aMgr.privilegeFromName(Privilege.JCR_VERSION_MANAGEMENT),
aMgr.privilegeFromName(Privilege.JCR_MODIFY_PROPERTIES),
aMgr.privilegeFromName(Privilege.JCR_ADD_CHILD_NODES),
aMgr.privilegeFromName(Privilege.JCR_LOCK_MANAGEMENT),
aMgr.privilegeFromName(Privilege.JCR_NODE_TYPE_MANAGEMENT),
aMgr.privilegeFromName(Replicator.REPLICATE_PRIVILEGE) };
AccessControlList acl;
try {
// get first applicable policy (for nodes w/o a policy)
acl = (AccessControlList) aMgr.getApplicablePolicies(path).nextAccessControlPolicy();
} catch (NoSuchElementException e) {
// else node already has a policy, get that one
acl = (AccessControlList) aMgr.getPolicies(path)[0];
}
// remove all existing entries
for (AccessControlEntry e : acl.getAccessControlEntries()) {
acl.removeAccessControlEntry(e);
}
// add a new one for the special "everyone" principal
acl.addAccessControlEntry(EveryonePrincipal.getInstance(), privileges);
// the policy must be re-set
aMgr.setPolicy(path, acl);
// and the session must be saved for the changes to be applied
session.save();
} catch (Exception e) {
log.info("---> Not able to perform ACL Privileges..");
log.info("---> Exception.." + e.getMessage());
}
}
In code "datawrite" is a service mapping which is mapped with system user in "Apache Sling Service User Mapper Service" which is configurable in the OSGI configuration admin interface.
For more detail about system user check link - How to Create System User in AEM?
I am providing this code direcly from a training of an official Adobe channel, and it is based on AEM 6.1. So I assume this might be the best practice.
private void modifyPermissions() {
Session adminSession = null;
try{
adminSession = repository.loginService(null, repository.getDefaultWorkspace());
UserManager userMgr= ((org.apache.jackrabbit.api.JackrabbitSession)adminSession).getUserManager();
AccessControlManager accessControlManager = adminSession.getAccessControlManager();
Authorizable denyAccess = userMgr.getAuthorizable("deny-access");
AccessControlPolicyIterator policyIterator =
accessControlManager.getApplicablePolicies(CONTENT_GEOMETRIXX_FR);
AccessControlList acl;
try{
acl=(JackrabbitAccessControlList) policyIterator.nextAccessControlPolicy();
}catch(NoSuchElementException nse){
acl=(JackrabbitAccessControlList) accessControlManager.getPolicies(CONTENT_GEOMETRIXX_FR)[0];
}
Privilege[] privileges = {accessControlManager.privilegeFromName(Privilege.JCR_READ)};
acl.addAccessControlEntry(denyAccess.getPrincipal(), privileges);
accessControlManager.setPolicy(CONTENT_GEOMETRIXX_FR, acl);
adminSession.save();
}catch (RepositoryException e){
LOGGER.error("**************************Repo Exception", e);
}finally{
if (adminSession != null)
adminSession.logout();
}
smack presence listener in multi user chat not getting called. Used Smack Api to login and then added roster.addRosterListener(mRoasterListener); but could not get any success to listen when presence of other user of the chat room changes. I tried following code to get the presence listener to work :
connection.login(loginUser, passwordUser);
MultiUserChatManager manager =
MultiUserChatManager.getInstanceFor(connection);
muc = manager.getMultiUserChat(roomID + "#" +context.getString(R.string.group_chat_id));
Log.d("Join User: ", "Already Created");
muc.join(Utilities.getUserPhoneNo(context));
muc.addMessageListener(mGroupMessageListener);
Roster roster = Roster.getInstanceFor(connection);//luna
roster.addRosterListener(mRoasterListener);//roasterListener
Log.d("Joined User Phone: ", " " + Utilities.getUserPhoneNo(context));
and this class to listen for presence change...
public class RoasterListener implements RosterListener{
public RoasterListener(Context context){
}
#Override
public void entriesAdded(Collection<String> collection) {
}
#Override
public void entriesUpdated(Collection<String> collection) {
}
#Override
public void entriesDeleted(Collection<String> collection) {
}
#Override
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
}
}
I tried many links available by stackoverflow but could not get any success.
Please Help!
For Multi User Chat you don't have to use Roster, because it's normal to meet people you don't have in Roster.
To know who is in a muc, first ask for occupants:
muc.join(user,password);
List<String> occupantsAtJoinTime = muc.getOccupants();
for (String occupant : occupantsAtJoinTime)
{
System.out.println("occupant: "+occupant);
//actions
}
then, to keep Occupants list updated, register a DefaultParticipantStatusListener to your muc and define that Listner:
muc.addParticipantStatusListener(new CustomParticipantStatusListner());
definied as (there are many methods to implement if you need):
public class CustomParticipantStatusListner extends DefaultParticipantStatusListener
{
public void joined(String participant)
{
System.out.println(participant + "just joined MUC");
//actions (add occupantsRightNow)
}
public void left(String participant)
{
System.out.println(participant + " just left MUC");
//actions (remove occupantsRightNow)
}
}
All this with smack 4.1.7
It's about the Manage role modifications in Multi User Chat.
This example shows how to grant voice to a visitor and listen for the notification events:
// User1 creates a room
muc = new MultiUserChat(conn1, "myroom#conference.jabber.org");
muc.create("testbot");
// User1 (which is the room owner) configures the room as a moderated room
Form form = muc.getConfigurationForm();
Form answerForm = form.createAnswerForm();
answerForm.setAnswer("muc#roomconfig_moderatedroom", "1");
muc.sendConfigurationForm(answerForm);
// User2 joins the new room (as a visitor)
MultiUserChat muc2 = new MultiUserChat(conn2, "myroom#conference.jabber.org");
muc2.join("testbot2");
// User2 will listen for his own "voice" notification events
muc2.addUserStatusListener(new DefaultUserStatusListener() {
public void voiceGranted() {
super.voiceGranted();
...
}
public void voiceRevoked() {
super.voiceRevoked();
...
}
});
// User3 joins the new room (as a visitor)
MultiUserChat muc3 = new MultiUserChat(conn3, "myroom#conference.jabber.org");
muc3.join("testbot3");
// User3 will lister for other occupants "voice" notification events
muc3.addParticipantStatusListener(new DefaultParticipantStatusListener() {
public void voiceGranted(String participant) {
super.voiceGranted(participant);
...
}
public void voiceRevoked(String participant) {
super.voiceRevoked(participant);
...
}
});
// The room's owner grants voice to user2
muc.grantVoice("testbot2");
Details can be refered in http://web.mit.edu/svalente/lib/smack_3_0_4/documentation/extensions/muc.html .
Firstly, join a chat room:
public MultiUserChat joinMultiUserChat(String user, String roomsName,
String password) {
if (getConnection() == null)
return null;
try {
MultiUserChat muc = new MultiUserChat(getConnection(), roomsName
+ "#conference." + getConnection().getServiceName());
DiscussionHistory history = new DiscussionHistory();
history.setMaxChars(0);
// history.setSince(new Date());
muc.join(user, password, history,
SmackConfiguration.getPacketReplyTimeout());
Log.i("MultiUserChat", "Chat room【"+roomsName+"】joined........");
return muc;
} catch (XMPPException e) {
e.printStackTrace();
Log.i("MultiUserChat", "Chat room【"+roomsName+"】failed........");
return null;
}
}
Then, use MultiChatUser to send Message:
try {
multiUserChat.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
Add a Listener:
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
public class TaxiMultiListener implements PacketListener {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
String body = message.getBody();
}
}
Finally, call the Listener using MultiUserChat:
multiUserChat.addMessageListener(new TaxiMultiListener());
I am new to this OpenFire and asmack, i want the user to have a functionality of Multi Users Chatting so i searched around and i found MUC i have implemented this for creating a room and sending invitation to other users these works, other user receives the invitation but the other user is not able to join the room.
I am doing this on other user invitation receiving
Here connection is the connection of this user and room is the room name that we getting in invitation.
MultiUserChat muc3 = new MultiUserChat(connection,room);
muc3.join("testbot3");
testbot3 is just some random name.
But this throws 404 error.
Do i need to join the user before sending the invitation i.e if A user sending invitation to B , before invitation sent do A needs to join these users by default to room and then it depends on B to decline or just keep quite.
What i am doing is B receives invitation from A in that InvitationListner of B i am trying to join with the above code.
I have been trying for long now i am not sure what is going wrong, some one can give a sample code of how to do this it would be great help for me.
Thanks
Here is more information on my issue
As i go and check on Openfire i can see the room created by the user and he has been added himself as an owner so i dont think so it would be an issue with room getting created.
May be this can be an issue with room getting locked, as i have read through the room is locked when the room is not completely created , i guess this is an issue with form filling when we create the room, i am not filling in the password in the form can this be an issue ?
Please see the following code below inside the handler i am calling a method "checkInvitation" which does the same as above code posted still i get 404. Can you please tell me what i wrong in my code.
Do the nickname that needs to be added can be anything or it needs to something user specific ?
public void createChatroom(){
MultiUserChat muc = null;
try {
muc = new MultiUserChat(connection, "myroom#conference.localhost");
muc.create("testbot");
// Get the the room's configuration form
Form form = muc.getConfigurationForm();
// Create a new form to submit based on the original form
Form submitForm = form.createAnswerForm();
// Add default answers to the form to submit
for (Iterator fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
// Sets the new owner of the room
List owners = new ArrayList();
owners.add("admin#localhost");
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
// Send the completed form (with default values) to the server to configure the room
muc.sendConfigurationForm(submitForm);
muc.join("d");
muc.invite("b#localhost", "Meet me in this excellent room");
muc.addInvitationRejectionListener(new InvitationRejectionListener() {
public void invitationDeclined(String invitee, String reason) {
// Do whatever you need here...
System.out.println("Initee "+invitee+" reason"+reason);
}
});
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setConnection(XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody()
+ "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
checkInvitation();
}
});
}
}
}, filter);
mHandler.post(new Runnable() {
public void run() {
checkInvitation();
}
});
}
}
The 404 error indicates that:
404 error can occur if the room does not exist or is locked
So, ensure that your room is not locked or existed! The code below is how I join the room when there's an in-comming invitation:
private void setChatRoomInvitationListener() {
MultiUserChat.addInvitationListener(mXmppConnection,
new InvitationListener() {
#Override
public void invitationReceived(Connection connection,
String room, String inviter, String reason,
String unKnown, Message message) {
//MultiUserChat.decline(mXmppConnection, room, inviter,
// "Don't bother me right now");
// MultiUserChat.decline(mXmppConnection, room, inviter,
// "Don't bother me right now");
try {
muc.join("test-nick-name");
Log.e("abc","join room successfully");
muc.sendMessage("I joined this room!! Bravo!!");
} catch (XMPPException e) {
e.printStackTrace();
Log.e("abc","join room failed!");
}
}
});
}
Hope this helps your error!
Edit:this is how I config the room:
/*
* Create room
*/
muc.create(roomName);
// muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
Form form = muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
for (Iterator fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType())
&& field.getVariable() != null) {
show("field: " + field.getVariable());
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
List<String> owners = new ArrayList<String>();
owners.add(DataConfig.USERNAME + "#" + DataConfig.SERVICE);
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
submitForm.setAnswer("muc#roomconfig_roomname", roomName);
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
muc.sendConfigurationForm(submitForm);
// submitForm.
show("created room!");
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
show(packet.toXML());
Message mess = (Message) packet;
showMessageToUI(mess.getFrom() + ": " + mess.getBody());
}
});
With this cofiguration, I can join a room easily without password.
You may use the code snippet to join the chat:
public void joinMultiUserChatRoom(String userName, String roomName) {
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat multiUserChat = manager.getMultiUserChat(roomName + "#conference.localhost");
DiscussionHistory history = new DiscussionHistory();
history.setMaxStanzas(-1);
try {
multiUserChat.join(userName, "", history, connection.getPacketReplyTimeout());
} catch (Exception e) {
e.printStackTrace();
}
}
Invite a friend:
/**
* Invites another user to this room.
*
* #param userAddress the address of the user to invite to the room.(one
* may also invite users not on their contact list).
* #param reason a reason, subject, or welcome message that would tell
* the the user why they are being invited.
*/
public void invite(String userAddress, String reason)
{
multiUserChat.invite(userAddress, reason);
}
I have a problem using GAEJ and JDO for storing the data.
This is what I'm working with:
class Usuari.java:
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private String email;
#Persistent
private String rol="";
class DBUtils.java:
I've tried with two ways of doing the delete operation:
// This method removes a record from the database using its unique Key
public static boolean eliminar(Key k) throws Exception {
PersistenceManager pm = PMF.get().getPersistenceManager();
String kind;
Long id;
kind = k.getKind();
id = k.getId();
try {
if (k.getKind().equals("Usuari")) {
Usuari u = (Usuari)pm.getObjectById(k);
pm.deletePersistent(u);
_log.log(Level.INFO, "Deleted an entity->kind: " + kind + " id: " + id);
}
return true;
} catch (Exception e) {
_log.log(Level.SEVERE, "Unable to delete an entity->kind: " + kind + " id: " + id);
System.err.println(e.getMessage());
throw e;
}
finally {
pm.close();
}
}
// This method removes a record from the database using its unique Key - too
public static void eliminar2(Key k) throws Exception {
PersistenceManager pm = PMF.get().getPersistenceManager();
javax.jdo.Transaction tx = pm.currentTransaction();
try
{
tx.begin();
if (k.getKind().equals("Usuari")) {
Usuari u = (Usuari) pm.getObjectById(k);
pm.deletePersistent(u);
}
tx.commit();
}
catch (Exception e)
{
if (tx.isActive())
{
tx.rollback();
}
throw e;
}
}
I'm able to create new instances of some class "Usuari" but I can't delete them.
Everytime I call "eliminar" or "eliminar2" methods I get a "No such object" as result of trying to fetch it. I've checked manually and I see the object exists in my admin panel, with its ID and KIND, so I don't know what am I doing wrong.
Any help would be much appreciated.
PM.getObjectById does not take in a Key object, as per the JDO spec. It takes in an identity object, the same type as you would get from pm.getObjectId(obj); suggest you glance through the JDO spec. No doubt if you inspected what is returned from this method you would see that it can't find an object with that 'identity' because a Key is not an identity. You can also do
pm.getObjectById(Usuari.class, key);
which is shown very clearly in GAE documentation.
Still don't get why users are putting #Persistent on every field virtually every type is default persistent; only leads to making code more unreadable.