30 September, 2013

JAVA : Convert InputStream to String

You can use the following snippet to convert InputStream to String
 
    private static String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

Thanks

25 September, 2013

OAF Overview

This post will explains some terminologies that is used in Oracle Application Framework (OAF).

Entity Object - business component entity objects maps to database table or view that allow DML operations and that used to cache data result set and perform validation before post changes to database. 

Association Object - business component association objects implement the relationships between different entity objects and can mapped to database referential integrity constraint or non existing referential integrity constraint and this case constrain will be validated in OAF but not in database.

View Object - business component view objects are used to display data in UI pages and it can be based on
1- Entity Object or many entity objects and this case it supports DML operations.
2- SQL queries  : that's doesn't support DML operations
3- Static : Programmer create structure of view object attributes and can add static data also.
4- Programmatic : Programmer write code at runtime to get dynamic data of view object.

View Link - Establishes a master/detail relationship between different view objects and can be in more depth master/detail/detail/....

Validation View Object - A view object created exclusively for the purpose of performing light-weight SQL validation on behalf of entity objects or their experts.

Application Module - An application module is a container for related BC4J objects. The AM is connected to the database, and is responsible for the commit and rollback of a transaction.

Validation Application Module - An application module created exclusively for the purpose of grouping and providing transaction context to related validation view objects. Typically, a standalone entity object or the top-level entity object in a composition would have an associated validation application module.

Root Application Module - Each pageLayout region in an OA Framework application is associated with a "root" application module which groups related services and establishes the transaction context.

This transaction context can be shared by multiple pages if they all reference the same root application module, and instruct the framework to retain this application module (not return it to the pool) when navigating from page to page within the transaction task.

Entity Expert - A special singleton class registered with an entity object (EO) that performs operations on behalf of the EO.

Controller - The controller is the java code in charge of loading a page when we call it. It is also in charge of handling an event on a page, like a click on a button, or the call of a List Of Values.
 

Attribute Set - Bundles of region or item properties that can be reused either as is or with modifications. For example, all buttons sharing the same attribute set would have the same label and Alt text. 


Thanks

23 September, 2013

ADF : Working with ViewCriteria

View Criteria's are additional where clause added at runtime to base View Object Query.


 Programmer can create view criteria declaratively or programatically.

1. Create View Criteria Declaratively Open View Object in Edit and in "Query" tab you can click "+" add pencil to create new view criteria

 
2. Control View Criteria Programatically.


 a- Get View Criteria from View Criteria manager within View Object and then apply it  
ViewCriteria applyVC = myViewObject.getViewCriteria("MyViewCriteriaName");
myViewObject.applyViewCriteria(applyVC);
myViewObject.executeQuery();

b- Applying Multiple view Criteria's

 
When multiple view criteria's are applied to the view object, the view criterias gets appended or replaced depending upon the way you use applyViewCriteria API
Replacing Existing view criteria's :

 
myViewObject.applyViewCriteria(applyVC) or

myViewObject.applyViewCriteria(applyVC,false)
will erase all previously applied view criterias and apply the current view criteria only.
Appending to the Existing view criteria:


myViewObject.applyViewCriteria(applyVC, true) 

 Will append this view criteria to the existing view criteria(s) which is applied already.

c- Unapplying && Removing View Criteria

