Skip to content
fmartelli edited this page May 31, 2013 · 18 revisions

This page shows some sample usage of ODataJClient, either at high (e.g. Proxy) and low (e.g. Engine) level.

Proxy samples

The snippets below refer to the example presented in the design document.

Get Entity

        DemoService demoService = entityContainerFactory.getEntityContainer(DemoService.class);

        // Take the product with key value 3
        Product product3 = demoService.getProducts().get(3);

Asynchronous

        AsyncDemoService demoService = entityContainerFactory.getEntityContainer(AsyncDemoService.class);

        // Take the product with key value 3 asynchronously
        Future<Product> product3 = demoService.getProducts().get(3);

Create Entities

        DemoService demoService = entityContainerFactory.getEntityContainer(DemoService.class);

        // create Category (local)
        Category category = new Category();
        category.setName("a category name");        
        category = demoService.getCategories().save(category);
        
        // create Product (local)
        Product product = new Product();
        product.setName("a name");
        product.setDescription("a description");
        product.setPrice(11F);
        product.setReleaseDate(new Date());        
        product = demoService.getProducts().save(product);
        
        // link product and category
        product.setCategory(category);
        category.setProducts(Collections.singletonList(product));
        
        // any flush() will generate actual operations on the OData service
        demoService.getProducts().flush();

Invoke Operation

        DemoService demoService = entityContainerFactory.getEntityContainer(DemoService.class);

        // invoke GetProductsByRating
        Collection<Product> products = demoService.getProductsByRating(15);

Asynchronous

        AsyncDemoService demoService = entityContainerFactory.getEntityContainer(AsyncDemoService.class);

        // invoke GetProductsByRating asynchronously
        Future<Collection<Product>> productsFuture = demoService.getProductsByRating(15);
        while (!productsFuture.isDone()) {
            Thread.sleep(1000);
        }
        Collection<Product> products = productsFuture.get();

Entity Query

        DemoService demoService = entityContainerFactory.getEntityContainer(DemoService.class);

        // Typed query for products with price < 10.00
        EntityQuery<Product> productQuery = demoService.getProducts().createQuery(Product.class);
        productQuery.setFilter("Price lt 10.00");

        List<Product> matchingProducts = productQuery.getResultList();

        // ... do something with matchingProducts

        // Typed query for categories of products with price < 10.00
        EntityQuery<Category> categoryQuery = demoService.getProducts().createQuery(Category.class);
        productQuery.setFilter("Price lt 10.00");
        productQuery.setSelect("Category");

        List<Category> matchingCategories = categoryQuery.getResultList();
        
        // ... do something with matchingCategories

Asynchronous

        AsyncDemoService demoService = entityContainerFactory.getEntityContainer(AsyncDemoService.class);

        // Typed query for products with price < 10.00, to be execute asynchronously
        AsyncEntityQuery<Product> productQuery = demoService.getProducts().createQuery(Product.class);
        productQuery.setFilter("Price lt 10.00");

        Future<List<Product>> matchingProductsFuture = productQuery.asyncGetResultList();

        // ... do something with matchingProductsFuture

Untyped Query

        DemoService demoService = entityContainerFactory.getEntityContainer(DemoService.class);

        // Untyped query for names of products with price < 10.00
        Query query = demoService.getProducts().createQuery();
        query.setFilter("Price lt 10.00");
        query.setSelect("Name");

        List<? extends Serializable> match = query.getResultList();

        // ... do something with match

Asynchronous

        AsyncDemoService demoService = entityContainerFactory.getEntityContainer(AsyncDemoService.class);

        // Untyped query for names of products with price < 10.00, to be execute asynchronously
        AsyncQuery query = demoService.getProducts().createQuery();
        query.setFilter("Price lt 10.00");
        query.setSelect("Name");

        Future<List<? extends Serializable>> matchFuture = query.asyncGetResultList();

        // ... do something with matchFuture

Engine samples

Create entity

        // provide the target URI
        final ODataURIBuilder targetURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        targetURI.appendEntitySetSegment("Products");

        // build the new object
        final ODataEntity newEntity = EntityFactory.newEntity("Java Code");

        // Add a complex property
        final ODataComplexValue addressValue = new ODataComplexValue("Address");
        addressValue.add(new ODataProperty("city", new ODataPrimitiveValue("XXX", EdmSimpleType.String)));
        addressValue.add(new ODataProperty("street", new ODataPrimitiveValue("YYY", EdmSimpleType.String)));

        newEntity.addProperty(new ODataProperty("Address", addressValue));

        // Add a collection property
        final ODataCollectionValue preferredColors = new ODataCollectionValue("Colors");
        preferredColors.add(new ODataPrimitiveValue("red", EdmSimpleType.String));
        preferredColors.add(new ODataPrimitiveValue("yellow", EdmSimpleType.String));

        newEntity.addProperty(new ODataProperty("PreferredColors", preferredColors));
        // newEntity.set ...

        // just for example, add atom extensions
        ODataEntityAtomExtensions atomExtensions = new ODataEntityAtomExtensions();
        atomExtensions.setSummary("OData client Java framework");
        newEntity.setAtomExtensions(atomExtensions);

        // create your request
        final ODataCreateEntityRequest request =
                ODataRequestFactory.getCreateEntityRequest(targetURI.build(), newEntity);

        // execute the request
        ODataCreateEntityResponse res = client.<ODataCreateEntityResponse>execute(request);

        // retrieve created entity
        ODataEntity created = res.getBody();

        // retrieve and process execution results
        int statusCode = res.getStatusCode();
        String statusMessage = res.getStatusMessage();

