Quantcast
Channel: SCN : All Content - RESTful Web Services SDK
Viewing all 262 articles
Browse latest View live

OData 4.0 Services (CRUD) using Olingo(JSON supported): Part-1

$
0
0

1) Import the following  jars for OLINGO

odata-commons-api-4.0.0.jar

odata-commons-core-4.0.0.jar

odata-server-core-4.0.0.jar

slf4j-api-1.7.11.jar

commons-codec-1.9.jar

slf4j-simple-1.7.7.jar

jackson-dataformat-xml-2.4.2.jar

jackson-databind-2.4.2.jar

odata-server-api-4.0.0.jar

jackson-annotations-2.4.2.jar

antlr4-runtime-4.5.jar

stax2-api-3.1.4.jar

org.abego.treelayout.core-1.0.1.jar

jackson-module-jaxb-annotations-2.4.2.jar

commons.lang3-3.3.2.jar

jackson-core-2.4.2.jar

aalto-xml-0.9.10.jar

 

2) Create Provider that extends CsdlAbstractEdmProvider


  1. 1.Define Namespace, Container, EntityType names, EntitySet names.
  2. a. DEFINING NAMESPACE :

publicstaticfinal String NAMESPACE = "OData.Demo";

 

  1. b. DEFINING CONTAINER :

 

publicstaticfinal String CONTAINER_NAME = "Container";

publicstaticfinal FullQualifiedName CONTAINER = new FullQualifiedName(NAMESPACE, CONTAINER_NAME);

 

  1. c. DEFINING ENTITY TYPE NAMES :

publicstaticfinal String ET_STUDENT_NAME = "Student";

publicstaticfinalFullQualifiedNameET_STUDENT_FQN = newFullQualifiedName (NAMESPACE, ET_STUDENT_NAME);

 

publicstaticfinal String ET_SCHOOL_NAME = "School";

publicstaticfinalFullQualifiedNameET_SCHOOL_FQN =FullQualifiedName(NAMESPACE, ET_SCHOOL_NAME);

 

  1. d. DEFINING ENTITY SETS :

publicstaticfinal String ES_STUDENTS_NAME = "Students";

publicstaticfinal String ES_SCHOOLS_NAME = "Schools";

 

  1. e. DEFINING NAVIGATIONS:

 

publicstaticfinal String NAV_TO_SCHOOL = "School";

publicstaticfinal String NAV_TO_STUDENTS = "Students";

 

  1. 2. Override getEntityType, getEntitySet, getEntityContainerInfo, getEntityContainer, getSchemas methods .
  2. a. OVERRIDING getEntityType:

@Override

  public CsdlEntityType getEntityType(FullQualifiedName entityTypeName) {

 

    // this method is called for each EntityType that are configured in the Schema

    CsdlEntityType entityType = null;

 

    if (entityTypeName.equals(ET_STUDENT_FQN)) {

      // create EntityType properties

      CsdlProperty stu_id = new CsdlProperty().setName("stu_id")

          .setType(EdmPrimitiveTypeKind.Int32.getFullQualifiedName());

      CsdlProperty stu_name = new CsdlProperty().setName("stu_name")

          .setType(EdmPrimitiveTypeKind.String.getFullQualifiedName());

 

      // create PropertyRef for Key element

      CsdlPropertyRef propertyRef = new CsdlPropertyRef();

      propertyRef.setName("stu_id");

 

      // navigation property: many-to-one, null not allowed (student must have a school)

      CsdlNavigationProperty navProp = new CsdlNavigationProperty().setName(NAV_TO_SCHOOL)

          .setType(ET_SCHOOL_FQN).setNullable(false).setPartner("Students");

      //add all the navigation properties to a list

      List<CsdlNavigationProperty> navPropList = new ArrayList<CsdlNavigationProperty>();

      navPropList.add(navProp);

      

      // configure EntityType

      entityType = new CsdlEntityType();

      entityType.setName(ET_STUDENT_NAME);

      entityType.setProperties(Arrays.asList(stu_id, stu_name));

      entityType.setKey(Arrays.asList(propertyRef));

      entityType.setNavigationProperties(navPropList);

 

    } elseif (entityTypeName.equals(ET_SCHOOL_FQN)) {

      // create EntityType properties

      CsdlProperty school_id = new CsdlProperty().setName("school_id")

          .setType(EdmPrimitiveTypeKind.Int32.getFullQualifiedName());

      CsdlProperty school_name = new CsdlProperty().setName("school_name")

          .setType(EdmPrimitiveTypeKind.String.getFullQualifiedName());

 

      // create PropertyRef for Key element

      CsdlPropertyRef propertyRef = new CsdlPropertyRef();

      propertyRef.setName("school_name");

 

      // navigation property: one-to-many(a school can have many students)

      CsdlNavigationProperty navProp = new CsdlNavigationProperty().setName(NAV_TO_STUDENTS)

          .setType(ET_STUDENT_FQN).setCollection(true).setPartner("School");

\

      //add all navigation properties to a list

      List<CsdlNavigationProperty> navPropList = new ArrayList<CsdlNavigationProperty>();

      navPropList.add(navProp);

 

      // configure EntityType

      entityType = new CsdlEntityType();

      entityType.setName(ET_SCHOOL_NAME);

      entityType.setProperties(Arrays.asList(school_id, school_name));

      entityType.setKey(Arrays.asList(propertyRef));

      entityType.setNavigationProperties(navPropList);

    }

    returnentityType;

 

  }

 

  1. b. OVERRIDING getEntitySets:

 

@Override

  public CsdlEntitySet getEntitySet(FullQualifiedName entityContainer, String entitySetName) {

 

    CsdlEntitySet entitySet = null;

 

    if (entityContainer.equals(CONTAINER)) {

 

      if (entitySetName.equals(ES_STUDENTS_NAME)) {

 

        entitySet = new CsdlEntitySet();

        entitySet.setName(ES_STUDENTS_NAME);

        entitySet.setType(ET_STUDENT_FQN);

 

        // navigation

        CsdlNavigationPropertyBinding navPropBinding = new CsdlNavigationPropertyBinding();

        navPropBinding.setTarget("Schools"); // the target entity set, where the navigation property points to

        navPropBinding.setPath("School"); // the path from entity type to navigation property

        //add all navigation property bindings to a list

List<CsdlNavigationPropertyBinding> navPropBindingList = new ArrayList<CsdlNavigationPropertyBinding>();

        navPropBindingList.add(navPropBinding);

        entitySet.setNavigationPropertyBindings(navPropBindingList);

 

      } elseif (entitySetName.equals(ES_SCHOOLS_NAME)) {

 

        entitySet = new CsdlEntitySet();

        entitySet.setName(ES_SCHOOLS_NAME);

        entitySet.setType(ET_SCHOOL_FQN);

 

        // navigation

        CsdlNavigationPropertyBinding navPropBinding = new CsdlNavigationPropertyBinding();

        navPropBinding.setTarget("Students"); // the target entity set, where the navigation property points to

        navPropBinding.setPath("Students"); // the path from entity type to navigation property

      //add all navigation property bindings to a list

List<CsdlNavigationPropertyBinding> navPropBindingList = new ArrayList<CsdlNavigationPropertyBinding>();

 

        navPropBindingList.add(navPropBinding);

        entitySet.setNavigationPropertyBindings(navPropBindingList);

      }

    }

 

    returnentitySet;

  }

 

  1. c. OVERRIDING getEntityContainerInfo

 

