Wednesday, October 2, 2013

NESTED CLASSES - Static Nested and Inner Classes

Nested Class:

  • Introduced in version 1.1 of Java.
  • Class within another Class.
  • A nested class is a class whose definition appears inside the definition of another class, as if it were a member of the enclosing class.
  • A nested class can be declared private, public, protected, or package private. 
  • Nested class can be hidden from all other classes using 'private' modifier.
  • Nested Classes are compiled as separate class files with following format:
    • EnclosingClass$InnerClass.class
    • EnclosingClass$StaticNestedClass.class
  • To run main method of nested class, use "java EnclosingClass$StaticNestedClass".
  • Divided into two categories - static and non-static (Inner Classes)
  • Nested class may be nested within another Nested class.
      

      class EnclosingClass {
          ...
          static class StaticNestedClass {
              ...
          }
          class InnerClass {
              ...
          }
      }

Features of Nested Classes:

  • Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
  • Static nested classes do not have access to other members of the enclosing class.
  • Inner class is associated with an instance of enclosing instance.
  • A static nested class is associated with enclosing class(not object).
  • The way static methods cannot access non static members, static nested class cannot refer to non-static members without object reference. 
  • Inner Class can access non-static members.
  • Inner class cannot have static members (except constants) because it is linked to an instance of enclosing class.
  • A static nested class is same as any top-level class just that it has been packaged in another top-level class. Only difference is static nested class can access private static members.
  • Inner class instance knows about the enclosing class instance, it can access its members using "<EnclosingClassName>.this".
        this.<member-name> // Inner Class's member
        <EnclosingClassName>.this.<member-name>  // Enclosing Class's member
  • Static nested classes are known as nested top-level classes.
  • An enclosing class can have multiple inner classes extending other classes, thus providing a way to achieve multiple inheritence.
  • Inner class needn't be created at the time of creation of enclosing class, it can be created any time after that.
  • An enclosing class can have multiple instances of same inner class, each with its own state. (Ex. multiple iterators for a rowset).

Typical Usage:

Inner class extends another class or implements an interface (ex. java.util.Iterator). Inner class can access outer class members and closely perform operations on them.
Used for writing test cases, since nested classes have access to private members.
Inner classes are best used in the event handling mechanism and to implement the helper classes.

Why we need Inner Classes:

In the above example, if Iterator would have been a class and not interface, then design couldn't have survived without Inner class, because a class can only extend one class (in that case only Iterator).

Miscellaneous Facts on Nested Classes:

  • Java supports the concept of nested classes in interfaces, though its a teriible programming practice. Following code will compile:
    public interface EnclosingInterface {
        void testMethod();
        class InnerClass {
            int x = 10;
            public void testx() {
                System.out.println(x);
            }
        }
    }
  • Java supports nested interfaces within interfaces but its also a bad programming practice.
  • Java supports nested interfaces within classes, though they are helpful in rare scenarios. These also can be avoided with the use of top-level interfaces.

Local Classes

  • Local classes are classes that are defined in a block, typically inside a method body, though it can be within a loop, if-else blocks etc.
  • Local classes (since its Inner Class) are non-static because they have access to instance members of the enclosing block.
  • A local class (since its Inner Class) has access to the members of its enclosing class.
  • Local classes (since its Inner Class) they cannot define or declare any static members or initializers except constants.
  • Local classes defined in static methods, can only refer to static members of the enclosing class.
  • A local class has access to final local variables as well.
  • local class names are in this format:
    • <EnclosingFormat>$<number><LocalClassName>.class
    • <number> starts with 1, gets incremented by 1 and so on. <number> is coming here because class names can be repeated in different blocks.
    • Ex. EnclosingClass$1LocalA.class, EnclosingClass$1LocalB.class

