Showing posts with label adf. Show all posts
Showing posts with label adf. Show all posts

Tuesday, July 9, 2013

Use ADF logger in ADF application


Description: 


Oracle has provided a logging mechanism in ADF, so that a developer can use this logging feature to test the ADF applications. It's basically a thin wrapper around the java.util.Logging APIs with a few simple methods and, most importantly some specific features integrated into both JDeveloper and Enterprise Manager. It's preferable to use this built-in logger for these reasons, plus it can help you avoid the kind of class-loading issues if one uses some random version of something like Log4J.
Oracle Fusion Middleware components create diagnostic log files in the Oracle Diagnostic Logging (ODL) format. Log file naming and the format of the contents of log files conform to an Oracle standard. By default, the diagnostic messages are in text format.
You can also set up the Java logger to display Java diagnostic messages. Whichever logging format you choose, you can set several levels of logging to control the level and number of messages that are displayed.
You configure the logging session by editing the logging.xml file using the overview editor for Oracle Diagnostic Logging Configuration. You can set the logging level for both persistent and transient loggers and declare handlers for each logger. Logging configuration can be set at any time, even while the application is running in JDeveloper.

After you have created a log, you can view and filter the log messages with the Oracle Diagnostic Log Analyzer. This tool allows you to set filters for different log levels, define message time frames, and search on message text.

Configuration Steps :

Open logging.xml file :


  • In the Application Server Navigator, right-click IntegratedWebLogicServer and choose Configure Oracle Diagnostic Logging for server name.



  • Or, from the Log window Action menu, select Configure Oracle Diagnostic Logging.






  • In the overview editor, click the Overview tab, select ODL Log Levels or Java Log Levels for the logger types you want to view.



  • So what we see here is a hierarchy of all the packages in the running app server. Notice that some of the icons are green, these are packages or classes that have a presence in the logging.xml already and some are yellow. These latter groups are transient, that is, we can temporarily set up logging on that package or class for the duration of the application server, but once the application server shuts down, the entire logging configuration will be reverted. You'll notice the checkbox at the top of this screen that is labeled Hide Transient Loggers if you want to see persistent loggers only, select Hide Transient Loggers.

Setting up logging level: 

  • You can use the overview editor for Oracle Diagnostic Logging Configuration to configure the logging levels specified in the logging.xml file. The file can be configured before and while the application is running in Integrated WebLogic Server. The changes will apply without the need to restart the server.
  • When Integrated WebLogic Server is running, you can define both persistent and transient loggers. When the Integrated WebLogic Server is not running, you only can define persistent loggers. The transient loggers will last only for the session and will not be entered in logging.xml. If the server is not running, you must explicitly save the configuration changes to logging.xml for the updates to take effect in the next server run.



  • To set level of a package or class just expand the corresponding package or class, go to the level column drop down the list and select the required level.
  •  Now this class or package will show this level of message. If a package has a level set then all the sub package and classes under that package will show the same level of messages.

Add new logger :
  • To add a logger.
    1. If the server is running, click the add icon dropdown menu, and choose add persistent logger or add transient logger . If the server is not running, click Add to add a persistent logger. You cannot add a transient logger.
    2. In the Add Logger dialog, enter a logger name.
    3. Select the logging level.
    4. Click OK.
  • As well as the logging levels it is also possible to configure the handlers. In logging, the handler is the thing that takes your log message and does something with it - prints it to the console, writes it to a file etc. If you select the root logger in the editor here you will see that it defines three handlers listed in the Handler Declaration section of the screen at the bottom of the editor:
    • odl-handler
    • wls-domain
    • console
  • The first two would be the default for a standalone WLS instance, but the console we've automatically added for you in the case of the embedded WLS so that you will be able to see the output of your carefully placed logging commands in the log window of the IDE.
Logging.xml file

These changes are done from JDeveloper IDE in logging,xml file, which resides in following location:

C:\Documents and Settings\username\ApplicationData\JDeveloper\latest_system_ folder\DefaultDomain\config\fmwconfig\servers\DefaultServer