vo.removeApplyViewCriteriaName()
Unapply the view criteria if it is applied. The view criteria will still remain in View Criteria Manager (which means you can't apply this view criteria whenever you require in the future).
vo.removeViewCriteria()
Removes the view criteria from View Criteria Manager. If it is applied it is first unapplied and then removed. (which means you cant apply this View Criteria to the view object next time in the future.).


For example the below code returns null after removeViewCriteria has been applied.
ViewCriteria applyVC = myViewObject.getViewCriteria("
MyViewCriteriaName")

vo.clearViewCriterias()
Unapplies and removes all view criteria, both applied and unapplied from View Criteria Manager. Which means that you can't apply any View Criteria against View Object.
For example the below code returns null after clearViewCriterias() has been applied.
ViewCriteria applyVC = myViewObject.getViewCriteria("
MyViewCriteriaName")
myViewObject.applyViewCriteria(null)
The above statement unapplies all existing View Criterias and not remove it.



myViewObject.setNamedWhereClauseParam("MyParameter", "myValue)
The above statement set Named Parameter Value. It set the value of "MyParameter" to "myValue".

I post in previous post about  ADF : Change View Criteria Columns at Runtime

Thanks

16 September, 2013

Random Numbers in Java

Previously I posted  about Generate Random Passwords in Oracle that was using PLSQL.
Today I will post about java randoms.

Java provides two classes to generate random numbers: Random and SecureRandom.
Random is faster than SecureRandom, but it uses a 48 bits seeds which is not enough for the long type.
Moreover, it is not 'random enough' for cryptography. SecureRandom, is slower than Random, but can be used for cryptography.

The following code example shows how to generate a random number within a range for int, long, float and double.

Note rangeStart , rangeEnd is range period of generated numbers .

        int rangeStart = 50;
        int rangeEnd = 100;

        SecureRandom secRandom = new SecureRandom();
        int inclusive = rangeEnd - rangeStart + 1;
        int exclusive = rangeEnd - rangeStart;


        int randomIntInclusive = secRandom.nextInt(inclusive) + rangeStart;
        int randomIntExclusive = secRandom.nextInt(exclusive) + rangeStart;

        System.out.println("randomIntInclusive : " + randomIntInclusive);
        System.out.println("randomIntExclusive : " + randomIntExclusive);

        long randomLongInclusive =
            (secRandom.nextLong() % inclusive) + rangeStart;
        long randomLongExclusive =
            (secRandom.nextLong() % exclusive) + rangeStart;

        System.out.println("randomLongInclusive : " + randomLongInclusive);
        System.out.println("randomLongExclusive : " + randomLongExclusive);

        float randomFloat = (secRandom.nextFloat() * exclusive) + rangeStart;
        System.out.println("randomFloat : " + randomFloat);

        double randomDouble =
            (secRandom.nextDouble() * exclusive) + rangeStart;
        System.out.println("randomDouble : " + randomDouble);

The output will be
randomIntInclusive : 60
randomIntExclusive : 73
randomLongInclusive : 11
randomLongExclusive : 63
randomFloat : 65.19333
randomDouble : 84.14220368726888



Thanks

12 September, 2013

Close Resources in Java

In java when using any resources like Files, Streams, Database Connection and DataSets etc .... , you must close resources at end of processing at your code.

For Example : Streams 

        File f = new File("myFile.txt");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            // Do something...
        } catch (FileNotFoundException ex) {
            // Display error message
        } finally {
            // Closing resource
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use IOUtils Appache packages  to close resources quietly
      finally{
   IOUtils.closeQuietly(fos);
      }


For Example : Database Statement

 finally{
   DBTransaction txn = this.getDBTransaction();
        String sqlStmt =
            "Begin plsqlCode; END;";
        CallableStatement callStmt =
            txn.createCallableStatement(sqlStmt, DBTransaction.DEFAULT);
        try {
             //Write your code here to work with CallableStatement 
        } catch (SQLException e) {
             //Handle SQL Exception
        }finally {
            // Closing resource
            if (callStmt != null) {
                try {
                    callStmt .close();
                } catch (SQLException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use DBUtils Appache packages  to close resources quietly

      finally{
   DbUtils.closeQuietly(callStmt );
      }

Thanks

08 September, 2013

Run JavaScript from Native Java

I wrote in previous post Execute Javascript code from Java Code how to execute java script in Oracle ADF.
But in this post I will explain how to call Javascript from native Java.



The following code snippets will illustrate how to evaluate Javascript code and invoke functions and get return value.

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class CallJavaScript {
    public static void callJsCode(String jsCode) throws ScriptException,
                                                        NoSuchMethodException {

        // Retrieving the Javascript engine
        ScriptEngine se =
            new ScriptEngineManager().getEngineByName("javascript");
        try {
            se.eval(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        }

        try {
            Invocable jsinvoke = (Invocable)se;
            System.out.println("myFunction(2) returns: " +
                               jsinvoke.invokeFunction("myFunction", 2, 4));
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}

Then You can call this code using for example
       try {
            String jsCode =
                "function myFunction(x,y){return x+y;}";
            CallJavaScript.callJsCode(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }      

The output of previous code will be

myFunction(2) returns: 6.0

Thanks

05 September, 2013

Iterate Through Java Map

There are multiple ways to iterate through a Java Map.

Assuming the following map declaration:
Map mapObj = new HashMap();

//Use Iterator [Generic]
Iterator> iter= mapObj.entrySet().iterator();
while ( iter.hasNext() ) {
    Entry item = iterator.next();
    System.out.println(item.getKey() + " - " + item.getValue());
}


//User Iterator [Without Generic]
Iterator iter= mapObj.entrySet().iterator();
while ( iterator2.hasNext() ) {
    Entry item = (Entry) iterator.next();
    System.out.println(item.getKey() + " - " + item.getValue());
}


// Use For Each [Generic]
for ( Entry item : mapObj.entrySet() ) {
    System.out.println(item.getKey()+ " - " + item.getValue());
}


// Use For Each [Without Generic]
for ( Entry item : mapObj.entrySet() ) {
    System.out.println(item.getKey()+ " - " + item.getValue());
}


//Fetch Value using Key
for ( String key : mapObj.keySet() ) {
    System.out.println(key + " - " + mapObj.get(key));
}



// Loop through Keys only
for ( String key : mapObj.keySet() ) {
    System.out.println(key);
}



// Loop through Values only
for ( Object value : mapObj.values() ) {
    System.out.println(value);
}


Thanks