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

📄 server.java

📁 hsql是很有名的嵌入式数据库
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
            if (dbAlias[i] == null) {                continue;            }            printWithThread("Opening database: [" + dbType[i] + dbPath[i]                            + "]");            StopWatch sw = new StopWatch();            int       id;            try {                id = DatabaseManager.getDatabase(dbType[i], dbPath[i], this,                                                 dbProps[i]);                dbID[i] = id;                success = true;            } catch (HsqlException e) {                printError("Database [index=" + i + "db=" + dbType[i]                           + dbPath[i] + ", alias=" + dbAlias[i]                           + "] did not open: " + e.toString());                setServerError(e);                dbAlias[i] = null;                dbPath[i]  = null;                dbType[i]  = null;                dbProps[i] = null;                continue;            }            sw.stop();            String msg = "Database [index=" + i + ", id=" + id + ", " + "db="                         + dbType[i] + dbPath[i] + ", alias=" + dbAlias[i]                         + "] opened sucessfully";            print(sw.elapsedTimeToMessage(msg));        }        printWithThread("openDatabases() exiting");        if (!success && getServerError() == null) {            // database alias / path list is empty or without full info for any DB            setServerError(Trace.error(Trace.SERVER_NO_DATABASE));        }        return success;    }    /**     * Initialises the database attributes lists from the server properties object.     */    private void setDBInfoArrays() {        dbAlias = getDBNameArray();        dbPath  = new String[dbAlias.length];        dbType  = new String[dbAlias.length];        dbID    = new int[dbAlias.length];        dbProps = new HsqlProperties[dbAlias.length];        for (int i = 0; i < dbAlias.length; i++) {            if (dbAlias[i] == null) {                continue;            }            String path = getDatabasePath(i, true);            if (path == null) {                dbAlias[i] = null;                continue;            }            HsqlProperties dbURL = DatabaseURL.parseURL(path, false);            if (dbURL == null) {                dbAlias[i] = null;                continue;            }            dbPath[i]  = dbURL.getProperty("database");            dbType[i]  = dbURL.getProperty("connection_type");            dbProps[i] = dbURL;        }    }    /**     * Returns a possibly sparse array of all server.dbname.n values     * from the properties object.     */    private String[] getDBNameArray() {        final String prefix    = ServerConstants.SC_KEY_DBNAME + ".";        final int    prefixLen = prefix.length();        String[]     dblist    = new String[10];        int          maxindex  = 0;        try {            Enumeration en = serverProperties.propertyNames();            for (; en.hasMoreElements(); ) {                String key = (String) en.nextElement();                if (!key.startsWith(prefix)) {                    continue;                }                try {                    int dbnum = Integer.parseInt(key.substring(prefixLen));                    maxindex = dbnum < maxindex ? maxindex                                                : dbnum;                    dblist[dbnum] =                        serverProperties.getProperty(key).toLowerCase();                } catch (NumberFormatException e1) {                    printWithThread("dblist: " + e1.toString());                }            }        } catch (ArrayIndexOutOfBoundsException e2) {            printWithThread("dblist: " + e2.toString());        }        return (String[]) ArrayUtil.resizeArray(dblist, maxindex + 1);    }    /**     * Constructs and installs a new ServerSocket instance for this server.     *     * @throws Exception if it is not possible to construct and install     *      a new ServerSocket     */    private void openServerSocket() throws Exception {        String    address;        int       port;        String[]  candidateAddrs;        String    emsg;        StopWatch sw;        printWithThread("openServerSocket() entered");        if (isTls()) {            printWithThread("Requesting TLS/SSL-encrypted JDBC");        }        sw            = new StopWatch();        socketFactory = HsqlSocketFactory.getInstance(isTls());        address       = getAddress();        port          = getPort();        if (org.hsqldb.lib.StringUtil.isEmpty(address)                || ServerConstants.SC_DEFAULT_ADDRESS.equalsIgnoreCase(                    address.trim())) {            socket = socketFactory.createServerSocket(port);        } else {            try {                socket = socketFactory.createServerSocket(port, address);            } catch (UnknownHostException e) {                candidateAddrs =                    ServerConfiguration.listLocalInetAddressNames();                int      messageID;                Object[] messageParameters;                if (candidateAddrs.length > 0) {                    messageID         = Trace.Server_openServerSocket;                    messageParameters = new Object[] {                        address, candidateAddrs                    };                } else {                    messageID         = Trace.Server_openServerSocket2;                    messageParameters = new Object[]{ address };                }                throw new UnknownHostException(Trace.getMessage(messageID,                        true, messageParameters));            }        }        /*         * Following line necessary for Java 1.3 on UNIX.  See accept()         * comment elsewhere in this file.         */        socket.setSoTimeout(1000);        printWithThread("Got server socket: " + socket);        print(sw.elapsedTimeToMessage("Server socket opened successfully"));        if (socketFactory.isSecure()) {            print("Using TLS/SSL-encrypted JDBC");        }        printWithThread("openServerSocket() exiting");    }    /** Prints a timestamped message indicating that this server is online */    private void printServerOnlineMessage() {        String s = getProductName() + " " + getProductVersion()                   + " is online";        printWithTimestamp(s);        printResource("online.help");    }    /**     * Prints a description of the server properties iff !isSilent().     */    protected void printProperties() {        Enumeration e;        String      key;        String      value;        // Avoid the waste of generating each description,        // only for trace() to silently discard it        if (isSilent()) {            return;        }        e = serverProperties.propertyNames();        while (e.hasMoreElements()) {            key   = (String) e.nextElement();            value = serverProperties.getProperty(key);            printWithThread(key + "=" + value);        }    }    /**     * Puts this server into the SERVER_CLOSING state, closes the ServerSocket     * and nullifies the reference to it. If the ServerSocket is already null,     * this method exists immediately, otherwise, the result is to fully     * shut down the server.     */    private void releaseServerSocket() {        printWithThread("releaseServerSocket() entered");        if (socket != null) {            printWithThread("Releasing server socket: [" + socket + "]");            setState(ServerConstants.SERVER_STATE_CLOSING);            try {                socket.close();            } catch (IOException e) {                printError("Exception closing server socket");                printError("releaseServerSocket(): " + e);            }            socket = null;        }        printWithThread("releaseServerSocket() exited");    }    /**     * Attempts to bring this server fully online by opening     * a new ServerSocket, obtaining the hosted databases,     * notifying the status waiter thread (if any) and     * finally entering the listen loop if all else succeeds.     * If any part of the process fails, then this server enters     * its shutdown sequence.     */    private void run() {        StopWatch   sw;        ThreadGroup tg;        String      tgName;        printWithThread("run() entered");        print("Initiating startup sequence...");        printProperties();        sw = new StopWatch();        setServerError(null);        try {            // Faster init first:            // It is huge waste to fully open the databases, only            // to find that the socket address is already in use            openServerSocket();        } catch (Exception e) {            setServerError(e);            printError("run()/openServerSocket(): ");            printStackTrace(e);            shutdown(true);            return;        }        tgName = "HSQLDB Connections @"                 + Integer.toString(this.hashCode(), 16);        tg = new ThreadGroup(tgName);        tg.setDaemon(false);        serverConnectionThreadGroup = tg;        // Mount the databases this server is supposed to host.        // This may take some time if the databases are not all        // already open.        if (openDatabases() == false) {            setServerError(null);            printError("run()/openDatabases(): ");            shutdown(true);            return;        }        // At this point, we have a valid server socket and        // a valid hosted database set, so its OK to start        // listening for connections.        setState(ServerConstants.SERVER_STATE_ONLINE);        print(sw.elapsedTimeToMessage("Startup sequence completed"));        printServerOnlineMessage();        try {            /*             * This loop is necessary for UNIX w/ Sun Java 1.3 because             * in that case the socket.close() elsewhere will not             * interrupt this accept().             */            while (true) {                try {                    handleConnection(socket.accept());                } catch (java.io.InterruptedIOException iioe) {}            }        } catch (IOException ioe) {            if (getState() == ServerConstants.SERVER_STATE_ONLINE) {                setServerError(ioe);                printError(this + ".run()/handleConnection(): ");                printStackTrace(ioe);            }        } catch (Throwable t) {            printWithThread(t.toString());        } finally {            shutdown(false);    // or maybe getServerError() != null?        }    }    /**     * Sets this Server's last encountered error state.     *     * @param t The new value for the server error     */    protected void setServerError(Throwable t) {        serverError = t;    }    /**     * External method to shut down this server.     */    public void shutdown() {        shutdown(false);    }    /**     * Shuts down this server.     *     * @param error true if shutdown is in response to an error     *      state, else false     */    protected void shutdown(boolean error) {        StopWatch sw;        printWithThread("shutdown() entered");        sw = new StopWatch();        print("Initiating shutdown sequence...");        releaseServerSocket();        DatabaseManager.deRegisterServer(this);        if (dbPath != null) {            for (int i = 0; i < dbPath.length; i++) {                releaseDatabase(i);            }        }        // Be nice and let applications exit if there are no        // running connection threads        if (serverConnectionThreadGroup != null) {            if (!serverConnectionThreadGroup.isDestroyed()) {                for (int i = 0; serverConnectionThreadGroup.activeCount() > 0;                        i++) {                    int count;                    try {                        Thread.sleep(100);                    } catch (Exception e) {                        // e.getMessage();                    }                }                try {                    serverConnectionThreadGroup.destroy();                    printWithThread(serverConnectionThreadGroup.getName()                                    + " destroyed");                } catch (Throwable t) {                    printWithThread(serverConnectionThreadGroup.getName()                                    + " not destroyed");                    printWithThread(t.toString());                }            }            serverConnectionThreadGroup = null;        }        serverThread =

⌨️ 快捷键说明

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