@Override

  public CsdlEntityContainerInfo getEntityContainerInfo(FullQualifiedName entityContainerName) {

 

    // This method is invoked when displaying the service document at

    // eg: http://localhost:8088/school_stu_teachers/DemoService.svc/

    if (entityContainerName == null || entityContainerName.equals(CONTAINER)) {

      CsdlEntityContainerInfo entityContainerInfo = new CsdlEntityContainerInfo();

      entityContainerInfo.setContainerName(CONTAINER);

      returnentityContainerInfo;

    }

 

    returnnull;

  }

 

  1. d. OVERRIDING getSchemas

 

@Override

  public List<CsdlSchema> getSchemas() {

    // create Schema and set the namespace to schema

    CsdlSchema schema = new CsdlSchema();

    schema.setNamespace(NAMESPACE);

 

    // add EntityTypes

    List<CsdlEntityType> entityTypes = new ArrayList<CsdlEntityType>();

    entityTypes.add(getEntityType(ET_STUDENT_FQN));

    entityTypes.add(getEntityType(ET_SCHOOL_FQN));

    schema.setEntityTypes(entityTypes);

 

    // add EntityContainer

    schema.setEntityContainer(getEntityContainer());

 

    // finally add current schema to the list of schemas

    List<CsdlSchema> schemas = new ArrayList<CsdlSchema>();

    schemas.add(schema);

 

    returnschemas;

  }

 

  1. e. DEFINING getEntityContainer

@Override

  public CsdlEntityContainer getEntityContainer() {

 

    // create EntitySets

    List<CsdlEntitySet> entitySets = new ArrayList<CsdlEntitySet>();

    entitySets.add(getEntitySet(CONTAINER, ES_STUDENTS_NAME));

    entitySets.add(getEntitySet(CONTAINER, ES_SCHOOLS_NAME));

    // create EntityContainer

    CsdlEntityContainer entityContainer = new CsdlEntityContainer();

    entityContainer.setName(CONTAINER_NAME);

    entityContainer.setEntitySets(entitySets);

 

    returnentityContainer;

  }

}

 

 

 

 

 

 

 

Metadata:

3)Create processor (for Entity) that implements Entityprocessor:

  1. a. Create readEntity method that gets called on ‘GET’ request

/**

        * This method is invoked when a single entity has to be read. In our

        * example, this can be either a "normal" read operation, or a navigation:

        *

        * Example for "normal" read operation:

        * http://localhost:8080/school_stu_teachers/DemoService.svc/Students(1)

        *

        * Example for navigation

        * http://localhost:8080/school_stu_teachers/DemoService.svc/Students(1)/School

*/

