oracle.otnsamples.cmsxdb.useraction.DataUtils (Java2HTML)
/*
 * @author  : Pushkala
 * @version : 1.0
 *
 * Development Environment : Oracle9i JDeveloper

 * Name of the File        : DataUtils.java
 *
 * Creation / Modification History
 *    Pushkala           25-Jan-2003        Created
 *
 */
package oracle.otnsamples.cmsxdb.useraction;


import java.net.URLEncoder;

import java.util.HashMap;
import java.util.StringTokenizer;

import java.sql.Connection;
import java.sql.SQLException;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.StringReader;

import javax.servlet.http.HttpServletRequest;


import oracle.sql.CLOB;

import oracle.xml.parser.v2.XMLParseException;
import oracle.xml.parser.v2.SAXParser;
import oracle.xml.parser.v2.XMLParser;

import oracle.otnsamples.cmsxdb.useraction.ServletUtils;
import oracle.otnsamples.cmsxdb.useraction.JDBCQueryBean;
import oracle.otnsamples.cmsxdb.useraction.FileUploadUtils;
import oracle.otnsamples.cmsxdb.ConnParams;


import oracle.otnsamples.cmsxdb.exception.CMSAccessException;

/**
 * This class is instantiated by the JSPs to handle the client requests.
 * The JSPs pass on the content management operation requests to this class.
 * This class handles the client requests and depending on the operation
 * calls the ServletUtils class where the request is passed on to the database
 * servlet which perform the requested operation.
 *
 */

public class DataUtils {

  /**
   * Empty Default Constructor.
   */
  public DataUtils()  {

  }

  /**
   * This method creates an instance of ServletUtils. The input request URL is
   * encoded and is appended to the Database Servlet URL to be invoked.

   * The sendRequest method in ServletUtils is called passing the request URL
   * and the request information to it.
   *
   * @param   request     HttpServletRequest
   * @param   requestURL  URL to connect to in ServletUtils
   * @param   username    username
   * @param   password    password
   *
   * @return  String      status returned by the database servlet
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */

  public String callServletUtils(HttpServletRequest request, String requrl,
                                 String username, String password)
      throws CMSAccessException {

    ServletUtils utils = new ServletUtils();

    String encodedURL = null;
    try {

      // Encode the request URL string into application/x-www-form-urlencoded
      // format using UTF-8 scheme
      encodedURL = URLEncoder.encode(requrl, "UTF-8");

    } catch (UnsupportedEncodingException usee) {


      throw new CMSAccessException ( " Exception while encoding " +
                                     " URL in callServletUtils  " +
                                     usee.toString() );

    }

    // Append the above encoded URL to the Servlet URL
    String requestURL = new StringBuffer(ConnParams.dbCMSServlet)
                              .append("?")
                              .append( encodedURL ).toString( );

    // Call the sendRequest method in ServletUtils with the request,
    // request URL and the credentials of the logged in user
    Object retObj = utils.sendRequest(request, requestURL,

                                      username, password);

    // If the return Object is a String, format the
    // result String and return the formatted string
    if (retObj instanceof String ) {

      String res = (String) retObj;
      return formatResult(res);

    }

    if ( retObj == null ) {

      throw new CMSAccessException ( " The Database Servlet returned null  " );

    } else {


      throw new CMSAccessException ( " The Database Servlet returned " +
                                     " unknown object type " );
    }

  }

