Wednesday, December 14, 2011

Java 7 : Using Underscore in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. It can improve the readability of your code.

   1: public class TEST {
   2:  
   3:     static byte testByte = 0b0011_0101;
   4:     static long testLong = 333_2222_2222L;    
   5:     static int testInt=100_000;
   6:  
   7:     public static void main(String[] args) {
   8:         System.out.println(testByte);
   9:         System.out.println(testLong);        
  10:         System.out.println(testInt);        
  11:     }
  12: }

Allowed

we can place underscores only between digits

Not Allowed

we cannot place underscores in the following places:


  • At the beginning or end of a number  (_54 , 54_)
  • Adjacent to a decimal point in a floating point literal  (1._22)
  • Prior to an F or L suffix  (2.33_F)
  • In positions where a string of digits is expected

Java 7 : Use Switch With String

In the JDK 7 release, you can use a String object in the expression of a switch statement.

Comparing string object is case sensitive.

   1: public class TEST {
   2:  
   3:     public static void testSwt(String testswitch) {
   4:         String tw;
   5:         switch (testswitch) {
   6:             case "teststr":
   7:                 tw = "TestingSwitch with String";
   8:                 break;
   9:             case "testswitch2":
  10:                 tw = "Testing Switch with String one";
  11:                 break;
  12:             case "testswitch3":
  13:                 tw = "Testing Switch with String two";
  14:                 break;
  15:             default:
  16:                 tw = "ERROR";
  17:                 break;
  18:         }
  19:         System.out.println(tw);
  20:  
  21:     }
  22:  
  23:     public static void main(String[] args) {
  24:         String strswitch = "teststr";
  25:         TEST.testSwt(strswitch);
  26:  
  27:     }
  28: }

The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

Java 7: Project Coin

Project Coin is to determine what set of small language changes should be added to JDK 7.

Language Changes

binary literals
strings in switch
try-with-resources
diamond operator
multi-catch with final rethrow
safe var-args annotation

IDE Support for Project Coin.

IntelliJ IDEA 10.5 and later

Eclipse 3.7.1 and later

NetBeans 7.0 and later

Monday, November 14, 2011

Oracle ADF : Industry Automation Tools for Continuous Integration

In current industry environment we have automated tools for performing scheduled task like check development Branch , Trunk for health check of code line for application , Deploy periodically.

There are various tools available in market to perform this job , However , I would list few most used.

Task Needed to be Performed

Take last from version control system , Compile Code  , Generate Java Doc , Package the whole application in to Ear , Deploy it on Development or QA Server.

Tools for Build

-Apache Ant , Apache Maven

Tools for Continuous Integration

- Cruise Control , Hudson

ADF BC : Default Value for Attribute

If you want assign default value to attribute when creating row in ADF BC then do the following.

I am explaining with temporary field.

Create DefaultValAttr in EO and Set the Literal to default value 1. This can be any attribute EO Attribute , Transient etc.

So when you create a row in EO then this attribute will have value 1.

image

Add this attribute to VO

image

When I created the row ,it assigned 1 to defaultvaluettr , this applied to any type of attribute.

image

Thursday, November 10, 2011

ADF : Load Customer Specific Properties file in Application Scope

When software application is delivered or deployed on customer site then for each customer there is different setting.

Some architect use Database , Properties file or Some other method.

Here I am going to demo you how to use properties file.

Create General project in jdeveloper as below.

- Create Java File to read properties

- Create properties file in resource directory

image

Enter following content in properties file.

image

Write following java code and Run.

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class LoadProperties {
    public static void main(String[] args) throws IOException {
        Properties props = new Properties();
        InputStream st =
            Thread.currentThread().getContextClassLoader().getResourceAsStream("MyApp.properties");
        props.load(st);
        System.out.println(props.getProperty("CUST_CURRENCY"));
        System.out.println(props.getProperty("CUST_LANG"));
        System.out.println(props.getProperty("CUST_CITY"));
    }
}

Friday, November 4, 2011

ADF : Clean Table Filter Using Command Button

ADF Table and Form are the most used component by developer for day to day job. However , ADF Table component is out of box and there are various way we can customize to meet our requirement.

There is one of feature of ADF Table called in-build filter. However , For each column we have to press enter to search for our criteria.

image

After above filtering is done and if we want to clear the filter then we have to manually delete the text for all 3 filter and press enter.

Solution:- To solve this issue I created one button on Panelcollection component and bind action listener to following method and it took care of clearing all 3 value automatically and re rendering old result.

Note:-  I have managed bean with table binding available.

