Thursday, December 17, 2015

Rollback before navigation between pages is done

When you want to rollback any transaction before navigate to another page:
1- Create class that extends class called NavigationHandler then
    override method called handleNavigation as follows:


public class CustomNavigationHandler  extends NavigationHandler{
  
    private NavigationHandler navHandler=null;
  
    public CustomNavigationHandler(NavigationHandler navHandler)
    {
        super();
        this.navHandler=navHandler;
      
    }
    public void handleNavigation(FacesContext ctx,String action,String outcome){
        if (outcome !=null){
            ADFUtils.getAppImpl("AppModuleAM").getDBTransaction().rollback();
        }
        navHandler.handleNavigation(ctx,action,outcome);
    }   
}

2- Register the class at the faces-config.xml file as follows:

Sunday, December 13, 2015

Rollback specific page when navigating from it

UseCase
When you create new row in a page and start to set a form values then navigate to another page then commit the validation of the row at first page will be fired , you want to rollback any transaction on the first page when navigate to anther page.
We want to rollback when navigating out of a target specific page.
Solution
1- At first page (target),when click CreateInsert button, set a value for a session variable with name viewIdd
2- Create class that implements PagePhaseListener.
3-Override afterPhase method and make rollback if the session variable was set and the target page has changed.
public class MyPageListener implements PagePhaseListener {
    @Override
    public void afterPhase(PagePhaseEvent pagePhaseEvent) {
        int phaseId = pagePhaseEvent.getPhaseId();
        // if the variable was set and the current page isn't the target page
        if (JSFUtils.getFromSession("viewIdd") != null &&
       !FacesContext.getCurrentInstance().getViewRoot().getViewId().contains("TargetPage")) {
            // Lifecyce.getPhaseName(phaseId) == 
              if (Lifecycle.getPhaseName(phaseId) == Lifecycle.PREPARE_RENDER_ID) {
                ADFUtils.getAppImpl().getDBTransaction().rollback();
                ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
                HttpSession session = (HttpSession) context.getSession(false);
                if (session != null) {
                    session.removeAttribute("viewIdd");
                    //  JSFUtils.setManagedBeanValue("#{sessionScope.viewIdd}", null);
                }
            }
        }
    }

3- Register the class as a listener in /METAINF/adf-settings file located at Application Resources
<?xml version="1.0" encoding="US-ASCII" ?> 
<adf-settings xmlns="http://xmlns.oracle.com/adf/settings"> 
  <adfc-controller-config xmlns="http://xmlns.oracle.com/adf/controller/config"> 
    <lifecycle> 
      <phase-listener> 
        <listener-id>MyPageListener1</listener-id> 
        <class>view.MyPageListener</class> 
        <before-id-set> 
          <listener-id> MyPageListener1</listener-id> 
        </before-id-set> 
        <after-id-set> 
          <listener-id>MyPageListener1</listener-id> 
        </after-id-set> 
     </phase-listener> 
    </lifecycle> 
  </adfc-controller-config> 
</adf-settings>

Performing Partial Rollback

http://www.awasthiashish.com/2014/04/performing-partial-rollback-undo.html

UseCase
Two tables on page Departments and Employees, and i have changed one row in Departments table and same time created a row in Employees table, now i want to rollback the changes done in Departments table only.
Solution
1-  add a new transient attribute in Departments Vo to get current state of each row
/**
     * Gets the attribute value for the calculated attribute RowStatusTrans.
     * @return the RowStatusTrans
     */
    public Integer getRowStatusTrans() {
        /*here row is reference variable of collection, this expression returns an int value if it is
         2-Modified
         0-New
         1-Unmodified
        -1-Initialized
        */
        byte entityState = this.getEntity(0).getEntityState();
        return new Integer(entityState);
    }

2- create a method to remove newly added row , and to undo changes in existing rows of departments VO in Impl class
     /**Method to revert changes of current row
     * @param curRow
     */
    public void revertChangesCurrentRow(Row curRow) {
        if (curRow != null) {
            curRow.refresh(Row.REFRESH_UNDO_CHANGES | Row.REFRESH_WITH_DB_FORGET_CHANGES);
        }
    }
    /**Method to check whether row should be removed or not 
     * If it is new - removed
     * If old one- Undo Changes
     * */
    public void revertOrremoveRowValues() {
        ViewObject deptVo = this;
        RowSetIterator deptIter = deptVo.createRowSetIterator(null);
        while (deptIter.hasNext()) {
            Row nextRow = deptIter.next();
            if (nextRow.getAttribute("RowStatusTrans") != null) {
                Integer rowStatus = (Integer) nextRow.getAttribute("RowStatusTrans");
                if (rowStatus == 2) {
                    System.out.println("Modified Rows-" + nextRow.getAttribute("DepartmentId"));
                    revertChangesCurrentRow(nextRow);
                } else if (rowStatus == 0) {
                    System.out.println("New Row Removed");
                    nextRow.remove();
                }
            }
        }
        this.executeQuery();
    }

Saturday, November 21, 2015

Manage Memory for permanent generation space (permgen)

If your JDeveloper IDE  is slow, you can increase the memory by: 
Edit the "jdev.conf" file located at path "YOUR_Oracle_Home\jdeveloper\jdev\bin​"
and add following line:
AddVMOptionHotspot  -XX:MaxPermSize=1024M

also you can show the consumed memory and force for garbage collection by adding the following line:
AddVMOption -DMainWindow.MemoryMonitorOn=true

See the file after modifying:


See the change as new bar at Jdeveloper IDE, the arrow points to link that do job for Garbage Collecting:
  • Now you are more far from the error: OutOfMemoryError PermGen Space Error.
  • Java 8 is moved from PermGen Space to Metaspace.Java Metaspace space setting is to be unbounded (dynamic resize) by default.
  •  JDeveloper 12.1.3 in test can be configured to develop/compile against JDK 8, and introduces support for JDK 8 language features.


http://waslleysouza.com.br/en/2014/04/increase-the-performance-of-jdeveloper-11g/
http://www.oracle.com/technetwork/developer-tools/jdev/documentation/121300-cert-2164864.html
http://java.dzone.com/articles/java-8-permgen-metaspace
http://en.wikipedia.org/wiki/Java_virtual_machine

Thursday, November 19, 2015

ADF InputColor Component

When you need to pick a color from a popup you can deal with ADF component called af:InputColor.
Use Case
Need coloring a number values according to specific ranges.
Example: 
Numbers between 0 and 50 will be colored with black.
Implementations
Create a table that saves the desired color for each specific range.
Because the InputColor  component needs a value of type Color, create a transient attribute with type java.awt.Color , you will change the type at XML level manually:
When page loads you will need to get a color object, so convert the color string to object of type color.
When you set color object you will need to convert the chose color object to string and set the color string to be saved in the database after commit.

Drag and drop the InputColor component and set it's value to the color object attribute.

The result will looks like this:

Thursday, October 15, 2015

DOM VS. SAX For XML Parsing

DOM (Document Object Model)
  • DOM Parser for Java is in JAXP (Java API for XML Parsing) package.
  • It represent an XML Document into tree format.
  • DOM Parser creates an In Memory tree representation of XML file and then parses it, so it requires more memory

SAX ( Simple API for XML Parsing)
  • It’s recommended to use SAX XML parser for parsing large xml files in Java because it doesn't require to load whole XML file in Java and it can read a big XML file in small parts.
  • SAX is an event based XML Parsing and it parse XML file step by step so much suitable for large XML Files.
  • SAX XML Parser fires event when it encountered opening tag, element or attribute and the parsing works accordingly. 
DOM VS. SAX 
  • DOM and SAX parser are extensively used to read and parse XML file in java
  • I recommend use DOM parser over SAX parser if XML file is small enough and go with SAX parser if you don’t know size of xml files to be processed or they are large.
  • SAX is an event based parser and raise and event, while DOM is not . 
  • At DOM Traverse in any direction.
  • At SAX Top to bottom traversing.
  • SAX is read only , DOM is read and write both. 
Read more:
http://javarevisited.blogspot.com/2011/12/difference-between-dom-and-sax-parsers.html#ixzz2WfmBqdl9


Saturday, October 3, 2015

SQL - Parameter Sniffing

If a SQL query has parameters, SQL Server creates an execution plan tailored to them to improve performance, via a process called 'parameter sniffing'.
This plan is created the first time ( whenever SQL Server is forced  to compile or recompile  ) a stored procedure is executed and is stored and reused since it is usually the best execution plan. Just occasionally, it isn't, and you can then hit performance problems.
Every subsequent call to the same store procedure with the same parameters will also get an optimal plan, whereas calls with different parameter values may not always get an optimal plan.
How to Deal With Parameter Sniffing ISSUES:
Option 1: With Recompile
The problem with parameter sniffing is the fact that the first set of parameter values are used to determine the execution plan.  To overcome this problem, all you need to do is to recompile the stored procedure every time it is executed. 
 This can be accomplished by using the “WITH RECOMPILE” options when you create a stored procedure
The drawback of this option is the store procedure is recompiled with every execution.
Option 2: Disabling Parameter Sniffing
change the way the parameter values were used within the stored procedure.  By creating two different local variables  inside my procedure, setting those variables to the passed parameters, 
Option 3: Creating Multiple Stored Procedures
This option uses multiple stored procedures where each stored procedure can be optimize for a specific type of parameters values. 

To clear procedure cache (execution plan)
For SQLServer:
DBCC FREEPROCCACHE

For Oracle
alter system flush shared_pool;

SQL - Delete vs Drop vs Truncate

