OData 4.0 Services (CRUD) using Olingo(JSON supported): Part-2
- c. Create updateEntity method that gets called on ‘PUT’ method
public void updateEntity(ODataRequest request, ODataResponse response,
UriInfo uriInfo, ContentType requestFormat,
ContentType responseFormat) throws ODataApplicationException,
DeserializerException, SerializerException {
//eg..http://localhost:8088/school_stu_teachers/DemoService.svc/Schools(‘gct‘)
List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
// Note: only in our example we can assume that the first segment is the EntitySet
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
//get entityset
EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
EdmEntityType responseEdmEntityType = edmEntitySet.getEntityType();
if(responseEdmEntityType.getName().equals(DemoEdmProvider.ET_SCHOOL_NAME))
{
int school_id;
//get school name
List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
for(UriParameter a:keyPredicates)
{
System.out.println(a.getText().replaceAll(“‘”,“”));
}
InputStream requestInputStream = request.getBody();
try {
//convert data(from post) to list of maps
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> jsonmap = mapper.readValue(
requestInputStream,
new TypeReference<List<Map<String, Object>>>() {
});
Map<String, Object> b=new HashMap<String, Object>();
for (Map<String, Object> a : jsonmap) {
for (String i : a.keySet()) {
System.out.println(“key “ + i + ” value “ + a.get(i));
}
b.put(“school_id”, a.get(“school_id”));
b.put(“schoolName”, a.get(“school_name”));
b.put(“studentsDto”, a.get(“studentsDto”));
String mapAsJson = new ObjectMapper().writeValueAsString(b);
//convertjson string to dto
//ie..convert json object to java object
SchoolDto scho= (SchoolDto) fromJson1(mapAsJson);
SchoolDto schoolDto=new SchoolDto();
SchoolServiceDao dao = new SchoolServiceDao();
SchoolDo schoolDo=new SchoolDo();
schoolDo=schoolDto.getEntity(scho);
try {
} catch (Exception e) {
System.out.println(“Exception:”+e.getMessage());
}
//get school entity
Entity school_entity = storage.readEntityData(edmEntitySet, keyPredicates);
school_id=(int)school_entity.getProperty(“school_id”).getValue();
//update schoolDo with input Do by matching id
dao.update1(schoolDo,school_id);
}
} catch (Exception e1) {
System.out.println(“Exception1:”+e1.getMessage());
}}
}
- d. deleteEntity method that gets called on ‘DELETE’ request
public void deleteEntity(ODataRequest request, ODataResponse response,
UriInfo uriInfo) throws ODataApplicationException {
// 1. Retrieve the entity set which belongs to the requested entity
List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
// Note: only in our example we can assume that the first segment is the EntitySet
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
EdmEntityType responseEdmEntityType = edmEntitySet.getEntityType();
if(responseEdmEntityType.getName().equals(DemoEdmProvider.ET_SCHOOL_NAME))
{
String school_name=“”;
List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
for(UriParameter a:keyPredicates)
{
//eg. http://localhost:8088/school_stu_teachers/DemoService.svc/Schools(‘psg‘)
//here,’psg‘ is keypredicate
System.out.println(school_name=a.getText().replaceAll(“‘”,“”));
}
// storage.deleteEntityData(edmEntitySet, keyPredicates);
SchoolServiceDao dao = new SchoolServiceDao();
//delete entry from db
dao.delete(school_name);
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
}
else
if(responseEdmEntityType.getName().equals(DemoEdmProvider.ET_STUDENT_NAME))
{
String student_id=“”;
// 2. delete the data in backend
List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
for(UriParameter a:keyPredicates)
{
//String name=a.getName();
System.out.println(student_id=a.getText());
}
// storage.deleteEntityData(edmEntitySet, keyPredicates);
SchoolServiceDao dao = new SchoolServiceDao();
dao.delete1(Integer.parseInt(student_id));
//dao.delete(4);
//3. configure the response object
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
}
}
3)Create processor (for Entity Collection) that implements EntityCollectionprocessor:
- a. Create readEntityCollection method that gets called on ‘GET’ request
/*
* This method is invoked when a collection of entities has to be read.
* In our example, this can be either a “normal” read operation, or a navigation:
*
* Example for “normal” read entity set operation:
* http://localhost:8080/DemoService/DemoService.svc/Categories
*
* Example for navigation
* http://localhost:8080/DemoService/DemoService.svc/Categories(3)/Products
*/
public void readEntityCollection(ODataRequest request, ODataResponse response,
UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, SerializerException {
SerializerResult serializerResult=null;
List<UriResource> resourceParts = uriInfo.getUriResourceParts();
int segmentCount = resourceParts.size();
System.out.println(“segment count”+segmentCount);
// 1st: retrieve the requested EntitySet from the uriInfo (representation of the parsed URI)
List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
// in our example, the first segment is the EntitySet
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
// 2nd: fetch the data from backend for this requested EntitySetName and deliver as EntitySet
EntityCollection entityCollection = storage.readEntitySetDataFromDatabase(edmEntitySet);
List<UriParameter> keyPredicates = uriResourceEntitySet
.getKeyPredicates();
System.out.println(“segment c”);
if(segmentCount==1){
//eg..http://localhost:8088/school_stu_teachers/DemoService.svc/Schools
// EntityCollection entityCollection = storage.readEntitySetData(edmEntitySet);
EntityCollection modifiedEntityCollection = new EntityCollection();
List<Entity> modifiedEntityList = new ArrayList<Entity>();
modifiedEntityList.addAll(entityCollection.getEntities());
// 3rd: Apply system query option
// The system query options have to be applied in a defined order
// 3.1.) $filter
modifiedEntityList = applyExpandQueryOption(modifiedEntityList, edmEntitySet, uriInfo.getExpandOption());
// 3.8.) $select
SelectOption selectOption = uriInfo.getSelectOption();
// Set the (may) modified entityList to the new entity collection
modifiedEntityCollection.getEntities().addAll(modifiedEntityList);
// 4th: create a serializer based on the requested format (json)
ODataSerializer serializer = odata.createSerializer(responseFormat);
// we need the property names of the $select, in order to build the context URL
EdmEntityType edmEntityType = edmEntitySet.getEntityType();
String selectList = odata.createUriHelper()
.buildContextURLSelectList(edmEntityType, uriInfo.getExpandOption(), selectOption);
ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).selectList(selectList).build();
// adding the selectOption to the serializerOpts will actually tell the lib to do the job
final String id = request.getRawBaseUri() + “/” + edmEntitySet.getName();
EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with()
.contextURL(contextUrl)
.count(uriInfo.getCountOption())
.select(selectOption)
.expand(uriInfo.getExpandOption())
.id(id)
.build();
serializerResult = serializer.entityCollection(srvMetadata, edmEntityType,
entityCollection, opts);
}
if(segmentCount==2){
//eg..http://localhost:8088/school_stu_teachers/DemoService.svc/Schools(‘psg’)/Students
//in this case get(1) represents schools entity set
UriResource navSegment = resourceParts.get(1);
UriResourceNavigation uriResourceNavigation = (UriResourceNavigation) navSegment;
EdmNavigationProperty edmNavigationProperty = uriResourceNavigation
.getProperty();
EdmEntityType targetEntityType = edmNavigationProperty.getType();
// contextURL displays the last segment
//System.out.println(” “+startEdmEntitySet.getEntityType());
EdmEntitySet TargetEntitySet = Util.getNavigationTargetEntitySet(
edmEntitySet, edmNavigationProperty);
//in this case keypredicates is ‘psg‘
if(keyPredicates.size()!=0 && keyPredicates!=null)
{
//get school that has name ‘psg‘…ie) get school entity
Entity entity = storage.readEntityDataFromDatabase(edmEntitySet,keyPredicates);
//here, get students for the related school ie) students of school psg
entityCollection=storage.getRelatedEntityCollection(entity, targetEntityType);
}
ODataSerializer serializer = odata.createSerializer(responseFormat);
ContextURL contextUrl = ContextURL.with().entitySet(TargetEntitySet).build();
final String id = request.getRawBaseUri() + “/” + TargetEntitySet.getName();
EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with()
.contextURL(contextUrl)
.count(uriInfo.getCountOption())
.id(id)
.build();
serializerResult = serializer.entityCollection(srvMetadata, targetEntityType,
entityCollection, opts);
}
// and serialize the content: transform from the EntitySet object to InputStream
InputStream serializedContent = serializerResult.getContent();
// 5th: configure the response object: set the body, headers and status code
response.setContent(serializedContent);
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
- b. Method for ‘expand’ query option
private List<Entity> applyExpandQueryOption(List<Entity> modifiedEntityList,
EdmEntitySet edmEntitySet, ExpandOption expandOption) {
// in our example: http://localhost:8088/school_stu_teachers/DemoService.svc/Schools?$expand=Students
// or http://localhost:8088/school_stu_teachers/DemoService.svc/Students?$expand=School
if (expandOption != null) {
//since we have more than 1 navigation property ie..students and teachers,we use loop
//http://localhost:8088/school_stu_teachers/DemoService.svc/Schools?$expand=Students,Teachers
for(int i=0;i<expandOption.getExpandItems().size();i++){
// retrieve the EdmNavigationProperty from the expand expression
EdmNavigationProperty edmNavigationProperty = null;
ExpandItem expandItem = expandOption.getExpandItems().get(i);
if (expandItem.isStar()) {
List<EdmNavigationPropertyBinding> bindings = edmEntitySet.getNavigationPropertyBindings();
// we know that there are navigation bindings
// however normally in this case check if navigation bindings exists
if (!bindings.isEmpty()) {
//since we have more than 1 navigation binding ie. for teachers,for students
EdmNavigationPropertyBinding binding = bindings.get(i);
EdmElement property = edmEntitySet.getEntityType().getProperty(binding.getPath());
// we don’t need to handle error cases, as it is done in the Olingo library
if (property instanceof EdmNavigationProperty) {
edmNavigationProperty = (EdmNavigationProperty) property;
}
}
} else {
// can be ‘School’ or ‘Students’, no path supported
UriResource uriResource = expandItem.getResourcePath().getUriResourceParts().get(0);
// we don’t need to handle error cases, as it is done in the Olingo library
if (uriResource instanceof UriResourceNavigation) {
edmNavigationProperty = ((UriResourceNavigation) uriResource).getProperty();
}
}
// can be ‘School’ or ‘Students’, no path supported
// we don’t need to handle error cases, as it is done in the Olingo library
if (edmNavigationProperty != null) {
String navPropName = edmNavigationProperty.getName();
EdmEntityType expandEdmEntityType = edmNavigationProperty.getType();
for (Entity entity : modifiedEntityList) {
Link link = new Link();
link.setTitle(navPropName);
link.setType(Constants.ENTITY_NAVIGATION_LINK_TYPE);
link.setRel(Constants.NS_ASSOCIATION_LINK_REL + navPropName);
if (edmNavigationProperty.isCollection()) { // in case of Schools/$expand=Students
// fetch the data for the $expand (to-many navigation) from backend
EntityCollection expandEntityCollection = storage.getRelatedEntityCollection(entity, expandEdmEntityType);
link.setInlineEntitySet(expandEntityCollection);
link.setHref(expandEntityCollection.getId().toASCIIString());
} else { // in case of Students?$expand=School
// fetch the data for the $expand (to-one navigation) from backend
// here we get the data for the expand
Entity expandEntity = storage.getRelatedEntity(entity, expandEdmEntityType);
link.setInlineEntity(expandEntity);
link.setHref(expandEntity.getId().toASCIIString());
}
// set the link – containing the expanded data – to the current entity
entity.getNavigationLinks().add(link);
}
}
}
}
return modifiedEntityList;
}