These customizations in xml file looks like :

<loggers>
      <logger name="oracle.adf" level="INFO"/>
      <logger name="oracle.adf.faces" level="FINE"/>
      <logger name="oracle.adf.controller" level="INFO"/>
      <logger name="oracle.bc4j" level="INFO"/>
      <logger name="oracle.adf.portal" level="INFO"/>
      <logger name="oracle.vcr" level="INFO"/>
      <logger name="oracle.portlet" level="INFO"/>
      <logger name="oracle.adfinternal" level="INFO"/>
      <logger name="oracle.adfdt" level="INFO"/>
      <logger name="oracle.adfdtinternal" level="INFO"/>
</loggers>

Use of ADF Logger


  • Using logger for model configuration :
  1. In the Application Navigator, double-click the user interface project.
  2. In the Project Properties dialog, click the Run/Debug/Profile node and create a new run configuration.
  3. In the Run Configurations list, double-click the new run configuration to edit its properties.
  4. In the Edit Run Configuration dialog, for Launch Settings, enter the following Java options for the default virtual machine: 
  5. -Djbo.debugoutput=adflogger
  6. This option will now pick the settings from logging.xml file.

  • Using Logger for java classes
    • First define the logger itself - usually a static variable in a particular class - for example one of your managed beans:
    private static ADFLogger _logger = 
                ADFLogger.createADFLogger(MainPageBackingBean.class); 
    
    • • Next, throughout your code you can sprinkle logging statements at various levels which are (I hope) fairly self explanitory, for example in this constructor:
    public MainPageBackingBean() {
            super();
            _logger.info("Creating a new instance");
            if (BindingContext.getCurrent() == null) {
                _logger.warning("Injected Data-Binding Reference is null");
            } else {
                try {
                    doSomethingComplex();
                } catch
                weirdAppException waex;
                {
                    _logger.severe("Unexpected exception doing complex thing",
                                   waex);
                }
            }
        }
    
    
    • As you can see we generally just pass a String message to the logger, although in the error case we can pass a throwable exception as well. You can also grab your Strings from a resource bundle, rather than hardcoding them. This probably makes sense for error messages but may be overkill for programmers eyes only messages. To grab the resource bundle you simply call the getFormattedMessage() function on the logger, or you can also get hold of the resource bundle that it references using getResourceBundle().
    _logger.severe(_logger.getFormattedMessage("errors.db_connection")); 
    
    • Where the resource bundle contains something like:
    errors.db_connection=Unable to establish connection with database!
    
    • You can pass parameters to inject into the resource string as well
    • The final thing to mention in this posting was the use of guard conditions. Although logging calls themselves are cheap if logging is not enabled, you may actually need to do quite a lot of work to prepare the stuff you want to log. For example, I have a standardized method that I use as a Task Flow Initializer to dump out the contents of the PageFlowScope for that taskflow. That's a pretty expensive operation so you want to bypass that whole thing if you know that every single log message within it will be ignored.
    • Therefore you can use the isLoggable() method to wrap the whole thing. Here's the example:
    public void diagnosticInitializer() {
            //Only do the work if we need to
            if (_logger.isLoggable(Level.INFO)) {
                AdfFacesContext actx = AdfFacesContext.getCurrentInstance();
                FacesContext fctx = FacesContext.getCurrentInstance();
                //Gather key information to dump
                String windowName =  actx.getWindowIdProvider().getCurrentWindowId(fctx);
                String viewPort = ControllerState.getInstance().getCurrentViewPort().getClientId();
                Map pageflowScopeMap = actx.getPageFlowScope();
    
                _logger.info("TaskFlow Diagnostics for " + viewPort);
    
                if (!pageflowScopeMap.isEmpty()) {
                    Iterator mapIter = pageflowScopeMap.entrySet().iterator();
                    while (mapIter.hasNext()) {
                        Map.Entry entry = (Map.Entry)mapIter.next();
                        String varKey = entry.getKey().toString();
                        Object varValue = entry.getValue();
                        String varClass = "n/a";
                        if (varValue != null){
                            varClass = varValue.getClass().getName();
                        }
                        StringBuilder bldr = new StringBuilder();
                        Formatter formatter = new Formatter(bldr, Locale.US);
                        formatter.format("Key:\"%s\" Value:\"%s\" Type:[%s]", varKey, varValue, varClass);                    
                        _logger.info(bldr.toString());
                    }
                } else {
                    _logger.info("No PageFlowScope associated with this TaskFlow instance");
                }
            }
        }
    
    

