@SuppressWarnings("unchecked")
private void handleRequestMessage(String remoteJID, String localJID, Relation relation) throws InvalidRelationException {
// Are required fields for a new relation setup present ?
if (!relation.hasNature() || !relation.hasStatus() || !relation.hasFrom() || !relation.hasTo() || !relation.hasId()) {
throw new InvalidRelationException("Relation is missing required elements");
}
// The relation should be between the sender and the receiver
if (getDirection(relation, remoteJID, localJID) == 0) {
throw new InvalidRelationException("Relation from/to do not match message from/to");
}
// Cannot add a relation to yourself
if (relation.getFrom().equals(relation.getTo())) {
throw new InvalidRelationException("Cannot add relation to yourself");
}
// Verify that this relation is not already here
final EntityManager em = OswPlugin.getEmFactory().createEntityManager();
Query query = em.createQuery("SELECT x FROM Relation x WHERE x.owner = ?1 AND x.guid = ?2");
query.setParameter(1, localJID);
query.setParameter(2, relation.getId());
List<PersistentRelation> relations = query.getResultList();
// If there is a match, we give up
// TODO Not that fast. The other end may jut have not received any
// answer and wants to try again
// we should deal with all these recovery features.
if (relations.size() > 0) {
throw new InvalidRelationException("This relation has already been requested");
}
// Save the relation
PersistentRelation persistentRelation = (PersistentRelation) relation;
persistentRelation.setOwner(localJID);