Search in sources :

Example 1 with ConnectionInfo

use of org.h2.engine.ConnectionInfo in project traccar by tananaev.

the class ConsoleServlet method init.

@Override
public void init() {
    super.init();
    try {
        Field field = WebServlet.class.getDeclaredField("server");
        field.setAccessible(true);
        org.h2.server.web.WebServer server = (org.h2.server.web.WebServer) field.get(this);
        ConnectionInfo connectionInfo = new ConnectionInfo("Traccar|" + Context.getConfig().getString("database.driver") + "|" + Context.getConfig().getString("database.url") + "|" + Context.getConfig().getString("database.user"));
        Method method;
        method = org.h2.server.web.WebServer.class.getDeclaredMethod("updateSetting", ConnectionInfo.class);
        method.setAccessible(true);
        method.invoke(server, connectionInfo);
        method = org.h2.server.web.WebServer.class.getDeclaredMethod("setAllowOthers", boolean.class);
        method.setAccessible(true);
        method.invoke(server, true);
    } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        Log.warning(e);
    }
}
Also used : Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) Field(java.lang.reflect.Field) ConnectionInfo(org.h2.server.web.ConnectionInfo)

Example 2 with ConnectionInfo

use of org.h2.engine.ConnectionInfo in project h2database by h2database.

the class Engine method createSessionAndValidate.

private Session createSessionAndValidate(ConnectionInfo ci) {
    try {
        ConnectionInfo backup = null;
        String lockMethodName = ci.getProperty("FILE_LOCK", null);
        FileLockMethod fileLockMethod = FileLock.getFileLockMethod(lockMethodName);
        if (fileLockMethod == FileLockMethod.SERIALIZED) {
            // In serialized mode, database instance sharing is not possible
            ci.setProperty("OPEN_NEW", "TRUE");
            try {
                backup = ci.clone();
            } catch (CloneNotSupportedException e) {
                throw DbException.convert(e);
            }
        }
        Session session = openSession(ci);
        validateUserAndPassword(true);
        if (backup != null) {
            session.setConnectionInfo(backup);
        }
        return session;
    } catch (DbException e) {
        if (e.getErrorCode() == ErrorCode.WRONG_USER_OR_PASSWORD) {
            validateUserAndPassword(false);
        }
        throw e;
    }
}
Also used : FileLockMethod(org.h2.store.FileLockMethod) DbException(org.h2.message.DbException)

Example 3 with ConnectionInfo

use of org.h2.engine.ConnectionInfo in project h2database by h2database.

the class SessionRemote method connectServer.

private void connectServer(ConnectionInfo ci) {
    String name = ci.getName();
    if (name.startsWith("//")) {
        name = name.substring("//".length());
    }
    int idx = name.indexOf('/');
    if (idx < 0) {
        throw ci.getFormatException();
    }
    databaseName = name.substring(idx + 1);
    String server = name.substring(0, idx);
    traceSystem = new TraceSystem(null);
    String traceLevelFile = ci.getProperty(SetTypes.TRACE_LEVEL_FILE, null);
    if (traceLevelFile != null) {
        int level = Integer.parseInt(traceLevelFile);
        String prefix = getFilePrefix(SysProperties.CLIENT_TRACE_DIRECTORY);
        try {
            traceSystem.setLevelFile(level);
            if (level > 0 && level < 4) {
                String file = FileUtils.createTempFile(prefix, Constants.SUFFIX_TRACE_FILE, false, false);
                traceSystem.setFileName(file);
            }
        } catch (IOException e) {
            throw DbException.convertIOException(e, prefix);
        }
    }
    String traceLevelSystemOut = ci.getProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT, null);
    if (traceLevelSystemOut != null) {
        int level = Integer.parseInt(traceLevelSystemOut);
        traceSystem.setLevelSystemOut(level);
    }
    trace = traceSystem.getTrace(Trace.JDBC);
    String serverList = null;
    if (server.indexOf(',') >= 0) {
        serverList = StringUtils.quoteStringSQL(server);
        ci.setProperty("CLUSTER", Constants.CLUSTERING_ENABLED);
    }
    autoReconnect = ci.getProperty("AUTO_RECONNECT", false);
    // AUTO_SERVER implies AUTO_RECONNECT
    boolean autoServer = ci.getProperty("AUTO_SERVER", false);
    if (autoServer && serverList != null) {
        throw DbException.getUnsupportedException("autoServer && serverList != null");
    }
    autoReconnect |= autoServer;
    if (autoReconnect) {
        String className = ci.getProperty("DATABASE_EVENT_LISTENER");
        if (className != null) {
            className = StringUtils.trim(className, true, true, "'");
            try {
                eventListener = (DatabaseEventListener) JdbcUtils.loadUserClass(className).newInstance();
            } catch (Throwable e) {
                throw DbException.convert(e);
            }
        }
    }
    cipher = ci.getProperty("CIPHER");
    if (cipher != null) {
        fileEncryptionKey = MathUtils.secureRandomBytes(32);
    }
    String[] servers = StringUtils.arraySplit(server, ',', true);
    int len = servers.length;
    transferList.clear();
    sessionId = StringUtils.convertBytesToHex(MathUtils.secureRandomBytes(32));
    // TODO cluster: support more than 2 connections
    boolean switchOffCluster = false;
    try {
        for (String s : servers) {
            try {
                Transfer trans = initTransfer(ci, databaseName, s);
                transferList.add(trans);
            } catch (IOException e) {
                if (len == 1) {
                    throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, e, e + ": " + s);
                }
                switchOffCluster = true;
            }
        }
        checkClosed();
        if (switchOffCluster) {
            switchOffCluster();
        }
        checkClusterDisableAutoCommit(serverList);
    } catch (DbException e) {
        traceSystem.close();
        throw e;
    }
}
Also used : Transfer(org.h2.value.Transfer) IOException(java.io.IOException) TraceSystem(org.h2.message.TraceSystem) DbException(org.h2.message.DbException)