  /**
   * This method is called from the JSPs to check if resource path represents
   * a container (folder), else corrects the resource path and returns it.
   *
   * @param   request    HttpServletRequest
   * @param   abspath    Resource path
   * @param   username   username
   * @param   password   password
   *
   * @return  String     resource path

   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String checkAbspath(HttpServletRequest request, String abspath,
                             String username, String password)
      throws CMSAccessException {

    String  status         = "None";
    String  correctabspath = abspath;

    Connection     conn    = null;

    conn = JDBCQueryBean.getConnection(username, password);

    status = this.isValidAbsPath(abspath, conn);

    // The return status 'FALSE', indicates a file

    // Correct the abspath to the folder containing the file
    if ("FALSE".equals(status)) {

      StringTokenizer st     = new StringTokenizer(correctabspath, "/");
      String          temp   = "";
      int             count  = 0;
      int             len    = st.countTokens();

      // Get all the tokens in the input resource path separated by '/'
      while (st.hasMoreTokens()) {

        String midpath  = st.nextToken();

        count  += 1;

        if (count < len) {

          // Append all the tokens to the temp String, separated by '/'
          temp = temp + "/" + midpath;


        } else {

          // last token is the file name which is not required, hence
          // discard the last token and return the temp String value
          correctabspath = temp;
          break;

        }

      }

    }


    try {

      if ( conn  != null ) conn.close(); // close the connection

    } catch(SQLException ex) {


      throw new CMSAccessException (  "SQLException in checkabspath " +
                                      "while closing connection : "+
                                      ex.toString() );

    }


    return correctabspath;

  }

  /**
   * This method queries the PATH_VIEW and checks if the input resource path
   * refers to a folder or file.
   *
   * @param    abspath      Resource path
   * @param    connection   database connection object
   *
   * @return   String       If resource is a folder : 'TRUE'
   *                        If resource is a file   : 'FALSE'

   *                        Else                    : 'None'
   *
   * @exception  CMSAccessException  if any Exception occurs
   *
   */
  private String isValidAbsPath(String abspath, Connection conn)
      throws CMSAccessException {

    String retMessage = "None";
    PreparedStatement pstmt   = null;
    ResultSet         rset    = null;

    String  query =
      " SELECT UPPER(extractValue(res, '/Resource/@Container')) "+
      " FROM   XDB.path_view "+
      " WHERE  PATH = ? ";

    try {

      // Prepare the statement
      pstmt = conn.prepareStatement(query);


      // Bind the input parameter
      pstmt.setString(1, abspath);

      // Execute the query
      rset = pstmt.executeQuery();

      // Loop through the result set
      while (rset.next()) {
        retMessage = rset.getString(1);
      }

    } catch(SQLException ex) {

      throw new CMSAccessException (  "SQLException in isValidAbspath : " +
                                      ex.toString() );

    } finally {

      try {

        if ( pstmt != null )  pstmt.close(); // close the statement
        if ( conn  != null )   conn.close(); // close the connection


      } catch(SQLException ex) {

        throw new CMSAccessException (  "SQLException in isValidAbspath " +
                                        "while closing statements : "+
                                        ex.toString() );

      }

    }

    return retMessage;

  }