Friday, November 2, 2012

Installation Of ADF Runtime Environment to Weblogic Server

In previous post I show the Installation process of Weblogic server. This post is in continuation. 
Now to run ADF application on weblogic server first we have to install ADF runtime in to Weblogic server. This will provide needed ADF library in weblogic server so that ADF application can be deployed in to the server. ADF run time is not installed in to weblogic server autometically, it is done manually.
To do this we need Jdeveloper installer. Run Jdeveloper Installer in welcome screen click next to start setup.



Go to next screen , this will show option to select existing middleware home or to create a new middleware home. Choose an existing home where weblogic server is installed. Here home for weblogic server is (C:\Oracle\Middleware). Then click next.


This screen shows Components this installer can install. Weblogic server component will come disabled as it is already installed in this middleware home, we just need ADF runtime, So we will select this option . No need to install jdeveloper. Click Next to proceed.




On JDK selection option, SUN SDK already selected as weblogic is installed with SUN SDK. So simply click next in this step.



Next step is for selection of installation directory. As this middleware home is created previously so skip this step and press next button.



Now screen is showing installation summary. Click next to proceed.



Now installation process is started .



At the end installation is complete message comes. Click on done button will exit the installation.


Weblogic server is now ready for ADF application Deployment. Next step is to Create a new domain in weblogic server for production mode.

Thursday, November 1, 2012

Installation Of Weblogic Server

Oracle have provided Weblogic Server to run ADF application created in Jdeveloper. when we install Jdeveloper Weblogic Server also get installed. This is our scenario for development. Now we need to install stand alone Weblogic Server to a machine for production purpose.

Here I will show the steps of installation of stand alone Weblogic Server.

Run setup for weblogic server.


A welcome window will come up to start installation of weblogic server. Click next button to start installation.


 Next screen will ask for a middleware home. If you want to use existing home then select one of the appeared home or simply create a new one.


Click next to go to next step. Select custom installation type. In typical it installs Oracle coherence and Oracle Enterprise pack for Eclipse. We do not need them, so choose custom installation


Go to next step by clicking next.  This screen shows components to install. Select Weblogic server and leave other option unchecked


Go to next step. There are two option for java installation first one is Sun SDK and other is Oracle JRockit . Choose Sun SDK and click next.


In next window it will show where weblogic server will be installing.


Now select no option for Node manager service. We will do this later manually.


Choose shortcut option for weblogic server. Click next.


Next window shows summery of installation.


Clicking next button will start process of installation.


After installation it shows complete message in window. Done will exit the process. 

This is the process of weblogic server installation.

Monday, October 22, 2012

ADF Utility Classes

Following files can be used in ADF to ease coding.  These java files contain very useful methods. 


Monday, September 17, 2012

Set Text Style in input text field


    In ADF application default style of input text is lower case. Whenever user types in input text he has to decide to type in lower case or upper case or first letter capital style. If a developer want to restrict the format of a input text to lower case or upper case or capitalized style then it can be done by changing style.
     As this style property is set, this will give desired format regardless the user's keyboard's caps lock button is on or not.
      To do this go to contentStyle property of input text and set one of the following values:


For Capatalized text
text-transform:capitalize

For Lowercase:
text-transform:lowercase

For UPPERCASE:
text-transform:uppercase

Tuesday, August 21, 2012

Get Current Date and time

  • We usually need to get current date and time in java class. It is easy to get current date for java.util.Date class.