Create link

        // provide the source URI
        final ODataURIBuilder sourceURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        sourceURI.appendEntityTypeSegment("Products(1)");

        // provide the target URI
        final ODataURIBuilder targetURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        targetURI.appendEntityTypeSegment("Suppliers(5)");

        // build the new link
        final ODataLink newLink =
                EntityFactory.newEntityLink("Supplier", targetURI.build());

        // create your request
        final ODataAddLinkRequest request =
                ODataRequestFactory.getAddLinkRequest(sourceURI.build(), newLink);

        // execute the request
        ODataLinkOperationResponse res = client.<ODataLinkOperationResponse>execute(request);

        // retrieve and process execution results
        int statusCode = res.getStatusCode();
        String statusMessage = res.getStatusMessage();

Update entity (PATCH)

        // provide the target URI
        final ODataURIBuilder targetURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        targetURI.appendEntityTypeSegment("Products(2)");

        // build the new object to change Rating value
        final ODataEntity changes = EntityFactory.newEntity("Java Code");
        changes.addProperty(new ODataProperty("Rating", new ODataPrimitiveValue(3, EdmSimpleType.Int32)));

        // create your request
        final ODataUpdateEntityRequest request =
                ODataRequestFactory.getUpdateEntityRequest(targetURI.build(), changes, UpdateType.PATCH);

        // execute the request
        ODataUpdateEntityResponse res = client.<ODataUpdateEntityResponse>execute(request);

        // retrieve update object if returned
        ODataEntity updated = res.getBody();

        // retrieve and process execution results
        int statusCode = res.getStatusCode();
        String statusMessage = res.getStatusMessage();

Delete entity

        // provide the target URI
        final ODataURIBuilder targetURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        targetURI.appendEntityTypeSegment("Products(2)");

        // create your request
        final ODataDeleteRequest request = ODataRequestFactory.getDeleteRequest(targetURI.build());

        // execute the request
        ODataDeleteResponse res = client.<ODataDeleteResponse>execute(request);

        // retrieve and process execution results
        int statusCode = res.getStatusCode();
        String statusMessage = res.getStatusMessage();

Async Entity Create

        // provide the target URI
        final ODataURIBuilder targetURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        targetURI.appendEntitySetSegment("Products");

        // build the new object
        final ODataEntity newEntity = EntityFactory.newEntity("Java Code");
        // newEntity.set ...

        // create your request
        final ODataRequest request = ODataRequestFactory.getCreateEntityRequest(targetURI.build(), newEntity);

        // execute the request
        final Future<ODataCreateEntityResponse> res = 
                client.<ODataCreateEntityResponse>asyncExecute(request);

        if (res.isDone()) {
            try {
                // retrieve and process execution results
                int statusCode = res.get().getStatusCode();
                String statusMessage = res.get().getStatusMessage();

                // .....
            } catch (InterruptedException ex) {
                // ...
            } catch (ExecutionException ex) {
                // ...
            }
        }

Query

        // prepare URI
        final ODataURIBuilder uri = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        uri.appendEntityTypeSegment("Products(0)").expand("Supplier").select("Rating,Supplier/Name");

        // create new request
        final ODataQueryRequest request = ODataRequestFactory.getQueryRequest(uri.build());

        // execute request
        final ODataQueryResponse res = client.<ODataQueryResponse>execute(request);

        // retrieve and process the query result
        for (ODataEntity entity : res.<ODataEntity>getBody()) {
            // .................
        }

Invoke Function

        // provide the target URI
        final ODataURIBuilder targetURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        targetURI.appendFunctionSegment("GetProductsByRating").addQueryParameter("rating", "4");

        // create your request
        final ODataInvokeRequest request = ODataRequestFactory.getInvokeFunctionRequest(targetURI.build());

        // execute the request
        ODataInvokeResponse res = client.<ODataInvokeResponse>execute(request);

        for (ODataEntity result : res.<ODataEntity>getBody()) {
            // process retrieved entity ...
        }

Invoke Bindable Action

        // provide the target URI
        final ODataURIBuilder targetURI = new ODataURIBuilder("http://services.odata.org/OData/Odata.svc");
        targetURI.appendEntityTypeSegment("Product(0)").appendActionSegment("UpdateProductRating");

        final ODataPrimitiveValue value = new ODataPrimitiveValue(2, EdmSimpleType.Int32);
        final Map<String, ODataValue> parameters = 
                Collections.<String, ODataValue>singletonMap("rating", value);

        // create your request
        final ODataInvokeRequest request =
                ODataRequestFactory.getInvokeActionRequest(targetURI.build(), parameters);

        // execute the request
        ODataInvokeResponse res = client.<ODataInvokeResponse>execute(request);

Metadata Query

        // create new request
        final ODataMetadataRequest request =
                ODataRequestFactory.getMetadataRequest("http://services.odata.org/OData/Odata.svc");

        // execute request
        final ODataMetadataResponse res = client.<ODataMetadataResponse>execute(request);

        // get access to metadata object
        ODataMetadata metadata = res.getBody();

        // (sample) access EntityType
        EntityType entityType = metadata.getSchema(0).getEntityTypes().get(1);

        // (sample) access EntityContainer
        EntityContainer entityContainer = metadata.getSchema(0).getEntityContainers().get(0);

Clone this wiki locally