Sunday, December 13, 2009

Use Checkbox For Selecting Multiple Rows From af:table

One of the feature which existed in JDeveloper 10g but not found in JDeveloper 11g is using checkbox for selecting multiple rows from af:table.
This is my workaround for achieving this feature in JDeveloper 11g. Follow this steps:

1- Make a new ADF fusion web Application.
2- choose your database connection. (assume we are using HR Schema)
3- Make one viewObject based on entity (assume Employees viewObject based on Employees Entity)
4- Open your Employees ViewObject and make a new transient attribute with type boolean and make it always updatable (assume the transient Attribute name is 'TransientAttr').


5- Make a new page and drag your employee view as a table and don't check on Row Selection checkbox.
6- In your Structure Palette goto your inputText Transient attribute and right click and choose Convert to.






7- From opening dialog choose Select Boolean Checkbox ---> Ok ----> Ok.

8- Make the selectBooleanCheckbox component AutoSubmit with true and put its Id in the table partialTrigger and clear its lable and text.
9-
Select all columns and goto Style Property and inlineStyle write
this #{(row.TransientAttr)?"background-color: #ffaaaa":""};
where #ffaaaaa is the color of the selected row (you can change this color as you want).
10-Now any row has its transient Attribute with true value, this row will be selected row.

Sunday, November 8, 2009

Getting the Value from a SelectOneChoice List (Not Index)

One of the Issue I found when I use af:selectOneChoice component that when I want to get the selected value from one of the selectOneChoice attribute from backingbean I found the return value is the index of selected value not the value. (Using HR Schema)
assume we have an EmployeesView which has a DepartmentId (as a lookup to DepartmentView) and want to get the the value of selected Department. To solve this problem do this :

BindingContainer bindings =BindingContext.getCurrent().getCurrentBindingsEntry();
JUCtrlListBinding listBinding =(JUCtrlListBinding)bindings.get("DepartmentId");
Row selectedValue = (Row) listBinding.getSelectedValue();
System.out.println(selectedValue.getAttribute("DepartmentId"));

Where:

- DepartmentId the selectOneChoice Attribute
which you want to get its value.
- selectedValue is the row of the lookup attribute (In this case will be the row of the selected department).

Monday, November 2, 2009

How To Make Declarative Component

Declarative Component is used to build a reusable UI component. You can design your own component using ADF Faces Component. To establish declarative component follow this Steps :
1- Make a new ADF Application.
2- In ViewController Project, right click in a web content folder -----> new.
3- In Web tier -->JSF--> JSF Declarative Component.
4- Enter Declarative component name (e.g. UserInfo) and package.
5- Define a tag library name. This tag library name will be the name of the library in which the component will be stored and is the name you will see in the drop down of the component palette when you use the component.
There is a facet Definitions - Attributes – Methods. You can define any of these
depend on your component. Assume we want to make a component for user
Information it contain a three text as name, Address and telephone and one toolbar that
can manage user to add any button to do any action. In this case we need one facet to
add in the toolbar and three attributes then press Ok.
6- Drag and Drop af:panelBox in the page and set its Text to User Information thin in panelBox toolbar facet drag af:facetRef and choose your facet.


7- Drag af:panelFormLayout and insert inside it a three inputText and set its label to Name, Address and Telephone.












8- In the af:inputText (Name) edit the value by choosing Expression Builder then from JSP Object choose attrs then Name.
9- Repeat this Steps to af:inputText (Address) and af:inputText (Telephone).
10- In ViewController Project right click then choose Project Properties.
11- Choose Deployment then press new.


12- In Archive Type choose ADF Library JAR File and Enter the name of Jar as (UserInfoJar) then press Ok.





13- In ViewController Project right click then choose Deploy -->UserInfoJar-->To ADF Library JAR.






14- In Recourse Palette -> New Connection -->File System.

15- Enter A connection name and the path of your JAR file then Press Ok.

16- To use this component at any project open the project and go to Resource Palette and right click on the UserInfoJar.jar file then choose Add To Project then press to Apply Library.




17- Now go to Component Palette you will find your UserInfo Component.

You Can Download the declarative component example from this link :

Sunday, November 1, 2009

How Can You Manipulate With Table Column Filter Fields