publicvoid readEntity(ODataRequest request, ODataResponse response,UriInfouriInfo, ContentType responseFormat)throws ODataApplicationException, SerializerException {

 

       EdmEntityType responseEdmEntityType = null; // we'll need this to build

                                                                                          //the ContextURL

       Entity responseEntity = new Entity(); // required for serialization of theresponse body

       EdmEntitySet responseEdmEntitySet = null; // we need this for building

 

              // 1st step: retrieve the requested Entity: can be "normal" read

              // operation, or navigation (to-one)

       List<UriResource> resourceParts = uriInfo.getUriResourceParts();

       intsegmentCount = resourceParts.size();

 

       UriResource uriResource = resourceParts.get(0); // in our example, the

                                                                                                // first segment is the

                                                                                                // EntitySet

       if (!(uriResourceinstanceof UriResourceEntitySet)) {

              thrownew ODataApplicationException("Only EntitySet is supported",

                                  HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),

                                  Locale.ENGLISH);

              }

 

       UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource;

       EdmEntitySet startEdmEntitySet = uriResourceEntitySet.getEntitySet();

 

              // Analyze the URI segments

       if (segmentCount == 1) {

              // no navigation

       responseEdmEntityType = startEdmEntitySet.getEntityType();

       responseEdmEntitySet = startEdmEntitySet; // since we have only one

                                                                                                                     //http://localhost:8088/school_stu_teachers/DemoService.svc/Schools('psg')

                        if(responseEdmEntityType.getName().equals(DemoEdmProvider.ET_SCHOOL_NAME))

                        {

List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();

//get the school entity that has name psg

                                  responseEntity=storage.readEntityDataFromDatabase(responseEdmEntitySet,keyPredicates);

                        }

                      

                            

 

       } elseif (segmentCount == 2) {

                     //eg..Students(1)/School

       System.out.println("segment count 2");

                     // navigation

       UriResource navSegment = resourceParts.get(1); //so gets school entity set

       if (navSegmentinstanceof UriResourceNavigation) {

       UriResourceNavigation uriResourceNavigation = (UriResourceNavigation) navSegment;

       EdmNavigationProperty edmNavigationProperty = uriResourceNavigation.getProperty();

       responseEdmEntityType = edmNavigationProperty.getType();

                           // contextURL displays the last segment

                           //System.out.println(""+startEdmEntitySet.getEntityType());

       responseEdmEntitySet = Util.getNavigationTargetEntitySet(

                                         startEdmEntitySet, edmNavigationProperty);

 

                         

       List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();

                           // fetch the data from backend.

                           // e.g. for Students(1)/School we have to find first  Students(1)

                           Entity sourceEntity = storage.readEntityData(startEdmEntitySet,keyPredicates);

 

                           // now we have to check if the navigation is

                           // a) to-one: e.g. Students(1)/School

                           // b) to-many with key: e.g. Schools('psg')/Students(5)

                           // the key for nav is used in this case:

                           // Schools('psg')/Students(5)

List<UriParameter> navKeyPredicates = uriResourceNavigation.getKeyPredicates();

                         

if (navKeyPredicates.isEmpty()) { // e.g. DemoService.svc/Students(1)/School

                                       

responseEntity = storage.getRelatedEntity(sourceEntity,

                                                responseEdmEntityType);

} else { // e.g. DemoService.svc/Schools(3)/Students(5)

                                                                     responseEntity = storage.getRelatedEntity(sourceEntity,

                                                responseEdmEntityType, navKeyPredicates);

                           }

                     }

              } else {

                     // this would be the case for e.g.

                     // Students(1)/School/Students(1)/School

                     thrownew ODataApplicationException("Not supported",

                                  HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);

              }

 

              if (responseEntity == null) {

                     // this is the case for e.g. DemoService.svc/Schools('psg') or

                     // DemoService.svc/Schools('psg')/Students(999) where student with id 999 not exists

                     thrownew ODataApplicationException("Nothing found.",

                                  HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);

              }

 

              SelectOption selectOption = uriInfo.getSelectOption();

              ExpandOption expandOption = uriInfo.getExpandOption();

              // in our example: http://localhost:8080/school_stu_teachers/DemoService.svc/Schools('psg')/$expand=Students

              // or http://localhost:8080/school_stu_teachers/DemoService.svc/Students(1)?$expand=Schools

              if(expandOption != null) {

                     //since more than 1 expand option eg. students,teachers

                     for(inti=0;i<expandOption.getExpandItems().size();i++)

                     {

                     // retrieve the EdmNavigationProperty from the expand expression

                     // Note: in our example, we have only one NavigationProperty, so we can directly access it

                     EdmNavigationProperty edmNavigationProperty = null;

                   

                     ExpandItem expandItem = expandOption.getExpandItems().get(i);

                     if(expandItem.isStar()) {

                           List<EdmNavigationPropertyBinding> bindings = responseEdmEntitySet.getNavigationPropertyBindings();

                           // we know that there are navigation bindings

                           // however normally in this case a check if navigation bindings exists is done

                           if(!bindings.isEmpty()) {

                                  //since we have more than 1 nav bindings

                                  EdmNavigationPropertyBinding binding = bindings.get(i);

                                  EdmElement property = responseEdmEntitySet.getEntityType().getProperty(binding.getPath());

                                  // we don't need to handle error cases, as it is done in the Olingo library

                                  if(propertyinstanceof EdmNavigationProperty) {

                                         edmNavigationProperty = (EdmNavigationProperty) property;

                                  }

                           }

                     } else {

                           // can be 'School' or 'Students', no path supported

                           UriResource expandUriResource = expandItem.getResourcePath().getUriResourceParts().get(0);

                           // we don't need to handle error cases, as it is done in the Olingo library

                           if(expandUriResourceinstanceof UriResourceNavigation) {

                                  edmNavigationProperty = ((UriResourceNavigation) expandUriResource).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) {

                           EdmEntityType expandEdmEntityType = edmNavigationProperty.getType();

                           String navPropName = edmNavigationProperty.getName();

 

                           // build the inline data

                           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('psg')/$expand=Students

                                  // fetch the data for the $expand (to-many navigation) from backend

                                  // here we get the data for the expand

                                  System.out.println("iscollection");

                                  //get students of given school

                                  EntityCollection expandEntityCollection =

              storage.getRelatedEntityCollection(responseEntity, expandEdmEntityType);

                                  link.setInlineEntitySet(expandEntityCollection);

          link.setHref(expandEntityCollection.getId().toASCIIString());

                           } else// in case of Students(1)?$expand=School

                                  // fetch the data for the $expand (to-one navigation) from backend

                                  // here we get the data for the expand

                                  //get school of given student

                                  Entity expandEntity = storage.getRelatedEntity(responseEntity, expandEdmEntityType);

                                  link.setInlineEntity(expandEntity);

          link.setHref(expandEntity.getId().toASCIIString());

                           }

 

                           // set the link - containing the expanded data - to the current entity

                           responseEntity.getNavigationLinks().add(link);

                     }

              }

                           // 3. serialize

              EdmEntityType edmEntityType = responseEdmEntitySet.getEntityType();

              // we need the property names of the $select, in order to build the context URL

              String selectList = odata.createUriHelper().buildContextURLSelectList(edmEntityType, expandOption, selectOption);

              ContextURL contextUrl = ContextURL.with().entitySet(responseEdmEntitySet)

                                         .selectList(selectList)

                                         .suffix(Suffix.ENTITY).build();

 

              // make sure that $expand and $select are considered by the serializer

              // adding the selectOption to the serializerOpts will actually tell the lib to do the job

              EntitySerializerOptions opts = EntitySerializerOptions.with()

                                         .contextURL(contextUrl)

                                         .select(selectOption)

                                         .expand(expandOption)

                                         .build();

 

              ODataSerializer serializer = this.odata.createSerializer(responseFormat);

              SerializerResult serializerResult = serializer.entity(srvMetadata, edmEntityType, responseEntity, opts);

 

              // 5. configure the response object

              response.setContent(serializerResult.getContent());

              response.setStatusCode(HttpStatusCode.OK.getStatusCode());

              response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());

       }

       //if expand null

              else{

              ContextURL contextUrl =

                            ContextURL.with().entitySet(responseEdmEntitySet).suffix(Suffix.ENTITY).build();

                            EntitySerializerOptions opts =

                            EntitySerializerOptions.with().contextURL(contextUrl).build();

                         

                            ODataSerializer serializer =

                            this.odata.createSerializer(responseFormat);

                            SerializerResult serializerResult =

                            serializer.entity(this.srvMetadata,

                            responseEdmEntityType, responseEntity, opts);

                         

                            // 4. configure the response object

                            response.setContent(serializerResult.getContent());

                            response.setStatusCode(HttpStatusCode.OK.getStatusCode());

                            response.setHeader(HttpHeader.CONTENT_TYPE,

                            responseFormat.toContentTypeString());}

                         

       }

  1. b. Create createEntity method that gets called on ‘POST’ request:

