Archive for the ‘Java Development’ Category

Trinidad 2.0.0 PPR Bug with JSF 2.0 outputText Tag

Tuesday, August 16th, 2011

I am currently in the process of porting all of my Oracle AS 10G R2 (OC4J) applications over to WebLogic  10.3.5.  After upgrading Oracle JDeveloper to version 11.1.2 and hand converting an old ADF 10.1.3 application to Trinidad, I ran into a curios issue.  None of my components that used PPR (Partial Page Rendering) would respond to events.  Most notably, pop-up dialogs triggered  by Command Buttons, or Command Links.  The dialogs would not pop-up, but I could see the events executing in the backing beans. After a couple of weeks of tracing log files, running code through the debugger, and digging into the source code for both JSF 2.0 and Trinidad 2.0.0, I came up with with nothing.  No error messages are ever thrown.  I even filed a bug report under an existing (similar) bug report (Trinidad-1813) with the Trinidad project group (they did respond and are looking into it).  To make a long story short, I finally found the issue.  All of my screens contained a outputText tag from the JSF component library (<h:outputText value=”This will cause PPR to fail.”/>).  As soon as I replaced this tag with the outputText tag from the Trinidad component library (<tr:outputText value=”This will not cause PPR to fail.”/>), my PPR events started behaving as expected.

I hope this helps someone who may be experiencing a similar issue.  This issue did not occur with the earlier releases of Trinidad and JSF.

ADF Faces: Passing a Java Collection from a Custom ViewObjectImpl Class to a PL/SQL Function

Sunday, August 23rd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Sunday, August 17, 2008)