public void clearEmpQbeFilter(ActionEvent actionEvent) {        
    FilterableQueryDescriptor qd = 
                      (FilterableQueryDescriptor)t1.getFilterModel();
    if (qd != null && qd.getFilterCriteria() != null) {
      qd.getFilterCriteria().clear();
      t1.queueEvent(new QueryEvent(t1, qd));            
   }
}


All filter cleared and result re rendered.image

Monday, October 31, 2011

ADF : Clean your drs , mds folder using Script

In day to day ADF development we run in to various issue and one of the issue is sometime taskflow fragment do no show latest changes  when you run the application from jdeveloper. so you stop the embedded  weblogic server in Jdeveloper and delete the deployed application folder from DRS and MDS directory in jdeveloper.

Locate weblogic by looking in to jdeveloper running integrated weblogic.

image

Based on above path , my drs  and o.mds.dt is located in below folder path.

C:\Users\hasim\AppData\Roaming\JDeveloper\system11.1.1.4.37.59.23\o.j2ee\drs

C:\Users\hasim\AppData\Roaming\JDeveloper\system11.1.1.4.37.59.23\o.mds.dt\adrs

Delete specific project or all project based on your need from above folder and run your application again and you can see your latest changes in taskflow , so issue is resolved.

Write Script to perform cleaning job

You will face this issue regularly , so why don’t you write script that will perform the above deletion.

1. open your notepad and copy paste below content.

ECHO OFF
CD YOUR_DRS_DIRECTORY
rd. /S /Q .
CD YOUR_MDS_DIRECTORY
rd. /S /Q .
ECHO "All Project deleted from drs,mds folder"


Replace YOUR_DRS_DIRECTORY and YOUR_MDS_DIRECTORY with your corresponding directory and try this script with only /S option that will actually prompt you before deletion.



2.Save this file as “MyJdevClean.bat” and run this script whenever you want to clean your drs,mds folder.



Integrate script to Jdeveloper How about integrating this script to jdeveloper,so you can run from there instead of any drive . Go to below menu and click yes.



image



You will get this dialog



image



Click new and give the path of your bat file. after you are finished , you will see the bat file in your jdeveloper.



image





You can follow same approach to create your own little world toolbar for your day to day need.

Saturday, October 29, 2011

ADF : Create Help Library using javadoc

For every software application creating help document for all functions and methods is most important thing for future reference.

Fortunately and very thanks to Oracle ADF Framework development team for providing help comment by default in Oracle ADF BC Impl files.

Here is following example of  EntityImpl.java files.

Normal Comment

Normal comment in java begin with /* and ends with */ and every thing between this two is ignored by compiler.

Javadoc

A javadoc comment begin with /** and end’s with */ and every thing between this two is ignored by compiler.Please create simple ADF BC project and generate Java files for EO , VO object.

To generate documentation we just have to run following command.

javadoc DepartmentsImpl.java

It will generate Help file just like Java Documentation online.

image

Monday, October 17, 2011

Weblogic : WLST CMO object (Current Management Object)

 

In previous blog if you have noticed that I have used cmo.setConsoleEnabled(true) in WLST offline mode.

What is cmo ?

cmo is WLST inbuilt variable which stands for Current Management Object. We can use cmo to point to current MBean instance. cmo value changes when we navigate to different hierarchy of MBeans under Weblogic MBean Tree except JNDI Tree.

Once we are connected to WLST , we can use cmo for various operation like get , set , invoke on management object.

Example :-

wls:/mydomain/edit> cmo.setAdministrationPort(7001)

This variable is available in all hierarchy except custom and jndi.

CMO value is current WLST Path. Each time we change directory WLST change path.

image

Sunday, October 16, 2011

Weblogic : Disable Console and Enable it using WLST

In Big Companies where there are 100’s of weblogic instance ,it is not best practice to use Console to do weblogic administration.  However , it is WLST that is used to do day to day weblogic administration task.

So first let us disabled the console ,so it can’t be accessed.

Click the domain to go to following tab;

image

In Advanced section uncheck this box.

image

After restarting weblogic server you will not be able to access http://localhost:7001/console it will throw 404 Not Found Error.

Now let us say if you want to set this flag again then we must use WLST to set this flag again.

Go to WL_HOME\common\bin\wlst.cmd ( Weblogic Scripting Tool)

run the following command

//Connect to weblogic admin server
connect('weblogic','welcome1') 
//mark it for edit
edit()
//start the edit
startEdit()
//set the flag to true
cmo.setConsoleEnabled(true)
//save the changes
save()
//activate the changes
activate()