  1. DELETE operation remove some or all rows and need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. will cause all DELETE triggers on the table to fire.
  2. TRUNCATE removes all rows  from a table and no DML triggers will be fired.
  3. DROP removes a table from the database, indexes and privileges, No DML triggers will be fired.
  • DROP and TRUNCATE are DDL commands, DELETE is a DML command.
    Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
  • TRUCATE is faster and doesn't use as much undo space as a DELETE.
  • Specify CASCADE CONSTRAINTS to drop all referential integrity constraints(at the detail table) that refer to primary and unique keys in the dropped table. If you omit this clause, and such referential integrity constraints exist, then the database returns an error and does not drop the table.
           Example
                drop table Dept cascade constraints 

http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

Saturday, September 19, 2015

SQL - What is an Index?

What is an Index?

  • An index is a performance-tuning method of allowing faster retrieval of records. 
  • An index creates an entry for each value that appears in the indexed columns.By default, Oracle creates B-tree indexes.
  • Some indexes are created implicitly through constraints that are placed on a table. For example, a column with the constraint that its values be unique causes Oracle to create a unique key index.
  • Indexes don’t fix all performance problems and can actually degrade performance if used improperly.
    Always test all applications with any new index you create.

Example
select Employees.FIRST_NAME from employees where EMPLOYEES.SALARY >1000  and Employees.FIRST_NAME like 'M%';
Oracle indexing Types
  1.             B-tree index,
  2.             Bitmap indexes,
  3.             Function-based indexes,
  4.             index-only tables (IOTs);



How these indexes may dramatically increase the speed of Oracle SQL queries ?
B-tree