Anonymous Classes

  • They are like local classes except that they do not have a name.
  • Use them if you need to use a local class only once.
  • They enable you to declare and instantiate a class at the same time. 
  • It is an abbreviated notation for creating a simple local object "in-line" within any expression, simply by wrapping the desired code in a "new" expression.
  • While local classes are class declarations, anonymous classes are like expressions.
  • Anonymous class must be part of a statement since its like an expression.
  • Anonymous classes enable you to make your code more concise.
  • The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.
  • Anonymous classes have the same access to local variables of the enclosing scope as local class.
  • Anonymous classes also have the same restrictions as local classes with respect to their members
  • you cannot declare constructors in an anonymous class.
  • Since anonymous classes have no names, the Java compiler uses numbers to provide anonymous class names. Ex. EnclosingClass$1.class.
  • The anonymous class expression consists of the following:
    • The new operator
    • The name of an interface to implement or a class to extend.
    • Parentheses that contain the arguments to a constructor. In case of implementing an interface, there shouldn't be any parameters.
    • Body of class. Method declarations are allowed in body but statements are not. 
  • Syntax:
    new class-name ( [ argument-list ] ) { class-body }
    or:
    new interface-name () { class-body }
    // No argument list with interface.
  • These are mostly used in event handling.
  • They are useful for writing small encapsulated "callbacks," such as enumerations, iterators, visitors, etc.
  • Like local classes, anonymous classes cannot be public, private, protected, or static.  

When to use Member, Local and Anonymous classes?

  • When to use anonymous classes and when to use local classes depends on number of instances needed. If number of instances are more, its local class.
  • When to use local classs and when to use member class depend on the availability of the new type. If wide availability is needed, its member class.

How Inner Classes are Implemented in JVM?

  • Inner classes were introduced in Java 1.1.
  • Introduction of inner classes did not change the Java Virtual Machine or the Java class file format.
  • For Java interpreter and JVM all classes are normal top-level classes.
  • Java compiler inserts hidden fields, methods (getters for instance references), and constructor arguments into the classes it generates. 

Java 8 Enhancements:

  • Local class can access local variables effectively final (whose value is never changed after initialization).
  • Local class can access parameters of the enclosing block, i.e., method parameters in case Local class is defined in a method.

Saturday, September 28, 2013

Java Annotations - An Overview

Introduction

  • Introduced in JDK 1.5
  • One of the biggest ever feature added in Java.
  • A form of syntactic metadata that can be added to Java source code. Its basically Data about Data.
  • Annotations don't do anything on their own, they don't do any processing. They act like a modifier and become useful only when they are processed.
  • Annotations can be processed at compile time, run time or deployment time.
  • Annotations are tags that we insert into our code, to be processed by tools like compiler, deployment tools or other external packages. Annotations are part of the code.
  • Can be embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time.(Reference: Retention policy)
  • Prior to Annotations, Java provided only ad-hoc and non-standardized mechanism, including Serializable interface (other market interfaces), transient modifier, Javadoc comments, @deprecated tag in comments.One of the main reasons for adding annotation and metadata to the Java platform is to enable development and runtime tools to have a common infrastructure.
  • Annotations are part of java code, Java Docs are not. 
  • java.lang.annotations package provides library support for the Java programming language annotation facility.
  • Normally a developer needn't create Annotations.
  • Annotation-based programming is an extensible mechanism for generating application artifacts, packaging the application, and readying the application for execution.
  • Annotation-based programming offers a set of tags and a processing mechanism that allow you to embed additional metadata into code. Application then uses this additional metadata to derive the artifacts required to execute the application in a J2EE environment.

Defining Annotations:

     public @interface TestAnno
     {
        String str(); // It can never has any parameters.
        int count();
     } 

Implementation Key points:

  • @interface keyword is used to define annotations.
  • Annotation types are a form of interface.
  • Annotation elements must be compile time constant values.
  • There is no restriction of the type of annotation element.
  • All annotations consist solely of method declarations. These method declarations are called elements.
  • The declarations must not have any formal parameters or a throw clause.
  • java.lang.annotation.Annotation is super-interface for all annotations.
  • Annotations cannot include the extends clause.
  • Annotations can be applied to any declaration, ex. classes, methods, fields, parameters, enum, constants or even an annotation type.
  • There is a default value element in the annotations.
  • Annotations cannot use Generics, no generic member type, no type parameters.
     public class TestClass
     {
        @TestAnno (str="MyFirstAnnoTest", count=1001) 

        // When a element is given a value only name is used, 
        // paranthesis are not used.
        public static void main(String[] args)
        {
                ...
        }
     } 

  • If the annotation has no elements, then the parentheses can be omitted. Ex @Override.
  • If there is just one element named value, then the name can be omitted. Ex
    • @SuppressWarnings(value = "unchecked")
    • @SuppressWarnings("unchecked")
  • It is also possible to use multiple annotations on the same declaration: 
    • @TestAnno (str="MyFirstAnnoTest", count=1001)      
      @SuppressWarnings("unchecked")
      class  TestClass  { ... }
       

