Archive for the 'Java' Category

How to solve XML reffers to not existing parent error of dhtmlxTree

Written by coregps on Thursday, March 13th, 2008 in Java, AJAX, XML.

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

When I use dhtmlxTree dynamical loading with jsp, I always get the following exception:

Error type: DataStructure
Description: XML reffers to not existing parent

The code of the jsp page is as following:

<html>
<head>
</head>
<body>
    <link rel="STYLESHEET" type="text/css" href="css/dhtmlxtree.css">
    <script  src="js/dhtmlxcommon.js"></script>
    <script  src="js/dhtmlxtree.js"></script>
    <div id="treeboxbox_tree" style="width:100%; height:218;background-color:#f5f5f5;border :1px solid Silver;; overflow:auto;"></div>
    <script type="text/javascript">
		tree=new dhtmlXTreeObject("treeboxbox_tree","100%","100%",0);
		tree.attachEvent("onClick",onNodeSelect);
		tree.setImagePath("images/tree/");
		tree.setXMLAutoLoading("AdminFolderServlet?action=folder_treeview");
		tree.loadXML("AdminFolderServlet?action=folder_treeview&id=1");
		function onNodeSelect(nodeId){
		    document.getElementById("parent_folder_id").value = nodeId;
		}
    </script>
</body>
</html>

And the following is the code snippet used to generate XML file of the tree:

String id = request.getParameter("id");
if (id == null) id = "1";
Vector folders = Folder.getFolders(Integer.parseInt(id));
StringBuffer buff = new StringBuffer("< ?xml version=\"1.0\"?>“);
buff.append(”
“);
for (int i = 0; i < folders.size(); i++) {
	Folder f = (Folder)folders.get(i);
	buff.append("“);
}
buff.append(”“);
response.setContentType(”text/xml”);
response.setHeader(”Cache-Control”,”no-cache”); //HTTP 1.1
response.setHeader(”Pragma”,”no-cache”); //HTTP 1.0
response.setDateHeader(”Expires”, 0); //prevents caching at the proxy server
response.getWriter().write(buff.toString());

The generated XML is well formed.

<?xml version="1.0"?>
<tree id='1'>
	<item child='1' id='2' text='Games' im0='folderClosed.gif' im1='folderOpen.gif' im2='folderClosed.gif'></item>
	<item child='1' id='3' text='Music' im0='folderClosed.gif' im1='folderOpen.gif' im2='folderClosed.gif'></item>
	<item child='0' id='4' text='Books' im0='folderClosed.gif' im1='folderOpen.gif' im2='folderClosed.gif'></item>
	<item child='1' id='5' text='Movies' im0='folderClosed.gif' im1='folderOpen.gif' im2='folderClosed.gif'></item>
	<item child='1' id='6' text='Photos' im0='folderClosed.gif' im1='folderOpen.gif' im2='folderClosed.gif'></item>
	<item child='0' id='14' text='Articles' im0='folderClosed.gif' im1='folderOpen.gif' im2='folderClosed.gif'></item>
</tree>

I finally found the solution. The id attribute of the tree element must point to the parent id, which data will be linked, by default super-root ID = 0, but it can be changed while tree initialization ( 4th parameter of constructor ), In case of dynamic loading the tree id must be equal to the parent ID for which data requested.

In my database, the root id of the top level folder is 1, however, I use 0 in the tree initialization method.

tree=new dhtmlXTreeObject("treeboxbox_tree","100%","100%",0);

So, I got the exception. After changing the fourth parameter to 1, it works well.

tree=new dhtmlXTreeObject("treeboxbox_tree","100%","100%",1);

Hope this can help someone else in the future :)

propecia pricebuy propeciaorder ventolinbuy ventolincheap xenicalxenical onlneorder revatiorevatiofemale viagra onlinefemale viagracompare viagra cialisorder viagra cialischeap vpxlvpxl onlineorder levitra professionallevitra professional onlinebuy levitra prescriptionlevitralevitra onlineorder cialis jellycialis jellyorder cialis soft tabsbuy cialis soft tabsorder cialis super activecheap cialis super activeorder generic cialischeap generic cialiscialis professionalcialis professional onlinepurchase cialiscialis pricecialischeap brand viagrabrand viagra onlineviagra jelly onlineviagra jelly priceorder viagra soft tabsbuy viagra soft tabsviagra super active onlineviagra super activeorder generic viagracheap generic viagraviagra professional onlineviagra professionalpurchase viagraviagracheap viagraorder vpxlbuy vpxltake viagra cialis togetherorder viagra cialis onlinelevitra professional pricecheap levitra professionallevitrabuy levitracialis jelly pricecheap cialis jellycialis soft tabscialis soft tabs onlineorder cialis super activecialis super activeorder generic cialischeap generic cialischeap cialis professionalcialis professional priceorder cialischeap cialischeap brand viagrabrand viagra onlineorder viagra jellyviagra jelly pricecheap viagra tabsviagra soft tabs onlineviagra super active onlinecheapviagra super activegeneric viagrageneric viagra onlineorder viagra professionalcheap viagra professionalviagra pricebuy viagrabuy cialis ukwhat is cialiscialis sale ukpurchase generic cialisbuy cialis money orderbuy cialis low costbuy cialis in ukbuy cialis huge discounts onlinebuy cialis from usa onlinebuy cialis fedex shippingorder cialis and viagrabuy cialis no prescriptionbuy cialis amexbuy cialis by mailbest cialis pricesorder viagra international shipscheapest place to buy viagra onlineviagra purchasebuy taladafil viagraviagra mail order ukviagra low pricecheap site buy viagrabuy generic viagra canadaviagra drugs order brand pillviagra best quality lowest priceshow to buy viagra onlinebuy viagra online securelybuy viagra online pharmacybuy viagra online get prescriptionbest way to take levitrabest price viagra or levitrabest price viagra official drug storeorder viagra with master cardorder viagra upsbuy viagra in englandbuy viagra consumers discount

Removing duplicate whitespace using regular expression

Written by coregps on Friday, December 14th, 2007 in Java.

Just a simple note about how to remove duplicate whitespace using regular expression in java.

public class Test {
    public static void main(String[] args) {
        String str = "Hello      World!";
		System.out.println(str.replaceAll("\s+", " "));
	}
}

Remove Oracle CLOB ClassCastException

Written by coregps on Friday, January 5th, 2007 in Java, SQL Server, Oracle.

I recently migrated from SQL Server 2000 to Oracle 8.1.7 and now I have to handle Oracle CLOB data. To demonstrate my problem, I will create the following table:

CREATE TABLE test(testid number, content clob);

The following code snippet is used to write CLOB data into database:

String sql = "INSERT INTO test(testid, content) VALUES(?, EMPTY_CLOB())";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1, maxid);
pst.executeUpdate();
sql = "SELECT content FROM test WHERE testid=? FOR UPDATE";
pst = conn.prepareStatement(sql);
pst.setInt(1, maxid);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
    oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob(1);
    clob.putString(1, "Some content to write into database");
}