I recently had the challenge of creating several complex query search screens using ADF Faces.  These new search screens had to integrate seamlessly into our current application’s (not a J2EE application …) search screens (look the same, act the same, feel the same …).  One of the challenges that presented itself was to determine how to pass multiple search parameters with various operators (=, <, LIKE,SOUNDEX, etc …) and the values associated with them and map them to their associated columns in a dynamic where clause.  Since I was creating multiple screens with similar functionality, I needed a generic method of parameter passing.  The obvious answer was to use some sort of array or combination of arrays as the parameter transport mechanism.  The not so obvious part was how the heck I was going to pass an array of Java Objects to a PL/SQL function that was expecting a PL/SQL Collection object.  Luckily, this turned out to be less complicated than I thought thanks to Oracle and the developers of JDBC.  The Java to PL/SQL user-defined type mapping is accomplished using the java.sql.SQLData interface (http://java.sun.com/j2se/1.5.0/docs/api/java/sql/SQLData.html).  This interface was designed to allow for the mapping between a SQL UDT (user defined type) and a Java class.  The mapping of an array of these objects to an Oracle collection (or array) is accomplished using two Oracle JDBC classes: oracle.sql.ARRAY (http://www.oracle.com/technology/docs/tech/java/sqlj_jdbc/doc_library/javadoc/oracle.sql.ARRAY.html) and oracle.sql.ArrayDescriptor (http://www.oracle.com/technology/docs/tech/java/sqlj_jdbc/doc_library/javadoc/oracle.sql.ArrayDescriptor.html). Next problem … how to create a custom (generic) Programmatic ViewObjectImpl class that will accept a Collection object  as the parameter passing mechanism.  This turned out to be another simple task with the help of some Oracle ADF documentation: (http://download.oracle.com/docs/cd/B31017_01/web.1013/b25947/bcadvvo008.htm).  After that, it’s elementary!  All of the View Objects defined for each of my custom search screens were extended from this new custom ViewObjectImpl class.  The rest of this article details the steps and code I used to implement the solution.  For the sake of brevity, I will limit the code to just the generic ViewObjectImpl and PL/SQL collection mapping.  (The PL/SQL package used to implement the searches has some interesting bits of code, and I will publish that in a separate article.)

Step 1. Create SQL User Defined Types

Step one is to create the SQL user defined types.  In this instance I created two types.  The base type SEARCH_PARAM_TYPE and a collection of SEARCH_PARAM_TYPE called SEARCH_PARAM_ARRAY.  These two user defined types are defined by the following commands:

CREATE OR REPLACE TYPE SEARCH_PARAM_TYPE AS OBJECT(

PARAM_NAME      VARCHAR2(100),

PARAM_OPERATOR  VARCHAR2(4),

PARAM_VALUE     VARCHAR2(1000)

)

/

CREATE OR REPLACE TYPE SEARCH_PARAM_ARRAY AS TABLE OF SEARCH_PARAM_TYPE

/

The SEARCH_PARAM_TYPE contains a parameter name (or label or identifier), a parameter query operator code, and the value for the particular parameter.  The SEARCH_PARAM_ARRAY is just a simple array (PL/SQL Table) that may hold 0 or more SEARCH_PARAM_TYPES.  Each of these SQL types gets mapped in the Java code.

Step 2. Create Java Class to Match SQL Type SEARCH_PARAM_TYPE

Step two is to create a Java class to match the SQL user defined type SEARCH_PARAM_TYPE.  This class must implement java.sql.SQLData and java.io.Serializable.  The code below demonstrates how to implement the class that matches the SQL type SEARCH_PARAM_TYPE:

import java.io.Serializable;
import java.sql.SQLData;
import java.sql.SQLException;
import java.sql.SQLInput;
import java.sql.SQLOutput;

/***
* This class maps to an Oracle User Defined Type called
* SEARCH_PARAM_TYPE. It hold search parameter data
* consisting of a parameter name, operator code,
* and parameter value.
*
*/

public class SearchParamBean implements SQLData, Serializable{

/* Oracle User Defined Type Name */

private String sql_type = ”SEARCH_PARAM_TYPE”;

/* These String represent the attributes in the Oracle user defined type. */

Private String param_name = null;

private String param_operator = null;

private String param_value = null;

public SearchParamBean() {

}

public void setParamName(String p_param_name){
param_name = p_param_name;
}

public String getParamName(){
return param_name;
}

public void setParamOperator(String p_param_operator){
param_operator = p_param_operator;
}

public String getParamOperator(){
return param_operator;
}

public void setParamValue(String p_param_value){
param_value = p_param_value;
}

public String getParamValue(){
return param_value;
}

public String getSQLTypeName()
throws SQLException
{
return sql_type;
}

public void readSQL(SQLInput stream, String typeName)
{
/* No need to implement this */
}

public void writeSQL(SQLOutput stream) throws SQLException
{

/*
the order of values matters! The order must match the structure
of the user defined type exactly!
*/

stream.writeString(param_name);
stream.writeString(param_operator);
stream.writeString(param_value);

}

}

As you can see, this is a pretty straight forward class.  It is important to note that in the writeSQL method above, the order attribute assignements defined with the stream.writeString statements must match the order of attributes as defined in the SQL user defined type exactly (under the covers I’m sure it has to do with marshalling and unmarshalling the serialized objects and not knowing how to intuitively identify what value goes where).

Step 3. Create the Custom ViewObjectImpl Class

The third step is to create the (generic) custom ViewObjectImpl class that your actual ViewObjects will extend.  As stated at the start of this article, I made use of the example in the Oracle ADF documentation that details how to create a View Object using alternate data sources.  The key piece of code is the callStoredFunction method:

/**
* Mechanism to execute PL/SQL functions that populate rows and data
* for the ViewObject
* @param sqlReturnType
* @param stmt
* @param params
* @return
*/

protected Object callStoredFunction(int sqlReturnType,
String stmt,
SearchParamBean[] params) {

CallableStatement plsqlStmt = null;

StringBuffer sb_plsqlBlock = new StringBuffer();

Object dataSet = new Object();

try {

sb_plsqlBlock.append(”begin ? := ”).append(stmt).append(”; end;”);

plsqlStmt = getDBTransaction().createCallableStatement(

sb_plsqlBlock.toString(),0);

/* Register the first bind variable for the return value */

plsqlStmt.registerOutParameter(1, sqlReturnType);

/*This is where we map the Java Object Array to a PL/SQL Array */

ArrayDescriptor desc = ArrayDescriptor.createDescriptor(arrayDescriptor,plsqlStmt.getConnection());

ARRAY objectArray = new ARRAY (desc, plsqlStmt.getConnection(), params);

((OraclePreparedStatement) plsqlStmt).setARRAY(2,objectArray);

plsqlStmt.executeUpdate();

dataSet = plsqlStmt.getObject(1);

}

catch (SQLException e) {

throw new JboException(e);

}

finally {

if (plsqlStmt != null) {

try {

plsqlStmt.close();

}

catch (SQLException e) {System.err.println(e.getMessage());}

}

}

return dataSet;

}

The custom ViewObjectImpl also has methods that construct the ArrayList containing SearchParamBeans.  There are getter and setter methods provided in the class for adding and retrieving SearchParamBean objects. The SearchParamBean[] array you see in the code above is generated internally by the method:

/**
* Constructs the SearchParamBean array from the searchParams ArrayList
* @return
*/

protected SearchParamBean[] getParamBeanArray(){

return (SearchParamBean[])searchParams.toArray(new SearchParamBean[searchParams.size()]);

}

Rather than explain each method in detail, I’ll provide the code with appropriate comments.  It’s fairly straight forward code:

import adf.custom.beans.SearchParamBean;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import oracle.jbo.JboException;
import oracle.jbo.server.ViewObjectImpl;
import oracle.jbo.server.ViewRowImpl;
import oracle.jbo.server.ViewRowSetImpl;
import oracle.jdbc.OracleTypes;
import oracle.jdbc.driver.OraclePreparedStatement;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;

public class ObjectArrayVOImpl extends ViewObjectImpl{

/**
* Number of columns in result set returned by this VO.
*/

private int numberOfVOColumns = 0;

/**
* Name of PL/SQL function that will execute the query
* for the VO implemented by this code.
*/

private String queryFunction = null;

/**
* Name of PL/SQL function that will return the
* number of rows returned by this VO.
*/

private String countFunction = null;

/**
* Name of SQL User Defined Type/ PLSQL Collection Type
*/

private String arrayDescriptor = null;

/**
* ArrayList that holds SearchParamBean objects.
*/

private ArrayList searchParams = new ArrayList();

public ObjectArrayVOImpl() {

}

/**
* This method adds a SearchParamBean object to the ArrayList that
* is mapped to the PL/SQL Collection
* @param p_param_bean
*/

public void addSearchParamBean(SearchParamBean p_param_bean){

searchParams.add(p_param_bean);

}

public void clearSearchParamArray(){

searchParams.clear();

}

/**
* This method is used to set the name of the PL/SQL (packaged) Function that
* will accept the collection of parameters and execute a query returning the
* desired results.
* @param p_value
*/

public void setQueryFunction(String p_value){

queryFunction = p_value;

}

/**
* This method is used to set the name of the PL/SQL (packaged) Function that
* will return the number of rows that will be returned to the View Object from
* the PL/SQL package result set.
* @param p_value
*/

public void setCountFunction(String p_value){

countFunction = p_value;

}

/**
* The array descriptor is is used by the method callStoredFunction
* to map the SearchParamBean[] to the correct PL/SQL Array or SQL
* Type in the backing database.
* @param p_value
*/

public void setArrayDescriptor(String p_value){

arrayDescriptor = p_value;

}

public void setNumberOfVOColumns(int p_value){

numberOfVOColumns = p_value;

}

/**
* Returns the most current ArrayList containing search parameter beans.
* @return ArrayList
*/

public ArrayList getSearchParamArrayList(){

return searchParams;

}

/**
* Constructs the SearchParamBean array from the searchParams ArrayList
* @return
*/

protected SearchParamBean[] getParamBeanArray(){

return (SearchParamBean[])searchParams.toArray(new SearchParamBean[searchParams.size()]);

}

/**
* Overridden framework method.
*
* The role of this method is to ”fetch”, populate, and return a single row
* from the datasource by calling createNewRowForCollection() and populating
* its attributes using populateAttributeForRow().
*/

protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {

/*
* We ignore the JDBC ResultSet passed by the framework (null anyway) and
* use the resultset that we’ve stored in the query-collection-private
* user data storage
*/

rs = getResultSet(qc);

/*
* Create a new row to populate
*/

ViewRowImpl r = createNewRowForCollection(qc);

try {

/*
* Populate new row by attribute slot number for current row in Result Set
*/

for (int x=0; x

populateAttributeForRow(r,x,rs.getString(x+1));

}

}

catch (SQLException s) {

throw new JboException(s);

}

return r;

}

/**
* Overridden framework method.
*
* Return true if the datasource has at least one more record to fetch.
*/

protected boolean hasNextForCollection(Object qc) {

ResultSet rs = getResultSet(qc);

boolean nextOne = false;

try {

nextOne = rs.next();

/*
* When were at the end of the result set, mark the query collection
* as “FetchComplete”.
*/

if (!nextOne) {

setFetchCompleteForCollection(qc, true);

/*
* Close the result set, we’re done with it
*/

rs.close();

}

}

catch (SQLException s) {

throw new JboException(s);

}

return nextOne;

}

/**
* Overridden framework method.
*
* The framework gives us a chance to clean up any resources related
* to the datasource when a query collection is done being used.
*/

protected void releaseUserDataForCollection(Object qc, Object rs) {
/*
* Ignore the ResultSet passed in since we’ve created our own.
* Fetch the ResultSet from the User-Data context instead
*/

ResultSet userDataRS = getResultSet(qc);

if (userDataRS != null) {

try {

userDataRS.close();

}

catch (SQLException s) {

/* Ignore */

}

}

super.releaseUserDataForCollection(qc, rs);

}

/**
* Mechanism to execute PL/SQL functions that populate rows and data
* for the ViewObject
* @param sqlReturnType
* @param stmt
* @param params
* @return
*/

protected Object callStoredFunction(int sqlReturnType,
String stmt,
SearchParamBean[] params) {

CallableStatement plsqlStmt = null;

StringBuffer sb_plsqlBlock = new StringBuffer();

Object dataSet = new Object();

try {
sb_plsqlBlock.append(”begin ? := ”).append(stmt).append(”; end;”);

plsqlStmt = getDBTransaction().createCallableStatement(
sb_plsqlBlock.toString(),0);

/* Register the first bind variable for the return value */

plsqlStmt.registerOutParameter(1, sqlReturnType);

/*This is where we map the Java Object Array to a PL/SQL Array */

ArrayDescriptor desc = ArrayDescriptor.createDescriptor(arrayDescriptor,plsqlStmt.getConnection());

ARRAY objectArray = new ARRAY (desc, plsqlStmt.getConnection(), params);

((OraclePreparedStatement) plsqlStmt).setARRAY(2,objectArray);

plsqlStmt.executeUpdate();

dataSet = plsqlStmt.getObject(1);

}

catch (SQLException e) {

throw new JboException(e);

}

finally {

if (plsqlStmt != null) {

try {

plsqlStmt.close();

}

catch (SQLException e) {System.err.println(e.getMessage());}

}

}

return dataSet;

}

/**
* Return a JDBC ResultSet representing the REF CURSOR return
* value from our stored package function.
*/

private ResultSet retrieveRefCursor(Object qc, SearchParamBean[] params) {

ResultSet rs = (ResultSet)callStoredFunction(OracleTypes.CURSOR,

queryFunction,

params);

return rs ;

}

/**
* Retrieve the result set wrapper from the query-collection user-data
*/

private ResultSet getResultSet(Object qc) {
return (ResultSet)getUserDataForCollection(qc);
}

/**
* Store a new result set in the query-collection-private user-data context
*/

private void storeNewResultSet(Object qc, ResultSet rs) {

ResultSet existingRs = getResultSet(qc);

/* If this query collection is getting reused, close out any previous rowset */

if (existingRs != null) {

try {existingRs.close();} catch (SQLException s) {}

}

setUserDataForCollection(qc,rs);

hasNextForCollection(qc); // Prime the pump with the first row.

}

/**
* Overridden framework method.
*/

protected void create() {

getViewDef().setQuery(null);
getViewDef().setSelectClause(null);
setQuery(null);

}

/**
* Overridden framework method.
*/

public long getQueryHitCount(ViewRowSetImpl viewRowSet) {

Long count = Long.valueOf(“0″);

if (!searchParams.isEmpty()){

count= (Long)callStoredFunction(OracleTypes.BIGINT,
countFunction,
getParamBeanArray());

}

return count.longValue();
}

/**
* Overridden framework method.
*/

protected void executeQueryForCollection(Object qc,Object[] params,
int numUserParams) {

if (!searchParams.isEmpty()){

storeNewResultSet(qc,retrieveRefCursor(qc,getParamBeanArray()));
super.executeQueryForCollection(qc, params, numUserParams);

}

}

}

Step 4. Create a View Object based on the Custom ViewObjectImpl

The last step is to create a new ViewObject based on the custom ViewObjectImpl that was created in step three.  The easiest way to do this is to use the JDeveloper View Object creation wizard.  Select the ”Rows populated programmatically”  option.  Add any attributes (return columns) you need.   Under the Java section of the View Object definition, and set the VO to extend the new ViewObjectImpl class.   Edit the new View Object class and configure it to use the correct PL/SQL (packaged) functions.  Here is an example:

import adf.custom.model.customViewObjectImpl.ObjectArrayVOImpl;

/* ———————————————————————
— File generated by Oracle ADF Business Components Design Time.
— Custom code may be added to this class.
— Warning: Do not modify method signatures of generated methods.
———————————————————————*/

public class EmployeeQueryVOImpl extends ObjectArrayVOImpl {

/**This is the default constructor (do not remove)
*/

public EmployeeQueryVOImpl() {

/*
Set the name of the PL/SQL function that will act as the
query execution agent. This function will also return
a result set.
*/

this.setQueryFunction(”EmployeeSearch.executeQuery”);

/*
Set the name of the PL/SQL function that will returns the
row count of the query result set for this VO.
*/

this.setCountFunction(”EmployeeSearch.getRowReturnCount”);

/*
This sets the name of the SQL Type representing the PL/SQL collection
or PL/SQL table.
*/

this.setArrayDescriptor(”SEARCH_PARAM_ARRAY”);

/*
The VO needs to know how many columns of data will be returned when
constructing the VO’s result set.
*/

this.setNumberOfVOColumns(5);

}

}

Wrapping it Up …

This article illustrated how to create a custom ViewObjectImpl class that passes an array of Java objects to a PL/SQL Collection based upon a user defined type.  The article touched on a lot of peripheral topics: Creating custom ViewObjectImpl’s, mapping Java objects to SQL user defined types, and converting a Java Object Array into an Oracle Collection/Array.  Basically, it covered a lot of ground in a very brief text.  If you have questions (or suggestions) please feel to shoot me an email.

The Oracle Report Bean

Sunday, August 23rd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Sunday, June 15, 2008)

The Oracle Report Bean is a cool little bit of code I developed this week that will let you to execute an Oracle Report from within your JEE or plain old Java application.  The bean allows you to configure all of the report execution parameters and contains methods to execute the report as a printed report or have the report streamed back to the client if the chosen format (PDF, RTF, HTML, XML, etc).  The code basically constructs the URL you need to access the Oracle Reports servlet (rwservlet). I’m actually using the Oracle Report Bean as the interface to Oracle Reports in my current ADF Faces project.