Example 4 with ConnectionInfo

use of org.h2.engine.ConnectionInfo in project h2database by h2database.

the class TcpServerThread method run.

@Override
public void run() {
    try {
        transfer.init();
        trace("Connect");
        // and a list of allowed clients
        try {
            Socket socket = transfer.getSocket();
            if (socket == null) {
                // the transfer is already closed, prevent NPE in TcpServer#allow(Socket)
                return;
            }
            if (!server.allow(transfer.getSocket())) {
                throw DbException.get(ErrorCode.REMOTE_CONNECTION_NOT_ALLOWED);
            }
            int minClientVersion = transfer.readInt();
            int maxClientVersion = transfer.readInt();
            if (maxClientVersion < Constants.TCP_PROTOCOL_VERSION_MIN_SUPPORTED) {
                throw DbException.get(ErrorCode.DRIVER_VERSION_ERROR_2, "" + clientVersion, "" + Constants.TCP_PROTOCOL_VERSION_MIN_SUPPORTED);
            } else if (minClientVersion > Constants.TCP_PROTOCOL_VERSION_MAX_SUPPORTED) {
                throw DbException.get(ErrorCode.DRIVER_VERSION_ERROR_2, "" + clientVersion, "" + Constants.TCP_PROTOCOL_VERSION_MAX_SUPPORTED);
            }
            if (maxClientVersion >= Constants.TCP_PROTOCOL_VERSION_MAX_SUPPORTED) {
                clientVersion = Constants.TCP_PROTOCOL_VERSION_MAX_SUPPORTED;
            } else {
                clientVersion = maxClientVersion;
            }
            transfer.setVersion(clientVersion);
            String db = transfer.readString();
            String originalURL = transfer.readString();
            if (db == null && originalURL == null) {
                String targetSessionId = transfer.readString();
                int command = transfer.readInt();
                stop = true;
                if (command == SessionRemote.SESSION_CANCEL_STATEMENT) {
                    // cancel a running statement
                    int statementId = transfer.readInt();
                    server.cancelStatement(targetSessionId, statementId);
                } else if (command == SessionRemote.SESSION_CHECK_KEY) {
                    // check if this is the correct server
                    db = server.checkKeyAndGetDatabaseName(targetSessionId);
                    if (!targetSessionId.equals(db)) {
                        transfer.writeInt(SessionRemote.STATUS_OK);
                    } else {
                        transfer.writeInt(SessionRemote.STATUS_ERROR);
                    }
                }
            }
            String baseDir = server.getBaseDir();
            if (baseDir == null) {
                baseDir = SysProperties.getBaseDir();
            }
            db = server.checkKeyAndGetDatabaseName(db);
            ConnectionInfo ci = new ConnectionInfo(db);
            ci.setOriginalURL(originalURL);
            ci.setUserName(transfer.readString());
            ci.setUserPasswordHash(transfer.readBytes());
            ci.setFilePasswordHash(transfer.readBytes());
            int len = transfer.readInt();
            for (int i = 0; i < len; i++) {
                ci.setProperty(transfer.readString(), transfer.readString());
            }
            // override client's requested properties with server settings
            if (baseDir != null) {
                ci.setBaseDir(baseDir);
            }
            if (server.getIfExists()) {
                ci.setProperty("IFEXISTS", "TRUE");
            }
            transfer.writeInt(SessionRemote.STATUS_OK);
            transfer.writeInt(clientVersion);
            transfer.flush();
            if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_13) {
                if (ci.getFilePasswordHash() != null) {
                    ci.setFileEncryptionKey(transfer.readBytes());
                }
            }
            session = Engine.getInstance().createSession(ci);
            transfer.setSession(session);
            server.addConnection(threadId, originalURL, ci.getUserName());
            trace("Connected");
        } catch (Throwable e) {
            sendError(e);
            stop = true;
        }
        while (!stop) {
            try {
                process();
            } catch (Throwable e) {
                sendError(e);
            }
        }
        trace("Disconnect");
    } catch (Throwable e) {
        server.traceError(e);
    } finally {
        close();
    }
}
Also used : ConnectionInfo(org.h2.engine.ConnectionInfo) Socket(java.net.Socket)