One of the af:table feature is a filter over its column to filter its data. You can manipulate with this fields with backingbean, this manipulation can be as :
- Execute some code before filtering.
- Execute some code after filtering.
- Add something to the value you enter to filter before filtering.
- Re-execute query.
.
.
.


to do this follow this steps :

1- Bind your table in the backingbean (e.g.in Binding property of table set #{myBackingbean.myTable}).
2- In table QueryListener property set its value to
#{ myBackingbean.onTableQueryExecuted}
3- In your backingbean implement onTableQueryExecuted with:
public void onTableQueryExecuted(QueryEvent queryEvent) {
// If needed, do something before the table's query is processed

invokeMethod("#{bindings.DeptView1Query.processQuery}",QueryEvent.class,queryEvent);

// Where DeptView1Query is a searchRegion name in your binding
// If needed, do something after the table's query is processed
}

public static Object invokeMethod(String expr, Class[] paramTypes,
Object[] params) {
FacesContext fc = FacesContext.getCurrentInstance();
ELContext elc = fc.getELContext();
ExpressionFactory ef = fc.getApplication().getExpressionFactory();
MethodExpression me =
ef.createMethodExpression(elc, expr, Object.class, paramTypes);
return me.invoke(elc, params);
}

public static Object invokeMethod(String expr, Class paramType,
Object param) {
return invokeMethod(expr, new Class[] { paramType },
new Object[] { param });
}

To get the value which you enter to filter the column :

private FilterableQueryDescriptor getTableQueryDescriptor() {
return (FilterableQueryDescriptor)getMyTable().getFilterModel();
}
private Map getTableFilterCriteria() {
return getTableQueryDescriptor().getFilterCriteria();
}


getTableFilterCriteria().clear(); // to clear all filds.
getTableFilterCriteria().put("Dname","%N%");// to set value of the filterable field .
getTableFilterCriteria().remove("Dname"); // to clear the Dname Filterable text only.
getTableFilterCriteria().get("Dname");// to get the value that you enter to filter the table.


To re-execute query:
QueryEvent queryEvent = new QueryEvent(getMyTable(),getTableQueryDescriptor() );
queryEvent.setPhaseId(PhaseId.INVOKE_APPLICATION);
getTable().queueEvent(queryEvent);

Filling SelectOneChoice From Backingbean

On of the major component in tha ADF RC component is a af:selectOneChoice. You can fill this component from backingbean by tow ways:

A) Fill SelectOneChoice Component Programmatically:
1-In the backingbean you can define a variable that hold the selected Value (the value which you are select from selectOneChoice component ) [e.g public String selectedValue;] and make its setter and getter.
2- In the backingbean you can define an array of selectItem that will fill the selectOneChoice(e.g. public SelectItem[] elements = null; ) and make its getter and setter.
3- In the getter of selectItem write this code :



where : UCustomerView1Iterator is the Iterator which its data will fill the selectOneChoice (You must add this iterator in the pageDef).

You backingbean it should be like this :
-----------------------------------------------



4- In you page Drage a selectOneChoice component and set its value to :
#{yourBean.selectedValue}.
5- Insert f:selectItems inside af:selectOneChoice and set its value to:
#{yourBean.elements}.
--------------------------------------------------------------------------------
B) The second way to fill the selectOneChioce is to use af:forEach component and I prefer this way:
1- In the pageDef make a table in the binding section that will fill your selectOneChoice(assume that you make a DeptView1 table in the binding.
2- DeptView1 Table is point to the DeptView1Iterator make its length to -1.
3- Drag and drop a selectOneChoice component and set its value to the attribute in the backingbean.
4- Insert inside selectOneChoice af:forEach component and set Items property to : #{bindings.DeptView1.rangeSet} and set Var property to row.
5- Insert Inside af:forEach af:selectItem set Value Property to #{row.Deptno} this represent the return value of the selectOneChoice if you want the return value be a name of the department set Value Property to #{row.Dname}. Set the Label Property to #{row.Dname}.(Where Deptno and Dname is the attribute of the iterator you use to fill selectOneChoice).
you can download an example from here.

Get Bindings From Backingbean

In many situation we need to get binding container from our backingbean to execute some of the operation as ( Commit - Rollback - Next - Last - ExecuteWithParam - ............. ) or get your Iterator to get some information as (get Current Row - get ViewObject - get number of row count - refresh iterator - .............. ) There are two way to get your binding container from backingbean :

1- BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
then you can use bindings object to execute some of binding operation as commit operation as:
OperationBinding operationBinding = bindings.getOperationBinding("Commit");
operationBinding.execute();

2- The second way to get binding container is to define a method that return binding container as :

private BindingContainer bindings;
public BindingContainer getBindings() {
if (this.bindings == null) {
FacesContext fc = FacesContext.getCurrentInstance();
this.bindings = (BindingContainer)fc.getApplication().evaluateExpressionGet(fc,"#{bindings}",
BindingContainer.class);
}
return this.bindings;
}

to get binding and execute a commit operation :
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("Commit");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
}