Hitting the highlights …

The bean provides a set of constants (static variables) that represent rwservlet keywords (commands).   The code uses two Hash Maps (HashMap classes) for storing parameters.  One Hash Map holds the reports servlet keywords and values, and the other holds input parameters and values for the actual report being executed.  The Hash Maps are hidden behind getter and setter methods.  When setting a reports servlet key word, the developer may either use one of the static keyword references provided by the bean, or simply add one of their choosing (it’s up to them to make sure it’s a legitimate keyword/parameter at that point).  Using the Hash Maps makes it easier to construct the URL later using a simple loop.

The bean provides two methods for executing the report. One method, executePrintedReport, passes the fully constructed URL to the reports servlet and returns the response (either HTML or XML) as a String.  A helper method, formatXMLResponse, is provided to format the response returned by the reports server in client friendly manner (NOTE: The developer needs to set the status format to XML to use this helper method). This method is specifically intended for use with reports bound for external destinations (printers, email, etc.).  The other method, executeBinaryReport, passes the fully constructed URL to the reports servlet and then returns a data stream (InputStream class).  This method is intended for use with reports whose content will be returned directly to the client (the destination for these reports should be set to CACHE).  Use the executeBinaryReport method when you need to return report results directly to the client (desformats PDF, RTF, HTML, XML).  The bean also provides a method that simply returns the URL for executing the report: getReportServerURL.

Sample Bean Usages …

The following code snippet demonstrates how to setup the bean to execute a printed report:

{

OracleReportBean testBean = new OracleReportBean(“appserver”,”7778″,null);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_SERVER,”my_repserv”);

testBean.setKeyMap(“db_key”);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_ENVID,”orcl”);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_DESTYPE,

OracleReportBean.DESTYPE_PRINTER);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_DESNAME,

“myPrinter-01″);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_REPORT,

“MyReport.rdf”);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_ORIENTATION,

OracleReportBean.ORIENTATION_PORTRAIT);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_DESFORMAT,

OracleReportBean.DESFORMAT_HTML);

testBean.setReportParameter(“p_id”,”50″);

testBean.setReportParameter(“p_user”,”JASON BENNETT”);

System.out.println(testBean.formatXMLResponse(testBean.executePrintedReport()));

}

This code snippet demonstrates how to setup the bean to execute and retrieve a binary report (PDF, HTML, XML, RTF, …):

{

OracleReportBean testBean = new OracleReportBean(“appserver”,”7778″,null);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_SERVER,”my_repserv”);

testBean.setKeyMap(“db_key”);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_ENVID,”orcl”);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_DESTYPE,

OracleReportBean.DESTYPE_CACHE);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_REPORT,

“MyReport.rdf”);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_ORIENTATION,

OracleReportBean.ORIENTATION_PORTRAIT);

testBean.setReportServerParam(OracleReportBean.RS_PARAM_DESFORMAT,

OracleReportBean.DESFORMAT_HTML);

testBean.setReportParameter(“p_id”,”50″);

testBean.setReportParameter(“p_user”,”JASON BENNETT”);

try{

BufferedReader br;

br = new BufferedReader(

new    InputStreamReader(testBean.executeBinaryReport()));

String inputString = null;

while((inputString = br.readLine()) != null){

System.out.println(inputString);

};

}catch(Exception e){

e.printStackTrace();

}

}

The Code …

Finally, here is the code for the Oracle Report Bean:

import java.io.BufferedReader;
import java.io.InputStream;

import java.net.URLConnection;
import java.net.URL;
import java.io.InputStreamReader;
import java.io.StringReader;

import java.util.HashMap;
import java.util.Iterator;