java.util.Date date = new java.util.Date();

  • This date object gives current date and time. To use this date and time this can be formatted in needed date format as follows:

DateFormat dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            java.util.Date date = new java.util.Date();
            String datetime = dateFormat.format(date);

  • This will give desired format to current date. Now to use this format in code we need to change this string to java.util.Date

        try{
                java.util.Date date2 = dateFormat.parse (datetime);
                }catch(ParseException pe){
                    pe.printStackTrace();}

  • Now to get current date in oracle.jbo.domain.Date class do the following

        java.sql.Timestamp datetime = new java.sql.Timestamp(System.currentTimeMillis());
        oracle.jbo.domain.Date daTime = new  oracle.jbo.domain.Date(datetime);  

  • Or change java.util.Date to oracle.jbo.domain.Date
               DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    java.util.Date date = new java.util.Date();
                    String dateStr = dateFormat.format(date);
         try{
                java.util.Date date2 = dateFormat.parse (dateStr);
                    java.sql.Date sqldate = new java.sql.Date(date2.getTime());
                    oracle.jbo.domain.Date daTime = new  oracle.jbo.domain.Date(sqldate);
                    System.out.println("Current Date Time : jbo " + daTime);
                }catch(ParseException pe){
                    pe.printStackTrace();}  

To get only date use java.sql.Date and to get date with time use java.sql.Timestamp

Wednesday, September 28, 2011

Get value from task flow using Contextual Event


Often a page or a region within a page needs information from somewhere else on the page or from a different region. Among the options for passing information to and from regions, Contextual Events is the most powerful and the option that does not make regions refresh or require the referenced bounded task flow to restart.

Contextual events have two parts:
  • A publisher (or producer), such as a button that raises a named event, with or without a custom payload.
  • A handler (or consumer) that listens for a specifically named event or a wildcard event, to process that event.
Create a Contextual Event:

  • Create a bounded task flow with page fragment and create a view inside it. Create a view object and place it as a tree table or tree in page.
  • To create a contextual event just select the tree and go to its properties. There go under the option publish event and click on add button to create a contextual event. Select create new event and press ok, this will create a contextual event. Here event type will be currency change event.
Get Contextual Event:
  • Create a adf jar file of this application. Add this library to a new application where you will use the task flow as a region.
  • Create a page and put a input text on it, give its value from a bean class.
public class NewBean {
    private RichOutputText newtext;
    String MyValue=null;

    public NewBean() {
    }

    public void setNewtext(RichOutputText newtext) {
        this.newtext = newtext;
    }

    public RichOutputText getNewtext() {
        return newtext;
    }

    public void setMyValue(String MyValue) {
        this.MyValue = MyValue;
    }

    public String getMyValue() {
        return MyValue;
    }
}
  • Now create a event handler class which will act as a consumer of event generated by a producer. In it create a function which will get the value from producer event. This function will take a parameter of currency change event type which is produce by the tree node selection event.
public class EventHandler  {
    public EventHandler() {
        super();
    }
   