publicvoid createEntity(ODataRequest request, ODataResponse response,

                     UriInfo uriInfo, ContentType requestFormat,

                     ContentType responseFormat) throws ODataApplicationException,

                     DeserializerException, SerializerException {

              List<StudentDto> studList=new ArrayList<StudentDto>();

       EdmEntityType responseEdmEntityType = null; // we'll need this to build

                                                                                         // response body

       EdmEntitySet responseEdmEntitySet = null; // we need this for building

                                                                                         // the contextUrl

 

              // 1st step: retrieve the requested Entity: can be "normal" read

              // operation, or navigation (to-one)

       List<UriResource> resourceParts = uriInfo.getUriResourceParts();

       intsegmentCount = resourceParts.size();

 

       UriResource uriResource = resourceParts.get(0); // in our example, the

first segment is the EntitySet

              if (!(uriResourceinstanceof UriResourceEntitySet)) {

                     thrownew ODataApplicationException("Only EntitySet is supported",

                                  HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),

                                  Locale.ENGLISH);

              }

 

              UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource;

              EdmEntitySet startEdmEntitySet = uriResourceEntitySet.getEntitySet();

 

              // Analyze the URI segments

              if (segmentCount == 1) { // no navigation

                     responseEdmEntityType = startEdmEntitySet.getEntityType();

                     responseEdmEntitySet = startEdmEntitySet; // since we have only one

if (responseEdmEntityType.getName().equals(DemoEdmProvider.ET_STUDENT_NAME))

                      {

                   

                   

                            EntityCollection ec=new EntityCollection();

                                  //get data(body)  from post

                                  InputStream requestInputStream = request.getBody();

                                  InputStream is = null;

                                  try {

                                         ObjectMapper mapper = new ObjectMapper();

                                  //     convert inputstream to json

                                         List<Map<String, Object>> jsonmap = mapper.readValue(

                                                       requestInputStream,

                                                       new TypeReference<List<Map<String, Object>>>() {

                                                       });

 

for (Map<String, Object> a : jsonmap) {

       SchoolDto s=new SchoolDto();

       SchoolDo d=new SchoolDo();

       List<Map<String, Object>> stdo=new ArrayList<Map<String, Object>>();

       Map<String, Object> b=new HashMap<String, Object>();

                                  String school_name=(String) a.get("school_name");

                                  s=dao.readSchoolData(school_name);

                                  d=s.getEntity(s);

                                   System.out.println(a.get("studentsDto"));

              stdo= (List<Map<String, Object>>) a.get("studentsDto");

                                  System.out.println(stdo.size());

                                  for(Map<String, Object> i:stdo)

                                  {

                                          StudentDto stuDto=new StudentDto();

                                          ServiceDao dao = new ServiceDao();

                                          StudentDo stuDo=new StudentDo();

                           b.put("stu_name", i.get("stu_name"));   

                           String mapAsJson = new ObjectMapper().writeValueAsString(b);

                                  //Converting json string to java object

                                   StudentDto stud= (StudentDto) fromJson(mapAsJson);

                                

                                   //get studentdo from dto

                                   stuDo=stuDto.getEntity(stud);

                                   stuDo.setSchoolIdRef(d);

                                   dao.create(stuDo);

                                  }

                                  }

                                

                                  }

                                  catch(Exception e)

                                  {System.out.println(e.getMessage());}

                   

                     // 4. configure the response object

              //     response.setContent(serializedResponse.getContent());

                     response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());

                     response.setHeader(HttpHeader.CONTENT_TYPE,

                                  responseFormat.toContentTypeString());

                      }

                      elseif(responseEdmEntityType.getName().equals(DemoEdmProvider.ET_SCHOOL_NAME))

                      {

 

                     InputStream requestInputStream = request.getBody();

                     try {

                           ObjectMapper mapper = new ObjectMapper();

                     //read data (body of post) and convert it to list of maps

                           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) {

                                  // Set<String> b = a.keySet();

 

                                  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"));

                                  b.put("teachersDto", a.get("teachersDto"));

                                  String mapAsJson = new ObjectMapper().writeValueAsString(b);

                                  //Converting json string to java object

                                   SchoolDto scho= (SchoolDto) fromJson1(mapAsJson);

                                  

                                   //create an object in DB

                                   SchoolDto schoolDto=new SchoolDto();

                                   SchoolServiceDao dao = new SchoolServiceDao();

                                   SchoolDo schoolDo=new SchoolDo();

                                   List<SchoolDo> schoolDoList =new ArrayList<SchoolDo>();

                                   //get schooldo from dto

                                   schoolDo=schoolDto.getEntity(scho);

                                   schoolDoList.add(schoolDo);

 

                                  try {

                                         System.out.println(mapAsJson);

                                  } catch (Exception e) {

                                         System.out.println("Exception:"+e.getMessage());

                                  }

                                  System.out.println("hao");

                                  dao.create(schoolDoList);

 

                           }

 

                     } catch (Exception e1) {

                           System.out.println("Exception1:"+e1.getMessage());

                     }

 

            

 

                     // 4. configure the response object

              //     response.setContent(serializedResponse.getContent());

                     response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());

                     response.setHeader(HttpHeader.CONTENT_TYPE,

                                  responseFormat.toContentTypeString());

                    

                      }

                          

              } elseif (segmentCount == 2) {

                     thrownew ODataApplicationException("Not implemented",

                                  HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);

              } else {

                     // this would be the case for e.g.

                     // Students(1)/School/Students(1)/School

                     thrownew ODataApplicationException("Not supported",

                                  HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);

              }

 

 

       }


OData 4.0 Services (CRUD) using Olingo(JSON supported): Part-2

$
0
0
  1. c. Create updateEntity method that gets called on ‘PUT’ method

publicvoid 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))

{

                        intschool_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());

              }}

 

               }

  1. d. deleteEntity method that gets called on ‘DELETE’ request

       publicvoid 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:

  1. 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

   */

  publicvoid readEntityCollection(ODataRequest request, ODataResponse response,

      UriInfo uriInfo, ContentType responseFormat)

      throws ODataApplicationException, SerializerException {

SerializerResult serializerResult=null;

List<UriResource> resourceParts = uriInfo.getUriResourceParts();

              intsegmentCount = 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());

         }

  1. 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(inti=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 (propertyinstanceof 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 (uriResourceinstanceof 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);

}

}

}

}

returnmodifiedEntityList;

         }

OData 4.0 Services (CRUD) using Olingo(JSON supported): Part-3

$
0
0

4)Create a class ‘Storage.java’

  1. a. readEntitySetDataFromDatabase

/* This method is called from readEntityCollection

   * It is used to fetch the list of students /schools from database

   * depending on the entityset provided

*/

 

public EntityCollection readEntitySetDataFromDatabase(EdmEntitySet edmEntitySet)