Annotation Uses:

  • Annotations helps moving away redundant code, remove config xml (ex. deployment descriptor), adds extra checks (ex. @override).
  • Provide information to Compiler - 
    • To detect errors or suppress warnings (@Deprecated, @Override, @SuppressWarning)
  • Compile-time and deployment-time processing -
    • Software tools can process annotation information to generate code, XML files, and so forth. Ex @WebServlet, @WebInitParam, @WebFilter, @WebListener etc.
  • Runtime processing - 
    • Marker Annotations

Default Value for Annotation elements

  • We can provide default values to annotations, that will be assigned if no value is specified.
  • A default value is specified by adding a default clause to a member's declaration.
  • Syntax:
    • type member() default default-value
    • default-value must be type compatible with member type.
       public @interface TestAnno
       {
          String str() default "testString" ; 

          int count() default -1 ;
       } 

Marker Annotations

  • Similar in concept with Marker interface - no member methods with sole purpose of marking a declaration.

Single-Member Annotations

  • As the name suggests, only one annotation contains only one member. 
  • member name should be value.
  • Uniqueness - allows to use shorthand, no need to specify the name of the member.
    public @interface TestSingleAnno
    {
       String value() ;

    }
    @TestSingleAnno("Testing Single Annotation")
    public static void main(Sting[] args)
    {
        ...
    }

Java SE Predefined Annotations:

  • @Deprecated
    • Defined in java.lang package.
    • Introduced in Java 1.5
    • When @Deprecated is used, documentation (javadoc @deprecated comment) should reflect why open is deprecated and what to use instead.
  • @Override
    • Defined in java.lang package. 
    • Introduced in Java 1.5  
    • If a method marked with @Override fails to correctly override a method, the compiler throws an error.
    • It helps to prevent errors. 
  • @SuppressWarning 
    • Defined in java.lang package. 
    • Introduced in Java 1.5  
    • Instructs the compiler to suppress specific warnings that it would otherwise generate.
    • Warnings like unused variables, deprecated methods will be suppressed by compiler. 
    • Ex. @SuppressWarnings("deprecation")
    • Ex. @SuppressWarnings({"unchecked", "deprecation"})
  • @SafeVarargs
    • Defined in java.lang package.
    • Introduced in Java 1.7
    • It asserts that the code does not perform potentially unsafe operations on its varargs parameter. 
    • Unchecked warnings relating to varargs usage are suppressed.
  • @FunctionalInterface
    • Defined in java.lang package.
    • Introduced in Java 1.8
    • An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.
    • Conceptually, a functional interface has exactly one abstract method.
    • However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.
    • If a type is annotated with this annotation type, compilers are required to generate an error message unless:
      • The type is an interface type and not an annotation type, enum, or class.
      • The annotated type satisfies the requirements of a functional interface.

Meta-Annotations

