Query q = getEntityManager().createQuery("FROM SharedResource WHERE uniqueKey = :uniqueKey");
q.setParameter("uniqueKey", uniqueKey);
List<SharedResource> resources = q.getResultList();
if (resources == null || resources.size() == 0)
{
SharedResource sr = new SharedResource();
sr.setUniqueKey(uniqueKey);
// find or create the StreamScope
List<StreamScope> scopes = getEntityManager().createQuery(
"From StreamScope WHERE scopeType=:scopeType AND uniqueKey=:uniqueKey").setParameter("scopeType",
ScopeType.RESOURCE).setParameter("uniqueKey", uniqueKey).getResultList();
if (scopes.size() == 1)
{
sr.setStreamScope(scopes.get(0));
}
else
{
sr.setStreamScope(new StreamScope(ScopeType.RESOURCE, uniqueKey));
}
getEntityManager().persist(sr);
if (sr.getStreamScope().getDestinationEntityId() == null)
{
sr.getStreamScope().setDestinationEntityId(sr.getId());
}
return sr;
}
return resources.get(0);