November 15, 2012

How to set binding object values from Java class?


This post is to explain how to set values of an object to another object of same type in adf bindings from java class. To understand better, let’s take an example. I have a java class to which data control was created.  The class contains an object of ServiceRequest class which was defined during some actions in the class. The object contains setters and getters. The object is available for data control and a form is created for the fields of the ServiceRequest class on JSF page from the data control. We have a button on the JSF page. On click of the button, a java been method is invoked in which a webservice call is being executed and a response object of type ServiceRequest class is returned. This returned object should be set to binding object. To do this, we should get values of all the fields of return object and then set them to second object in bindings. The following code will do this.


BindingContext bc = BindingContext.getCurrent();
   
    BindingContainer bindingContainer = bc.getCurrentBindingsEntry();
    DCBindingContainer bindingsImpl = (DCBindingContainer)bindingContainer;
    DCIteratorBinding iter =
      bindingsImpl.findIteratorBinding("serviceRequestIterator");
    //get current row of the binding iterator
    Row row = iter.getCurrentRow();
    //Assign all attributes of result object to attributes of current row object in binding's iterator
    try {
      String[] attributeNames = row.getAttributeNames();
      for (int i = 0; i < attributeNames.length; i++) {
       
        String getter =
          "" + Character.toUpperCase(attributeNames[i].charAt(0)) +
          attributeNames[i].subSequence(1, attributeNames[i].length());
        System.out.println("attribute: " + getter);
        try {
          //create method for getter of each attribute
          Method method =
            serviceRequest.getClass().getMethod("get" + getter, null);
          System.out.println("method has been created");
          //get value of the getter method
          String value = (String)method.invoke(serviceRequest, null);
          //System.out.println("value for " + method.toString() + ": " + value);
          //set the value to the current row of the binding
          row.setAttribute(attributeNames[i], value);
        } catch (NoSuchMethodException ex) {
        }

      }
    } catch (Exception ex) {
      System.out.println("Error : \n");
      ex.printStackTrace();
    }