⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 databasehelper.java

📁 Sun公司Dream项目
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the "License").  You may not use this file except
 * in compliance with the License.
 *
 * You can obtain a copy of the license at
 * http://www.opensource.org/licenses/cddl1.php
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * HEADER in each file and include the License file at
 * http://www.opensource.org/licenses/cddl1.php.  If 
 * applicable, add the following below this CDDL HEADER, 
 * with the fields enclosed by brackets "[]" replaced 
 * with your own identifying information: 
 * Portions Copyright [yyyy]
 * [name of copyright owner]
 */ 

/*
 * $(@)DatabaseHelper.java $Revision: 1.3 $ $Date: 2006/07/24 17:00:52 $
 * 
 * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
 */
package com.sun.licenseserver;



import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Properties;

import java.util.logging.Logger;



import javax.servlet.ServletContext;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;



import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;





/**

 * The singelton class that encapsulates the JDBC code

 * required to execute SQL statements. To use this class

 * one needs to call the init(...) method that will be used 

 * to initialize the JDBC properties (jdbc driver, url, username and password).

 * The class also checks whether the sunLsLicenses table exists in the database

 * and creates it if it does not exists.

 * 

 * 

 */

public class DatabaseHelper {

    

    /**

     * This is a singleton class and therefore a private constructor.

     */

    private DatabaseHelper() {

    }

    

    /**

     * 

     * This is a singleton class and therefore a private constructor.

     * @param The servlet context used to get a handle to the configuration file.

     */

    private DatabaseHelper(ServletContext sc) {

        m_log.finer("Entering Function...");

        String    confFile = "/WEB-INF/conf/license-server.xml";

        URL       confFileURL = null;

    	try {

	    	confFileURL = sc.getResource(confFile);

	    } catch (MalformedURLException e1) { 

            m_log.severe("License Server configuration file does not exists..");

		    m_initError = true;

		    e1.printStackTrace();

    	}

	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        DocumentBuilder        db  = null;

        Document               doc = null;

        try {

            db = dbf.newDocumentBuilder();

            doc = db.parse(confFileURL.openStream());

	    } catch (SAXException e2) {

           m_log.severe("Error in Parsing License Server Configuration File..");

	       e2.printStackTrace();

           m_initError = true;

	    } catch (IOException e2) {

           m_log.severe("Error in Parsing License Server Configuration File..");

           m_log.severe("Probably the file /WEB-INF/conf/license-server.xml does not exists");

           e2.printStackTrace();

           m_initError = true;

        } catch (ParserConfigurationException e) {

            m_log.severe("Error in Parsing License Server Configuration File..");

            e.printStackTrace();

            m_initError = true;

        }

        initializeProperties(doc);

        loadJDBCDriver();

        createTable();

        m_log.finer("Leaving Function...");

    }

    

    /**

     * 

     * This is a singleton class and therefore a private constructor.

     * @param The servlet context used to get a handle to the configuration file.

     */

    private DatabaseHelper(Document doc) {

        m_log.finer("Entering Function...");

        initializeProperties(doc);

        loadJDBCDriver();

        createTable();

        m_log.finer("Leaving Function...");

    }

    

    /**

     * One of the init functions should be called

     * before the database helper object can be used.

     * This init will be called from jsp pages.

     * 

     * @param sc

     * @return

     */

    public static DatabaseHelper init(ServletContext sc) {

        m_log.finer("Entering Function...");

        if (m_databaseHelper != null) {

           m_log.fine("No need to init. an instance already exists");

           return m_databaseHelper;     

        }

        m_log.fine("Creating a new instance");

        m_databaseHelper = new DatabaseHelper(sc);

        m_log.finer("Leaving Function...");

        return m_databaseHelper;

    }

    

    /**

     * One of the init functions should be called

     * before the database helper object can be used.

     * This init will be called by the LicenseServer servlet 

     * that needs to access some conf values.

     * 

     * @param doc

     * @return

     */

    public static DatabaseHelper init(Document doc) {

        m_log.finer("Entering Function...");

        if (m_databaseHelper != null) {

           m_log.fine("No need to init. an instance already exists");

           return m_databaseHelper;     

        }

        m_log.fine("Creating a new instance");

        m_databaseHelper = new DatabaseHelper(doc);

        m_log.finer("Leaving Function...");

        return m_databaseHelper;

    }

    

    /**

     * This class checks for the existence of the tables required for this

     * project and creates them if they do not exist.

     * 

     *

     */

    public void createTable() {

        if (m_initError) {

            m_log.severe("Databasehelper has not been initialized. Skipping table creation..");

            return;

        }

        

        try {

            if (!hasTable("sunLsLicenses")) {

                String sql = "CREATE TABLE sunLsLicenses ("

                             + "id varchar(20),"

                             + "contentId varchar(40), "

                             + "shopId varchar(40),"

                             + "userId varchar(40),"

                             + "license BLOB, " 

                             + "mime varchar(40)"

                             + ")";

                executeStatementWithoutResults(sql);

            }

        } catch (LicenseServerException e) {

            m_log.severe("Error in creating sunLsLicense table, or checking for its existense");

            m_initError = true;

            e.printStackTrace();

        }

        

    }

    

    /**

     * Open a connection to jdbc URL specified in configuration file.

     */

    public Connection getConnection() 

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        Properties  p = new Properties();

        Connection  con = null;

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

            p.put("user", m_databaseUser);

        }

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

            m_log.fine("Using Password");

            p.put("password", m_databasePassword);

        }

        m_log.fine("Using JDBC URL [" + m_databaseURL + "]");

        m_log.fine("Using JDBC Driver [" + m_databaseDriver + "]"); 

        m_log.fine("Connecting to database with user [" + m_databaseUser + "]");

        try {

	        con = DriverManager.getConnection(m_databaseURL, p);

	    } catch (SQLException e) {

	        m_log.severe("Error in establishing a connection to the database [" + e.getMessage() + "]");

            e.printStackTrace();

            if (con != null) {

               try {

				con.close();

			   } catch (SQLException e1) {

				   // TODO Auto-generated catch block

				   e1.printStackTrace();

                   throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                            "Error in getting a connection to DB and closing the partial connection" + e.getMessage());

			   }   

            }

            throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                    "Error in getting a connection to DB" + e.getMessage()); 

	    }

        m_log.finer("Leaving Function...");

        return con;

     }

    

    /**

     * Release the jdbc connection.

     * @param Connection object to be released

     */

    public void freeConnection(Connection con) 

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        if (con == null) {

        	return;

        }

        try {

			con.close();

		} catch (SQLException e) {

            m_log.severe("Error in closing a connection [" + e.getMessage() + "]");

		    throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                    "Error in frreing connection" + e.getMessage()); 

		}   

        m_log.finer("Leaving Function...");

    }



    /**

     * load JDBC driver specified in Configuration file.

     */

    private void loadJDBCDriver() {

        m_log.finer("Entering Function...");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -