Sunday, 31 May 2015

Create and Parse JSON using jackson in java

Required JSON String with Array:

{"NAME":"USER","AGE":25,"COUNTRY":"INDIA",
  "ADDRESS": [{"STREET":"xys","CITY":"Bangalore","POSTAL CODE":54321}]
}


CreateJson class having logic for creating and parsing JSON

import java.util.ArrayList;
import java.util.List;

public class CreateJson {

    public static void main(String[] args) {

        UserBean userData = new UserBean();
        userData.setName("USER");
        userData.setAge(25);
        userData.setCountry("INDIA");

        AddressBean address = new AddressBean();
        address.setCity("Bangalore");
        address.setPostalCode(54321);
        address.setStreet("xys");
        List<AddressBean> addressList = new ArrayList<AddressBean>();
        addressList.add(address);
       
        userData.setAddressList(addressList);
        String jsonString = JsonUtil.getJSONString(userData);
        System.out.println(jsonString);
       
        //Method Call to Parse JsonString

        parseMyJsonString(jsonString);

    }

    private static void parseMyJsonString(String jsonString) {
        UserBean userBean = JsonUtil.fromJsonToObject(jsonString);
        System.out.println(userBean.getAge());
        List<AddressBean> addressList = userBean.getAddressList();

        for (AddressBean list : addressList) {
            System.out.println("City " + list.getCity());
            System.out.println("Postal Code " + list.getPostalCode());
        }
    }
}

1. Create AddressBean.java


import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class AddressBean {
   
    @JsonProperty("STREET")
    private String street = null;
    @JsonProperty("CITY")
    private String city = null;
    @JsonProperty("POSTAL CODE")
    private int postalCode;
   
    public AddressBean(){
       
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getStreet() {
        return street;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCity() {
        return city;
    }

    public void setPostalCode(int postalCode) {
        this.postalCode = postalCode;
    }

    public int getPostalCode() {
        return postalCode;
    }
}

2. Create a UserBean.java


import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class UserBean {
  
   @JsonProperty("NAME")
   private String name = null;
    @JsonProperty("AGE")
   private int age = 0;
    @JsonProperty("COUNTRY")
   private String country = null;
   //List of AddressBean
   @JsonProperty("ADDRESS")
   private List<AddressBean> addressList = null;
  
   public UserBean(){
      
   }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry() {
        return country;
    }

    public void setAddressList(List<AddressBean> addressList) {
        this.addressList = addressList;
    }

    public List<AddressBean> getAddressList() {
        return addressList;
    }
}

3. Create a Util Class having logic for parsing and creating JSON of UserBean object

import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public final class JsonUtil {

    /**
     * Creates a JSON String
     * @param bean
     * @return String
     */

    public static String getJSONString(UserBean bean) {
        String jsonString = null;
        try {
            jsonString = createObjectMapper().writeValueAsString(bean);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    /**
     * Parse Json string to UserBean Object
     * @param json
     * @return UserBean
     */

    public static UserBean fromJsonToObject(String json) {
        UserBean responseObj = null;
        try {
            responseObj = createObjectMapper().readValue(json, UserBean.class);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        return responseObj;
    }

    /**
     * @return ObjectMapper
     */

    private static ObjectMapper createObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
                         true);
        mapper.configure(DeserializationConfig.Feature.USE_JAVA_ARRAY_FOR_JSON_ARRAY,
                         true);
        mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
                         true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS,
                         true);

        return mapper;
    }
}

*Using jackson-all-1.9.0.jar

*Comments and feedback are most welcomed, Thanks.

Creating and parsing JSON using Json-simple



1. Simple JSON string creation.

Requirement: {"NAME":"USER","AGE":25,"COUNTRY":"INDIA"}

    public static void main(String[] args) {
        JSONObject createUserJson = new JSONObject();
        createUserJson.put("NAME", "GOPAL");
        createUserJson.put("AGE", 25);
        createUserJson.put("COUNTRY", "INDIA");
       
        String jsonString =  JSONValue.toJSONString(createUserJson);
        System.out.println(jsonString); 
      
    }

2. JSON creation with Array

Requirement:  
{"NAME":"USER","AGE":25,"COUNTRY":"INDIA",
    "ADDRESS" : [ {"STREET":"xyz", "POSTAL CODE":"654321","CITY":"BANGALORE"} ,
                               {"STREET":"abc", "POSTAL CODE":"987654","CITY":"BANGALORE"}
                             ]                              
}


public static void main(String[] args) {
        JSONObject createUserJson = new JSONObject();
        createUserJson.put("NAME", "GOPAL");
        createUserJson.put("AGE", 25);
        createUserJson.put("COUNTRY", "INDIA");
        

        List<Map> jsonArray = new ArrayList<Map>();
        Map<String, String> streetXYZ = new HashMap<String, String>();
        streetXYZ.put("STREET", "xyz");
        streetXYZ.put("POSTAL CODE", "654321");
        streetXYZ.put("CITY", "BANGALORE");

        Map<String, String> streetABC = new HashMap<String, String>();
        streetABC.put("STREET", "xyz");
        streetABC.put("POSTAL CODE", "654321");
        streetABC.put("CITY", "BANGALORE");

        jsonArray.add(streetXYZ);
        jsonArray.add(streetABC);

        createUserJson.put("ADDRESS", jsonArray);
 

        String jsonString =  JSONValue.toJSONString(createUserJson);
        System.out.println(jsonString); 
      
    }

3. Parsing JSON String - Example is parsing above JSON created.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

private static void parsingJsonString(String jsonString) {
        JSONParser parser = new JSONParser();
        try {
            JSONObject jsonObject = (JSONObject)parser.parse(jsonString);
            String name = (String)jsonObject.get("NAME");
            System.out.println(name);
           
            JSONArray addressArray = (JSONArray)jsonObject.get("ADDRESS");
            for (int i = 0; i < addressArray.size(); i++) {
                Object arrayObj = parser.parse(addressArray.get(i).toString());
                JSONObject jsonArrayObject = (JSONObject)arrayObj;
                System.out.println("Street " + jsonArrayObject.get("STREET"));
                System.out.println("Postal Code " +
                                   jsonArrayObject.get("POSTAL CODE"));
                System.out.println("City " + jsonArrayObject.get("CITY"));
                System.out.println("-------------------------------------");
            }

        } catch (ParseException e) {
            e.getMessage();
        }
  
}

*Using Json-simple-1.1.1.jar

*Comments and feedback are most welcomed, Thanks.

Useful groovy expressions and resuable Java code in ADF

---------- Groovy Expressions ----------

1. Generate sequence using groovy.

(new oracle.jbo.server.SequenceImpl
("SEQUENCE_NAME",adf.object.getDBTransaction())).getSequenceNumber()

2. Fetching record of View Accessor in any attribute of View Object.

Suppose View accessor name is DepartmentVA

if (null!= DepartmentVA.first())
return DepartmentVA.first().getAttribute('DepartmentName');


2. Reusable JAVA code

import javax.el.ExpressionFactory;
import javax.faces.context.FacesContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.binding.OperationBinding;

    /**
     * This methos returns the operation bindings of the passed method name
     * @param operation name
     * @return
     */
    public static OperationBinding getOperBindings(String operation) {
        OperationBinding oper = null;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExpressionFactory exp = facesContext.getApplication().getExpressionFactory();
        DCBindingContainer bindingContainer =
            (DCBindingContainer) exp.createValueExpression(facesContext.getELContext(), "#{bindings}",
                                                           DCBindingContainer.class).getValue(facesContext.getELContext());
        oper = bindingContainer.getOperationBinding(operation);
        System.out.println("Exit - [Util : getOperBindings]");
        return oper;
    }

----------------------------------------------------------------------------------------------------------------------
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;

    /**
     * Programmatic evaluation of EL.
     * @param el EL to evaluate
     * @return Result of the evaluation
     */

    public static Object evaluateEL(String el) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);
        return exp.getValue(elContext);
    }

----------------------------------------------------------------------------------------------------------------------
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;

     /**
      * Sets a value into an EL object.
      * Provides similar functionality to the af:setActionListener tag, except the from is not an EL.
      * You can get similar behavior by using the following...
      * setEL(to, evaluateEL(from))     *
      * @param el EL object to assign a value
      * @param val Value to assign
      */

     public static void setEL(String el, Object val) {
         FacesContext facesContext = FacesContext.getCurrentInstance();
         ELContext elContext = facesContext.getELContext();
         ExpressionFactory expressionFactory =
             facesContext.getApplication().getExpressionFactory();
         ValueExpression exp =
             expressionFactory.createValueExpression(elContext, el,
                                                     Object.class);
         exp.setValue(elContext, val);
     }


----------------------------------------------------------------------------------------------------------------------
import oracle.adf.model.BindingContext;
import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;


      /**
       * Method will be used to execute the BC operations
       * such as : Commit, Rollback, Execute etc.
       * @param operation
       */

      public static OperationBinding commitUsingOperationBinding(String operation) {
          BindingContainer bindings =
              BindingContext.getCurrent().getCurrentBindingsEntry();
          OperationBinding oper = (OperationBinding)bindings.get(operation);
          oper.execute();
          return oper;
      }

