Search in sources :

Example 6 with Trace

use of org.h2.message.Trace in project h2database by h2database.

the class WebThread method process.

@SuppressWarnings("unchecked")
private boolean process() throws IOException {
    boolean keepAlive = false;
    String head = readHeaderLine();
    if (head.startsWith("GET ") || head.startsWith("POST ")) {
        int begin = head.indexOf('/'), end = head.lastIndexOf(' ');
        String file;
        if (begin < 0 || end < begin) {
            file = "";
        } else {
            file = head.substring(begin + 1, end).trim();
        }
        trace(head + ": " + file);
        file = getAllowedFile(file);
        attributes = new Properties();
        int paramIndex = file.indexOf('?');
        session = null;
        if (paramIndex >= 0) {
            String attrib = file.substring(paramIndex + 1);
            parseAttributes(attrib);
            String sessionId = attributes.getProperty("jsessionid");
            file = file.substring(0, paramIndex);
            session = server.getSession(sessionId);
        }
        keepAlive = parseHeader();
        String hostAddr = socket.getInetAddress().getHostAddress();
        file = processRequest(file, hostAddr);
        if (file.length() == 0) {
            // asynchronous request
            return true;
        }
        String message;
        byte[] bytes;
        if (cache && ifModifiedSince != null && ifModifiedSince.equals(server.getStartDateTime())) {
            bytes = null;
            message = "HTTP/1.1 304 Not Modified\r\n";
        } else {
            bytes = server.getFile(file);
            if (bytes == null) {
                message = "HTTP/1.1 404 Not Found\r\n";
                bytes = ("File not found: " + file).getBytes(StandardCharsets.UTF_8);
                message += "Content-Length: " + bytes.length + "\r\n";
            } else {
                if (session != null && file.endsWith(".jsp")) {
                    String page = new String(bytes, StandardCharsets.UTF_8);
                    if (SysProperties.CONSOLE_STREAM) {
                        Iterator<String> it = (Iterator<String>) session.map.remove("chunks");
                        if (it != null) {
                            message = "HTTP/1.1 200 OK\r\n";
                            message += "Content-Type: " + mimeType + "\r\n";
                            message += "Cache-Control: no-cache\r\n";
                            message += "Transfer-Encoding: chunked\r\n";
                            message += "\r\n";
                            trace(message);
                            output.write(message.getBytes());
                            while (it.hasNext()) {
                                String s = it.next();
                                s = PageParser.parse(s, session.map);
                                bytes = s.getBytes(StandardCharsets.UTF_8);
                                if (bytes.length == 0) {
                                    continue;
                                }
                                output.write(Integer.toHexString(bytes.length).getBytes());
                                output.write("\r\n".getBytes());
                                output.write(bytes);
                                output.write("\r\n".getBytes());
                                output.flush();
                            }
                            output.write("0\r\n\r\n".getBytes());
                            output.flush();
                            return keepAlive;
                        }
                    }
                    page = PageParser.parse(page, session.map);
                    bytes = page.getBytes(StandardCharsets.UTF_8);
                }
                message = "HTTP/1.1 200 OK\r\n";
                message += "Content-Type: " + mimeType + "\r\n";
                if (!cache) {
                    message += "Cache-Control: no-cache\r\n";
                } else {
                    message += "Cache-Control: max-age=10\r\n";
                    message += "Last-Modified: " + server.getStartDateTime() + "\r\n";
                }
                message += "Content-Length: " + bytes.length + "\r\n";
            }
        }
        message += "\r\n";
        trace(message);
        output.write(message.getBytes());
        if (bytes != null) {
            output.write(bytes);
        }
        output.flush();
    }
    return keepAlive;
}
Also used : Iterator(java.util.Iterator) Properties(java.util.Properties) SysProperties(org.h2.engine.SysProperties)

Example 7 with Trace

use of org.h2.message.Trace in project h2database by h2database.

the class LobStorageMap method createLob.

private ValueLobDb createLob(InputStream in, int type) throws IOException {
    byte[] streamStoreId;
    try {
        streamStoreId = streamStore.put(in);
    } catch (Exception e) {
        throw DbException.convertToIOException(e);
    }
    long lobId = generateLobId();
    long length = streamStore.length(streamStoreId);
    int tableId = LobStorageFrontend.TABLE_TEMP;
    Object[] value = { streamStoreId, tableId, length, 0 };
    lobMap.put(lobId, value);
    Object[] key = { streamStoreId, lobId };
    refMap.put(key, Boolean.TRUE);
    ValueLobDb lob = ValueLobDb.create(type, database, tableId, lobId, null, length);
    if (TRACE) {
        trace("create " + tableId + "/" + lobId);
    }
    return lob;
}
Also used : ValueLobDb(org.h2.value.ValueLobDb) IOException(java.io.IOException) DbException(org.h2.message.DbException)