  /**
   * This method is called from the JSP to get the folder contents.
   * This method creates an instance of ServletUtils. The input request URL is
   * encoded and is appended to the Database Servlet URL to be invoked.
   * The sendRequest method in ServletUtils is called passing the request URL
   * and the request information to it.
   *
   * @param   request     HttpServletRequest
   * @param   requestURL  URL to connect to in ServletUtils

   * @param   username    username
   * @param   password    password
   *
   * @return  HashMap     HashMap object returned by the database servlet
   *                      containing the folder and file details
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public HashMap serveRequest(HttpServletRequest request, String abspath,
                              String username, String password)
      throws CMSAccessException {

    String        res   = "None";
    ServletUtils  utils = new ServletUtils();

    // Prepare the parameters list string to be passed to the database servlet
    StringBuffer params = null;
    String requestURL   = null;

    try {

      params = new StringBuffer()
                 .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                 .append("&username=").append(URLEncoder.encode(username, "UTF-8"))

                 .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                 .append("&ACTION=").append("FOLDERCONTENTS");

      // Append the above encoded URL to the Servlet URL
      requestURL = new StringBuffer( ConnParams.dbCMSServlet )
                             .append("?")
                             .append( URLEncoder.encode(params.toString(),
                                                        "UTF-8"))
                             .toString( );

    } catch (UnsupportedEncodingException usee) {

      throw new CMSAccessException ( " Exception while encoding " +
                                     " URL in serveRequest  " +
                                     usee.toString() );

    }

    // Call the sendRequest method in ServletUtils with the request,
    // request URL and the credentials of the logged in user
    Object retObj = utils.sendRequest(request, requestURL,
                                      username, password);


    // If the return Object is a hashMap, return it
    if (retObj instanceof HashMap ) {


      HashMap hm = (HashMap) retObj;
      return hm;

    }

    if ( retObj == null ) {

      throw new CMSAccessException ( " The Database Servlet returned null  " );

    } else {

      throw new CMSAccessException ( " The Database Servlet returned " +
                                     " unknown object type " );
    }

  }

  /**
   * This method is called from the JSP to get the contents of the input
   * resource path. This method creates an instance of ServletUtils.
   * The sendXDBServletRequest method in ServletUtils is called passing
   * the database Web URL and the request information to it.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path for which the contents is required
   * @param   username    username

   * @param   password    password
   *
   * @return  String      String containing the contents of the resource path
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String getContents(HttpServletRequest request, String abspath,
                            String username, String password)
      throws CMSAccessException {

    String        res   = "None";
    ServletUtils  utils = new ServletUtils();

    StringTokenizer st  = new StringTokenizer(abspath, "/");
    String  encodedURL  = "";

    while (st.hasMoreElements()) {
      // Encode all the tokens individually
      try {

        // Encode the request URL string into application/x-www-form-urlencoded
        // format using UTF-8 scheme
        String encodedstr = URLEncoder.encode(st.nextToken(), "UTF-8");

        encodedURL = encodedURL + "/" + encodedstr;

      } catch (UnsupportedEncodingException usee) {


        throw new CMSAccessException ( " Exception while encoding " +
                                       " URL in callServletUtils  " +
                                       usee.toString() );

      }

    }

    // Call the sendXDBServletRequest method in ServletUtils with the request,
    // Database Web URL and the credentials of the logged in user
    res = utils.sendXDBServletRequest(request, ConnParams.dbWebURL+encodedURL,
                                      username, password);

    return res;

  }


  /**
   * This method is called from the JSP to perform the version control
   * operations on the input resource path. The file version control
   * operations can be simulataneously requested for multiple files, hence
   * this method passes the action to ServletUtils for every file separately,
   * appends the return status along with the filename and finally returns the
   * status for all the files to the calling JSP.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path

   * @param   username    username
   * @param   password    password
   *
   * @return  String      String containing the status of the
   *                      version control operations
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String versionControl(HttpServletRequest request, String abspath,
                               String username, String password)
      throws CMSAccessException {

    // Since the JSP allows multiple files to be selected for
    // version control operations, get all the values
    String[]     verFiles   = request.getParameterValues("fileloc");
    String[]     allFiles   = request.getParameterValues("filename");

    // The operation can be one of 'MAKEVERSION', 'CHECKIN',
    // 'CHECKOUT' or 'UNDOCHECKOUT'
    String       operation  = request.getParameter("OPERATION");

    // Track the return status for each file version control request
    StringBuffer sb         = new StringBuffer();

    // Loop through all the files
    for (int i=0; i < verFiles.length; i++) {

      String filePath = verFiles[i];
      String fileName = allFiles[i];


      if (filePath != null && !filePath.equals("")) {

        // Prepare the parameters list string to be passed to the database servlet
        StringBuffer params = null;

        try {

          params = new StringBuffer()
                     .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                     .append("&username=").append(URLEncoder.encode(username, "UTF-8"))
                     .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                     .append("&filepath=").append(URLEncoder.encode(filePath, "UTF-8"))
                     .append("&ACTION=").append(operation);

        } catch (UnsupportedEncodingException usee) {

          throw new CMSAccessException ( " Exception while encoding " +
                                         " URL in versionControl  " +
                                         usee.toString() );

        }

        String res = this.callServletUtils(request, params.toString(),
                                           username, password);

        // Append the filename and the return status
        sb.append(fileName + " : " + res +"<BR>");

      }


    }

    return sb.toString();

  }

  /**
   * This method is called from the JSP to perform the delete operation on
   * one or more file/s or folder/s in the XML DB Repository.
   * This method passes the action to ServletUtils for every file separately,
   * appends the return status along with the filename and finally returns the
   * status for all the files to the calling JSP.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path
   * @param   username    username
   * @param   password    password
   *
   * @return  String      String containing the return status of the deletion
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String deleteResource(HttpServletRequest request, String abspath,
                               String username, String password)
      throws CMSAccessException {

    StringBuffer  sb         = new StringBuffer();
    StringBuffer  params     = null;
    String        operation  = request.getParameter("OPERATION");

    if (operation != null && operation.equals("DELETEFOLDER")) {


      // Get all the folder paths to be deleted
      String[] delFolders = request.getParameterValues("folderloc");

      // Loop through all the folder paths
      for (int i=0; i < delFolders.length; i++) {

        String deletePath = delFolders[i];

        if (deletePath != null && !deletePath.equals("")) {

          try {

            // Prepare the parameters list string
            // to be passed to the database servlet
            params = new StringBuffer()
                     .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                     .append("&username=").append(URLEncoder.encode(username, "UTF-8"))
                     .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                     .append("&deletepath=").append(URLEncoder.encode(deletePath, "UTF-8"))
                     .append("&ACTION=").append("DELETEFOLDER");

          } catch (UnsupportedEncodingException usee) {

            throw new CMSAccessException ( " Exception while encoding " +
                                           " URL in deleteResource  " +
                                           usee.toString() );

          }

          String res = this.callServletUtils(request, params.toString(),
                                             username, password);


          // Append the folder and the return status
          sb.append(deletePath + " : " + res +"<BR>");

        }
      }

    } else if (operation != null && operation.equals("DELETEFILE")) {

        // Get all the file paths to be deleted
        String[] delFiles = request.getParameterValues("fileloc");

        // Loop through all the file paths
        for (int i=0; i < delFiles.length; i++) {

          String deletePath = delFiles[i];

          if (deletePath != null && !deletePath.equals("")) {

            try {

              // Prepare the parameters list string
              // to be passed to the database servlet
              params = new StringBuffer()
                       .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                       .append("&username=").append(URLEncoder.encode(username, "UTF-8"))
                       .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                       .append("&deletepath=").append(URLEncoder.encode(deletePath, "UTF-8"))
                       .append("&ACTION=").append("DELETEFILE");

            } catch (UnsupportedEncodingException usee) {

              throw new CMSAccessException ( " Exception while encoding " +
                                             " URL in deleteResource  " +
                                             usee.toString() );


            }

            String res = this.callServletUtils(request, params.toString(),
                                               username, password);

            // Append the filename and the return status
            sb.append(deletePath + " : " + res +"<BR>");

          }
        }
    }

    return sb.toString();

  }

  /**
   * This method is called from the JSP to set the preference of the user.
   * This method passes the action to ServletUtils and returns the return
   * status from the database servlet.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path
   * @param   username    username
   * @param   password    password
   *
   * @return  String      String containing the return status
   *                      from the database servlet
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String changeView(HttpServletRequest request, String abspath,
                           String username, String password)

      throws CMSAccessException {

    String viewtype = request.getParameter("ViewType");
    String xslLoc   = request.getParameter("XSLLoc");
    String action   = request.getParameter("ACTION");

    // Prepare the parameters list string to be passed to the database servlet
    StringBuffer params = null;

    try {

      params = new StringBuffer()
                 .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                 .append("&username=").append(URLEncoder.encode(username, "UTF-8"))
                 .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                 .append("&viewtype=").append(URLEncoder.encode(viewtype, "UTF-8"))
                 .append("&xslloc=").append(URLEncoder.encode(xslLoc, "UTF-8"))
                 .append("&ACTION=").append(action);

    } catch (UnsupportedEncodingException usee) {

      throw new CMSAccessException ( " Exception while encoding " +
                                     " URL in changeView  " +
                                     usee.toString() );

    }

    String res = this.callServletUtils(request, params.toString(),
                                       username, password);

    return res;

  }

  /**
   * This method is called from the JSP to get the contents of the input

   * previous version of the input resource path. This method passes the
   * action to ServletUtils and returns back the return value from the
   * database servlet.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path
   * @param   username    username
   * @param   password    password
   * @param   version     version
   * @param   operation   operation
   *
   * @return  String      String containing the return value
   *                      from the database servlet
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String getPrevContents(HttpServletRequest request, String abspath,
                                String username, String password,
                                String version, String operation)
      throws CMSAccessException {

    // Prepare the parameters list string to be passed to the database servlet
    StringBuffer params = null;

    try {

      params = new StringBuffer()
                 .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                 .append("&username=").append(URLEncoder.encode(username, "UTF-8"))
                 .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                 .append("&version=").append(version)
                 .append("&ACTION=").append(operation);

    } catch (UnsupportedEncodingException usee) {

      throw new CMSAccessException ( " Exception while encoding " +

                                     " URL in getPrevContents  " +
                                     usee.toString() );

    }

    String res = this.callServletUtils(request, params.toString(),
                                       username, password);

    return res;

  }


  /**
   * This method is called from the JSP to create a new folder
   * at the input resource path. This method passes the action
   * to ServletUtils and returns the status returned from the
   * database servlet.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path
   * @param   username    username
   * @param   password    password
   * @param   name        name of the new folder
   *
   * @return  String      String containing the return status
   *                      from the database servlet
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String newFolder(HttpServletRequest request, String abspath,
                          String username, String password, String name)
      throws CMSAccessException {

    // Prepare the parameters list string to be passed to the database servlet
    StringBuffer params = null;


    try {

      params = new StringBuffer()
                 .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                 .append("&username=").append(URLEncoder.encode(username, "UTF-8"))
                 .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                 .append("&name=").append(URLEncoder.encode(name, "UTF-8"))
                 .append("&ACTION=").append("CREATEFOLDER");

    } catch (UnsupportedEncodingException usee) {

      throw new CMSAccessException ( " Exception while encoding " +
                                     " URL in newFolder  " +
                                     usee.toString() );

    }

    String res = this.callServletUtils(request, params.toString(),
                                       username, password);

    return res;

  }


  /**
   * This method is called from the JSP to rename a resource.
   * This method passes the action to ServletUtils and returns
   * the status returned from the database servlet.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path
   * @param   username    username
   * @param   password    password
   * @param   oldname     oldname of the resource
   * @param   newname     newname of the resource
   * @param   xslcheck    String indicating whether the resource is an
   *                      XSL file and to check if the XSL file is
   *                      set as a preference by some user

   *
   * @return  String      String containing the return status
   *                      from the database servlet
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String rename(HttpServletRequest request, String abspath,
                       String username, String password,
                       String oldname, String newname,
                       String xslcheck)
      throws CMSAccessException {

    // Prepare the parameters list string to be passed to the database servlet
    StringBuffer params = null;

    try {

      params = new StringBuffer()
                 .append("ABSPATH=").append(URLEncoder.encode(abspath, "UTF-8"))
                 .append("&username=").append(URLEncoder.encode(username, "UTF-8"))
                 .append("&password=").append(URLEncoder.encode(password, "UTF-8"))
                 .append("&oldname=").append(URLEncoder.encode(oldname, "UTF-8"))
                 .append("&newname=").append(URLEncoder.encode(newname, "UTF-8"))
                 .append("&xslcheck=").append(URLEncoder.encode(xslcheck, "UTF-8"))
                 .append("&ACTION=").append("RENAME");

    } catch (UnsupportedEncodingException usee) {

      throw new CMSAccessException ( " Exception while encoding " +
                                     " URL in rename  " +
                                     usee.toString() );

    }

    String res = this.callServletUtils(request, params.toString(),
                                       username, password);

    return res;


  }


  /**
   * This method is used to format the string value returned from the
   * database servlet depending on whether it is an exception message
   * or warning message.
   *
   * @param   res        String to be formatted
   *
   * @return  String     formatted string
   *
   */
  private String formatResult(String res) {

    String formatString = res;

    if (res.startsWith("<EXC>")) {

      String exceptionMessage = res.substring(5, res.indexOf("</EXC>"));
      formatString = "<font class=\"errhead\">" + exceptionMessage + "</font>";

    } else if (res.startsWith("<MSG>")) {

      String message = res.substring(5, res.indexOf("</MSG>"));
      formatString = "<font class=\"msgdata\">" + message + "</font>";

    }

    return formatString;

  }