----------------------------------------------------------------------------------------------------------------------
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.jbo.RowSetIterator;

    /**
     * Method to retrieve row set iterator by iterator name
     * @param iteratorName
     * @return RowSetIterator
     */

    public static RowSetIterator getRowSetIter(String iteratorName) {
        DCBindingContainer dcBindings =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding iteratorBinding =
            (DCIteratorBinding)dcBindings.get(iteratorName);
        RowSetIterator rowSetIterator =
            iteratorBinding.getViewObject().createRowSetIterator(null);
        rowSetIterator.reset();
        return rowSetIterator;
    }

---------------------------------------------------------------------------------------------------------------------- 
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

     /**
      * Refresh page from root
      */

     public static void rootRefresh() {
         FacesContext facesContext = FacesContext.getCurrentInstance();
         String refreshpage = facesContext.getViewRoot().getViewId();
         ViewHandler viewHandler =
             facesContext.getApplication().getViewHandler();
         UIViewRoot viewroot =
             viewHandler.createView(facesContext, refreshpage);
         viewroot.setViewId(refreshpage);
         facesContext.setViewRoot(viewroot);
     }


*Comments and feedback are most welcomed, Thanks.

Tuesday, 13 May 2014

Calling a Java method using javascript in ADF



Calling a java method from JavaScript can be useful in achieving many use case requirement in adf and this can be easily achieve using clientListener and serverListener tags.

<af:serverListener><af:clientListener>

ClientListener tag register a client-side script to be run when a specified event is triggered. 
ServerListener tag will register a server-side listener that should be run when a custom client-event is triggered and AdfCustomEvent.queue() JavaScript method will be use to fire a custom event.

Syntax : AdfCustomEvent(AdfUIComponent source, String type, Object params, Boolean immediate);

  • source” argument is the source UI component. It may be the component with the id - “d1”
  •  “type” argument is name of the serverListener component. E.g – “ReadJavaScript”
  •  params” argument is array consist of key:value pair delimited by commas,  e.g.{key1:value1,key2:value2,...}
  • The "immediate" flag determines whether the server call is handled during the JSF APPLY_REQUEST phase or during the InvokeApplication phase.

Let’s understand the concept by a sample application. 

Requirement: Capture the browser detail in java on load of the jspx page. If browser name is “Microsoft Internet Explorer” it should return true else false in java method.

Steps for implementation:

Step 1: Create a java class such as Demo.java. 
Step 2: Create a Jspx page such as Demo.jspx.

 


Step 3:  Add Demo class as managed bean in adfc-config.xml as shown below:  

 

Step 4: Add Client Listener method in Demo.java.

package com.test.demo;

import oracle.adf.view.rich.render.ClientEvent;

/**
 * Demo class
 */
public class Demo {


    /**
     * Method will be triggered using serverListener
     * Reads the values set in the javascript
     * @param clientEvent
     */
    public void readJavaScriptValue(ClientEvent clientEvent) {
        System.out.println("[Demo : readJavaScriptValue()] - Entry");
         //isIEBrowser is a key set in javascript
        System.out.println("Client return value - "+clientEvent.getParameters().get("isIEBrowser"));
    }

Step 5: Adding JavaScript, ClientListener and ServerListener in jspx page.

<?xml version='1.0' encoding='UTF-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
  <jsp:directive.page contentType="text/html;charset=UTF-8"/>
  <f:view>
  <af:document id="d1" title="Demo application">
    <af:resource type="javascript">
    function
browserCheck(event){
        var eventData = event.getSource();
        var browserName = navigator.appName;
        if(browserName == "Microsoft Internet Explorer"){
            AdfCustomEvent.queue(eventData, "readJavaScript",{'isIEBrowser' : 'true'},false);
        }else{
            AdfCustomEvent.queue(eventData, "readJavaScript",{'isIEBrowser' : 'false'},false);
        }       
    }

    </af:resource>
    <af:clientListener method="browserCheck" type="load"/>
    <af:serverListener type="readJavaScript" method="#{demo.readJavaScriptValue}"/>
      <af:form id="f1">
        <af:pageTemplate viewId="/oracle/templates/threeColumnTemplate.jspx"
                         id="pt1">
          <f:facet name="center">
          <af:outputText value="JavaScript Demo application" id="ot1"/>
          </f:facet>
          <f:facet name="header"/>
        </af:pageTemplate>
      </af:form>
    </af:document>
  </f:view>
</jsp:root> 

Step 6: Console output as on Chrome:

 
*Comments and feedback are most welcomed, Thanks.