{

        EntityCollection entityCollection = new EntityCollection();

        if (edmEntitySet.getName().equals(DemoEdmProvider.ES_STUDENTS_NAME)) {

              // entityCollection = getStudents();

               List<SchoolDo> SchoolDoList = dao.readAll();

Entity entity =null;

 

for(SchoolDo Do:SchoolDoList)

{

for(StudentDo a:Do.getStudentsDo())

{

entity = new Entity();

entity.addProperty(new Property(null, "stu_id", ValueType.PRIMITIVE, a.getStu_id()));

entity.addProperty(new Property(null, "stu_name", ValueType.PRIMITIVE,a.getStu_name()));

 

           entity.setType(DemoEdmProvider.ET_STUDENT_FQN.getFullQualifiedNameAsString());

entity.setId(createId(entity, "stu_id"));

// schoolList.add(entity);

entityCollection.getEntities().add(entity);

                     }

System.out.println("testing1 students");

}

 

 

}

elseif (edmEntitySet.getName().equals(DemoEdmProvider.ES_SCHOOLS_NAME)) {

List<SchoolDo> SchoolDoList = dao.readAll();

Entity entity =null;

 

for(SchoolDo Do:SchoolDoList)

{

entity = new Entity();

entity.addProperty(new Property(null, "school_id", ValueType.PRIMITIVE, Do.getSchool_id()));

entity.addProperty(new Property(null, "school_name", ValueType.PRIMITIVE,Do.getSchoolName()));

 

           entity.setType(DemoEdmProvider.ET_SCHOOL_FQN.getFullQualifiedNameAsString());

entity.setId(createId(entity, "school_name"));

System.out.println(entity.getId());

// schoolList.add(entity);

entityCollection.getEntities().add(entity);

System.out.println("testing1 schools");

}

 

//System.out.println("hai");

//schoolList);

}

        returnentityCollection;

}

  1. b. readEntityData

/* This method is called from readEntity or updateEntity

* */

  public Entity readEntityData(EdmEntitySet edmEntitySet, List<UriParameter> keyParams) {

    Entity entity = null;

 

    EdmEntityType edmEntityType = edmEntitySet.getEntityType();

 

      entity =readEntityDataFromDatabase(edmEntitySet, keyParams);

 

   

 

    returnentity;

  }

  1. c. readEntitySetDataFromDatabase

/* This method is called from readEntityData

* */

 

public Entity readEntityDataFromDatabase(EdmEntitySet edmEntitySet, List<UriParameter> keyParams) {

       

Entity entity = new Entity();

 

EdmEntityType edmEntityType = edmEntitySet.getEntityType();

 

if (edmEntityType.getName().equals(DemoEdmProvider.ET_STUDENT_NAME)) {

entity = getStudent(edmEntityType, keyParams);

} elseif (edmEntityType.getName().equals(DemoEdmProvider.ET_SCHOOL_NAME)) {

      

String school_name=null;

                for(UriParameter a:keyParams)

                            {

                                  school_name=a.getText().replaceAll("'", "");

                                                              }

              List<SchoolDo> SchoolDoList = dao.readAll();

              for(SchoolDo Do:SchoolDoList)

       {

             

              if(Do.getSchoolName()!=null){

              if(Do.getSchoolName().equalsIgnoreCase(school_name))

              {

                                  

                  entity.addProperty(new Property(null, "school_id", ValueType.PRIMITIVE, Do.getSchool_id()));

                  entity.addProperty(new Property(null, "school_name", ValueType.PRIMITIVE,Do.getSchoolName()));

               

           entity.setType(DemoEdmProvider.ET_SCHOOL_FQN.getFullQualifiedNameAsString());

                 entity.setId(createId(entity, "school_id"));

              }}

       }

}

 

returnentity;

         }

  1. d. getStudent

/* This method is called from readEntitySetDataFromDatabase

This method for eg..fetches the required student from the list of students from database */

  private Entity getStudent(EdmEntityType edmEntityType, List<UriParameter> keyParams) {

String stu_id=null;

    // the list of entities at runtime

         for(UriParameter w:keyParams)

         {

               stu_id = w.getText();

         }

    EntityCollection entityCollection = getStudentsFromDatabase(Integer.parseInt(stu_id));

 

    /* generic approach to find the requested entity */

    return Util.findEntity(edmEntityType, entityCollection, keyParams);

  }

  1. e. getStudentsFromDatabase

 

/* This method is called from getStudent

This method returns all the students from database */

 

private EntityCollection getStudentsFromDatabase(intstu_id)

{

       Entity entity=null;

EntityCollection collect=new EntityCollection();

       Session session = MySessionFactory.getConnection().openSession();

       SchoolDto dto=new SchoolDto();

              //List<SchoolDto> listDto=new ArrayList<SchoolDto>();

              Criteria c= session.createCriteria(StudentDo.class);

              c.add(Restrictions.eq("stu_id", stu_id));

              List<StudentDo> list = c.list();

              for(StudentDo ldo:list)

              {

                     entity=new Entity();

                     entity.addProperty(new Property(null, "stu_id", ValueType.PRIMITIVE, ldo.getStu_id()));

entity.addProperty(new Property(null, "stu_name", ValueType.PRIMITIVE, ldo.getStu_name()));

entity.addProperty(new Property(null, "schoolIdRef", ValueType.PRIMITIVE, ldo.getSchoolIdRef()));

entity.setType(DemoEdmProvider.ET_STUDENT_FQN.getFullQualifiedNameAsString());

entity.setId(createId(entity, "stu_id"));

 

                     collect.getEntities().add(entity);

              }

returncollect;

}

  1. f. getRelatedEntity

/*This method is called from applyExpandQueryOption

which in turn calls getRelatedEntityCollection

* */

public Entity getRelatedEntity(Entity entity, EdmEntityType relatedEntityType) {

    EntityCollection collection = getRelatedEntityCollection(entity, relatedEntityType);

    if (collection.getEntities().isEmpty()) {

      returnnull;

    }

    returncollection.getEntities().get(0);

  }

/*This method is called from readEntity

which in turn calls getRelatedEntityCollection

* */

public Entity getRelatedEntity(Entity entity, EdmEntityType relatedEntityType, List<UriParameter> keyPredicates) {

 

    EntityCollection relatedEntities = getRelatedEntityCollection(entity, relatedEntityType);

    return Util.findEntity(relatedEntityType, relatedEntities, keyPredicates);

  }

 

  1. g. getRelatedEntityCollection

/*This method is called from getRelatedEntity

* This method returns all the students/schools depending upon the targetEntityType

* if targetEntityType is students then it returns all the students of the

* corresponding sourceEntity(eg..schools(‘psg’))

* */