Please restart the server.



Now try to access the console and you will be able to access it.

Thursday, October 6, 2011

Weblogic : Lock your Weblogic Configuration using Change Center

 

If you are sharing same development weblogic instance with multiple developer then it is best in interest of team to use locking feature provided by weblogic server Change Center, so only one developer can make changes at a time to weblogic configuration.

If you login to weblogic console you will see following Change Center above Domain Structure of your weblogic.

image

Change Center not Visible

If it is not visible then please to go

Home > Domain_Name > Preferences

image

Click User Preferences

Uncheck – Automatically Acquire Lock and Activate Changes

Note:- This feature is not available in Production Mode to disable Change Center.

image

If unchecking this option you will see Change Center with multiple button.

Lock & Edit

If you decide to do some operation on console like create Data Source etc. then first click Lock & Edit and make the changes and then click button below Lock & Edit which will be usually “Activate Changes” or “Release Configuration”

Apply Changes

After you click button to apply the changes then configuration changes are distributed to each of the servers. if changes are accepted by each servers , then they take effect. if any server cannot accept change ,then all changes are rollback from all the server in domain.

The  changes are left in pending state; you can then either edit pending changes to resolved issue or revert previous configuration.

You can explore other options available in Preferences.

Friday, September 30, 2011

Weblogic : Back Up Config.xml file

 

Config.xml is heart of weblogic server  and if you mess your configuration then how will you recover old configuration.

You don’t need to copy paste file on your handy drive every time when you change configuration.

Weblogic will take care of making sure you have back file maintained and created automatically for you.

Login to weblogic console

Click Domain –> Configuration –> General  (Advanced)

Check Configuration Archive Enabled and Count.

true - backups of the configuration will be made during server boot.

Change will take place after you redeploy module or restart the server

image

it will create following files in domain.

config-booted.xml

config-original.xml

image

Web logic : Importance of Web logic.jar and Weblogic.Admin Command

 

web logic.Server is a java class with main method which is packed in web logic.jar , web logic server starts like any java class.

There are several ways of starting weblogic server and each way calls the main method of this class by virtual machine.

Some Gems of Weblogic.Admin Command

This command is use for administration purpose.

After setting environment  you can run following command where url , username , password is compulsory and then you can give command.

java weblogic.Admin -url localhost:7001 -username weblogic -password welcome1  [COMMAND]

COMMAND – There are many commands  PING , CONNECT , VERSION , HELP , START , SHUTDOWN , FORCE SHUTDOWN , RESUME , SERVERLOG , THREAD_DUMP

Most of command are self explanatory.

SERVERLOG – Display server log file for specific server

THREAD_DUMP –  Display status of thread of weblogic server that are running.

LIST – List JNDI tree

Sunday, September 18, 2011

Weblogic : Change context path of Weblogic Console for Dev , QA , Production


Let us say if you have same physical machine and all weblogic server in your company Dev , QA , Production is located on same physical machine.
Then you will access all three console using following url

URL : DEV_PORT / Console
URL : QA_PORT / Console
URL : PROD_PORT / Console

In this *_PORT will be different for each server, but rest of the URL will be same.

Can we change “Console” context to give better differentiation apart from PORT ?
So final accessible url will be.

URL : DEV_PORT / DevConsole
URL : QA_PORT / QAConsole
URL : PROD_PORT / ProdConsole

To achieve
- Click Base_Domain or what ever domain you have.

image

Go to General on right side and click advanced below and change
Console Context Path to DevConsole.

image

Click Save , it is asking me to restart server.

image

Now access your console using
URL : PORT / DevConsole

image

Weblogic : Installation of weblogic using three different way

 

There are various way of installing weblogic server.

- GUI Mode

- Console Mode

- Silence Mode

1. GUI Mode

Double click the EXE file that you downloaded from oracle website.

It will come up with this screen which you can click next to provide JDK , Middleware home and finally configure weblogic server.

image

2. Console Mode

wls1034_win32.exe -mode=console –log=filepath

It is like installing using window command window or unix command shell.

3.Silent Mode

It is one time configuration which can be used to install weblogic on multiple machine. We need to create silent.xml file and provide all necessary information for installation including JAVA_HOME , MW_HOME etc.

wls1034_win32.exe –mode=silent –silent_xml=pathofslientfile

image

For further information please refer to Documentation

Since I have weblogic suite installed which contains Coherence , Oracle Enterprise Pack for Eclipse with Oracle JRocket . I have following directory structure inside Middleware Home.

image

Middleware Home (MW_HOME)                                    C:/…../Middleware1035