import oracle.xml.parser.v2.DOMParser;
import oracle.xml.parser.v2.XMLConstants;
import oracle.xml.parser.v2.XMLDocument;
import oracle.xml.parser.v2.XMLElement;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/***
* This bean performs the following functions:
* Constructing the Report URL with various parameters passed in by client.
* Sending the report request.
* Execute printed report and retrieve return status in the indicated format.
* Execute a binary report (PDF, RTF, XML, with DESTYPE CACHE) and return the
* InputStream for processing.
*/
public class OracleReportBean {

/* Report Servlet Host Settings */
private String http_host = null;
private String http_port = null;

/* Default path as per generic Oracle Appserver install */
private String servlet_path = “/reports/rwservlet”;

/* Report Servlet URL params */
public static final String RS_PARAM_SERVER = “server”;
public static final String RS_PARAM_REPORT = “report”;
public static final String RS_PARAM_ENVID = “envid”;
public static final String RS_PARAM_DESTYPE = “destype”;
public static final String RS_PARAM_DESFORMAT = “desformat”;
public static final String RS_PARAM_STATUSFORMAT = “statusformat”;
public static final String RS_PARAM_DESNAME = “desname”;
public static final String RS_PARAM_PAGESTREAM = “pagestream”;
public static final String RS_PARAM_DELIMITER = “delimiter”;
public static final String RS_PARAM_ORIENTATION = “orientation”;
public static final String RS_PARAM_DISTRIBUTE = “distribute”;

private String value_keyMap = null;

/* Static values for destination formats */
public static final String DESFORMAT_PDF = “PDF”;
public static final String DESFORMAT_HTML = “HTML”;
public static final String DESFORMAT_POSTSCRIPT = “POSTSCRIPT”;
public static final String DESFORMAT_DELIMITED = “DELIMITED”;
public static final String DESFORMAT_XML = XML;
public static final String DESFORMAT_RTF = “RTF”;

/* Static values for destination types*/
public static final String DESTYPE_MAIL = “mail”;
public static final String DESTYPE_PRINTER = “printer”;
public static final String DESTYPE_FILE = “file”;
public static final String DESTYPE_LOCAL_FILE = “localFile”;
public static final String DESTYPE_CACHE = “cache”;

/* Static values for distribute */
public static final String DISTRIBUTE_YES = “YES”;
public static final String DISTRIBUTE_NO = “NO”;

/*Static values for status format */
public static final String STATUSFORMAT_XML = XML;
public static final String STATUSFORMAT_HTML = “HTML”;

/* Static values for report orientation */
public static final String ORIENTATION_PORTRAIT = “PORTRAIT”;
public static final String ORIENTATION_LANDSCAPE = “LANDSCAPE”;
public static final String ORIENTATION_DEFAULT = DEFAULT;

/* HashMap to hold individual report parameters*/
private HashMap reportParams = new HashMap();

/* HashMap to hold report server params */
private HashMap reportServerParams = new HashMap();

/* Report Servlet */
private StringBuffer reportURL = new StringBuffer();
private String XMLReturnStatus = null;

/***
* Constructor
*/
public OracleReportBean(String p_http_host,
String p_http_port,
String p_servlet_path)
{
http_host = p_http_host;
http_port = p_http_port;

/* If the servlet path is null, we assign the default path. */
if (p_servlet_path != null){
servlet_path = p_servlet_path;
}

/* Default the status format to XML */
setReportServerParam(RS_PARAM_STATUSFORMAT,STATUSFORMAT_XML);

}

/*****
* Private utility methods …
*
*/
private String buildKeyValueString(HashMap p_map){

String map_key = null;
String param_sep = “&”;
String param_equal = “=”;
StringBuffer keyValueBuffer = new StringBuffer();

if (!p_map.isEmpty()){

Iterator mapKeys = p_map.keySet().iterator();

while (mapKeys.hasNext()){
map_key = (String)mapKeys.next();
keyValueBuffer.append(map_key).append(param_equal).append(p_map.get(map_key));

if(mapKeys.hasNext()){
keyValueBuffer.append(param_sep);
}
}
}

return keyValueBuffer.toString();

}

/* Construct the URL for accessing the Oracle Reports Servlet */
private void constructURL(){

String param_sep = “&”;

/* Clearout current URL */
reportURL = new StringBuffer();

/* HOST Section */

reportURL.append(“http://”);

reportURL.append(http_host);

if (http_port != null){
reportURL.append(“:”).append(http_port);
}

/* Add “/” separator if necessary. */
if (servlet_path.indexOf(“/”) > 0){
reportURL.append(“/”);
}

reportURL.append(servlet_path);
reportURL.append(“?”);

if(value_keyMap != null){
reportURL.append(value_keyMap).append(param_sep);
}

/*Construct Report Server Parameter URL component*/
reportURL.append(buildKeyValueString(reportServerParams));

if(!reportServerParams.isEmpty()){
reportURL.append(param_sep);
}

/*Construct Report Parameters URL Component*/
reportURL.append(buildKeyValueString(reportParams));
}

/***
* Getters and Setters for the Reports Servlet
* URL parameter values.
*/

public void setReportServerParam(String p_param,
String p_value){
reportServerParams.put(p_param,p_value);
}

public String getReportServerParam(String p_param){
if(reportServerParams.containsKey(p_param)){
return (String)reportServerParams.get(p_param);
} else {
return null;
}
}

/* Set/Get the value of a Reports KeyMap file */
public void setKeyMap(String p_keyMap){
value_keyMap = p_keyMap;
}

public String getKeyMap(){
return value_keyMap;
}

/* Add/Update and retrieve individual report parameters */
public void setReportParameter(String paramName,
String paramValue){

reportParams.put(paramName,paramValue);
}

public String getReportParameter(String paramName){

if (reportParams.containsKey(paramName)){
return (String)reportParams.get(paramName);
} else {
return null;
}

}

/****
* Construct and return a URL that can be used to execute the report.
*/
public String getReportServerURL(){
constructURL();
return reportURL.toString();
}

/***
* Execute a report whose destination is a printer or other
* non-client destination. (i.e. the report is not coming back
* to the calling client in binary format …)
*/
public String executePrintedReport(){

String v_return_status = null;
StringBuffer serverResponse = new StringBuffer();

try{

BufferedReader br;

br = new BufferedReader(new InputStreamReader(executeBinaryReport()));

String inputString = null;
while((inputString = br.readLine()) != null){
serverResponse.append(inputString);
};

v_return_status = serverResponse.toString();

}catch(Exception e){
e.printStackTrace();
v_return_status = “Error printing report: “+e.getMessage();
}
return v_return_status;
}

/***
* This method is used to execute a binary report
* that is intended to be returned to the
* A binary report is a report that is returned as
* a physical file such as PDF, RTF, etc
* DESTYPE needs to be CACHE in order to get a return
* stream (file …).
*/
public InputStream executeBinaryReport() throws Exception{

URL url = new URL(getReportServerURL());
URLConnection urlc= url.openConnection();

return urlc.getInputStream();
}

/****
* This method takes the XML response generated by the Oracle Reports Server
* servlet and generates a more user friendly response message.
* NOTE: This only works for the XML statusformat type.
*/
public String formatXMLResponse(String p_response){

StringBuffer formattedResponse = new StringBuffer();

try{

DOMParser parser = new DOMParser();
parser.showWarnings(false);
parser.setValidationMode(XMLConstants.NONVALIDATING);
parser.parse(new InputSource(new StringReader(p_response)));

XMLDocument doc = parser.getDocument();

XMLElement elements = (XMLElement)doc.getDocumentElement();

NodeList nl = elements.getElementsByTagName(“error”);

if (nl.getLength() > 0){
String err_component = doc.selectSingleNode(“//error[1]/@component”).getNodeValue();
String err_code = doc.selectSingleNode(“//error[1]/@code”).getNodeValue();
String err_message = doc.selectSingleNode(“//error[1]/@message”).getNodeValue();

formattedResponse.append(“Oracle Reports job submit error; “).append(err_component);
formattedResponse.append(“-”).append(err_code).append(“: “).append(err_message);
}else{

String job_id = doc.selectSingleNode(“//job[1]/@id”).getNodeValue();
String job_status = doc.selectSingleNode(“//status[1]/text()”).getNodeValue();
String job_status_code = doc.selectSingleNode(“//status[1]/@code”).getNodeValue();

if ((job_id == null)||(job_status==null)||(job_status_code==null)){

formattedResponse.append(“Oracle Reports job submit problem; “).append(“Job Id=”).append(job_id);
formattedResponse.append(“, Code=”).append(job_status_code).append(“, Status=”).append(job_status);

}else{

formattedResponse.append(“Report submitted successfully!”);

}

}

}catch(Exception e){
e.printStackTrace();
String error = “Error processing Oracle Report Server response: “+e.getMessage();
System.err.println(error);
formattedResponse.append(error);
}

return formattedResponse.toString();

}
}

ADF Faces: How To Use a Single JSP for both INSERTING and UPDATING

Sunday, August 23rd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Thursday, June 05, 2008)

In this entry, I’ll go over my technique for using a single JSP for both inserting and updating data. This technique utilizes custom methods in the target ViewObjectImpl class, and Page Definition action methods in the Page Definition associated with our ADF/JSF JSP. There are probably other ways to do this, but this one is fairly straight forward. (Note: I believe Steve Muench recommended a similar technique using methods in the ApplicationModuleImpl class)

Preparing the View Object

Most of the View Objects in my applications (that are used for data entry) contain a bind variable in the WHERE clause that is associated with the target table’s primary key (I use dumb keys versus natural keys).   In order to put the page in update mode, we need to pass a PK value to the View Object and pre-populate it prior to rendering the page.  Otherwise, the page is rendered in insert mode.  This is pretty much a universal concept.  How do we go about passing the PK value (or parameter) to the View Object?  First, we need to create a couple of custom public methods in the View Object’s ViewObjectImpl class.   One method will take the PK param value and pre-populate the View Object instance, and the other method will clear the state of (empty the data from) the current instance of the View Object.   The  methods look  like this:

/***
* This method will be used to pre-populate the view object using a passed value.
*/

public void queryViewById(String p_id) {

/*setp_emp_id is ADF generated method for setting the bind variable
value defined in my View Object (p_emp_id). */

setp_emp_id(p_id);
executeQuery();

}

/***
* This method will clear any data out of the existing VO.
*/

public void clearView() {

if (getWhereClause() != null) {

setWhereClause(null);

}

executeQuery();

}

Preparing the Page Definition File

ADF Faces JSPs use an XML based Page Definition file to bind data to the user interface and to perform some actions prior to rendering the page (overly simplified definition …).  Each View Object referenced by an ADF Faces JSP component is represented in that page’s Page Definition file.  ADF Faces comes with some canned page actions (such as Create and Delete) that can be “dropped” into the page definition file and then applied to event (or actions) that occur later in JSP page.  We can also create custom actions (known as method actions) that are mapped to methods we have created.  The two methods we created in the last section (queryViewById and clearView) will be included as custom method actions the Page Definition file for our ADF/JSF JSP page.  The method action entries go in the “bindings” section of the page, and look like this (I have my own View Object referenced in the example):

<methodAction
MethodName=”clearView”
RequiresUpdateModel=”true” Action=”999″
IsViewObjectMethod=”true” DataControl=”AppModuleDataControl”
InstanceName=”AppModuleDataControl.MyemployeeView1″/>

<methodAction
MethodName=”queryViewById” RequiresUpdateModel=”true”
Action=”999″ IsViewObjectMethod=”true”
DataControl=”AppModuleDataControl”
InstanceName=”AppModuleDataControl.MyemployeeView1″>
<NamedData NDName=”p_id” NDValue=”#{param.p_emp_id}”
NDType=”java.lang.String” />
</methodAction>

Notice the “#{param.p_emp_id}” in NDValue attribute above.  Any request parameter passed to the your page can be accessed using “#{param.<parameter name>}”.  The only caveat is if you use the <f:param> tag in conjunction with a command link or command button and the navigation rule behind your navigation action specifies a “redirect” … the parameters will not be passed.  Here is a quick break down of the attributes for the “methodAction” tag above:

  • The “id” attribute represents the identifier of this methodAction tag as it relates to other components (tags) in the current Page Definition file.
  • The “MethodName” attribute defines the binding name for this method action when called from the “invokeAction” tag ( tag that is responsible for executing the code).
  • The “RequiresUpdateModel” attribute specifies whether or not the model needs to be updated prior to executing the method.
  • The “Action” attribute identifies the internal class for which the data control is created.  Always seems to be 999 for custom class.
  • The “IsViewObjectMethod” attribute indicates whether the method being invoked is defined within a View Object.
  • The “InstanceName” attribute points to the View Object instance as defined by the application data control.
  • The “NamedData” tag is used to map any parameters that the method might take. It contains attributes “NDName” (method parameter name), “NDValue” (value being passed), and “NDType” (data type of the parameter).

In order for the page to be rendered in INPUT mode, we have to include a “Create” action in the page definition.  Place the following tag in the “bindings” section (before or after the “methodAction” tags):

<action IterBinding=”MyemployeeView1Iterator”
InstanceName=”AppModuleDataControl.MyemployeeView1″
DataControl=”AppModuleDataControl” RequiresUpdateModel=”true”
Action=”41″/>

(Note:  The instance name references my View Object … you would replace the reference with yours.)

The next step in preparing the Page Definition is to add “invokeAction” tags to the “executables” section.  The “invokeAction” tags define what actions will be executed and under what conditions they will be executed.  The invoke actions for our methods look like:
<invokeAction
Binds=”clearView”
RefreshCondition=”#{adfFacesContext.postback == false and not empty param.p_emp_id}”
Refresh=”prepareModel”/>

<invokeAction
Binds=”queryViewById”
RefreshCondition=”#{adfFacesContext.postback == false and not empty param.p_emp_id}”
Refresh=”prepareModel”/>

<invokeAction Binds=”Create”
Refresh=”renderModel”
RefreshCondition=”${adfFacesContext.postback == false and empty param.p_emp_id and empty bindings.exceptionsList}”/>

The “RefreshCondition” condition attribute determines whether or not the action will be triggered. The three action invocations below determine how the page will be rendered to the user. If  the call to the page is not a post back from the current page, and the “p_emp_id” param is not null, then associated View Object(s) will be cleared of existing data, passed the p_emp_id param and will execute and populate. This will put the screen in UPDATE mode.  Otherwise, if the “p_emp_id” param is null and the call to the page is not a post back, the screen will be presented in INSERT mode.

Passing a Parameter to the Page

Passing a parameter is a fairly simple matter.  You could pass it via a command link or command button with a param tag (NOTE: The navigation rule definition for the “action” can not contain a redirect reference.):

<af:commandButton text=”Some Text” action=”SomeAction”>
<f:param value=”123″/>
</af:commandButton>

or

<af:commandLink text=”Some Text” immediate=”true”
action=”SomeAction”>
<f:param value=”#{somebinding.value}”/>
</af:commandLink>
You can also pass a parameter via a standard URL:

http://someserver.some.domain:7778/myapp/faces/somepage.jsp?p_emp_id=123

Passing no parameters will result in the page rendering in INPUT mode.

Wrapping It Up …

As always, if you have questions, or input, please shoot me an email.

ADF Faces JavaScript Hack: How to Move a Generated Tag Event Handler

Saturday, August 22nd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Saturday, March 15, 2008)

You may have noticed that ADF Faces generates some very specific JavaScript code for handling page level (tag level) events (onclick, onChange, onBlur, etc …). These event handlers “handle” all of those cool features such as “Partial Submit” and “Auto Submit”. Most of the time, we as developers (and users of ADF) have no direct control over where these framework generated event handlers are placed, or specific control over when they will fire. The focus of this entry is on how to move a generated event handler from one event to another on the same tag. For example: Let’s say that you want to implement a feature that will allow a user to type in an employee Id and then have the rest of the employee information (name, etc ..) auto populate. No problem, you just bind a method from a backing bean to a ValueChangeListener and turn on Auto Submit and you are done! However, what if you also want to use a command link to implement an LOV dialog on the same data entry field and use the data (i.e. the employee id) to limit the results of the LOV? Now you have a problem. If you enter data in the employee id field, and then try to navigate to your LOV link, the value change event (onChange) fires before the LOV triggers and nullifies the LOV event. The solution to the problem is obvious … just change the triggering event from onChange to onKeyPress (for the auto population … you would also need to add code to check for the triggering “Hot Key”). But wait … that code was generated by ADF Faces. We (the developers) have no direct control over where they place their code. Now, the problem becomes slightly more challenging (or interesting). The solution (one solution anyway …) is to write a JavaScript function that will move it for you and leave the original code intact. My version of the function looks like this:

function moveEventFunction(p_id,p_curr_event,p_new_event,conditionalFunc){

/* Get instance of the tag we are modifying. */

var formItem = document.getElementById(p_id);

var eventFunc = null;

/* Get text of target event handler code */

var existingEventCode = formItem.attributes[p_curr_event].value;

/* Only execute the move if the targeted event handler is populated */

if (existingEventCode.length > 0){

/* Convert text of existing event handler back into a working function */

var existingFunction = new Function(existingEventCode);

/* Create a function that will assign a new event handler to the desired item event.
* This needs to be dynamic since we can only make a direct assignment under “normal”
* circumstances. Ex. node.onclick= or node.onchange
*/

var addNewEvent = new Function(“node”,”eventfunc”,”node.”+p_new_event+”=eventfunc;”);

/* We assign “nothing” to the existing event handler. This must be dynamic
* for the same reason as the function above.
*/

var removeExistingEvent = new Function(“node”,”node.”+p_curr_event+”=”;”);

/* If a conditinal function (boolean function that can halt the event …)
* is provided, then wrap it around the existing code. Otherwise, execute
* the original handler under the new event.
*/

if (typeof(conditionalFunc) != “undefined”){

eventFunc = function(){ if (conditionalFunc()){ existingFunction()}};

}else{

eventFunc = existingFunction;

}

/* Add the new event handler */

addNewEvent(formItem,eventFunc);

/* Remove the old event handler */

removeExistingEvent(formItem);

}

}

The function, moveEventFunction, will move or swap the code assigned to one event handler and move it to a new event handler on the same node (or tag). The function also gives the developer the option of wrapping a new conditional (Boolean) function around the original event handler code.

Now that we have a solution, how do we apply it? You have a couple of options. First, place the call to moveEventFunction at the bottom of the page (between script tags). It will fire after all of the ADF/JSF HTML has been rendered.

<script>

moveEventFunction(<id of target tag>,<existing event name>,<new event    name>,<optional conditional function>);

</script>

However, if you plan on making the target tag a partial target (dynamic refresh), you will lose the swap. The second option handles this situation. Place the call on the onFocus event of the target tag. Doing so guarantees it the swap:

onFocus=”moveEventFunction(this.id,<existing event name>,<new event name>,<optional conditional function>);”

The conditional function (the last parameter) can perform multiple tasks prior to executing the main function (original function). In the case of the scenario above, the conditional function would check for the “Hot Key” that triggers our auto population. However, it must return true or false at the end of its execution.  The conditional function needs to be defined in the manner:

var fnc_MyConditionalFunction = function MyConditionalFunction(){ …}

This will allows allows you to pass the actual function as a parameter without it actually being executed (or evaluated) . Instead of passing in MyConditionalFunction, you pass in fnc_MyConditionalFunction.

(Another option that isn’t JavaScript related might be to get an instance of the UIComponent prior to page rendering and make the swap … haven’t tried that yet.)

ADF Faces – How To Get a DBTransaction Object Anytime You Need One

Saturday, August 22nd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Thursday, March 06, 2008)

If you decide to execute a SQL statement or some PL/SQL code from with your ADF Faces application outside of the ADF BC framework (i.e. without using Entity Objects and View Object), you will need access to a JDBC connection.  Do you need to instantiate your own connections, or maintain a separate connection pool?  The answer is no!  ADF BC provides us with (abstracted) access to the JDBC connection object that is associated with our current application session.  Access is provided through the oracle.jbo.server.DBTransaction class.  You can get an instance of the DBTransaction object from several places within the ADF BC Framework: ViewObjectImpl, TransactionEventImpl, EntityImpl, and ApplicationModuleImpl.  All of these classes have a method called getDBTransaction() that return an instance of the DBTransaction object.  Armed with this knowledge, how do we go about getting an instance of DBTransaction anytime we want one?  By “anytime time we want one”, I mean externally from a View Object or Entity Object instance.  The answer is pretty simple.  We just need to access to an instance of the current ApplicationModule.  Using the following code, you can get a DBTransaction object anytime you want:

/***
* This method returns the current instance of the session DBTransaction object.
* The method below is implemented from a Singleton Object for utilitarian purposes.
*/
public static synchronized DBTransaction getDBTransaction(){

FacesContext ctx = FacesContext.getCurrentInstance();

ValueBinding vb = ctx.getCurrentInstance().getApplication().createValueBinding(“#{data}”);
BindingContext bc = (BindingContext)vb.getValue(ctx.getCurrentInstance());

//Use your own data control name when creating the DataControl object
//Look in the DataBindings.cpx file … the id attribute of the BC4JDataControl tag
DataControl dc = bc.findDataControl(“MyApplicationModuleControl”);
ApplicationModuleImpl am = ((ApplicationModuleImpl)(ApplicationModule)dc.getDataProvider());

return am.getDBTransaction();

}

Place the code listed above in a utility class. I prefer to use a static class or Singleton.

ADF Faces: Retrieve and/or Set values in a SelectOneChoice Component backed by a RowSetIterator

Saturday, August 22nd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Thursday, January 31, 2008)

This entry covers how to retrieve values from a SelectOneChoice component that is backed (populated) by a ViewObject as defined in a ADF Faces page definition file.

I’ve been working on a fairly large and complex ADF Faces project for my current employer.  I often find myself having to both retrieve and set values in SelectOneChoice components in my backing beans.  I was initially confounded by the fact that the HTML generated by the component did not include my own code values behind the select options. Rather, each option (option tag) uses a numeric value instead of the actual code you would normally see if you were creating the HTML yourself (such as “NC” as the code for description “North Carolina”).  After some digging, I found that the numbers correspond to the Iterator index values of the Iterator that is bound to SelectOneChoice component.   By the way, setting the valuePassThru attribute on the component to true did not work for some reason.

Armed with this new knowledge, I was able to create two utility methods that reside in my base (utility) managed bean class.

The first method, getSelectOneChoiceValues, retrieves both the code (the actual code from your database or view object) and the description value from the Iterator that is bound to the SelectOneChoice component given the index value.  Here is the code for first method:

/***
* This method returns the code and desc values from a SelectOneChoice.
* Parameters
* (1) p_iteratorIndex – represents the index value of the iterator row we want. You get
* this value from bound ADF component.
* Ex. (Integer)boundSelectItem.getValue()
*
* (2) p_iterator – Name of the Iterator that populates the SelectOneChoice component
* (3) p_code_colname – Column attribute name of the column containing the code value (get this
* from the PageDefinition file for the screen, or the ViewObject that
* is bound to the Iterator.)
* (4) p_codedesc_colname – Column attribute name of the column containing the code desc (get this
* from the PageDefinition file for the screen, or the ViewObject that
* is bound to the Iterator.)
* (5) p_noselection_val – Set this value to “true” if you chose to add a “No Selection” row
* or null value row to your selection object. This row will become the
* zero index row. This “null” value row is not represented in the
* Iterator and throws the index values off by 1.
*
* The return value is a HashMap, but you could create a simple class for this as well.
*/
protected HashMap getSelectOneChoiceValues(int p_iteratorIndex,
String p_iterator,
String p_code_colname,
String p_codedesc_colname,
boolean p_noselection_val)
{
HashMap hm_lovVals = new HashMap();
String lovTypeCode = null;
String lovTypeDesc = null;
int noSelectIncrementor = 0;

if (p_noselection_val){
noSelectIncrementor = 1;
}

try{

// The code for “getRowSetIterator” can be found in the blog entry I published directly
// before this entry or Google “Jason getRowSetIterator”

RowSetIterator lovIter = getRowSetIterator(p_iterator);

Row iterRow = null;

iterRow = lovIter.getRowAtRangeIndex(p_iteratorIndex-noSelectIncrementor);

lovTypeCode = iterRow.getAttribute(p_code_colname).toString();
lovTypeDesc = iterRow.getAttribute(p_codedesc_colname).toString();

}catch(Exception e){
System.err.println(“Error looking up values for LOV iterator “+p_iterator);
}

//the keys “code” and “desc” should not be hard coded values in your production code …
hm_lovVals.put(“code”,lovTypeCode);
hm_lovVals.put(“desc”,lovTypeDesc);

return hm_lovVals;
}

The second method, getSelectOneChoiceIndex, performs the opposite function. Given code value and code column, it returns the actual index value. This allows you set the value of SelectOneChoice component on the screen ( Ex. selectionComponent.setValue(indexVal); ). Here is the code for the second method:

/***
* This method returns the index value for an item in a SelectOneChoice.
* Parameters
*
* (1) p_iterator – Name of the Iterator that populates the SelectOneChoice component
* (2) p_code_value – Code value whose index we are looking for.
* Ex. We pass in “NC” and get the index for the row in the Iterator
* that contains the code “NC”.
*
* (3) p_code_column – Column attribute name of the column containing the code value (get this
* from the PageDefinition file for the screen, or the ViewObject that
* is bound to the Iterator.)
*
* (4) p_noselection_val – Set this value to “true” if you chose to add a “No Selection” row
* or null value row to your selection object. This row will become the
* zero index row. This “null” value row is not represented in the
* Iterator and throws the index values off by 1.
*
* The return value is an Integer.
*/

protected Integer getSelectOneChoiceIndex(String p_iterator,
String p_code_value,
String p_code_column,
boolean p_noselection_val){
int v_code_index = 0;
int noSelectIncrementor = 0;

if (p_noselection_val){
noSelectIncrementor = 1;
}

try{

// The code for “getRowSetIterator” can be found in the blog entry I published directly
// before this entry or Google “Jason getRowSetIterator”

RowSetIterator lovIter = getRowSetIterator(p_iterator);
Row lovRow = null;

for (int x=0;x

lovRow = lovIter.getRowAtRangeIndex(x);

if(lovRow.getAttribute(p_code_column).equals(p_code_value)){
v_code_index = x+noSelectIncrementor;
break;
}

}

}catch(Exception e){
System.err.println(“Error looking up index value for LOV iterator “+p_iterator);
}

return new Integer(v_code_index);

}

An ADF Faces Base Class for a Backing/Managed Bean

Saturday, August 22nd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Friday, November 23, 2007)

Over the last few months, I’ve been working on an ADF based project for my current employer.  The project is my first venture into JSF and ADF.  In this time I’ve developed a little base class that I extend when creating a backing bean (or managed bean) for my pages.  The base class contains several helpful utility methods that I thought I would share.  Some of these I discovered for myself, and a few others were inspired by samples provided by folks like: Steve Muench, Frank Nimphius, and Jonas Jacobi.  I have put the code below.  Each method has a comment at the top to explain what the method does:

The Code …

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import oracle.binding.OperationBinding;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCDataControl;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.faces.component.core.data.CoreTable;
import oracle.adf.view.faces.context.AdfFacesContext;
import oracle.binding.BindingContainer;
import oracle.jbo.ApplicationModule;
import oracle.jbo.Row;
import oracle.jbo.RowSet;
import oracle.jbo.server.EntityImpl;
import oracle.jbo.RowSetIterator;
import oracle.jbo.ViewObject;
import oracle.jbo.server.ViewRowImpl;
import oracle.jbo.uicli.binding.JUCtrlValueBindingRef;

public class ManagedBeanBase {

/**
* Contains page binding references
* This can be populated manually or
* automatically based on config setting
* in faces-config.xml
*
* This is a sample of an entry you would put in
* the faces-config.xml file. Notice the ‘managed-property’
* tag with property name ‘bindings’. This property will be
* set by the faces servlet using the setBindings method below.
*
*
* MyPageBackingBean
* MyPageMB
* request
*
*
bindings * #{bindings}
*
*
*/
*/
protected BindingContainer bindings;

public ManagedBeanBase() {
}

public BindingContainer getBindings() {

return this.bindings;
}

public void setBindings(BindingContainer bindings) {
this.bindings = bindings;
}

/**
* Use this to manually set page bindingings.
*/
public void setBindings(){
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
bindings = (DCBindingContainer) app.getVariableResolver().resolveVariable(context, “bindings”);
}

/**
* Call this method to refresh the binding container
* with any changes.
*/
protected void refreshBindingContainer(){

DCBindingContainer dcBind = (DCBindingContainer)bindings;
dcBind.refresh();

}

/**
* This method is used the removed the currently selected
* row from and ADF (JSF) table. The method requires
* that the table object be passed in as a parameter.
*/
protected void deleteSelectedRow(CoreTable pageTable){

JUCtrlValueBindingRef rwData = (JUCtrlValueBindingRef)pageTable.getSelectedRowData();

Row rw = rwData.getRow();

rw.remove();

}

/**
* This method takes the name of a given iterator (as defined in the page def file)
* and returns the current rowset.
*/
protected RowSetIterator getRowSetIterator(String p_iterator){

DCBindingContainer dcBind = (DCBindingContainer)bindings;
DCIteratorBinding iterBind= (DCIteratorBinding)dcBind.get(p_iterator);

return iterBind.getLovRowSetIterator();

}

/**
* This method will return the ViewObject (object) associated
* with a given iterator.
*/
protected ViewObject getViewObjectFromIterator(String p_iterator){

DCBindingContainer dcBind = (DCBindingContainer)bindings;
DCIteratorBinding iterBind= (DCIteratorBinding)dcBind.get(p_iterator);

return iterBind.getViewObject();

}

/**
* This method will execute the query associated the view object
* with which the iterator is associated.
*/
protected void executeIterQuery(String p_iterator){

DCBindingContainer dcBind = (DCBindingContainer)bindings;

DCIteratorBinding iterBind= (DCIteratorBinding)dcBind.get(p_iterator);

iterBind.executeQuery();

}

/**
* This method issues a rollback again the current transaction.
*/
protected void rollbackCurrentChanges(){

DCBindingContainer dcBind = (DCBindingContainer)bindings;
dcBind.getDataControl().getApplicationModule().getTransaction().rollback();

}

/**
* Manually add a page component to the partial target list
* for partial page refresh.
*/
protected void addPartialTarget(UIComponent p_target_object){
AdfFacesContext.getCurrentInstance().addPartialTarget(p_target_object);
}

}

Oracle ADF Faces Tip: How to hide the Asterisk (*) when the “required” Property is Set to “true”

Saturday, August 22nd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Monday, July 23, 2007)

If this one is common knowledge, then forgive me.  I just jumped into ADF and JSF a few weeks ago (I was a STRUTS man), and am drinking from the firehose!  There is a property on some of the ADF Faces components (inputText, selectOneChoice, etc …) called “required”.  If set to true, this property will ensure that the user enters a value for the item (in DB terms, it makes the field a NOT NULL field).  This is a convenient feature with one small exception.  Setting the property to true places a green asterisk(*) on the left side of the data entry item.  The asterisk appears whether you want it to or not  and there is no option/property available for turning it off (NOTE: This is an ADF inputText feature, not a standard JSF inputText feature).  This is an issue if your development standards say to put an asterisk on the RIGHT side of the input field (as mine do).

The solution to the problem was fairly straight forward.  Since I had implemented a custom skin for this ADF Faces application and created a custom CSS document (see this article by Jonas Jacobi), I simply over-rode the existing style for the required icon with this one:

.AFRequiredIconStyle { display:none }

Presto!  No more little green asterisk.

Passing Mod_Plsql Basic Authentication Credentials Across Applications

Saturday, August 22nd, 2009

(Originally posted on the “old” Jason Bennett’s Developer Corner, Saturday, June 23, 2007)

I was recently tasked with the “seamless” integration of a large Web PL/SQL based application and newer J2EE application. The older application uses a mod_plsql DAD to authenticate users (using the Basic Authentication method), and the newer application built with Oracle ADF and JSF. Each user has a separate database account, and application security is database role based. The problem: How do I pass the users credentials (basically their database login information) to the J2EE application in order to create a user specific database connection? The user accesses the new application from a hyperlink on the existing application’s main menu. It sounds easy enough. Simply write a servlet filter to capture the “AUTHORIZATION” HTTP header and decode the credentials, right? Wrong. Since the J2EE application in seemingly different domain or session space, the “AUTHORIZATION” header is not passed. By the way, SSO and other “new” technologies were not currently available. So, how do we get around the cross domain/session space issue? It turns out to be fairly simple. Both applications are served through the same Apache web-server (OracleAS 10g R1), allowing us to use a very simple method that leverages mod_rewrite (pre-installed and configured with OracleAS 10g).

The Method …

The method uses the following three steps:

1. The URL from the older (calling) application to the newer (target) application has to look as if it is using the mod_plsql DAD. This gives the false impression that the target of the URL is in the same domain/session space as the current application. The URL would look something like: http://servername:7778/<;dad name>/application.do. This basically fools the browser into passing the domain/session space HTTP headers (specifically the “AUTHORIZATION” header) along with the request.

2. In the httpd.conf file (or a separate include .conf file) associated with your Apache instance, place a mod_rewrite directive like this one:

RewriteRule ^(//application.do)$ //application.do [PT]

3. In the Servlet Filter (or whatever portion of your application that can capture incoming HTTP request headers), get the value of the “AUTHORIZATION” HTTP request header. Here is an example of how this code looks using Java: String credentials = req.getHeader(“AUTHORIZATION”); (req is an instance of HttpServletRequest).

Decrypting the Credentials

After you get the credentials using the three step method above, you need to decrypt them. The value of the “AUTHORIZATION” HTTP header will be a string encoded using the base64 encoding method. It will look something like this:

Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== ( )

Decrypting the string is pretty simple using a base64 decoder such as Sun’s sun.misc.BASE64Decoder class. Before decrypting the string, we need parse out the credential portion of the string (i.e. we need to remove the “Basic” portion of the string). When decrypted, the above string will look like this:

Aladdin:open sesame (:
)

Once we get the credentials decrypted, simply parse the string to obtain the username and password. The following is a simple Java class that will aid in decrypting and returning the username and password:

import java.util.StringTokenizer;
import sun.misc.BASE64Decoder;

public class BasicAuthDecoder {

private String authType = “Basic”;

private String codedCredential = null;
private String username = null;
private String password = null;

public BasicAuthDecoder(String rawCredentialString) {

if (rawCredentialString != null){

setCodedCredential(rawCredentialString);

decodeCredentials();

}

}

private void setCodedCredential(String rawCredentialString){

StringTokenizer authTokens = new StringTokenizer(rawCredentialString);

if (authTokens.hasMoreTokens()){

if (authTokens.nextToken().equalsIgnoreCase(authType)){

codedCredential = authTokens.nextToken();

}

}

}

private void decodeCredentials(){

String decodedCredentialString = null;

try{

BASE64Decoder decoder = new BASE64Decoder();
decodedCredentialString = new String(decoder.decodeBuffer(codedCredential));

StringTokenizer authTokens = new StringTokenizer(decodedCredentialString,”:”);

if (authTokens.hasMoreTokens()){

username = authTokens.nextToken();
password = authTokens.nextToken();

}

}catch(Exception e){
System.err.println(“Error decoding user credentials “+e.getMessage());
}

}

public String getUsername(){

return username;

}

public String getPassword(){

return password;

}

}

Automatically Print Web-based Oracle Reports (PDF format) to a User’s Local/Default Printer

Saturday, August 22nd, 2009

(Originally posted in the “old” Jason’s Developer Corner, Tuesday, November 29, 2005)

Working for a major metropolitan police department, I get some interesting development assignments. One such assignment was to allow officers connected to our network via VPN to send their printed reports to the default printer assigned to the machine they are using. No problem! Oracle Reports has a setting that will send a PDF version of the report back to the user’s web browser using the Adobe Acrobat plug-in. They can just hit the print button in the Acrobat viewer and print the report to any printer available to the machine! No sweat! Oh … by the way … the officer is not allowed to save the report to his/her machine (for security and privacy reasons). This is where the task got sticky. The Acrobat Viewer has a ‘Save’ button. This feature cannot be turned off programmatically. A command has to be impeded in PDF document at the time it is created to keep it from being saved. Unfortunately, Oracle Reports doesn’t offer this as an option for reports being created in a PDF format (at least in our version). After a little searching, I found a solution. The rest of this entry will show you how to do it using an open source tool and some standard browser features. Nothing is impossible …

The Solution …

The solution to the problem was to imbed a JavaScript command in the PDF document that forced an auto print to the default printer while accessing the document from a hidden IFRAME (width 0, height 0).  The only hitch � how the heck do we imbed a JavaScript command in a PDF document that is being generated by Oracle Reports.  This is where the open source option came into play.  After some searching, I came across an open source project called iText (http://www.lowagie.com/iText/). iText is a library that allows you to generate or modify (to some extent) PDF files on the fly.  iText is available in both Java and .NET flavors.  Being a Java fan and an Oracle Application Server customer, I chose the Java flavored iText solution.  I created a servlet that acted as a proxy to the Oracle Reports Servlet.  The servlet, acting as a proxy, is then able to received the data stream from the Oracle Reports servlet.  In this case, the data stream is a PDF document.  Using the iText library, I added the auto print command to the PDF document and then had the proxy servlet pass the altered document to the user’s browser.  To keep the user from saving this document, I had the request for the report sent to the proxy servlet through an IFRAME with a width and height of 0This kept the user from seeing the document in the Adobe Acrobat plug-in and kept them from saving the document.

The Code …

Being a left-handed right-brained developer, I tend to learn more from actually seeing the code than reading about it.  The iText APIs are well documented at the iText website (http://www.lowagie.com/iText) along with examples.  JavaScript commands as they relate to PDF documents can be found at http://partners.adobe.com/public/developer/pdf/library/index.html.   I have included comments in the code in key locations.  As usual, if you have questions, shoot me an email.  Here is the code for the servlet:

import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import javax.servlet.*;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.net.MalformedURLException;

//iText Open Source PDF APIs … awesome code!

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;

public class PDFLocalPrint extends HttpServlet
{

private static final String CONTENT_TYPE = “application/pdf”;

public void init(ServletConfig config) throws ServletException
{

super.init(config);

}

private ByteArrayOutputStream getDoc(String p_url)
{

Document document = null;

PdfCopy writer = null;

PdfImportedPage page;

ByteArrayOutputStream baos = null;

int v_pages = 0;

try{

URL url = new URL(p_url);

URLConnection urlc= url.openConnection();

int length = urlc.getContentLength();

InputStream in = urlc.getInputStream();

baos = new ByteArrayOutputStream();

PdfReader oracleReport = new PdfReader(in);

oracleReport.consolidateNamedDestinations();

v_pages = oracleReport.getNumberOfPages();

document = new Document(oracleReport.getPageSizeWithRotation(1));

writer = new PdfCopy(document,baos);

document.open();

//Copy content from PDF streaming from Reports Server to new PDF Document.

for(int i=0;i0)

{

//Pass the altered document back to the requesting browser or application.

doc = getDoc(v_report_url);

response.setContentType(CONTENT_TYPE);

response.setContentLength(doc.size());

doc.writeTo(out);

doc.close();

out.flush();

}else{
out.println(“No Data”);
out.close();

}

}

}

Uploading Binary Files (BLOBS) to An Oracle Table Using a Servlet

Saturday, August 22nd, 2009

(Originally posted in “Old” Jason’s Developer Corner on Saturday, February 05, 2005)

The purpose of this entry is to provide the reader with the actual code required to upload a binary file (image, excel spreadsheet, Word Doc, PDF, etc) from a web browser and store it in the BLOB column of database table. After searching high and low for a specific example (I did find one that showed how to upload the file and save it to disk, which helped quite a bit), I vowed to publish my code for anyone else searching for a similar example. Some of this code comes from an actual application, and may not seem to ‘flow’, as I have omitted non-relevant portions. The goal here is to impart the method for the upload and storage of BLOB data from the browser to the database.

Multipart Form-Data … A brief explanation

It is important at the start to realize that binary data is uploaded as multipart/form-data  data from a form on a web page.  This means that the parameter values passed up from the form cannot be retrieved from the receiving servlet using the traditional request.getParameter method.  The form tag will look something like:

<FORM action=”/uploadservlet/imageUpload.do”

enctype=”multipart/form-data”

method=”POST” >

The file upload component of the form uses an input tag of the format:

<INPUT>

The rest of the form input parameter are just like any other:

<INPUT>

All of the data is sent up in a specific format.  The passed parameters are strings of the form:

Content-Disposition: form-data;

Joe smith

————–AaB03x

In the example above, p_user is a form parameter name and Joe Smith is the value.  NOTICE that there is a blank line between the parameter string and the actual value. Each of the parameter string value pairs is separated by a delimiter or boundary. The boundary line separating each individual data element looks something like:

————–AaB03x

The value of this boundary varies. The first line in the stream will contain this value. It is important to grab and store this value, as the code will later demonstrate.

The binary content, or file, will be the last parameter string value pair in the input stream (basically the rest of the input stream).  The parameter string for the file looks like this:

content-disposition: form-data;; filename=”test.jpeg”

Content-Type: image/pjpeg

… FILE CONTENT …

The next string or line after the file parameter string is the content indicator string.  The actual content of the file follows content type string. NOTICE that the file data is separated from the content string by a blank line. For more info see

(http://www.faqs.org/rfcs/rfc1867.html).

The Code …..

The code for uploading the image into the data consists of a PL/SQL function on the data base side that takes the BLOB passed from the servlet and stores it in a new table, and the Java Servlet and related classes that handle the upload request.  First, lets look at the PL/SQL.  The following code comes from an application used to upload juvenile mugshots into a database in a juvenile arrest system:

FUNCTION pre_load_image_table(p_juvmast_id JUVENILE_MASTERS.ID%TYPE := NULL,
p_label JUVENILE_PHOTOS.label%TYPE := NULL,
p_user JUVENILE_PHOTOS.created_by%TYPE := NULL,
p_mime_type JUVENILE_PHOTOS.MIME_TYPE%TYPE := NULL) RETURN NUMBER
IS

v_return NUMBER := NULL;

BEGIN

EXECUTE IMMEDIATE ‘SELECT jpo_seq.nextval FROM dual’ INTO v_return;

EXECUTE IMMEDIATE ‘INSERT INTO juvenile_photos(id,juvmast_id,label,lineup_order,mime_type,juv_image,created_by,date_created) ‘||
‘ values (:id,:p_juvmast_id,:p_label,:p_lineup,:p_mime_type,empty_blob(),:created_by,:date_created)’
USING
v_return,
p_juvmast_id,
p_label,
getNextLineupOrder(p_juvmast_id),
p_mime_type,
p_user,
SYSDATE;

RETURN v_return;

END;

FUNCTION externalSaveImage(p_juvmast_id JUVENILE_MASTERS.ID%TYPE := NULL,
p_label JUVENILE_PHOTOS.label%TYPE := NULL,
p_user JUVENILE_PHOTOS.created_by%TYPE := NULL,
p_mimetype JUVENILE_PHOTOS.MIME_TYPE%TYPE := NULL) RETURN t_refcursor
IS

v_refcur kbcJuvenileImages.t_refcursor;
v_pk NUMBER(12) := 0;

BEGIN

–Creates a new row in the image table with an empty_blob() and returns new PK.

v_pk := pre_load_image_table(p_juvmast_id,UPPER(p_label),p_user,p_mimetype);

OPEN v_refcur FOR ‘SELECT juv_image FROM juvenile_photos WHERE id = :id FOR UPDATE’ USING v_pk;

RETURN v_refcur;

END;

The first function is called by the second to create a new row in the image table containing the data passed from the webpage describing the image.  Please note that an EMPTY BLOB is inserted into the blob column of this table.  The second function selects the BLOB column of the new record for update and passes this value back to the calling Java application as a refcursor.  This creates an input stream that allows the blob data to be streamed back to the database.

The image upload Java class is our next piece of code.  The class extends another class that I have not included.  The base class is merely a JDBC helper class containing code to obtain a connection object from a connection factory.  The important code here is the code that illustrates how to stream the binary data back to the database:

package imageupload;

import java.io.*;
import java.sql.*;
import javax.sql.*;
import oracle.sql.*;
import oracle.jdbc.*;
import javax.servlet.ServletInputStream;

/**
* The purpose of this class is to take the remaining portion
* of the input stream containing the body of the uploaded file
* and pass it to a database stored proc that saves it to a
* BLOB column in a table.
* This class extends a JDBC helper class called
* JDBC connection base.
*/

public class ImageLoader extends JDBCConnectionBase
{

public void insertImageData(ServletInputStream p_image_stream,
int p_id,
String p_label,
String p_user,
String p_mime_type,
String p_delimiter)
{
try{

BLOB v_image_blob = null;

String lineCheck;

setPooledConnection();

//Using the stored procedure removes some of the complexity from
//the Java application.

CallableStatement cs =

conn.prepareCall(“begin ? := kbcJuvenileImages.externalSaveImage(?,?,?,?); end;”);

cs.registerOutParameter(1,OracleTypes.CURSOR);

cs.setInt(2,p_id);

cs.setString(3,p_label);

cs.setString(4,p_user);

cs.setString(5,p_mime_type);

cs.execute();

rset = (ResultSet)cs.getObject(1);

if (rset.next()){

v_image_blob = ((OracleResultSet)rset).getBLOB(1);

}

OutputStream outstream = v_image_blob.getBinaryOutputStream();

byte[] buffer = new byte[256];

int length = -1;

while ((length = p_image_stream.readLine(buffer,0,256)) != -1)

{

lineCheck = new String(buffer,0,length);

if (lineCheck.indexOf(p_delimiter)== -1) {

outstream.write(buffer,0,length);

}

}

outstream.close();

cs.close();

conn.commit();

}catch(SQLException e)

{

System.err.println(“Error creating image record: “+e.getMessage());

v_error.append(“Error creating image record: “).append(e.getMessage());

}catch(Exception e)

{

System.err.println(“Error creating image record: “+e.getMessage());

v_error.append(“Error creating image record.”).append(e.getMessage());

e.printStackTrace();

}finally

{

closeConnections();

}

}

}

The next bit of Java code is the actual servlet that handles the request for upload. I think I have sufficiently commented the code, but if you have questions just shoot me an email.

package imageupload;

import oracle.sql.BLOB;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletInputStream;
import java.io.PrintWriter;
import java.io.IOException;

public class uploadServlet extends HttpServlet
{

//The following six variables represent tokens
//used to parse the content submitted in the
//multi-part form.

private static final String CONTENT_TYPE
= “text/html; charset=windows-1252″;

private static final String DATA_INDICATOR
= “Content-Disposition: form-data; name=\”";

private static final String FIELD_INDICATOR = “name=\”";
private static final String FILE_INDICATOR = “filename=\”";
private static final String FILE_MIME_INDICATOR = “Content-Type:”;
private String REQUEST_DELIMITER = null;

//HashMap to store field names and values
//passed from the calling form.

private HashMap fields = new HashMap();

/**
* Check to see if the line passed in
* contains a field type indicator.
*/

private boolean checkField(String p_value)
{

boolean v_return = false;

if(p_value.indexOf(FIELD_INDICATOR) != -1)
{

v_return = true;

}

return v_return;

}

/**
* Check to see if the line passed in
* contains a file type indicator.
*/

private boolean checkFile(String p_value)
{

boolean v_return = false;

if(p_value.indexOf(FILE_INDICATOR) != -1)
{

v_return = true;

}

return v_return;

}

/**
* Check to see if the line passed in
* is a delimiter line. Delimiters
* separate the different sections
* of multipart form.
*/

private boolean checkDelimiter(String p_value)
{

boolean v_return = false;

if(p_value.indexOf(REQUEST_DELIMITER) != -1)
{

v_return = true;

}

return v_return;

}

/**
* Check to see if the line passed in
* contains the file content type indicator.
*/

private boolean checkContentIdicator(String p_value)
{

boolean v_return = false;

if(p_value.indexOf(FILE_MIME_INDICATOR) != -1)

{

v_return = true;

}

return v_return;

}

/**
* Check to see if the line passed in
* contains a data value type indicator.
*/

private boolean checkDataIndicator(String p_value)
{

boolean v_return = false;

if(p_value.indexOf(DATA_INDICATOR) != -1)

{

v_return = true;

}

return v_return;

}

/**

* Returns the value of field stored in the
* ‘fields’ HashMap based upon the key passed
* in to the method. The key relates directly
* to the parameter names in the passing form.
*/

private String getFieldValue(String p_name)
{

String v_value = new String();

try{

v_value =(String)fields.get(p_name);

}catch(Exception e)

{

v_value = “”;

}

return v_value.trim();

}

/**
* Parse the value of the parameter passed in
* on line containing parameter/field data.
*/

private String parseFieldValue(ServletInputStream in) throws Exception
{

byte[] line = new byte[128];

int i = 0;

StringBuffer fieldValue = new StringBuffer(128);
String newline;

newline = new String();

while (i != -1 && !checkDelimiter(newline)) {

i = in.readLine(line, 0, 128);

newline = new String(line, 0, i);

if (!checkDelimiter(newline)){

fieldValue.append(newline);

}

}

return fieldValue.toString();

}

/**
* Parse the value of the parameter name in
* on line containing parameter/field data.
*/

private String parseFieldName(String p_name)
{

int pos = 0;
String v_content = new String();

pos = p_name.indexOf(FIELD_INDICATOR);

if (pos > 0){

v_content = p_name.substring(pos+6, p_name.length()-3);

}

return v_content;

}

/**
* Parse the value of the content type passed in
* on line containing file content data.
*/

private String getContentType(String p_name)
{

int pos = 0;

String v_content = new String();

pos = p_name.indexOf(“:”);

if (pos != -1){

v_content = p_name.substring(pos+1,p_name.length());

}

return v_content;

}

/**
* Place field name and value in the “fields” HashMap
* for easy retrieval later. The field (or parameter)
* name becomes the hashmap key.
*/

private void setFieldValue(String p_name,
String p_value)
{

fields.put(p_name,p_value);

}

/**
* This method takes the input stream containing the
* multipart form data and processes it. Processing
* means separating out the different items such as
* parameter values and passes off the binary data
* to a handler object that loads the data into a
* database field. The method returns a success or
* failure value in the form of a String.
*/

private String processInputStream(ServletInputStream in) throws Exception
{

String v_return_value = new String();

String v_content = new String();

String newline = new String();

ImageLoader imageLoader = new ImageLoader();

try{

byte[] line = new byte[256];

int i = in.readLine(line, 0, 256);

//First line is delimiter/boundary

REQUEST_DELIMITER = new String(line, 0, i);

while (i != -1) {

newline = new String(line, 0, i);

//System.out.println(newline);

if (checkDataIndicator(newline)) {

if (checkFile(newline)) {

i = in.readLine(line, 0, 256);

newline = new String(line, 0, i);

//System.out.println(newline);

while (!checkContentIdicator(newline))
{

i = in.readLine(line, 0, 256);

newline = new String(line, 0, i);

}

if (checkContentIdicator(newline)){

v_content = getContentType(newline);

}

//Consume extra line

i = in.readLine(line, 0, 256);

//newline = new String(line, 0, i);
//System.out.println(newline);

if (getFieldValue(ApplicationConstants.PARAM_NAME).length() > 0){

imageLoader.insertImageData(in,
Integer.parseInt(getFieldValue(“p_id”)),
getFieldValue(“p_label”),
getFieldValue(“p_user”),
v_content,
REQUEST_DELIMITER);

}else

{

v_return_value=”Photo Upload failed: ID is required.”;

break;

}

}else{

String fieldName =parseFieldName(newline);

//System.out.println(“fieldName:” + fieldName);
// blank line

i = in.readLine(line, 0, 128);

setFieldValue(fieldName,parseFieldValue(in));

}

}

//read the next line.

i = in.readLine(line, 0, 128);

}

if (imageLoader.existErrors())

{

v_return_value = “Photo Upload failed: “+imageLoader.getErrors();

}

}catch(Exception e)

{

v_return_value = “Photo Upload failed: “+e.getMessage();

}finally
{

in.close();

}

if (v_return_value.length() < 1)

{

v_return_value = “Photo Uploaded Successfully.”;

}

return v_return_value;

}

private void displayResponse(PrintWriter out,
String p_text)
{

int v_error = p_text.indexOf(“failed”);

out.println(“”);

out.println(“”);

out.println(“”);</p> <p> out.println(“.errorText {color: red;”);</p> <p> out.println(” font-style: italic;”);</p> <p> out.println(” font-weight: bold;}”);</p> <p> out.println(” .greenText {color:#006600;}”);</p> <p> out.println(“”);

out.println(“Upload Juvenile Master Photo
“);

if (v_error >= 0)

{

out.println(”

“);

}else

{

out.println(”

“);

}

out.println(p_text);

out.println(“

“);

out.println(“”);

out.println(“”);

}

public void init(ServletConfig config) throws ServletException
{

super.init(config);

}

public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException

{

String v_upload_result = new String();

PrintWriter out = response.getWriter();

ServletInputStream in = null;

response.setContentType(CONTENT_TYPE);

try{
in = request.getInputStream();

v_upload_result = processInputStream(in);

}catch(Exception e)

{
v_upload_result=”Image Upload failed: “+e.getMessage();
}finally

{

in.close();

}

displayResponse(out,v_upload_result);

out.close();

}

}