  •       A tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time.
  •       The B-tree is a generalization of a binary search tree in that a node can have more than two children.
  •       Indexes contain pointers (in the form of ROWIDs) to table data, This reduces I/O by eliminating the need to sequentially scan a table’s blocks when searching for a row (sequential scan of table blocks is called a "full table scan"). 




Friday, September 18, 2015

SQL – Union vs. Union All – Which is better for performance?

UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL
  • The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.

The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.

Which is better for performance?
A UNION statement effectively does a SELECT DISTINCT on the results set.
If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

Example
select Employees.FIRST_NAME from employees where EMPLOYEES.SALARY>1000 union
select Employees.FIRST_NAME from employees where  Employees.FIRST_NAME like 'M%';

SQL Tuning Advisor

Grant advisor to hr;
grant SELECT_CATALOG_ROLE to HR;
grant SELECT ANY DICTIONARY to HR;
ALTER system SET CONTROL_MANAGEMENT_PACK_ACCESS='DIAGNOSTIC+TUNING';

Sunday, September 6, 2015

Validate creation of one master record with one detail record at least

Case
Any new Department must provide at least one Employee.

Implementation Method
  1. Create "Business Component from Tables" for Departments and Employees.
  2. Check the property "Composition Association" at the association.
There are many method to apply the validation of existing one Employee for each Department:
  • Using "Entity Validators" of type "Script Expression"
    Create new "Validator" on the Department of type script Expression and write:
 if(DETAIL_ACCESSOR_NAME.count('ANY_DETAIL_ATTRIBUTE_NAME') >=1)
return true;
return false;
  • Using "Entity Validators" of type"Collection":
    Cretae new entity validators on Department of type "Collection",
    Choose the :
    Operation =  "Count"
    Accessor  = Accessor Name of Employee.
    Atribute   = any attribute
    Operator  = "GreaterOrEqualTo"
    Enter Literal Value = 1
  • Create managed been class implements "BindingContainerValidator" interface and overrides "validateBindingContainer" method:
@Override
public void validateBindingContainer(BindingContainer bindingContainer) {
if(  ( (DCIteratorBinding) bindingContainer.get("DETAIL_ITERATOR_NAME")).getCurrentRow()==null){
throw new ValidatorException(new FacesMessage("Create a new Contact info before commit"));
        }
    }
       then go to page definition properties and set two properties
       CustomValidator="#{YOUR_CUSTOM_VALIDATE_MANAGED_BEAN}"
      SkipValidation="custom"

EntityState ( STATUS_NEW , STATUS_INITIALIZED )

EntityState
  1. STATUS_INITIALIZED ( -1 )This status indicates a new record that is not yet a candidate to insert into the database as no changes have yet occurred to its attributes, it's basically just empty.
  2. STATUS_NEW ( 0 )Says that at least one of the attributes of the EO has been updated ( attribute is AutoSubmit or a  button is  clicked then the validation will start) and thus the record is a candidate to be inserted to the database.
When you click "CreateInsert" button, the new record status is STATUS_INITIALIZED

When you set any attribute value, the entity's state transitions into NEW and will be added to the transaction.

When an entity row is created, modified, or removed, it is automatically enrolled in the transaction's list of pending changes.