Weblogic Server home (WL_HOME)    C:/……../Middleware1035/wlserver_10.3

Node Manager Directory                  WL_HOME/server/bin/startNodeManager

Weblogic :- Switch between Sun JDK and JRockit

 

When we configure weblogic server , it ask to select development or production mode with Sun or JRocket JDK which are now both owned by Oracle.

image

Sun JDK :- It clearly says that Sun JDK on Development is better for startup and performance during iterative development.

JRocket JDK :- It do not poll for application to deploy and it is recommended for better runtime performance and management.

We should choose Sun JDK for development mode and JRocket JDK for Production Mode.

Let us say if we have Sun JDK in production mode and if we want to switch to JRocket then perform the following steps.

Go to FMW_HOME\user_projects\domains\domainname\bin

Open setDomainEnv.cmd or sh based on your environment.

There is variable called JAVA_VENDOR

set JAVA_VENDOR = Oracle (Will set JRocket)

set JAVA_VENDOR = sun (will set SUN JDK)

setDomaineEnv.cmd

image

Here I have both BEA_JAVA_HOME and SUN_JAVA_HOME pointing to corresponding JDK.

If we set JAVA_VENDOR=”Oracle” before executing startWeblogic.cmd then BEA_JAVA_HOME will be chosen.

if we set JAVA_VENDOR=”Sun” then SUN_JAVA_HOME will be chosen else JAVA_VENDOR is default set to “Sun” as you can see.

Conclusion :-

so you can set JAVA_VENDOR in setDomainEnv.cmd or sh before above logic or you can do it externally

set JAVA_VENDOR=”Sun”

startWeblogic.cmd

or

set JAVA_VENDOR=”Oracle”

startWeblogic.cmd

Thursday, September 15, 2011

Download File in Oracle ADF GUI : -af:fileDownloadActionListener and getRealPath() and weblogic.xml and show-archived-real-path-enabled

 

I had simple requirement to allow the user to download file from ADF Application i.e. PDF file , Word file.

So I am creating simple application with commandbutton with filedownloadactionlistener.

Please download the application Download Here

I added testdownload.txt file inside ViewController\public_html folder

Command Button

image

I added following code to dwdFile method.

FileDownloadActionListener Method  

    public void dwdFile(FacesContext facesContext, OutputStream out) {
        FacesContext fx = FacesContext.getCurrentInstance();
        ServletContext servCtx =
            (ServletContext)fx.getExternalContext().getContext();
        System.out.println(servCtx.getRealPath("/"));
        File file = new File(servCtx.getRealPath("/") + "testdownload.txt");
        FileInputStream fdwd;
        byte[] bt;
        try {
            System.out.println(file.getCanonicalPath());
            System.out.println(file.getAbsolutePath());
            fdwd = new FileInputStream(file);
            int checkline;
            while ((checkline = fdwd.available()) > 0) {
                bt = new byte[checkline];
                int rst = fdwd.read(bt);
                out.write(bt, 0, bt.length);
                if (rst == -1)
                    break;
            }
            out.flush();
        } catch (IOException e) {
            this.addMessage(FacesMessage.SEVERITY_ERROR,
                            "File cannot be downloaded , Please contact administrator.");
        }
    }
 
When I ran the jspx locally it downloaded the file successfully.
 

Deploying application as EAR

 

When I deployed application as ear and click the download button it did not downloaded the file and it printed null for getRealPath().

 

After some time I figured out that I have to generate weblogic.xml

 

image

 

and set the following property to true.

Enable getRealPath() results for archived web apps.

 

image

 

image



 

Now when I deployed the application on EAR ,it allowed me to download the file successfully.


Reason


There is known CR with Weblogic for this Issue


CR299135 -  Weblogic getRealPath Issue

Monday, September 12, 2011

ADF JSF : Stopping Auto Binding in backing Bean

 

When you create JSF , JSFF page in ADF you have two option.

- Do Not Automatically Expose UI Component

- Automatically Expose UI Component

image

Let say you selected to Automatically Expose UI Component then each component will automatically have getter and setter in Backing Bean.

If you want to get rid of that behavior in mid development which should be in standard practice from beginning then go to design view of page.

Design –> Page Properties – Component Binding –> Uncheck Auto Bind

image

Un check this Auto Bind for backing bean.

image

ADF JSF : ADFc: Scope object serialization failed (object not serializable) and Managed Bean , Backing Bean


When I was testing I noticed on web logic EM logs that there is constant exception coming every second.


Download Code from Here Download Here , After Download go to TestSer.java and remove Serializable and run code you will notice below exception and then implement serializable this exception will be gone.