Example 5 with ConnectionInfo

use of org.h2.engine.ConnectionInfo in project h2database by h2database.

the class WebServer method saveProperties.

/**
 * Save the settings to the properties file.
 *
 * @param prop null or the properties webPort, webAllowOthers, and webSSL
 */
synchronized void saveProperties(Properties prop) {
    try {
        if (prop == null) {
            Properties old = loadProperties();
            prop = new SortedProperties();
            prop.setProperty("webPort", "" + SortedProperties.getIntProperty(old, "webPort", port));
            prop.setProperty("webAllowOthers", "" + SortedProperties.getBooleanProperty(old, "webAllowOthers", allowOthers));
            prop.setProperty("webSSL", "" + SortedProperties.getBooleanProperty(old, "webSSL", ssl));
            if (commandHistoryString != null) {
                prop.setProperty(COMMAND_HISTORY, commandHistoryString);
            }
        }
        ArrayList<ConnectionInfo> settings = getSettings();
        int len = settings.size();
        for (int i = 0; i < len; i++) {
            ConnectionInfo info = settings.get(i);
            if (info != null) {
                prop.setProperty(String.valueOf(len - i - 1), info.getString());
            }
        }
        if (!"null".equals(serverPropertiesDir)) {
            OutputStream out = FileUtils.newOutputStream(serverPropertiesDir + "/" + Constants.SERVER_PROPERTIES_NAME, false);
            prop.store(out, "H2 Server Properties");
            out.close();
        }
    } catch (Exception e) {
        DbException.traceThrowable(e);
    }
}
Also used : OutputStream(java.io.OutputStream) SortedProperties(org.h2.util.SortedProperties) SysProperties(org.h2.engine.SysProperties) Properties(java.util.Properties) SortedProperties(org.h2.util.SortedProperties) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) IOException(java.io.IOException)

Aggregations

DbException (org.h2.message.DbException)10 ConnectionInfo (org.h2.engine.ConnectionInfo)9 Properties (java.util.Properties)8 IOException (java.io.IOException)5 SQLException (java.sql.SQLException)5 Database (org.h2.engine.Database)4 Session (org.h2.engine.Session)4 SysProperties (org.h2.engine.SysProperties)4 ConnectionInfo (org.h2.server.web.ConnectionInfo)3 SortedProperties (org.h2.util.SortedProperties)3 File (java.io.File)2 Field (java.lang.reflect.Field)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 Socket (java.net.Socket)2 JdbcConnection (org.h2.jdbc.JdbcConnection)2 Transfer (org.h2.value.Transfer)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 DataInputStream (java.io.DataInputStream)1 EOFException (java.io.EOFException)1