Annotations that apply to other annotations.
It is information about annotation.There are several meta-annotation types defined in java.lang.annotati
  • @Retention 
    • Specifies how the marked annotation is stored, at what point, its discarded.
    • Java defines 3 such policies encapsulated in java.lang.annotation.RetentionPolicy enumeration - SOURCE, CLASS, RUNTIME.
    • SOURCE - Retained only in source file and discarded during compilation.
    • CLASS - Stored in .class file during compilation, but its not available through JVM during runtime.
    • RUNTIME - Stored in .class file during compilation, and available through JVM during runtime. It offers the greatest annotation persistence.
    • Default Retention level is CLASS. If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS
    • Ex. @Retention(RetentionPolicy.RUNTIME) 
  • @Documented
    • Indicates whenever the specified annotation is used those elements should be documented using the Javadoc tool. 
    • By default, annotations are not included in Javadoc.
    • To make the information in @TestAnno appear in Javadoc-generated documentation, you must annotate the @TestAnno definition with the @Documented annotation:
        // import this to use @Documented
        import java.lang.annotation.*;

        @Documented
        public @interface TestAnno 
        { 
           String str(); // It can never has any parameters. 
           int count(); 
        }

  • @Target
    • Indicates the kinds of program element to which an annotation type is applicable.
    • If a Target meta-annotation is not present on an annotation type declaration, the declared type may be used on any program element.
    • A target annotation specifies one of the following element types as its value:
      • ElementType.ANNOTATION_TYPE can be applied to an annotation type.
      • ElementType.CONSTRUCTOR can be applied to a constructor.
      • ElementType.FIELD can be applied to a field or property.
      • ElementType.LOCAL_VARIABLE can be applied to a local variable.
      • ElementType.METHOD can be applied to a method-level annotation.
      • ElementType.PACKAGE can be applied to a package declaration.
      • ElementType.PARAMETER can be applied to the parameters of a method.
      • ElementType.TYPE can be applied to any element of a class.
       Ex. @Target({ElementType.FIELD, ElementType.METHOD, 
                    ElementType.FIELD})           

           public @interface TestAnno {
            ...

           }
 

           @Target(ElementType.ANNOTATION_TYPE)
           public @interface TestAnno {
            ...
   
       }
  •  @Inherited
    • Indicates that the annotation type is automatically inherited from the super class.
    • This annotation applies only to class declarations.
    • By Default a class doesn't inherit annotations of its super class.
    • When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type.

Java 8 Enhancements

Type Annotations and Pluggable Type Systems

  • Before the Java SE 8 release, annotations could only be applied to declarations.
  • As of the Java SE 8 release, annotations can also be applied to any type use.
  • A few examples of where types are used are class instance creation expressions (new), casts, implements clauses, and throws clauses.
  • This form of annotation is called a type annotation, following are few examples:
    new @Interned MyObject(); //Class instance creation 

    myString = (@NonNull String) str; //Type cast 

    @NonNull String str;  

    class UnmodifiableList<T> implements
   
    @Readonly List<@Readonly T> { ... } //implements clause 


    void monitorTemperature() throws
         @Critical TemperatureException { ... } //Thrown exception declaration

  • Type annotations were created to support improved analysis of Java programs way of ensuring stronger type checking. 
  • The Java SE 8 release does not provide a type checking framework. 
  • It allows you to write (or download) a type checking framework that is implemented as one or more pluggable modules that are used in conjunction with the Java compiler.

@Repeatable

  • Indicates that the marked annotation can be applied more than once to the same declaration or type use.
  •  There are situations where you want to apply same annotation multiple times to a declaration or type use. Following are few examples:
    • A Project could fall under several project categories.
    • A process needs to be scheduled for multiple time.
    • An event could be observed by multiple roles.
    //custom annotation without repeatable
    public @interface Schedule { ... }
 

    //container annotation for repeatable
    public @interface Schedules {
         Schedule[] value;
    }
 

    //custom annotation with repeatable
    //The value of @Repeatable meta-annotation is container annotation.
    @Repeatable(Schedules.class)
    public @interface Schedule { ... }

Saturday, August 31, 2013

Java - Confusing Terms

Iterable vs Iterator

Implementing Iterable allows an object to be the target of the "foreach" statement. It is in java.lang package. It has one method - Iterator<T> iterator().
Iterator represents iterator over a collection. It is in java.util package. It has three methods - hasNext, Next and remove.

Collection vs Collections

Collection is the root interface in the collection hierarchy. It is in package java.util. This interface is typically used to pass collections around and manipulate them where maximum generality is desired. It implements java.util.Iterable.
Collections class consists exclusively of static methods that operate on or return collections. It doesn't extend/implement any class/interface from collections hierarchy.


Comparator vs Comparable