image


Let me demo you precisely why this happened.


Backing Bean


This is actually BackingBean which has one to one relationship with each and every component in java file.


image


It has getter and setter for each component on GUI.


image


Here is sample GUI and if you double click button it will allow you to create action inside this backing bean.


image


Also, before running please don’t forget to set following java option.


image


org.apache.myfaces.trinidad.CHECK_STATE_SERIALIZATION – This check is disabled by default. It checks no unserializable state content on session attributes is detected

After running application when I clicked button , it simply printed button called without any exception’


image


Managed Bean : Practice in ADF


Generally In ADF Development developer will not create backing bean for each and every JSF , JSFF. he will instead create one Managed Bean for whole TaskFlow consisting of multiple JSFF. Each JSFF page will call that managed bean to perform it operation.


image


So I created new Managed Bean (TestSer.java) and bind it to second button then ran the application without Serializable implemented in TestSer bean it was throwing above exception from both button.


but when I implemented Serializable in TestSer.java then it stopped throwing above exception from both button.


Note:- I did not implements Serializable in backingBean TestSerialization.java.


image


So please make sure you implements Serializable in this type of Managed bean॥


When you are designing an application to run in a clustered environment, you must:
Ensure that all managed beans with a life span longer than one request are serializable (that is, they implement the java.io.Serializable interface). Specifically, beans stored in session scope, page flow scope, and view scope need to be serializable.

Thursday, September 8, 2011

Weblogic : WLST Engine Location

 

I mentioned in previous blog about WLST and how to start using it.

However , WLST engine is located in following MW Directory.

MW\oracle_common\common\bin

wlst.cmd and wlst.sh

Wednesday, September 7, 2011

Weblogic : How to connect to weblogic using WSLT

 

WLST stands for Weblogic Scripting Tool that system admin use to monitor weblogic instances and domains and perform most of admin task using this tool e.g. check server status , create domain , managed server , start , stop server etc..

WSLT is based on java scripting interpreter , jython (www.jython.org).

WSLT can be used in three ways

1) Using command line

2)Using script file (.py extension) , which can be run as

java weblogic.WLST filename.py

3)Embedding Mode

We can embed WLST in java code

import weblogic.management.scripting.utils.WLSTInterpreter;
import org.python.util.InteractiveInterpreter

Java  Class and Logic

{

}

How to connect to weblogic

- Open Command window.

- Set the environment for weblogic

image

- java weblogic.WLST

image

After connecting to WSLT , we can run command in two mode offline and online.

offline mode

To use offline enter command , set variables or run script at WSLT prompt.

online mode

To use it online we need to connect to weblogic server first and then use command against running server.

I connect to localhost weblogic for demo using connect command.

connect(username , pwd , t3: // url)

image

Note : we have security warning because it is always advisable to connect to weblogic using secure channel.

Now we are free to perform action against our connected server.

If you need help type following command , it tells how to locate all important command.

image

There is common phrase that before entering some thing please be well informed how to exit.

So here is command to exit WLST Window.

exit()

Now we can play around with all the WSLT command as needed.

Sunday, September 4, 2011

ADF BC : LOV Switching in ADF BC

 

If we have a requirement to bind multiple LOV to single attribute in ADF View object then Oracle ADF BC has LOV switcher concept to achieve it.

I will use standard HR schema ,but on top of that I will create my own table to play with LOV Switch.

CREATE TABLE LOV_SWITCH (ID NUMBER(10) , LOV_RETURN_ID VARCHAR(20))

image

Two LOV

Here we are going to have two LOV one that will return department id and other that  will return employee id on single attribute ID.

We have LOV_RETURN_ID field which will be check box for triggering the switch.

When I create EO/VO for LOV_SWITCH Table it generated following VO definition and I added extra transient attribute lovswitchvar.

image

Then you can see I added two LOV one will return employee id and other department id to ID attribute. Also , I selected List of Value Switcher as lovswitchvar.

LOV Definition can be found below.

image

Employee LOV

image

If I run the application will it work ? NO

LovReturnId :- I made LovReturnId as check box and I am comparing value of LovReturnId in lovswitchervar ,if check box is clicked then use LOV_Id otherwise use LOV_Id1.

Now add groovy express to lovswitchvar.

image

Run Application Module tester.

When I click + icon first time to create row check box is unchecked.

UnCheck :-  EmployeeId in LOV.

image

Check :-  DepartmentId in LOV.

image

We have used LOV switcher in ADF BC layer , we can also used on Taskflow , Page Definition.