Thursday, October 29, 2009

Using Jasper Reports In ADF Applications

You can check this for step by step calling jasper report

http://sameh-nassar.blogspot.ie/2012/12/using-jasper-report-in-adf-application.html


One of the solutions for generating reports when you use JDeveloper is using Jasper Report.
Jasper report is some of libraries (.Jar files) and .xml or .jrxml file that represent your report.
One of the easy ways to write .xml file is using IReport program. IReport is a program that manage you to design your report graphically then save your report to xml or jrxml file. From JDeveloper after you add jasper reports libraries to your project you can read your report (.xml file) and print it as PDF file or Excel File or Jasper Viewer.
Jasper Report Libraries is:
1-commons-digester-1.7.jar
2-itext-1.4.5.jar
3-jasperreports-3.0.0.jar
4-poi-2.5.1-final-20040804.jar
5- jasper-compiler-jdt-5.5.15.jar

You Can Download IReport From :
To configure your application to use Jasper Reports:
1- Add jasper report libraries to your project.
2- In web.xml add this
< resource-ref>
< res-ref-name> jdbc/OracleDBConnectionDS < /res-ref-name>
< res-type> javax.sql.DataSource < /res-type>
< res-auth> Container < /res-auth>
< /resource-ref>
3- From backingbean write this method:
----------- Imports ----------------
import java.io.*;
import java.util.*;
import java.sql.Connection;import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.InitialContext;import javax.naming.NamingException;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;
----------------------------------------
public void printReport() throws FileNotFoundException, JRException, NamingException, SQLException, IOException {
InputStream input = new FileInputStream(new File("c:/yourJasperReport.xml"));
JasperDesign design = JRXmlLoader.load(input);
JasperReport report = JasperCompileManager.compileReport(design);
Map parameters = new HashMap();
// parameters.put("jasperParamenterName", "ParameterValue"); Used if you want to pass a parameter to a jasper report
InitialContext initialContext = new InitialContext();
DataSource ds = (DataSource)initialContext.lookup("java:comp/env/jdbc/OracleDBConnectionDS"); // get from your application module configuration
Connection conn = ds.getConnection();
JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);
///// For printing report as PDF file ////////
ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream(); JasperExportManager.exportReportToPdfStream(print,byteArrayOutputStream);
out.write(byteArrayOutputStream.toByteArray());
out.flush();
out.close();
FacesContext.getCurrentInstance().responseComplete();
//////// For printing report as excel file //////
OutputStream ouputStream = new FileOutputStream(new File("c:/yourReport.xls")); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, print); exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, byteArrayOutputStream);
exporterXLS.exportReport();
ouputStream.write(byteArrayOutputStream.toByteArray());
ouputStream.flush();
ouputStream.close();
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:/yourReport.xls");
///// for printing report as a jasper report viewer /////
JasperViewer.viewReport(print, true);
}
For More Information About Using Jasper Report :

Wednesday, October 28, 2009

Read Variable From PageDef

In your page definition you can define a variable and set a value to it and you can read this variable and retrieve its value from backingbean as :

1- goto your page definition and in the executables section right click in the variables then choose insert inside the variables ----> variable.
2- set the name as "sameh" and the type to "String" then Ok.
3- set a default value to this variable with "Great Man".
4- in your backingbean write this :