Comparable interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
Comparable has int compareTo(T o) method. It is in java.lang package.


A comparator object (a class that implements Comparator interface) can compare any two objects and these two objects are passed as parameters to compare() method.

Comparator is used to sort objects in other than its natural ordering.
Comparator has int compare(T o1, T o2) and equals method. It is in java.util package.
 

Following is the result of the compare methods:
    a) A positive integer value if obj1 is greater than obj2.
    b) 0 value if obj1 and obj2 are equal.
    c) A negative integer value if obj1 is less than obj2.



Hashmap vs Hashtable

  • HashMap is non-synchronized whereas Hashtable is synchronized.
  • Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.
  • HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls
  • HashMap does not guarantee that the order of the map will remain constant over time.
  • HashMap can be synchronized by:
    • Map m = Collections.synchronizeMap(hashMap);

Iterator vs Enumeration

  • Iterator has a remove() method while Enumeration doesn't.
  • Enumeration is very basic and twice as fast as Iterator and uses very less memory. 
  • Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException.
  • Enumeration has two methods and both are available in iterator. Method names for both of them are shortened.

 Fail Fast vs Fail Safe

  • Fail fast means not concealing the error, bringing it out as soon as its detected.
  • Business is obstructed, but we get a chance to rectify.
  • Fail-Fast results in interrupted availability, over a period it results in a robust system.
  • Fail ensures system doesn't continue after a failure and creates data corruption and irreversible changes.
  • Fail Fast is a better approach in most scenarios but for life critical, mission critical applications we need fail safe programs and not fail fast. Fail-Safe is Achieved with Exception Handling.

Fail Fast Iterator vs Fail Safe Iterator

  • Difference between Fail Safe Iterator and Fail Fast Iterator is same as discussed above.
  • Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException in Java.

ConcurrentHashMap vs Collections.synchronizedMap vs Hashtable vs Hashmap

  • Collections.synchronizedMap provide a basic thread-safe implementation of Map. 
  • Collections.synchronizedMap has fail-fast iterator and single collection-wide lock, which at times is obstruction to scalability and concurrency. 
  • Collections.synchronizedMap and Hashtable give poor performance if the size is large due to single collection-wide lock.
  • ConcurrentHashMap implementations provide much higher concurrency while preserving thread safety. 
  • ConcurrentHashMap introduced concept of segmentation , ConcurrentHashMap only locked certain portion of Map to provide thread safety so many other readers can still access map without waiting for iteration to complete.
  • ConcurrentHashMap do not allow null keys or null values while HashMap allows null keys.

Interfaces vs Abstract Classes

  • Interface in Java can only contains declaration.
  • Abstract class may contain both abstract and concrete methods, which makes abstract class an ideal place to provide common or default functionality.
  • A class can inherit multiple interfaces, but it can inherit only one abstract class.
  • By extending abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies.
  • Methods in an abstract class can be protected, private, static etc. But, all items in an interface are implicitly public. 
  • Abstract classes can contain fields that are not static and final.
  • Interface defines a CAN-DO relationship, Classes (including Abstract) than IS-A relationship.
  • In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

Vector vs ArrayList

  • Vector and ArrayList are derived from AbstractList and implements List interface, which means both of them are ordered collection and allows duplicates.
  • Vector vs ArrayList is that both are index based Collection and you can use get(index) method to retrieve objects from Vector and ArrayList.
  • All the methods of Vector are synchronized and methods of ArrayList are not synchronized.
  • Both the ArrayList and Vector hold onto their contents using an Array.
  • A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Vector vs ArrayList vs LinkedList

  • LinkedList is implemented as a double linked list. Its performance on add and remove is better than Arraylist, but worse on get and set methods.
  • LinkedList also implements Queue interface which adds more methods than ArrayList and Vector, such as offer(), peek(), poll(), etc.
  • While an ArrayList uses an array internally to store the data, a LinkedList uses nodes to hold the elements.
  • LinkList is a series of instances of a private nested class Entry, which has next, previous and element references.