    public void handleEventStringPayload(DCBindingContainerCurrencyChangeEvent customPayLoad) {

        this.setNewValue(customPayLoad.getSource().toString());
        FacesContext fctx = FacesContext.getCurrentInstance();
        ELContext elctx = fctx.getELContext();
        ExpressionFactory exprFactory = fctx.getApplication().getExpressionFactory();
        ValueExpression ve = exprFactory.createValueExpression(elctx, "#{NewBean}", Object.class);
        NewBean pageBean = (NewBean)ve.getValue(elctx);
        pageBean.setMyValue(customPayLoad.getSource().toString());
        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        adfFacesContext.getCurrentInstance().addPartialTarget(pageBean.getNewtext());

    }
  • To make this function available at the binding level, create this java class' data control. To do this right click on this java class and go to create data control. Select all 3 option if you are using release 2 of jdeveloper.
  • Now go to page , drag and drop task flow from library and make it a region or dynamic region. By this event will also be available in this page. Go to binding section of page and add new method binding to it. Add method from data control to it. By this, method can be accessed from this page.
  • Again go to binding tab of page and open contextual event tab. In this tab go to subscriber tab and click on add button. This will pop up a window. Click on the search button it will show available events in this page. Select previously defined event in task flow's page.
  • select the publisher or keep it any. Now go to handler option and click search button it will show available functions in bindings. Select the function created for event handling. Go to last part of subscriber parameter. Give parameter name same given in event handler function. Its value will be ${payLoad}.
  • Now run application it will show selected tree value in output box which is outside the region.

Monday, August 1, 2011

ADF-BC Validations


This framework provides very good feature of validation. In ADF we can validate user inputs at different levels. Which are
  • Attribute level: Fires on value change.
  • Entity level: Fires on moving from one record to another.
  • Transaction level: Fires after attribute and entity level validations are complete. It validates Master-detail validations.
These validations are defined in Entity object and View object level. There are many rules of possible validations and ADF-BC provide lots of them. These validations rules are:
  • Compare: Attribute value compared with other attribute's value or an expression or a literal.
  • List: Value is validated against a list of values.
  • Key Exists: Its like a foreign key validator, it checks the value whether it exists or not. Like value for employee will check for the department to check whether it is present or not.
  • Regular Expressions: Value compared against provided regular expression. Like for email validation, Number Format validation.
  • Script Expression: Groovy expression are used to do validations.
  • Method Validator: When a method validator is created it adds a method in corresponding entityImpl calss. Like
public boolean validateEname(String ename) {  
return true;
}

Tuesday, June 21, 2011

Refresh Resource Bundle


  • Resource bundle can not be refreshed using ResourceBundle class. using following code do not clear the cache.
Class type = ResourceBundle.class;
Field cacheList = type.getDeclaredField("cacheList");
cacheList.setAccessible(true);
((Map)cacheList.get(ResourceBundle.class)).clear();
  • If you want to refresh resource bundle of your application you should need to use Resource bundle manager instead of Resource bundle class.
ResourceBundleManagerRT rt = (ResourceBundleManagerRT)ResourceBundleManagerRT.getResourceBundleManager();
 rt.flush();

Monday, June 20, 2011

Use external XML file for Resource Bundle


  • Create list resource bundle file for default and supported locale. And read label value from xml file.
  • This approach gives a facility to change label or message value, without compilation and redeployment of application.
  • To do this first crate a xml file containing key and value pair, so that you can use label according to their key.


 
 
 

  • This method also give an option to use single file for different application, which are used as a library.
  • Here you can write code to read xml file and assign key value pair to an object of resource bundle class.
public class MyResources extends ListResourceBundle {

    public MyResources() {
        super();
    }
  
  private static final Object[][] contents =
    { { "", "" }, { "", "" }, { "", "" } };

    protected Object[][] getContents() {
        try {
            File file = new File("C:\\Users\\admin\\Desktop\\locale\\Resource.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("label");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element)nNode;

                    contents[temp][0] = getTagValue("key", eElement);
                    contents[temp][1] = getTagValue("value", eElement);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contents;
    }

    private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node)nlList.item(0);

        return nValue.getNodeValue();
    }

}

Friday, June 10, 2011

Jdeveloper 11g release 2 , with lots of new features


Oracle released a new version of Jdeveloper 11g, containing lots off new features and even rapid development of application. These new features take jdeveloper to another level and now can be compared with other J2EE IDE such as java bean and eclipse.


Main features of new jdeveloper are:

  • Hot deployment: There is no need now to run application after any change in application files. Now just save the changed file and refresh the page.
  • Skin Editor: This new editor for skin is very use full to create css for application. It made it easy to select different properties of a component and change their attributes.

You can also get installation guides for this new release and for new skin editor in this link : http://www.oracle.com/technetwork/developer-tools/jdev/documentation/index.html

Check for the related documents: http://download.oracle.com/docs/cd/E16162_01/index.htm