Ejemplo n.º 1
0
 public void createDirs(String fileName) {
   fileName = translateFileName(fileName);
   try {
     String[] path = StringUtils.arraySplit(fileName, '/', false);
     long parentId = 0;
     int len = path.length;
     if (fileName.endsWith("/")) {
       len--;
     }
     len--;
     for (int i = 1; i < len; i++) {
       PreparedStatement prep = prepare("SELECT ID FROM FILES WHERE PARENTID=? AND NAME=?");
       prep.setLong(1, parentId);
       prep.setString(2, path[i]);
       ResultSet rs = prep.executeQuery();
       if (!rs.next()) {
         prep = prepare("INSERT INTO FILES(NAME, PARENTID, LASTMODIFIED) VALUES(?, ?, ?)");
         prep.setString(1, path[i]);
         prep.setLong(2, parentId);
         prep.setLong(3, System.currentTimeMillis());
         prep.execute();
         rs = prep.getGeneratedKeys();
         rs.next();
         parentId = rs.getLong(1);
       } else {
         parentId = rs.getLong(1);
       }
     }
     commit();
   } catch (SQLException e) {
     rollback();
     throw convert(e);
   }
 }
Ejemplo n.º 2
0
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    try {
      org.h2.Driver.load();

      // This will get the setting from a context-param in web.xml if defined:
      ServletContext servletContext = servletContextEvent.getServletContext();
      String url = getParameter(servletContext, "db.url", "jdbc:h2:~/test");
      String user = getParameter(servletContext, "db.user", "sa");
      String password = getParameter(servletContext, "db.password", "sa");

      // Start the server if configured to do so
      String serverParams = getParameter(servletContext, "db.tcpServer", null);
      if (serverParams != null) {
        String[] params = StringUtils.arraySplit(serverParams, ' ', true);
        server = Server.createTcpServer(params);
        server.start();
      }

      // To access the database in server mode, use the database URL:
      // jdbc:h2:tcp://localhost/~/test
      conn = DriverManager.getConnection(url, user, password);
      servletContext.setAttribute("connection", conn);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 3
0
 private long getId(String fileName, boolean parent) {
   fileName = translateFileName(fileName);
   log(fileName);
   try {
     String[] path = StringUtils.arraySplit(fileName, '/', false);
     long id = 0;
     int len = parent ? path.length - 1 : path.length;
     if (fileName.endsWith("/")) {
       len--;
     }
     for (int i = 1; i < len; i++) {
       PreparedStatement prep = prepare("SELECT ID FROM FILES WHERE PARENTID=? AND NAME=?");
       prep.setLong(1, id);
       prep.setString(2, path[i]);
       ResultSet rs = prep.executeQuery();
       if (!rs.next()) {
         return -1;
       }
       id = rs.getLong(1);
     }
     return id;
   } catch (SQLException e) {
     throw convert(e);
   }
 }
 /**
  * Convert a String to a map.
  *
  * @param s the string
  * @return the map
  */
 public static SortedProperties fromLines(String s) {
   SortedProperties p = new SortedProperties();
   for (String line : StringUtils.arraySplit(s, '\n', true)) {
     int idx = line.indexOf('=');
     if (idx > 0) {
       p.put(line.substring(0, idx), line.substring(idx + 1));
     }
   }
   return p;
 }
Ejemplo n.º 5
0
 private void readSettingsFromURL() {
   // 如url=jdbc:h2:tcp://localhost:9092/test9;optimize_distinct=true;early_filter=true;nested_joins=false
   DbSettings defaultSettings = DbSettings.getDefaultSettings();
   int idx = url.indexOf(';'); // 用";"号来分隔参数,第一个";"号表明url和参数的分界,之后的";"号用来分隔多个参数
   if (idx >= 0) {
     // optimize_distinct=true;early_filter=true;nested_joins=false
     String settings = url.substring(idx + 1);
     // jdbc:h2:tcp://localhost:9092/test9
     url = url.substring(0, idx);
     // [optimize_distinct=true, early_filter=true, nested_joins=false]
     String[] list = StringUtils.arraySplit(settings, ';', false);
     for (String setting : list) {
       if (setting.length() == 0) {
         continue;
       }
       int equal = setting.indexOf('=');
       if (equal < 0) {
         throw getFormatException();
       }
       String value = setting.substring(equal + 1);
       String key = setting.substring(0, equal);
       key = StringUtils.toUpperEnglish(key);
       // info中除了可以配三种参数外(相关文档见:E:\H2\my-h2\my-h2-docs\999 可配置的参数汇总.java中的1、2、3项)
       // 还可以配其他参数,但是被忽略
       // 但是url中只能配三种参数
       if (!isKnownSetting(key) && !defaultSettings.containsKey(key)) {
         throw DbException.get(ErrorCode.UNSUPPORTED_SETTING_1, key);
       }
       // 不能与info中的参数重复(如果值相同就不会报错)
       // 例子见my.test.ConnectionInfoTest
       String old = prop.getProperty(key);
       if (old != null && !old.equals(value)) {
         throw DbException.get(ErrorCode.DUPLICATE_PROPERTY_1, key);
       }
       prop.setProperty(key, value);
     }
   }
 }
Ejemplo n.º 6
0
 /** INTERNAL */
 @Override
 public void init(
     Connection conn,
     String schemaName,
     String triggerName,
     String tableName,
     boolean before,
     int type)
     throws SQLException {
   this.schema = schemaName;
   this.table = tableName;
   this.indexPath = getIndexPath(conn);
   this.indexAccess = getIndexAccess(conn);
   ArrayList<String> keyList = New.arrayList();
   DatabaseMetaData meta = conn.getMetaData();
   ResultSet rs =
       meta.getColumns(
           null,
           StringUtils.escapeMetaDataPattern(schemaName),
           StringUtils.escapeMetaDataPattern(tableName),
           null);
   ArrayList<String> columnList = New.arrayList();
   while (rs.next()) {
     columnList.add(rs.getString("COLUMN_NAME"));
   }
   columnTypes = new int[columnList.size()];
   columns = new String[columnList.size()];
   columnList.toArray(columns);
   rs =
       meta.getColumns(
           null,
           StringUtils.escapeMetaDataPattern(schemaName),
           StringUtils.escapeMetaDataPattern(tableName),
           null);
   for (int i = 0; rs.next(); i++) {
     columnTypes[i] = rs.getInt("DATA_TYPE");
   }
   if (keyList.size() == 0) {
     rs = meta.getPrimaryKeys(null, StringUtils.escapeMetaDataPattern(schemaName), tableName);
     while (rs.next()) {
       keyList.add(rs.getString("COLUMN_NAME"));
     }
   }
   if (keyList.size() == 0) {
     throw throwException("No primary key for table " + tableName);
   }
   ArrayList<String> indexList = New.arrayList();
   PreparedStatement prep =
       conn.prepareStatement(
           "SELECT COLUMNS FROM " + SCHEMA + ".INDEXES WHERE SCHEMA=? AND TABLE=?");
   prep.setString(1, schemaName);
   prep.setString(2, tableName);
   rs = prep.executeQuery();
   if (rs.next()) {
     String cols = rs.getString(1);
     if (cols != null) {
       for (String s : StringUtils.arraySplit(cols, ',', true)) {
         indexList.add(s);
       }
     }
   }
   if (indexList.size() == 0) {
     indexList.addAll(columnList);
   }
   keys = new int[keyList.size()];
   setColumns(keys, keyList, columnList);
   indexColumns = new int[indexList.size()];
   setColumns(indexColumns, indexList, columnList);
 }
Ejemplo n.º 7
0
 public String getFileName(String fileName) {
   fileName = translateFileName(fileName);
   String[] path = StringUtils.arraySplit(fileName, '/', false);
   return path[path.length - 1];
 }
Ejemplo n.º 8
0
 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 = Boolean.parseBoolean(ci.getProperty("AUTO_RECONNECT", "false"));
   // AUTO_SERVER implies AUTO_RECONNECT
   boolean autoServer = Boolean.parseBoolean(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 (int i = 0; i < len; i++) {
       String s = servers[i];
       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;
   }
 }