Dictionary & Properties

  • Dictionary is an abstract class. Map is an interface.
  • Dictionary is parent class of Hashtable.
  • Properties is child class of Hashtable.
  • Properties represents a persistent set of properties.
  • Each key and its corresponding value in the property list is a string, while in hashtable it can be any object.
  • Properties is thread safe.
  • Properties is a very specialized class that's designed to hold configuration and/or resources that are usually stored in some file.
  • Properties supports reading and writing its content to a well-defined plain-text format (using load()/store())
  • Properties supports reading and writing its content to a well-defined XML-based format (using loadFromXML()/storeToXML())
  • The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values.

Wait vs Sleep

  • sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. 
  • wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.

Notity vs Notify All

  • notify( ) wakes up the first thread that called wait( ) on the same object.
  • notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first. 

Java SE(Standard Edition) vs Java EE(Enterprise Edition) vs Java ME(Micro Edition)

  • Java SE - Plain vanilla version of Java. Java SE has a large library of code which includes many utilities, algorithms, data structures etc. Java EE and Java ME are built on top of Java SE.
  • Java EE - Builds on Java SE. Java EE contains additional libraries of code and development tools that are uniquely useful in developing web-based business applications.
  • Java ME - A reduced version of Java SE and an associated library of software that addresses the unique needs of Java applications that should run on limited capability devices like mobile phones and PDAs.


The list will continue, please contribute.

Wednesday, June 26, 2013

Session Values - putSessionValue vs putSessionValueDirect


  • Values set with putSessionValue function are cleared when redirected to homepage, but values set by putSessionValueDirect are cleared by logout, session invalidation and manual removal only.
  • putSessionValue can store only String, Number or Date but putSessionValueDirect can store any object.
  • Use of putSessionValueDirect is not recommended.
  • putSessionValueDirect is typically for passing information between self-service pages and non self-service pages.
  • Puts a value on the servlet session directly (through HttpSession.putValue(String name, Object value)) without associating it with a specific transaction ID.

Note: putSessionValueDirect has been used in Multple Transactions in One OAF Page.

Note: Session is not preferred place to store and pass values between pages. Refer to OAF: Passing Parameters, Encryption, Encoding.

Sunday, May 19, 2013

OAF: Passing Parameters, encryption, encoding

OAF: Passing Parameters between pages

Following are three common means of passing parameters between pages:
  • Request
  • Transaction
  • Session
In addition the values set in the View Attributes are available to all pages participating in the transaction.

Request :

  • Short-lived object created for each HTTP request.
  • It contains following application state:
    • URL Parameters
    • Updatable Field values (Message Text Input etc) and Hidden Field Values (form values) in case of post
    • Event trigggering bean and the action in case of post.
  • Request values are accessed using OAPageContext.getParameter() methods.
  • In OAF, we don't interact with Request directly, we interact with Request through PageContext.

Ways to pass parameters in Request:

  • Adding in URL: We can specify parameters as literal values or token substituted values (mapped to VO Attributes). Following are the examples:
    • OA.jsp?page=/xxabc/oracle/apps/xxabc/custommodule/webui/CustomPG&order={@OrderNum}
    • OA.jsp?OAFunc=XXABC_ADM_SUPP_ENGR&asset=123
  • OAPageContext.putParameter()
    • Values are not technically added to request, but are stored in a special page cache.
    • Equivalent to HttpServletRequest.setAttribute()
  • Hidden fields (form values)
  • Passing parameters in Hashmap using setForwardUrl().
Passing parameters in Hashmap is the better approach for following reasons:

  1. URL has size restrictions.
  2. URL is visible to users.
  3. putParamater() and hidden fields are not stored in Request as parameters, thus if we navigate with Breadcrumbs or for other reasons in case the webBean hierarchy needs to be reconstructed, these will not be available.

Transaction:

Transaction has wider scope than Request thus its not preferred approach.
  • OAPageContext.putTransactionValue()
  • OAPageContext.getTransactionValue()
  • ((OADBTransactionImpl)getTransaction()).putValue()
  • ((OADBTransactionImpl)getTransaction()).getValue()

Session:

