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 ...