And the code used to convert CLOB data to String:

public static String clobToString(Object obj) {
    StringBuffer content= new StringBuffer("");
    if (obj != null) {
        CLOB clob = (CLOB)obj;
        Reader is;
        try {
            is = clob.getCharacterStream();
            BufferedReader br = new BufferedReader(is);
            String s = br.readLine();
            while (s != null) {
                content.append(s);
                s = br.readLine();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
    return content.toString();
}

I was able to successfully run the code above when I use the connection obtained from normal DriverManager.getConnection method.

DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
String url = “jdbc:oracle:thin:@ubuntu:1521:oradb”;
String userName = “scott”;
String password = “tiger”;
conn = DriverManager.getConnection(url, userName, password);

But got some trouble when I use a datasource lookup.

<Resource name="jdbc/oraDB" auth="Container" type="javax.sql.DataSource"
   driverClassName="oracle.jdbc.driver.OracleDriver"
   factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
   url="jdbc:oracle:thin:@server:1521:oradb"
   username="scott"
   password="tiger"
   maxWait="-1" removeAbandoned="true"
   maxActive="20" maxIdle="10"
   removeAbandonedTimeout="180" logAbandoned="true" accessToUnderlyingConnectionAllowed="true" />

public class DBConn {
    private static Context initCtx = null;
	  private static DataSource ds = null;
    private static String resource = "java:comp/env/jdbc/oraDB";

  	/**
  	 * Get a connection from pool
  	 *
  	 * @return a Connection
  	 */
  	public static Connection getConnection() {
  		  Connection conn = null;
  		  try {
  			    if (initCtx == null) {
  				      initCtx = new InitialContext();
  			    }
  			    if (ds == null) {
  				      ds = (DataSource) initCtx.lookup(resource);
  			    }
  			    try {
  				      conn = ds.getConnection();
  			    } catch (SQLException e1) {
  			    }
  		  } catch (NamingException e) {
  		  }
  		  return conn;
  	}
}

The following line will throw a ClassCastException “java.lang.ClassCastException: oracle.sql.CLOB”.

oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob(1);

I first found the following section in Oracle forum(http://forums.oracle.com/forums/message.jspa?messageID=855366):

It ONLY works if the Connection is an oracle.jdbc.driver.OracleConnection object. If it's not an oracle.jdbc.driver.OracleConnection, you get a ClassCastException.

The problem happens because when I run my code in Tomcat and get the database connection via a DataSource object that I lookup via JNDI, the connection is not a real OracleConnection object, but an object that wraps the real OracleConnection.

In more detail:

Tomcat uses the Apache Commons DBCP package (see http://jakarta.apache.org/commons/dbcp/) for database connection pooling. When you lookup a DataSource object using JNDI, like this:

Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/ari");

the object that you get is an instance of class org.apache.commons.dbcp.BasicDataSource. When you call getConnection on this object, you get an instance of class org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper (which obviously implements java.sql.Connection, and wraps the OracleConnection object).

To be able to call CLOB.createTemporary successfully, we need to find the wrapped OracleConnection object. A number of steps are necessary to reach this:

First of all, by default the PoolingDataSource$PoolGuardConnectionWrapper does not allow access to the wrapped Connection object (don't ask me why, but that's how the Apache developers decided it should be). You must enable access by configuring it in the <context> of the web application (in Tomcat's server.xml configuration file), for example:

<context path="/ariweb" docBase="ariweb.war">
<resource name="jdbc/ari" auth="Container" type="javax.sql.DataSource"/>
<resourceparams name="jdbc/ari">
<parameter>
<name>driverClassName</name>
<value>oracle.jdbc.driver.OracleDriver</value>
</parameter>
<parameter>
<!-- NOTE: This is necessary to enable access to the Oracle connection object -->
<name>accessToUnderlyingConnectionAllowed</name>
<value>true</value>
</parameter>
<!-- Other configuration parameters -->
...
</resourceparams>
</context>

The PoolingDataSource$PoolGuardConnectionWrapper extends class org.apache.commons.dbcp.DelegatingConnection, which has a getDelegate method. We can call this method to get the wrapped connection.

Unfortunately, the story is not yet finished. The getDelegate method of the PoolingDataSource$PoolGuardConnectionWrapper does not return the OracleConnection object - it returns an instance of class org.apache.commons.dbcp.PoolableConnection, which is a second wrapper around the OracleConnection object.

The PoolableConnection class also extends DelegatingConnection, so we can call getDelegate again and finally we have the OracleConnection object.

So here is the final code:

// conn is the Connection I got from the DataSource
Connection oracleConnection = conn;

if (conn instanceof org.apache.commons.dbcp.DelegatingConnection) {
// This returns a org.apache.commons.dbcp.PoolableConnection
Connection pc = ((org.apache.commons.dbcp.DelegatingConnection)conn).getDelegate();

// The PoolableConnection is a DelegatingConnection itself - get the delegate (the Oracle connection)
oracleConnection = ((org.apache.commons.dbcp.DelegatingConnection)pc).getDelegate();
}

CLOB clob = CLOB.createTemporary(oracleConnection, true, CLOB.DURATION_SESSION);
clob.open(CLOB.MODE_READWRITE);
...

However, after trying the solution above as following:

conn = DBConn.getConnection();
if (conn instanceof DelegatingConnection) {
    // This returns a org.apache.commons.dbcp.PoolableConnection
    Connection pc = ((DelegatingConnection)conn).getDelegate();

    // The PoolableConnection is a DelegatingConnection itself - get the delegate (the Oracle connection)
    conn = ((DelegatingConnection)pc).getDelegate();
}

I still got the same problem. Finally I found the right answer:

The two classes are the same (oracle.sql.CLOB), but they are loaded by different classloader. This usually happens when you put your JDBC driver jars both in server’s and webapp’s libraries and use the jndi datasource; the db objects (like CLOB) are created by the server (using its classloader) so when the webapp tries to cast those objects it gets that error, even if everything works fine when not using casts; you probably would have the same issue if you try to cast the ResultSet to OracleResultSet. I would recommend to put the JDBC driver(s) jars ONLY in the server lib dir; In Tomcat it would be the commons directory.

So, It is not necessary to get the wrapped OracleConnection object. Just put the Oracle jdbc driver ONLY in the Tomcat\Common\lib directory.

Hope this helps if you meet the same trouble.

IBM Open Source Application Server Gains Support of More Than 600 Partners in Six Months ? IBM has announced that more than 600 independent software vendors (ISVs) and systems integrators have joined IBM’s WebSphere Application Server (WAS) Community Edition partner initiative since it was launched just six months ago. WAS Community Edition is IBM’s open source application server based on Apache Geronimo.

Canonical and Sun Expand Joint Ubuntu/Sun Presence in the Enterprise and Open Source Communities ? Sun Microsystems, and Canonical, the commercial sponsor of the rapidly-growing Ubuntu GNU/Linux distribution, have announced that the open-source Java Enterprise Edition 5 application server (specifically, the GlassFish Community reference implementation) will be made available on the widely popular Ubuntu operating system.



Site Navigation