  /**
   * This method is used to handle the creation of new resource
   * or updation of XML contents of existing resources.
   *
   * @param   request     HttpServletRequest
   * @param   abspath     Resource path
   * @param   username    username

   * @param   password    password
   * @param   action      'CREATERESOURCE' or 'UPDATERESOURCE'
   *
   * @return  String      status of the performed operation
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  public String resource(HttpServletRequest request, String abspath,
                         String username, String password, String action)
      throws CMSAccessException {

    String           retMessage = "Error in resource method of DataUtils";

    // Use FileUploadUtils, this value is true only if the input
    // content type is 'multipart/form-data'
    boolean          useFU      = false;

    // Handles the file upload requests
    FileUploadUtils  fu         = null;

    // Performs the resource creation or updation by calling
    // the corresponding PL/SQL packages

    // Get the content type
    String           content    = request.getHeader( "Content-Type" );

    Connection       conn       = null;

    // Get the connection object required to be passed to
    // FileUploadUtils for CLOB and BLOB content handling
    conn = JDBCQueryBean.getConnection(username, password);

    // If the content type indicates file upload
    if ( content != null && content.startsWith( "multipart/form-data" ) ) {

      useFU   = true; // Set flag

      // Instantiate FileUploadUtils with the request and connection
      fu = new FileUploadUtils(request, conn);

    }


    if (action.equals("CREATERESOURCE")) {

      try {

        String  filename  = "";
        String  file      = "";

        if (useFU) {

          // If the flag is set, get the filename value
          // from FileUploadUtils. File content will be either in the
          // CLOB or BLOB value in FileUploadUtils which can be obtained later
          filename = fu.getParameter("filename");

        } else {

          // If the flag is not set,
          // get the filename and file content from the request parameter
          filename = request.getParameter("filename");
          file     = request.getParameter("XMLFile");

        }

        if ( filename.length() <= 128 ) {
        // Continue processing if the file name is within 128 characters length

        boolean  xmldata    = false; // XML data indicator
        boolean  wellformed = true;  // Indicates whether data is wellformed

        if ( filename.toLowerCase().endsWith(".xml") ||
             filename.toLowerCase().endsWith(".xsl") ||
             filename.toLowerCase().endsWith(".xsd") ||
             filename.toLowerCase().endsWith(".rdf") ) {

          // If the file content is XML, the XML content needs to be parsed

          xmldata = true; // Set XML data indicator

          if (useFU) {

            // If the flag is set,
            // parse the CLOB content in FileUploadUtils

            wellformed = this.parseClob(fu.getClobVal());

          } else {

            // If the flag is not set, parse the
            // file content obtained from the request parameter
            wellformed = this.parseString(file);

          }

        }

        if (wellformed) {

          // If the parsing of XML content returns wellformed as true

          String  resource = abspath + "/" + filename;
          String  status   = "<EXC>Failed to create the resource</EXC>";

          if (xmldata) {

            // If the file content is XML

            if (useFU) {

              // If the flag is set, create the
              // resource with the CLOB content in FileUploadUtils
              status = JDBCQueryBean.createresource(conn, resource, abspath,
                                                    fu.getClobVal());

              String chksts = "<MSG>Resource created successfully</MSG>";

              if (chksts.equals(status)) {

                String allowversion = fu.getParameter("verctrl");

                if ("YES".equals(allowversion)) {

                  // If the resource is created successfully, and If the user
                  // requested for the resource to be version controlled,
                  // add the resource to version control by calling
                  // ServletUtils with action as 'MAKEVERSION'

                  // Prepare the parameters list string

                  // to be passed to the database servlet
                  StringBuffer params = null;

                  try {

                    params = new StringBuffer()
                               .append("ABSPATH=")
                               .append(URLEncoder.encode(abspath, "UTF-8"))
                               .append("&username=")
                               .append(URLEncoder.encode(username, "UTF-8"))
                               .append("&password=")
                               .append(URLEncoder.encode(password, "UTF-8"))
                               .append("&filepath=")
                               .append(URLEncoder.encode(resource, "UTF-8"))
                               .append("&ACTION=").append("MAKEVERSION");

                  } catch (UnsupportedEncodingException usee) {

                    throw new CMSAccessException ( " Exception while encoding " +
                                                   " URL in resource  " +
                                                   usee.toString() );

                  }

                  String tempstr = this.callServletUtils(request,
                                                         params.toString(),
                                                         username, password);

                  // Append the status to the resource creation status
                  status = this.formatResult(status) + "<BR>" + tempstr;

                }

              }

            } else {

              // If the flag is not set, create the
              // resource with the file content from the request parameter
              status = JDBCQueryBean.createresource(conn, resource,
                                                    abspath, file);

            }

          } else {


            // If the file content is not XML

            if (useFU) {

              // If the flag is set, create the
              // resource with the BLOB content in FileUploadUtils
              status = JDBCQueryBean.createresource(conn, resource, abspath,
                                                    fu.getBlobVal());

              String chksts = "<MSG>Resource created successfully</MSG>";

              if (chksts.equals(status)) {

                String allowversion = fu.getParameter("verctrl");

                if ("YES".equals(allowversion)) {

                  // If the resource is created successfully, and If the user
                  // requested for the resource to be version controlled,
                  // add the resource to version control by calling
                  // ServletUtils with action as 'MAKEVERSION'

                  // Prepare the parameters list string
                  // to be passed to the database servlet
                  StringBuffer params = null;

                  try {

                    params = new StringBuffer()
                               .append("ABSPATH=")
                               .append(URLEncoder.encode(abspath, "UTF-8"))
                               .append("&username=")
                               .append(URLEncoder.encode(username, "UTF-8"))
                               .append("&password=")
                               .append(URLEncoder.encode(password, "UTF-8"))
                               .append("&filepath=")
                               .append(URLEncoder.encode(resource, "UTF-8"))
                               .append("&ACTION=").append("MAKEVERSION");

                  } catch (UnsupportedEncodingException usee) {

                    throw new CMSAccessException ( " Exception while encoding " +
                                                   " URL in resource  " +
                                                   usee.toString() );


                  }

                  String tempstr = this.callServletUtils(request,
                                                         params.toString(),
                                                         username, password);

                  // Append the status to the resource creation status
                  status = this.formatResult(status) + "<BR>" + tempstr;

                }

              }

            } else {

              // If the flag is not set, create the
              // resource with the file content from the request parameter
              status = JDBCQueryBean.createresource(conn, resource,
                                                    abspath, file);

            }

          }

          retMessage = this.formatResult(status);

        } else {

          // If the parsing of XML content returns wellformed as false

          retMessage = this.formatResult("<EXC>The XML is not wellformed</EXC>");

        }

        } else {

          retMessage = this.formatResult("<EXC>File Name length exceeds" +
                                             " 128 characters</EXC>");

        }

      } catch (SQLException sqlex) {

        throw new CMSAccessException (  "SQLException in createresource "+
                                        "in resource method of DataUtils : " +
                                        sqlex.toString() );


      }

    } else if (action.equals("UPDATERESOURCE")) {

      try {

        String   file        = (String)request.getParameter("XMLFile");

        // Only XML resources can be updated, hence
        // parse all request parameter file content
        boolean  wellformed  = this.parseString(file);

        if (wellformed) {

          // If the parsing of XML content returns wellformed as true

          // Update the resource and get the status
          String status = JDBCQueryBean.updateresource(conn, abspath, file);

          retMessage = this.formatResult(status);

        } else {

          // If the parsing of XML content returns wellformed as false

          retMessage = this.formatResult("<EXC>The XML is not wellformed</EXC>");

        }

      } catch (SQLException sqlex) {

        throw new CMSAccessException (  "SQLException in updateresource "+
                                        "in resource method of DataUtils : " +
                                        sqlex.toString() );

      }

    }


    try {

      if ( conn != null ) conn.close();

    } catch (SQLException sqlex) {

      throw new CMSAccessException (  "SQLException while closing connection "+
                                      "in resource method of DataUtils : " +

                                      sqlex.toString() );

    }

    return retMessage;

  }


  /**
   * This method is used to parse the input string.
   *
   * @param   xmlStr     XML String
   *
   * @return  boolean    indicates whether the XML is wellformed or not
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  private boolean parseString(String xmlStr)
      throws CMSAccessException {

    // Initialize SAX Parser
    SAXParser sp         = new SAXParser();

    boolean   parsedwell = false;

    sp.setValidationMode(XMLParser.NONVALIDATING);
    sp.setPreserveWhitespace(true);

    try {

      // Parse the file through the Reader instance
      StringReader input = new StringReader(xmlStr);
      sp.parse(input);
      parsedwell = true;

    } catch (IOException ioe) {

      parsedwell = false;

      throw new CMSAccessException (  "IOException in parseString : " +
                                      ioe.toString() );

    } catch (XMLParseException xpe) {

      parsedwell = false;

    } catch (org.xml.sax.SAXException ex) {


      parsedwell = false;

      throw new CMSAccessException (  "SAXException in parseString : " +
                                      ex.toString() );

    } catch (Exception ex) {

      parsedwell = false;

      throw new CMSAccessException (  "Generic Exception in parseString : " +
                                      ex.toString() );

    }

    return parsedwell;

  }


  /**
   * This method is used to parse the input CLOB.
   *
   * @param   clobdata     CLOB data
   *
   * @return  boolean      indicates whether the CLOB data is wellformed or not
   *
   * @exception  CMSAccessException  if any error or exception occurs
   *
   */
  private boolean parseClob(CLOB clobdata)
      throws CMSAccessException {

    // Initialize SAX Parser
    SAXParser sp         =