public EntityCollection getRelatedEntityCollection(Entity sourceEntity, EdmEntityType targetEntityType) {

    EntityCollection navigationTargetEntityCollection = new EntityCollection();

    Entity entity=null;

    FullQualifiedName relatedEntityFqn = targetEntityType.getFullQualifiedName();

    String sourceEntityFqn = sourceEntity.getType();

 

    if (sourceEntityFqn.equals(DemoEdmProvider.ET_STUDENT_FQN.getFullQualifiedNameAsString())

        && relatedEntityFqn.equals(DemoEdmProvider.ET_SCHOOL_FQN)) {

       System.out.println("get related entity collection method");

       navigationTargetEntityCollection.setId(createId(sourceEntity, "stu_id", DemoEdmProvider.NAV_TO_SCHOOL));

       intstu_id = (int) sourceEntity.getProperty("stu_id").getValue();

      

      

       for(SchoolDto sdto:dao.readStudentData(stu_id))

       {

              entity = new Entity();

              System.out.println("stu id is"+sdto.getSchool_id());

           entity.addProperty(new Property(null, "school_id", ValueType.PRIMITIVE, sdto.getSchool_id()));

           entity.addProperty(new Property(null, "school_name", ValueType.PRIMITIVE, sdto.getSchoolName()));

          

           entity.setType(DemoEdmProvider.ET_SCHOOL_FQN.getFullQualifiedNameAsString());

           entity.setId(createId(entity, "school_name"));

           navigationTargetEntityCollection.getEntities().add(entity);

       

       }

    } elseif (sourceEntityFqn.equals(DemoEdmProvider.ET_SCHOOL_FQN.getFullQualifiedNameAsString())

        && relatedEntityFqn.equals(DemoEdmProvider.ET_STUDENT_FQN)) {

  1. navigationTargetEntityCollection.setId(createId(sourceEntity, "school_name", DemoEdmProvider.NAV_TO_STUDENTS));

      // relation Category->Products (result all products)

String school_name = (String) sourceEntity.getProperty("school_name").getValue();

  1. System.out.println("school name inside storage java"+school_name);

SchoolDto dto=new SchoolDto();

SchoolServiceDao dao=new SchoolServiceDao();

dto=dao.readSchoolData(school_name);

  1. System.out.println("hee");

for(StudentDto sdto:dto.getStudentsDto())

{

       entity = new Entity();

       System.out.println("stu id is"+sdto.getStu_id());

    entity.addProperty(new Property(null, "stu_id", ValueType.PRIMITIVE, sdto.getStu_id()));

    entity.addProperty(new Property(null, "stu_name", ValueType.PRIMITIVE, sdto.getStu_name()));

   

    entity.setType(DemoEdmProvider.ET_STUDENT_FQN.getFullQualifiedNameAsString());

    entity.setId(createId(entity, "stu_id"));

    navigationTargetEntityCollection.getEntities().add(entity);

}

 

    elseif (sourceEntityFqn.equals(DemoEdmProvider.ET_SCHOOL_FQN.getFullQualifiedNameAsString())

            && relatedEntityFqn.equals(DemoEdmProvider.ET_TEACHER_FQN)) {

       TeacherDto dto_tea=new TeacherDto();

    navigationTargetEntityCollection.setId(createId(sourceEntity, "school_name", DemoEdmProvider.NAV_TO_TEACHERS));

          // relation Category->Products (result all products)

    String school_name = (String) sourceEntity.getProperty("school_name").getValue();

    System.out.println("school name inside storage java"+school_name);

    SchoolDto dto1 = new SchoolDto();

    SchoolServiceDao dao=new SchoolServiceDao();

    dto1=dao.readSchoolData(school_name);

    System.out.println("school dto1 size"+dto1);

    for(TeacherDto tdto:dto1.getTeachersDto())

    {

       entity = new Entity();

       System.out.println("TEACHER id is"+tdto.getTeacher_id());

        entity.addProperty(new Property(null, "teacher_id", ValueType.PRIMITIVE, tdto.getTeacher_id()));

        entity.addProperty(new Property(null, "teacher_name", ValueType.PRIMITIVE, tdto.getTeacher_name()));

       

        entity.setType(DemoEdmProvider.ET_TEACHER_FQN.getFullQualifiedNameAsString());

        entity.setId(createId(entity, "teacher_id"));

        navigationTargetEntityCollection.getEntities().add(entity);

    }}

    if (navigationTargetEntityCollection.getEntities().isEmpty()) {

      returnnull;

    }

 

    returnnavigationTargetEntityCollection;

  }

  1. h. createId

/*This method is creates id(uri) by appending entityset name followed by navigation name

* */

public URI createId(Entity entity, String idPropertyName) {

    return createId(entity,idProperName,null);

  }

 

  private URI createId(Entity entity, String idPropertyName, String navigationName) {

    try {

      StringBuilder sb = new StringBuilder(getEntitySetName(entity)).append("(");

      final Property property = entity.getProperty(idPropertyName);

      sb.append(property.asPrimitive()).append(")");

      if(navigationName != null) {

        sb.append("/").append(navigationName);

      }

      returnnew URI(sb.toString());

    } catch (URISyntaxException e) {

      thrownew ODataRuntimeException("Unable to create (Atom) id for entity: " + entity, e);

    }

  }

 

  1. i. getEntitySetName

/*This method is called from createId method

*Returns entitySetName for the required entity

* */

private String getEntitySetName(Entity entity) {

    if(DemoEdmProvider.ET_SCHOOL_FQN.getFullQualifiedNameAsString().equals(entity.getType())) {

      return DemoEdmProvider.ES_SCHOOLS_NAME;

    } elseif(DemoEdmProvider.ET_STUDENT_FQN.getFullQualifiedNameAsString().equals(entity.getType())) {

      return DemoEdmProvider.ES_STUDENTS_NAME;

    }

    returnentity.getType();

  }

  1. j.createEntityData,createSschool,createStudent

/*This method is called from createEntity method in processor

*which inturn calls createSchool/createStudent based on entity set name

* */

public Entity createEntityData(EdmEntitySet edmEntitySet, Entity entityToCreate) {

 

EdmEntityType edmEntityType = edmEntitySet.getEntityType();

 

// actually, this is only required if we have more than one Entity Type

if (edmEntityType.getName().equals(DemoEdmProvider.ET_STUDENT_NAME)) {

return createStudent (edmEntityType,entityToCreate);

}

if (edmEntityType.getName().equals(DemoEdmProvider.ET_SCHOOL_NAME)) {

System.out.println("school name matched");

                    return createSchool(edmEntityType, entityToCreate);

}

returnnull;

         }

 

/*This method is called from createEntityData method

*This method gets school entity,creates new school_id and add to schools list

* */

  private Entity createSchool(EdmEntityType edmEntityType, Entity entity) {

       // TODO Auto-generated method stub

         intnewId = 1;

while (schoolIdExists(newId)) {

newId++;

}

 

Property idProperty = entity.getProperty("school_id");

if (idProperty != null) {

idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));

} else {

// as of OData v4 spec, the key property can be omitted from the POST request body

entity.getProperties().add(new Property(null, "school_id", ValueType.PRIMITIVE, newId));

}

entity.setId(createId(entity, "school_id"));

this.schoolList.add(entity);

 

returnentity;

 

}

 

/*This method is called from createEntityData method

*This method gets student entity,creates new student_id and add to students list

* */

 