Again, a wider scope than Transaction and not recommended.

  • pageContext.putSessionValue();
  • pageContext.getSessionValue();

Using VO Attributes for passing values

Values stored in VO attributes are available in all pages within the transaction with same Root AM.


URL Parameters : Encryption and Encoding

When we are passing parameters in URL, following need to be considered:

{@Attr} - encodes. Changes Prince Kapoor to Prince%20Kapoor
{!Attr} - encrypts. Encrypts sensitive information.
{$Attr} - plain token substitution (no encoding or encryption)
{@@RETURN_TO_MENU} - Used for E-Business Suite Personal Home Page. Same as OAWebBeanConstants.RETURN_TO_MENU_URL.
{@@RETURN_TO_PORTAL} - Return the user to a launching Portal page. Same as OAWebBeanConstants.RETURN_TO_PORTAL_URL.

Thursday, February 14, 2013

Oracle 11g Memory Structure


11g Memory Structure

Oracle has many different memory structures for the various parts of the software's operation.

  • System Global Area
    Shared memory structures for data and sql. It is shared by both background processes and server processes. SGA is Oracle's structural memory area that facilitates the transfer of data and information between clients and the Oracle database. The size of the SGA is controlled by the DB_CACHE_SIZE parameter. Oracle 11g allows users to tune both PGA and SGA areas with a single parameter, called MEMORY_TARGET.
      show parameter memory_target
      • Shared Pool -
        • Library Cache - A library of ready-to-go SQL statements.
        • Dictionary Cache - For storing the most recently used data definitions in the Oracle DB. These data definitions may include information about: database files, tables, indexes, privileges, users, etc.
        • Quickest Result Cache
          • SQL Result Cache - Stores sql query result. Oracle skips execution next time.
          • PLSQL Function Result Cache - Cache contains the result from a previous call to the function with the same parameter values, the system returns the cached result to the invoker and does not re-execute the function body.
      • Database Buffer Cache - 
      • Largest portion of SGA. To cache data in memory for quicker access. Buffer refers to database block. A block in buffer cache could be in any of the three states: Free, Pinned and Dirty.
      • Redo Log Buffer - 
      • Buffer that records every sql statement that changes data. The statement itself and any information required to reconstruct it is called Redo Entry. This buffer protects against loss of dirty blocks.
      • Large Pool -
      • Optional component. It relieves shared pool of sometimes-transient memory requirements. Features using the Large Pool - Oracle Recovery Manager, Oracle Shared Server, Parallel Processing, I/O-related server processes.Without large pool configured, these processes share the memory from shared pool's SQL area.
      • Java Pool - 
      • Optional component. This area handles the memory for Java methods, class definitions, etc.  The java_pool_size  parameter controls the amount of memory for this area.
      Following are key SQL Queries related to SGA: 
        • SHOW SGA
        • SELECT * FROM v$sga;
        • select * from v$sgainfo;
        • select * from v$sga_dynamic_components;
       
    • Program Global Area
      A program global area (PGA) is a memory region that contains data and control information for a server process. It is a nonshared memory created by Oracle when a server process is started. Access to it is exclusive to that server process and is read and written only by Oracle code acting on behalf of it.
      When you start a user process, that process has a private RAM area, used for sorting SQL results and managing special joins called “hash” joins.
      The PGA can be critical to performance, particularly if your application is doing a large number of sorts.  Sort operations occur if you use ORDER by and GROUP BY commands in your SQL statements.
      • Private SQL Area -
        • Variables that might be assigned values during SQL execution
        • Work areas for processing specific SQL needs: sorting, hash-joins, bitmap operations
        • Cursors
      • Session memory -
        • login information
        • session variables and settings
      Following are key SQL Queries related to PGA:
        • select * from v$pgastat;
        • select * from v$pga_target_advice order by pga_target_for_estimate;
        • select max(pga_used_mem), max(pga_alloc_mem), max(pga_max_mem) from v$process;

    Monday, January 21, 2013

    Java Versions, Features and History

    Came across following excellent blog on Java language:
    http://javapapers.com


    Liked following post on Java Versions, Features and History:
     http://javapapers.com/core-java/java-features-and-history/