private Response updateOrCreateEntity(String id,Set<Representation> parsed,
String method,
boolean create,
boolean update,
HttpHeaders headers){
Entityhub entityhub = ContextHelper.getServiceFromContext(Entityhub.class, servletContext);
MediaType accepted = getAcceptableMediaType(headers,
JerseyUtils.ENTITY_SUPPORTED_MEDIA_TYPES,
MediaType.APPLICATION_JSON_TYPE);
if(entityhub == null){
return Response.status(Status.INTERNAL_SERVER_ERROR).
entity("The Entityhub is currently unavailable.")
.header(HttpHeaders.ACCEPT, accepted).build();
}
//(1) if an id is parsed we need to filter parsed Representations
if(id != null){
for(Iterator<Representation> it = parsed.iterator(); it.hasNext();){
Representation rep = it.next();
String aboutId = ModelUtils.getAboutRepresentation(rep);
if(!(id.equals(rep.getId()) ||
id.equals(aboutId))){
it.remove(); //not the Entity nor the metadata of the parsed ID
}
}
}
//First check if all parsed Representation can be created/updated
if(!(create && update)){ //if both create and update are enabled skip this
for(Representation representation : parsed){
boolean exists;
try {
exists = entityhub.isRepresentation(representation.getId());
} catch (EntityhubException e) {
log.error(String.format("Exception while checking the existance " +
"of an Entity with id %s in the Entityhub.",
representation.getId()),e);
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity(String.format("Unable to process Entity %s because of" +
"an Error while checking the current version of that" +
"Entity within the Entityhub (Message: %s)",
representation.getId(),e.getMessage()))
.header(HttpHeaders.ACCEPT, accepted).build();
}
if((exists && !update) || (!exists && !create)){
return Response.status(Status.BAD_REQUEST).entity(String.format(
"Unable to %s an Entity %s becuase it %s and %s is deactivated. " +
" You might want to set the '%s' parameter to TRUE in your Request",
exists ? "update" : "create",
representation.getId(),
exists ? "does already exists " : "does not",
exists ? "updateing existing" : "creating new",
exists ? "does already" : "does not exists",
exists ? "update" : "create"))
.header(HttpHeaders.ACCEPT, accepted).build();
}
}
}
//store the Representations
//If someone parses data for more than a single Entity, but does not
//provide an ID for the Entity to update, this will update/create all
//the parsed entity. However the response can only return a single
//Entity!
//This can not be changed easily as long as there are no local URIs
//for remote Entiteis as suggested by
// http://incubator.apache.org/stanbol/docs/trunk/entityhub/entityhubandlinkeddata.html
Map<String,Entity> updated = new HashMap<String,Entity>();
for(Representation representation : parsed){
try {
Entity entity = entityhub.store(representation);
updated.put(entity.getId(), entity);
}catch (EntityhubException e) {
log.error(String.format("Exception while storing Entity %s" +
"in the Entityhub.",representation),e);
}