private Entity createStudent(EdmEntityType edmEntityType, Entity entity) {

 

// the ID of the newly created product entity is generated automatically

intnewId = 1;

while (studentIdExists(newId)) {

newId++;

}

 

Property idProperty = entity.getProperty("stu_id");

if (idProperty != null) {

idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));

} else {

// as of OData v4 spec, the key property can be omitted from the POST request body

entity.getProperties().add(new Property(null, "stu_id", ValueType.PRIMITIVE, newId));

}

entity.setId(createId(entity, "stu_id"));

this.studentList.add(entity);

 

returnentity;

 

         }

 

  1. k. studentIdExists

/*This method is called from createStudent

*This method checks if the student id already exists in database

* */

privateboolean studentIdExists(intid) {

 

for (Entity entity : this.studentList) {

Integer existingID = (Integer) entity.getProperty("stu_id").getValue();

if (existingID.intValue() == id) {

returntrue;

}

}

 

returnfalse;

         }

 

 

 

 

/*This method is called from createSchool

*This method checks if the school id already exists in database

* */

privateboolean schoolIdExists(intid) {

 

  for (Entity entity : this.schoolList) {

                    Integer existingID = (Integer) entity.getProperty("school_id").getValue();

                    if (existingID.intValue() == id) {

                      returntrue;

                    }

}

 

returnfalse;

                }

creating table element

$
0
0

Hi,

 

I am trying to add table element but getting below error, I am using BO 4.1 SP2

 

Is this BO version issue?, I can also see only two elements "cell" and "section" for creating element mentioned In Restful guide for 4.1 SP2

 

  • <error>
  •    <error_code>101</error_code>
  •    <message>The resource of type 'Report element' cannot be created.</message>
  •    <stack_trace>com.sap.webi.raylight.RaylightException: The resource of type 'Report element' cannot be created.&#13;
  •   at com.sap.webi.raylight.context.Messenger.createException(Messenger.java:57)&#13;
  •   at com.sap.webi.raylight.actions.reportelement.CreateReportElementAction.execute(CreateReportElementAction.java:48)&#13;
  •   at sun.reflect.GeneratedMethodAccessor278.invoke(Unknown Source)&#13;
  •   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)&#13;
  •   at java.lang.reflect.Method.invoke(Method.java:597)&#13;
  •   at com.sap.webi.raylight.actions.ActionInvoker.invokeWith(ActionInvoker.java:123)&#13;
  •   at com.sap.webi.raylight.actions.ActionDispatcher.invoke(ActionDispatcher.java:105)&#13;
  •   at com.sap.webi.raylight.RaylightServiceReportElements.createReportElement(RaylightServiceReportElements.java:105)&#13;
  •   at sun.reflect.GeneratedMethodAccessor270.invoke(Unknown Source)&#13;
  •   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)&#13;
  •   at java.lang.reflect.Method.invoke(Method.java:597)&#13;
  •   at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:173)&#13;
  •   at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:89)&#13;
  •   at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:164)&#13;
  •   at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:242)&#13;
  •   at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:242)&#13;
  •   at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:242)&#13;
  •   at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:242)&#13;
  •   at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:91)&#13;
  •   at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)&#13;
  •   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)&#13;
  •   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)&#13;
  •   at java.util.concurrent.FutureTask.run(FutureTask.java:138)&#13;
  •   at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)&#13;
  •   at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)&#13;
  •   at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255)&#13;
  •   at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:113)&#13;
  •   at org.apache.cxf.transport.servlet.ServletDestination.invoke(ServletDestination.java:102)&#13;
  •   at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:464)&#13;
  •   at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:149)&#13;
  •   at com.sap.bip.rs.server.servlet.BIPServletController.invoke(BIPServletController.java:93)&#13;
  •   at org.apache.cxf.transport.servlet.AbstractCXFServlet.invoke(AbstractCXFServlet.java:148)&#13;
  •   at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:179)&#13;
  •   at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:103)&#13;
  •   at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)&#13;
  •   at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:159)&#13;
  •   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)&#13;
  •   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)&#13;
  •   at com.businessobjects.sdk.actionfilter.WorkflowFilter.doFilter(WorkflowFilter.java:45)&#13;
  •   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)&#13;
  •   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)&#13;
  •   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)&#13;
  •   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)&#13;
  •   at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)&#13;
  •   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)&#13;
  •   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)&#13;
  •   at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)&#13;
  •   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)&#13;
  •   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)&#13;
  •   at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)&#13;
  •   at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)&#13;
  •   at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)&#13;
  •   at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)&#13;
  •   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)&#13;
  •   at java.lang.Thread.run(Thread.java:743)&#13;
  • </stack_trace>
  • </error>

Schedule a Publication in BO 4.1 with Webi Prompts

$
0
0

Hello,

 

I have a publication in BO 4.1 SP4, and I know how to schedule with the SDK api, but there are Webi reports inside, is there any tricks to modify prompts, since it's not available anymore in REBEAN SDK.

 

The only way to perform this, for me, actually  is to schedule each webi reports, through REST api, and wait for the end of generations, and schedule publication without refreshing document.

 

Do I have miss a point ?

 

Thanks by advance.

Suppress Prompts in RESTful API

$
0
0

Hi Experts,

 

In XI3.1 Deski, macros have the ability to suppress prompts to refresh the document.  I am wondering if there is a way to do the same in RESTful API in BO 4.1 SP6.  I am now using this trick to accomplish:

1) check the document to see if it has prompts by calling GET.../biprws/raylight/v1/documents/documentId/parameters

2) if it has prompts, I use the default value to refresh by calling PUT.../biprws/raylight/v1/documents/documentId/parameters with prompts; otherwise, refresh without prompts or empty parameters.

 

This works fine but I want to eliminate an extra call to the server if I may.

 

Thank you.

Variables DataFilter is not working in RESTful API

$
0
0

Hi Experts,

 

I have a document that has multiple data providers (say, dataprovider1, dataprovider2, dataprovider3) which I merge them in to one (dataprovider merged).  Then I create a variable (dataprovider) in the variables folder.  When I process it in RESTful API by supplying the datafilter <datafilter><and><condition key="[dataprovider]" operator="Equal"><value>my value</value></condition></and></datafilter> using API http://host:port/biprws/raylight/v1/documents/<documentId>/reports/<reportId>/datafilter, but I get an error:

<error><error_code>WSR 00400</error_code> <message>The expression "[dataprovider]" can't be found in the document dictionary. Please enter another expression.</message></error>

 

Please help.  Most of all documents are like this.

 

Thank you.

BI 4.1 SP6 Scheduling Destinations

$
0
0

Hi all,

 

Is it possible to use the RESTful Web Services SDK to schedule a report to the SFTP or secure SMTP destinations that are now available in BI 4.1 SP6?

 