        The entity instance is added to the entity cache once the primary key is populated.


When you call commit() on the Transaction object, it processes its pending changes list, validating new or modified entity rows that might still be invalid.

When the entity rows in the pending list are all valid, the Transaction issues a database SAVEPOINT and coordinates saving the entity rows to the database. 

If all goes successfully, it issues the final database COMMIT statement.
If anything fails, the Transaction performs a ROLLBACK TO SAVEPOINT to allow the user to fix the error and try again.


The Transaction object used by an application module represents the working set of entity rows for a single end-user transaction.By design, it is not a shared, global cache.


The database engine itself is an extremely efficient shared, global cache for multiple, simultaneous users.



Setting row with status STATUS_INITIALIZED delay validation.

https://docs.oracle.com/cd/E57014_01/adf/api-reference-model/oracle/jbo/Row.html

Thursday, May 21, 2015

Fast Call 2 Database 4 DDL, DML, function and Procedure



public String print() {

        System.out.println(Calls2DatabaseHelper.exeucteSql("procedure", "Pro_Get_Employee_Name(?,?)", new String[] { "100" },

                                                           1));

        System.out.println(Calls2DatabaseHelper.exeucteSql("function", "fn_Get_Employee_Name(?)", new String[] { "100" },

                                                           1));

        String sql ="SELECT FIRST_NAME || ' ' ||  LAST_NAME Emp_Name FROM EMPLOYEES WHERE EMPLOYEE_ID = 100";

        System.out.println(Calls2DatabaseHelper.exeucteSql("select", sql, new String []{},

                                                           0));

        sql ="SELECT FIRST_NAME || ' ' ||  LAST_NAME Emp_Name FROM EMPLOYEES WHERE EMPLOYEE_ID = ?";

        System.out.println(Calls2DatabaseHelper.exeucteSql("select", sql, new String []{"100"},

                                                           0));

        sql ="update EMPLOYEES set  LAST_NAME = ? WHERE EMPLOYEE_ID = ?";

        System.out.println(Calls2DatabaseHelper.exeucteSql("update", sql, new String []{"MAhmoud","100"},

                                                           0));
        return "";


    }



public static DBTransaction getConnection() throws SQLException {

        return ADFUtils.getAppImpl().getDBTransaction();

    }

  