FacesContext facesContext = FacesContext.getCurrentInstance();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp = elFactory.createValueExpression(elContext, "#{bindings.sameh}", Object.class);
Object varValue = valueExp.getValue(elContext);
// varValue will be Great Man

Solving PermGem Errors

Locate the file: setDomainEnv.cmd which should be at:
[JDev Install Dir]\jdeveloper\system\system11.1.1.0.31.51.88\DefaultDomain\bin
There find the line:set MEM_MAX_PERM_SIZE=-XX:MaxPermSize=128m
and change it to:set MEM_MAX_PERM_SIZE=-XX:MaxPermSize=512m

Read From Excel File And Write To Excel File

You Can use Apache POI library with JARs file:
- poi-3.5-FINAL-20090928.jar
- poi-contrib-3.5-FINAL-20090928.jar
- poi-ooxml-3.5-FINAL-20090928.jar
- poi-scratchpad-3.5-FINAL-20090928.jar
You can download this from

http://www.filefactory.com/file/a07fc15/n/POIJars_rar

In you backingbean:


/////// ........................ Read From File ................
InputStream myxls = new FileInputStream("c:\\yourExcelFils.xls");
HSSFWorkbook wb = new HSSFWorkbook(myxls);
HSSFSheet sheet = wb.getSheetAt(0); // first sheet
HSSFRow row = sheet.getRow(1); // second row
HSSFCell cell = row.getCell((short)0); // first cell
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
System.out.println("The Cell was a String with value " + cell.getStringCellValue());
} else {
System.out.println ("The cell was nothing we're interested in");
}

/////// ........................ Write To File ................
HSSFWorkbook wb1 = new HSSFWorkbook();

HSSFSheet sheet = wb1.createSheet();
HSSFRow row = sheet.createRow((short)0);
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(1);
row.createCell((short)1).setCellValue(1.2);
row.createCell((short)2).setCellValue("This is a string");
row.createCell((short)3).setCellValue(true);

FileOutputStream fileOut = new FileOutputStream("c:\\yourExcelFils.xls");
wb1.write(fileOut);
fileOut.close();

Using Skin In Your ADF Application

One of the important thing you can do in ADF Application is to enhance a look and feel of  the application. This can be done by using skins.

To use skins in your ADF Application you can follow these steps:

1- Make a new file with name (trinidad-skins.xml) under WEB-INF Folder.
2- Write this in trinidad-skins.xml






3-From tools --- > Preferences ----> Css Editor thin check to ADF Faces Extension (optional step).

4- Write a .css file under Web content folder (With name as you write in trinidad-skins.xml file. e.g. mySkin.css)


5-In mySkin.css file you should write a selectors that affect to an ADF component.
(for more information about selectors check this URL
http://jdevadf.oracle.com/adf-richclient-demo/docs/skin-selectors.html)

6- In trinidad-config.xml change skin-family to "mySkin" as:




This an example for using skins in ADF Application http://www.filefactory.com/file/a07fgc1/n/SkinApplication_rar

Read Resource Bundle From Backingbean

ResourceBundle rb = ResourceBundle.getBundle("ResourceBundleFileName",FacesContext.getCurrentInstance().getViewRoot().getLocale());
rb.getString("key");

Get / Set Browser localization

Set Browser Locale:
FacesContext ctx = FacesContext.getCurrentInstance();
UIViewRoot uiRoot = ctx.getViewRoot();
Locale locale = new Locale("en");// set browser as english
uiRoot.setLocale(locale);
-----------------------------------------------------------
Get Browser Locale
FacesContext ctx = FacesContext.getCurrentInstance();
UIViewRoot uiRoot = ctx.getViewRoot();
uiRoot.getLocale();

How To Get Application Module From Your BackingBean

There are two ways to generate application module from your backnigbean:

1- Get application module from iterator:
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding dciter = (DCIteratorBinding)bindings.get("YourView1Iterator");
ApplicationModule am=dciter.getViewObject().getApplicationModule();
--------------------------------------------------------------
2- ApplicationModule am = this.getAm();
private ApplicationModule getAm() {
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, "#{data.AppModuleDataControl.dataProvider}",
Object.class);
return (ApplicationModule )valueExp.getValue(elContext);
}