Thanks,

Christian


Create piechart with rest api

$
0
0

Hi,

 

I have created piechart with rest api by creating dataprovider in document and updated query specification and finally with updating report specification.  Piechart is created but label name is showing as [?? DP0.DS1??] instead of column name as state . Please find snap as below.

 

Thanks,

Amol.

PieChart.PNG

Identify whether a data provider has a context

$
0
0

Hello Friends

 

Using RESTful web service SDK how can i identify whether a particular data provider in a BI 4.1 Webi document has a context or not?

 

I used the GET <webiURL>/documents/8722/dataproviders/DP5/queryplan call as suggested in the RESTful web service guide and searched for the "Missing contexts" keywords in the response but it isn't working.  The "Missing contexts" keywords are not present in the response even when the data provider had a context.

 

Is there any other way to identify whether a data provider has a context or not using RESTful web service SDK?

 

Regards,

-CF

Query specification

$
0
0

Hi guys,

 

I am using the Restful SDK to get the dataproviders query specification (http://server:6405/biprws/raylight/v1/documents/{ID}/dataproviders/DP0/specification). The result XML is something like this:

 

<queryspec:QuerySpec xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:parameter="http://com.sap.sl.parameter" xmlns:queryspec="http://com.sap.sl.queryspec" dataProviderId="DP0">

    <queryParameters>   

    </queryParameters>

    <queriesTree xsi:type="queryspec:QueryOperatorNode" queryOperator="Union">

        <children xsi:type="queryspec:QueryDataNode">

            <bOQuery name="Query" identifier="_DQwTUS-BEeWGVJVUo9we">

                <resultObjects identifier="DS0.DO4fc" name="asdasdad"/>

                <conditionPart>

                    <conditionTree xsi:type="queryspec:ConditionOperatorNode" logicalOperator="And">

                    

                    </conditionTree>

                </conditionPart>

            </bOQuery>

        </children>

    </queriesTree>

</queryspec:QuerySpec>

 

 

I have to parse this XML to identify all the universe objects used by the document (result objects and conditions too). Where can I find the formal schema/specification/documentation for this XML?

 

Are there any good examples available, to parse this XML?

 

Thx.

BI Universe Connector using Rest API

$
0
0

Using Rest API URL, I can send HTTP calls using Chrome Rest client and can see just the universe metadata like CUID, Description, Type etc.Using <Resturl>/sl/v1/universes/si_id , I can see the unx universe Folder and object names, Data Type.

 

I would like to know how to query the universe data as ODATA feed in MS Excel using the Rest API URL. If yes, what needs to be done and what the Odata URL would look like. Any guidance is appreciated.

Excel output error

$
0
0

Hi,

 

I am getting this error when exporting the Webi document to excel, any help appreciated.

 

<error>
    <error_code>RWS 00008</error_code>
    <message>No logon token provided in the X-SAP-LogonToken HTTP header or query parameter. (RWS 00008)</message>
</error>

 

Thanks,
Arun

retrive folders and report documents list

$
0
0

We are using raylight rest api.

 

<title>Web Intelligence - Raylight</title>

 

<version>1.0</version>

<vendor>SAP SE</vendor>

<build>14.1.6.1702</build>

 

 

Is any api to get list of folders ? (same like get documents api i.e http://localhost:6405/biprws/raylight/v1/documents)

 

Thanks

Samir

How to Retrive report documents / folders belong to given universe only?

$
0
0

Hi,

 

Right now i am calling api /biprws/infostore/Root%20Folder/children?type=folder&pageSize=50 and than made function to retrieve report documents under my list of folders.

I used api /biprws/infostore/[folder object id]/children?type=webi&pageSize=50 to retrive the report documents.

 

Here I am getting all report documents which belong to different universes.

 

How can we identity report document is related to which universe ? Means report document relationship is with which universe?

 

Thanks

Samir


Any specific settings required for REST services !!!

$
0
0

Hi,

 

I tried to get the content of webi reports using REST calls.

 

I am interested in querying the dataprovider properties (viz source, source type) and dataprovider details (objects in the data provider, links if any).

 

When I try to execute them in batch mode through java application, after fetching few reports details my requests are getting time out. I have the connection time out as 10 minutes.  When I retry the same report, I am getting the required data.

 

I am on BI 4.0 SP9.

 

Any specific settings needs to be made on WACS or any other services to avoid this issue.

 

Regards,

Subramanian S.

RESTful SDK: Retrieve which access rights a principal has on folders/reports

$
0
0

Hi,

 

I wonder whether it is possible to find out what exact access rights (also inherited rights) a specific user or usergroup has on a report or folder by using the RESTful Web Services SDK. The result I want is what can be found in the CMC (No access, View (inherited), Full Control, etc).

I am able to find the Folder structure/Hierarchy, and the UserGroup/User hierarchy using the RESTful API. However, I haven't been able to find the relation between a Folder and a Principal(Usergroup/User), and the access levels on this relation.

Does anyone know if this is possible with the RESTful SDK?

 

regards,

Dorien

Change text format in webi report

$
0
0

Hi,

 

I am able to export the webi report in xls using the RESTFUL SDK but the text field is wrapped. I can do that in webi, but is there a way i can unwrap the text (hard code it in the code) while exporting?

 

Thanks,
Arun

How to get a copy of the generated report?

$
0
0

Hi,

 

I am on BO 4.1 SP5.

 

I need to schedule a report and then get a copy of it once it is generated. I have figured out the the APIs needed for first browsing the folders, listing them, and scheduling the report of interest. However, once the scheduled report is generated (I am generating a pdf), I can't find an API to fetch that generated report. My experiments suggest that the generated report doesn't show up as part of "documents", and therefore I cannot use the document APIs to list/fetch it. The schedule APIs only provide further information about the schedule, but not actually giving me a copy of the report that I can save locally. Any inputs would be highly appreciated.

 

Thanks

-Ankit

dataSourceId is not an Int

$
0
0

Hi guys,

 

I am using the Rest API to query documents datasource details. In one exceptional case I got this response:

 

"dataprovider": {

  "id": "DP0",

  "name": "Name of the data provider",

  "dataSourceId": "213123;SomeStringHere",

  "dataSourceType": "bex",

  "updated": "2015-04-16T10:14:06.000+02:00",

  "duration": 2,

  "isPartial": false,

  "rowCount": 763,

  "flowCount": 1,

 

  more...

}

 

Why is the dataSourceId not an Int? In every other case it's an int. The documentation does not specify if it should be an int or not, but all the examples use an int.

 

Where can I find a formal specification of the Restful API response/result objects?

 

It is a real pain to guess the possible types of specific properties.

Viewing all 262 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>