    public static String exeucteSql(String operaition, String signature, String[] inValues, int numOutValues) {
        String returnValue = ""
        String begin = " begin ";
        String end = " end; ";
        String sql = "";
        System.out.println(sql);
        if (operaition == "procedure") {
            signature+=";";
              sql = begin + signature + end;
            try (CallableStatement cs = getConnection().createCallableStatement(sql, 0)) {
                for (int i = 1; i <= inValues.length; i++) {
                    cs.setString(i, inValues[i - 1]);
                }
                for (int i = inValues.length + 1; i <= numOutValues + 1; i++) {
                    cs.registerOutParameter(i, OracleTypes.VARCHAR);
                }
                cs.execute();
                returnValue = cs.getString(2);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
            else  if (operaition == "function") {
            signature+=";";
            signature="?:= "+signature;
            sql = begin + signature + end;
            System.out.println(sql);
            try (CallableStatement cs = getConnection().createCallableStatement(sql, 0)) {
                cs.registerOutParameter(1, OracleTypes.VARCHAR);
                for (int i = 2; i <= inValues.length+1; i++) {
                    cs.setString(i, inValues[i - 2]);
                }
                cs.execute();
                returnValue = cs.getString(1);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        else if(operaition== "select"){
            if(inValues.length>0){
            try( PreparedStatement cs = getConnection().createPreparedStatement(signature, 0);) {
                for (int i = 1; i <= inValues.length; i++) {
                    cs.setString(i, inValues[i - 1]);
                }
                ResultSet rs = cs.executeQuery();
                if (rs.next()) {
                 returnValue =   rs.getString("Emp_Name");
                }
            } catch (SQLException e) {
                e.printStackTrace();
             } 
        }  else{
          Statement stmt;
            try {
                stmt = getConnection().createStatement(0);
                ResultSet rs = stmt.executeQuery(signature);
                if (rs.next()) {
                 returnValue =   rs.getString("Emp_Name");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        }
            else {
                try( PreparedStatement cs = getConnection().createPreparedStatement(signature, 0);) {
                    if(inValues.length>0){
                    for (int i = 1; i <= inValues.length; i++) {
                        cs.setString(i, inValues[i - 1]);
                    }
                    }
                    int numChangedRows = cs.executeUpdate();
                    getConnection().commit();
                    System.out.println("numChangedRows="+numChangedRows);
                } catch (SQLException e) {
                    e.printStackTrace();
                 } 
            }
        return returnValue;
        }

Download Link

http://sameh-nassar.blogspot.com/2010/12/calling-sql-statment-inside-java-code.html

Saturday, May 16, 2015

Enum

An enum type is a special data type that enables for a variable to be a set of predefined constants.
  • Enums are type-safe.
  • You can define methods or fields in an enum definition,
  • You need to define enum elements first before any other attribute in an enum class.
  • For the enum constructor; only private is permitted.
  • The compiler automatically adds some special methods when it creates an enum.
    For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. 
  • All enums implicitly extend java.lang.Enum
  • You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private.
  • Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum.
  • Enum in Java can implement the interface.
  •  You can define abstract method and let each instance of Enum to define 
public class EnumTest {
    public enum days {
        STAURDAY,
        SUNDAY
    }
    public static void main(String[] args) {
        days day = days.SUNDAY;
        switch (day) {
        case STAURDAY:
            {
                System.out.println("day=STAURDAY");
                break;
            }
        case SUNDAY:
            {
                System.out.println("day=SUNDAY");
                break;
            }
        }
    }
}
Enum With Private Constructor:
public class EnumTest {
    public enum days {
        STAURDAY(0),
        SUNDAY(1);
        int value;
         private days(int _value){
            value = _value;
        }
    }

    public static void main(String[] args) {
        days day = days.SUNDAY;
        switch (day) {
        case STAURDAY:
            {
                System.out.println("day=STAURDAY="+day.value);
                break;
            }
        case SUNDAY:
            {
                System.out.println("day=SUNDAY="+day.value);
                break;
            }
        }
    }
} 
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Tuesday, May 5, 2015

Sorting , Filtering

Filtering
  • setQuery
    public void filter(){ setQuery(getQuery()+ " where department_id=1"); executeQuery();System.out.println(getQuery());
    }
  • setWhereClause
    - If the view object (VO) has where clause then set where clause will be joined ( anded ) with the actual vo where clause.
    - setWhereClause(null) doesn't effect the actual where clause written inside VO xml but affect only the written in VO implementation class.
    public void filter(){
    System.out.println(getQuery());
    setWhereClause("department_id=1");
    System.out.println(getQuery());
    executeQuery();
    System.out.println(getQuery());
    }
    
    Example
    If actual view object contains where clause department_id= 1,then output after set where clause programmatically is:
    select ....... where ( department_Name='Administration' ) and ((( department_id= 1 )))
  • View Criteria
    - Once we have the view object with the rows populated from the database,we can sort, filter, search with the existing rows in memory without re-querying the database.This will greatly help us to minimize the database round-trip.
    ViewCriteria.CRITERIA_MODE_QUERY  // Uses database.
    ViewCriteria.CRITERIA_MODE_CACHE  // Uses rows in memory without querying the database.
    - After we change the SQL mode, new setting will take effect the next time we call the executeQuery() method.

    
    public void applyViewCriteriaAtRunTime(){
    ViewCriteria vc = createViewCriteria();
    //Try this line when commented and then remove commented to see the diffident output
    //vc.setCriteriaMode(ViewCriteria.CRITERIA_MODE_CACHE);
    ViewCriteriaRow vcr = vc.createViewCriteriaRow();
    vcr.setAttribute("ManagerId", "200");
    //ViewCriteriaItem jobItem = vcr ensureCriteriaItem("ChannelId");
    //vci.setOperator(JboCompOper.OPER_ON_OR_AFTER);
    //jobItem.setOperator("=");
    //jobItem.getValues().get(0).setValue(channelId);
    vcr.setAttribute("FirstName","LIKE 'R%'");
    vc.addRow(vcr);// same as vc.add(vcr);
    System.out.println(getQuery());
    applyViewCriteria(vc);
    System.out.println(getQuery());
    executeQuery();
    System.out.println(getQuery());
    }
    
Test Case
Put two instances and apply view criteria for one of them by pressing edit, we see that:

The applied view criteria effects only the view that we applied the view criteria on it.
  • When you choose Database:
    New row created in first instance  will be added also to second  rowset due to the "association consistency".
    New row created in 2nd instance  will  Not be added also to second  rowset. 
  • When you choose In Memory:
New row created in first instance  will be added also to second  rowset due to the "association consistency"( better naming for this "new row consistency" )
New row created in 2nd instance  will  be  added  to the 1st if it matches the criteria.
Maintaining New Row Consistency in View Objects Based on the Same Entity
When multiple instances of entity-based view objects in an application module are based on the same underlying entity object, a new row created in one of them can be automatically added (without having to re-query) to the row sets of the others to keep your user interface consistent or simply to consistently reflect new rows in different application pages for a pending transaction.
In-memory filtering with RowMatch
Don't use RowMatch if you have the option to filter the values at database level.
In-memory filtering is much slower than filtering done at the database layer.
Sorting
  • setSortBy
Used when you want to sort transient attributes because it is done in memory, If you have table built using a transient ViewObject , a click on the sort icon for a column would call ViewObjectImpl::setSortBy(String sortBy) to perform in memory sorting.

 public void sortInMemory(){ 
        setQueryMode(ViewObject.QUERY_MODE_SCAN_VIEW_ROWS);
        setSortBy("ViewObjectAttributeName");   // setOrderByClause("Table_Column_Name")
        executeQuery();
        System.out.println(getQuery());
        System.out.println(getWhereClause());
}
http://bpetlur.blogspot.com/2013/11/adf-view-criteria-execution-modes.html

Thursday, April 30, 2015

Nested Classes

Types of Nested classes

  1. Member Inner Class ( Non-static Nested Class ).   
  2. Static Nested Class.
  3. Local (nested , inner) Class
  4. Anonymous (nested , inner) Class.
  • If you declare a nested class as static it will called Nested Static Class.
  • Non static nested class are simply referred as Inner Class.
  • For outer class, there is only two access modifier for it, public and package.
  • Inside an interface, the nested class or interface implicitly public and static.

Member Inner Class 

  1. Inner classes cannot have static declarations unless the member is a constant variable.
  2. An inner class may inherit static members that are not constant variables even
    though it cannot declare them. 
  3. Access fields of the enclosing class even if they are declared private. 
  4. Java makes it possible though, for the Inner class to refer to the text field of the Outer class. To do so it has to prefix the text field reference with Outer.this. (the outer class name + .this. + field name). 
  5. If a Java inner class declares fields or methods with the same names as field or methods in its enclosing class, the inner fields or methods are said to shadow over the outer fields or methods.
public class Outer {
  public class Inner {
  }
}
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

Nested Static Class

  1. One of the main benefits of nested static class over inner class is that instance of nested static class is not attached to any enclosing instance of Outer class.
    (You don't need any instance of Outer class to create instance of nested static class in Java)
  2. Non-static variable cannot be referenced from a static context.
  3. They are typically declared as either subclasses of an existing class, or as implementations of some interface.
public class Outer {
    public static class NestedStaticClass {
    }
}
Outer.NestedStaticClass obj = new Outer.NestedStaticClass();

Local Class

  1. You can define a local class inside any block ( method body, for loop, if clause ). 
  2. A local class can access local variables only that are declared final.(local variable is accessed from within inner class; needs to be declared final)
    From Java 8 local classes can also access local variables and parameters of the method the local class is declared in. The parameter will have to be declared final or be effectually final.

    Effectually final means that the variable is never changed after it is initialized.
     
  3. You cannot declare static method in a local class.
     Since you cannot declare a local variable static, you also
     cannot declare a local class static.
class Outer {
public void printText() {
        class Local {
        }
        Local local = new Local();
    }
}

Anonymous Class 

  1. You cannot declare constructors in an anonymous class. 
  2. Anonymous classes are ideal if you have to implement an interface that contains two or more methods.
    Can used in performing additional tasks such as method overloading
  3. Anonymous classes are defined in the new expression itself, so you cannot create multiple objects of an anonymous class. 
  4. An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. 
  5. There are no such things as anonymous interfaces.
  6. You cannot explicitly extend a class or explicitly implement interfaces when defining an
    anonymous class.
public class SuperClass {
  public void doIt() {
    System.out.println("SuperClass doIt()");
  }
}
SuperClass instance = new SuperClass() {
    public void doIt() {
        System.out.println("Anonymous class doIt()");
    }
};

instance.doIt();
Benefits of Nested Classes

The organizational advantage.

The callback advantage.

Implement helper classes.

Implement same interface multiple times inside class.

http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
http://tutorials.jenkov.com/java/nested-classes.html
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html 
www.javaworld.com/article/2077411/core-java/inner-classes.html 

Tuesday, April 28, 2015

Enumeration vs Iterator vs ListIterator

I found a good article describe the differences in a good description with summary:

Iterator , ListIterator and Enumeration interfaces are mainly used to iterate collection classes .

Enumeration :
java2db Enumeration  iterates Vector and Hashtable .
java2db Reverse iteration is not possible with enumeration.
java2db It cannot add or remove elements  while iteration .
Iterator :
java2db Iterator   iterates the  implementations of  List , Set .
java2db Reverse iteration is not possible  with Iterator .
java2db Iterator cannot add elements , but it can remove elements while iteration .
ListIterator :
java2dbListIterator  iterates  List  implementations (like  ArrayList , LinkedList  etc).
java2dbBoth forward and backward iterations are  possible with ListIterator .
java2dbBoth elements addition  and deletion can possible  with ListIterator .

Syntax for Iterator ListIterator and Enumeration :

Iterator  <Iterator variable  name>=  <set/List variable> . iterator();
while(<Iterator variable  name>.hasNext())  {
<Iterator variable  name> .next();               }
ListIterator <ListIterator variable name>=<list variable>.listIterstor();
while  (<ListIterator variable name>.hasNext() ){
<ListIterator variable name>.next(); }
Enumeration <Enumeration variable name>=<Vector / Hashtable variable>.elements();
while(<Enumeration variable name>.hasMoreElements()) {
<Enumeration variable name>.nextElement(); }

http://java2db.com/java-util/difference-between-iterator-listiterator-and-enumeration-in-java

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...