Example 8 with Trace

use of org.h2.message.Trace in project h2database by h2database.

the class LobStorageMap method init.

@Override
public void init() {
    if (init) {
        return;
    }
    init = true;
    Store s = database.getMvStore();
    MVStore mvStore;
    if (s == null) {
        // in-memory database
        mvStore = MVStore.open(null);
    } else {
        mvStore = s.getStore();
    }
    lobMap = mvStore.openMap("lobMap");
    refMap = mvStore.openMap("lobRef");
    dataMap = mvStore.openMap("lobData");
    streamStore = new StreamStore(dataMap);
    // garbage collection of the last blocks
    if (database.isReadOnly()) {
        return;
    }
    if (dataMap.isEmpty()) {
        return;
    }
    // search for the last block
    // (in theory, only the latest lob can have unreferenced blocks,
    // but the latest lob could be a copy of another one, and
    // we don't know that, so we iterate over all lobs)
    long lastUsedKey = -1;
    for (Entry<Long, Object[]> e : lobMap.entrySet()) {
        long lobId = e.getKey();
        Object[] v = e.getValue();
        byte[] id = (byte[]) v[0];
        long max = streamStore.getMaxBlockKey(id);
        // a lob may not have a referenced blocks if data is kept inline
        if (max != -1 && max > lastUsedKey) {
            lastUsedKey = max;
            if (TRACE) {
                trace("lob " + lobId + " lastUsedKey=" + lastUsedKey);
            }
        }
    }
    if (TRACE) {
        trace("lastUsedKey=" + lastUsedKey);
    }
    // delete all blocks that are newer
    while (true) {
        Long last = dataMap.lastKey();
        if (last == null || last <= lastUsedKey) {
            break;
        }
        if (TRACE) {
            trace("gc " + last);
        }
        dataMap.remove(last);
    }
    // don't re-use block ids, except at the very end
    Long last = dataMap.lastKey();
    if (last != null) {
        streamStore.setNextKey(last + 1);
    }
}
Also used : MVStore(org.h2.mvstore.MVStore) StreamStore(org.h2.mvstore.StreamStore) Store(org.h2.mvstore.db.MVTableEngine.Store) MVStore(org.h2.mvstore.MVStore) StreamStore(org.h2.mvstore.StreamStore)

Example 9 with Trace

use of org.h2.message.Trace in project h2database by h2database.

the class LobStorageMap method copyLob.

@Override
public ValueLobDb copyLob(ValueLobDb old, int tableId, long length) {
    init();
    int type = old.getType();
    long oldLobId = old.getLobId();
    long oldLength = old.getPrecision();
    if (oldLength != length) {
        throw DbException.throwInternalError("Length is different");
    }
    Object[] value = lobMap.get(oldLobId);
    value = value.clone();
    byte[] streamStoreId = (byte[]) value[0];
    long lobId = generateLobId();
    value[1] = tableId;
    lobMap.put(lobId, value);
    Object[] key = { streamStoreId, lobId };
    refMap.put(key, Boolean.TRUE);
    ValueLobDb lob = ValueLobDb.create(type, database, tableId, lobId, null, length);
    if (TRACE) {
        trace("copy " + old.getTableId() + "/" + old.getLobId() + " > " + tableId + "/" + lobId);
    }
    return lob;
}
Also used : ValueLobDb(org.h2.value.ValueLobDb)

Example 10 with Trace

use of org.h2.message.Trace 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)

Aggregations

SQLException (java.sql.SQLException)16 DbException (org.h2.message.DbException)14 Connection (java.sql.Connection)11 ResultSet (java.sql.ResultSet)10 PreparedStatement (java.sql.PreparedStatement)9 Statement (java.sql.Statement)8 IOException (java.io.IOException)7 Savepoint (java.sql.Savepoint)7 Random (java.util.Random)7 ArrayList (java.util.ArrayList)5 Properties (java.util.Properties)5 TraceSystem (org.h2.message.TraceSystem)5 Server (org.h2.tools.Server)5 ValueString (org.h2.value.ValueString)5 SQLClientInfoException (java.sql.SQLClientInfoException)4 SysProperties (org.h2.engine.SysProperties)4 JdbcConnection (org.h2.jdbc.JdbcConnection)4 SortedProperties (org.h2.util.SortedProperties)4 Value (org.h2.value.Value)4 Socket (java.net.Socket)3