/**
  * Append a time to the string builder.
  *
  * @param buff the target string builder
  * @param nanos the time in nanoseconds
  * @param alwaysAddMillis whether to always add at least ".0"
  */
 static void appendTime(StringBuilder buff, long nanos, boolean alwaysAddMillis) {
   if (nanos < 0) {
     buff.append('-');
     nanos = -nanos;
   }
   long ms = nanos / 1000000;
   nanos -= ms * 1000000;
   long s = ms / 1000;
   ms -= s * 1000;
   long m = s / 60;
   s -= m * 60;
   long h = m / 60;
   m -= h * 60;
   StringUtils.appendZeroPadded(buff, 2, h);
   buff.append(':');
   StringUtils.appendZeroPadded(buff, 2, m);
   buff.append(':');
   StringUtils.appendZeroPadded(buff, 2, s);
   if (alwaysAddMillis || ms > 0 || nanos > 0) {
     buff.append('.');
     int start = buff.length();
     StringUtils.appendZeroPadded(buff, 3, ms);
     if (nanos > 0) {
       StringUtils.appendZeroPadded(buff, 6, nanos);
     }
     for (int i = buff.length() - 1; i > start; i--) {
       if (buff.charAt(i) != '0') {
         break;
       }
       buff.deleteCharAt(i);
     }
   }
 }
  private void testFormat() throws IOException {
    Map<Long, byte[]> map = New.hashMap();
    StreamStore store = new StreamStore(map);
    store.setMinBlockSize(10);
    store.setMaxBlockSize(20);
    store.setNextKey(123);

    byte[] id;

    id = store.put(new ByteArrayInputStream(new byte[200]));
    assertEquals(200, store.length(id));
    assertEquals("02c8018801", StringUtils.convertBytesToHex(id));

    id = store.put(new ByteArrayInputStream(new byte[0]));
    assertEquals("", StringUtils.convertBytesToHex(id));

    id = store.put(new ByteArrayInputStream(new byte[1]));
    assertEquals("000100", StringUtils.convertBytesToHex(id));

    id = store.put(new ByteArrayInputStream(new byte[3]));
    assertEquals("0003000000", StringUtils.convertBytesToHex(id));

    id = store.put(new ByteArrayInputStream(new byte[10]));
    assertEquals("010a8901", StringUtils.convertBytesToHex(id));

    byte[] combined = StringUtils.convertHexToBytes("0001aa0002bbcc");
    assertEquals(3, store.length(combined));
    InputStream in = store.get(combined);
    assertEquals(1, in.skip(1));
    assertEquals(0xbb, in.read());
    assertEquals(1, in.skip(1));
  }
Example #3
0
 /** Test one string operation using the string cache. */
 void testString() {
   String a = randomString();
   if (returnNew) {
     String b = StringUtils.fromCacheOrNew(a);
     try {
       assertEquals(a, b);
     } catch (Exception e) {
       TestBase.logError("error", e);
     }
     if (a != null && a == b && a.length() > 0) {
       throw new AssertionError(
           "a=" + System.identityHashCode(a) + " b=" + System.identityHashCode(b));
     }
   } else {
     String b;
     if (useIntern) {
       b = a == null ? null : a.intern();
     } else {
       b = StringUtils.cache(a);
     }
     try {
       assertEquals(a, b);
     } catch (Exception e) {
       TestBase.logError("error", e);
     }
   }
 }
Example #4
0
 public void test() throws InterruptedException {
   returnNew = true;
   StringUtils.clearCache();
   testSingleThread(getSize(5000, 20000));
   testMultiThreads();
   returnNew = false;
   StringUtils.clearCache();
   testSingleThread(getSize(5000, 20000));
   testMultiThreads();
 }
Example #5
0
 private void testHMAC() {
   // from Wikipedia
   assertEquals(
       "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad",
       StringUtils.convertBytesToHex(SHA256.getHMAC(new byte[0], new byte[0])));
   assertEquals(
       "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8",
       StringUtils.convertBytesToHex(
           SHA256.getHMAC(
               "key".getBytes(), "The quick brown fox jumps over the lazy dog".getBytes())));
 }
Example #6
0
 @Override
 public String getSQL() {
   String s;
   if (type == Value.CLOB) {
     s = getString();
     return StringUtils.quoteStringSQL(s);
   }
   byte[] buff = getBytes();
   s = StringUtils.convertBytesToHex(buff);
   return "X'" + s + "'";
 }
Example #7
0
 @Override
 public String getPlanSQL() {
   StringBuilder buff = new StringBuilder();
   buff.append("DELETE ");
   buff.append("FROM ").append(tableFilter.getPlanSQL(false));
   if (condition != null) {
     buff.append("\nWHERE ").append(StringUtils.unEnclose(condition.getSQL()));
   }
   if (limitExpr != null) {
     buff.append("\nLIMIT (").append(StringUtils.unEnclose(limitExpr.getSQL())).append(')');
   }
   return buff.toString();
 }
Example #8
0
 private String getHashString(byte[] data) {
   byte[] result = SHA256.getHash(data, true);
   if (data.length > 0) {
     assertEquals(0, data[0]);
   }
   return StringUtils.convertBytesToHex(result);
 }
  private void readProperties(Properties info) {
    Object[] list = new Object[info.size()];
    info.keySet().toArray(list);
    DbSettings s = null;

    // 可在info中配三种参数,相关文档见:E:\H2\my-h2\my-h2-docs\999 可配置的参数汇总.java中的1、2、3项
    for (Object k : list) {
      String key = StringUtils.toUpperEnglish(k.toString());
      if (prop.containsKey(key)) {
        throw DbException.get(ErrorCode.DUPLICATE_PROPERTY_1, key);
      }
      Object value = info.get(k);
      // 支持org.h2.command.dml.SetTypes中的参数和ConnectionInfo与connectionTime相关的参数
      if (isKnownSetting(key)) {
        prop.put(key, value);
      } else {
        if (s == null) {
          s = getDbSettings();
        }
        // org.h2.constant.DbSettings中的参数
        if (s.containsKey(key)) {
          prop.put(key, value);
        }
      }
    }
  }
Example #10
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);
   }
 }
Example #11
0
 /**
  * Generate "CREATE" SQL statement for the view.
  *
  * @param orReplace if true, then include the OR REPLACE clause
  * @param force if true, then include the FORCE clause
  * @return the SQL statement
  */
 public String getCreateSQL(boolean orReplace, boolean force) {
   StatementBuilder buff = new StatementBuilder("CREATE ");
   if (orReplace) {
     buff.append("OR REPLACE ");
   }
   if (force) {
     buff.append("FORCE ");
   }
   buff.append("VIEW ");
   buff.append(getSQL());
   if (comment != null) {
     buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
   }
   if (columns.length > 0) {
     buff.append('(');
     for (Column c : columns) {
       buff.appendExceptFirst(", ");
       buff.append(c.getSQL());
     }
     buff.append(')');
   } else if (columnNames != null) {
     buff.append('(');
     for (String n : columnNames) {
       buff.appendExceptFirst(", ");
       buff.append(n);
     }
     buff.append(')');
   }
   return buff.append(" AS\n").append(querySQL).toString();
 }
Example #12
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);
   }
 }
Example #13
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();
    }
  }
Example #14
0
 private static void testConnectWithHash() throws SQLException {
   Connection conn = DriverManager.getConnection("jdbc:h2:mem:test", "sa", "sa");
   String pwd = StringUtils.convertBytesToHex(SHA256.getKeyPasswordHash("SA", "sa".toCharArray()));
   Connection conn2 =
       DriverManager.getConnection("jdbc:h2:mem:test;PASSWORD_HASH=TRUE", "sa", pwd);
   conn.close();
   conn2.close();
 }
  void mapObject(Object obj) {
    fieldMap.clear();
    initObject(obj, fieldMap);

    if (clazz.isAnnotationPresent(JQSchema.class)) {
      JQSchema schemaAnnotation = clazz.getAnnotation(JQSchema.class);
      // setup schema name mapping, if properly annotated
      if (!StringUtils.isNullOrEmpty(schemaAnnotation.name())) {
        schemaName = schemaAnnotation.name();
      }
    }

    if (clazz.isAnnotationPresent(JQTable.class)) {
      JQTable tableAnnotation = clazz.getAnnotation(JQTable.class);

      // setup table name mapping, if properly annotated
      if (!StringUtils.isNullOrEmpty(tableAnnotation.name())) {
        tableName = tableAnnotation.name();
      }

      // allow control over createTableIfRequired()
      createTableIfRequired = tableAnnotation.createIfRequired();

      // model version
      if (tableAnnotation.version() > 0) {
        tableVersion = tableAnnotation.version();
      }

      // setup the primary index, if properly annotated
      List<String> primaryKey = getColumns(tableAnnotation.primaryKey());
      if (primaryKey != null) {
        setPrimaryKey(primaryKey);
      }
    }

    if (clazz.isAnnotationPresent(JQIndex.class)) {
      JQIndex indexAnnotation = clazz.getAnnotation(JQIndex.class);

      // setup the indexes, if properly annotated
      addIndexes(IndexType.STANDARD, indexAnnotation.standard());
      addIndexes(IndexType.UNIQUE, indexAnnotation.unique());
      addIndexes(IndexType.HASH, indexAnnotation.hash());
      addIndexes(IndexType.UNIQUE_HASH, indexAnnotation.uniqueHash());
    }
  }
 private String getQuery(Object[] row) throws SQLException {
   StatementBuilder buff = new StatementBuilder();
   if (schema != null) {
     buff.append(StringUtils.quoteIdentifier(schema)).append('.');
   }
   buff.append(StringUtils.quoteIdentifier(table)).append(" WHERE ");
   for (int columnIndex : keys) {
     buff.appendExceptFirst(" AND ");
     buff.append(StringUtils.quoteIdentifier(columns[columnIndex]));
     Object o = row[columnIndex];
     if (o == null) {
       buff.append(" IS NULL");
     } else {
       buff.append('=').append(FullText.quoteSQL(o, columnTypes[columnIndex]));
     }
   }
   return buff.toString();
 }
Example #17
0
  private void testAES() {
    BlockCipher test = CipherFactory.getBlockCipher("AES");

    String r;
    byte[] data;

    // test vector from
    // http://csrc.nist.gov/groups/STM/cavp/documents/aes/KAT_AES.zip
    // ECBVarTxt128e.txt
    // COUNT = 0
    test.setKey(StringUtils.convertHexToBytes("00000000000000000000000000000000"));
    data = StringUtils.convertHexToBytes("80000000000000000000000000000000");
    test.encrypt(data, 0, data.length);
    r = StringUtils.convertBytesToHex(data);
    assertEquals("3ad78e726c1ec02b7ebfe92b23d9ec34", r);

    // COUNT = 127
    test.setKey(StringUtils.convertHexToBytes("00000000000000000000000000000000"));
    data = StringUtils.convertHexToBytes("ffffffffffffffffffffffffffffffff");
    test.encrypt(data, 0, data.length);
    r = StringUtils.convertBytesToHex(data);
    assertEquals("3f5b8cc9ea855a0afa7347d23e8d664e", r);

    // test vector
    test.setKey(StringUtils.convertHexToBytes("2b7e151628aed2a6abf7158809cf4f3c"));
    data = StringUtils.convertHexToBytes("6bc1bee22e409f96e93d7e117393172a");
    test.encrypt(data, 0, data.length);
    r = StringUtils.convertBytesToHex(data);
    assertEquals("3ad77bb40d7a3660a89ecaf32466ef97", r);

    test.setKey(StringUtils.convertHexToBytes("000102030405060708090A0B0C0D0E0F"));
    byte[] in = new byte[128];
    byte[] enc = new byte[128];
    test.encrypt(enc, 0, 128);
    test.decrypt(enc, 0, 128);
    if (!Arrays.equals(in, enc)) {
      throw new AssertionError();
    }

    for (int i = 0; i < 10; i++) {
      test.encrypt(in, 0, 128);
      test.decrypt(enc, 0, 128);
    }
  }
 /**
  * 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;
 }
 private static byte[] hashPassword(boolean passwordHash, String userName, char[] password) {
   // 如果PASSWORD_HASH参数是true那么不再进行SHA256vn
   if (passwordHash) {
     return StringUtils.convertHexToBytes(new String(password));
   }
   if (userName.length() == 0 && password.length == 0) {
     return new byte[0];
   }
   // 会生成32个字节,32*8刚好是256 bit,刚好对应SHA256的名字
   return SHA256.getKeyPasswordHash(userName, password);
 }
 /**
  * Add the existing data to the index.
  *
  * @param conn the database connection
  * @param schema the schema name
  * @param table the table name
  */
 protected static void indexExistingRows(Connection conn, String schema, String table)
     throws SQLException {
   FullTextLucene.FullTextTrigger existing = new FullTextLucene.FullTextTrigger();
   existing.init(conn, schema, null, table, false, Trigger.INSERT);
   String sql =
       "SELECT * FROM "
           + StringUtils.quoteIdentifier(schema)
           + "."
           + StringUtils.quoteIdentifier(table);
   ResultSet rs = conn.createStatement().executeQuery(sql);
   int columnCount = rs.getMetaData().getColumnCount();
   while (rs.next()) {
     Object[] row = new Object[columnCount];
     for (int i = 0; i < columnCount; i++) {
       row[i] = rs.getObject(i + 1);
     }
     existing.insert(row, false);
   }
   existing.commitIndex();
 }
 /**
  * Create the trigger.
  *
  * @param conn the database connection
  * @param schema the schema name
  * @param table the table name
  */
 protected static void createTrigger(Connection conn, String schema, String table)
     throws SQLException {
   Statement stat = conn.createStatement();
   String trigger =
       StringUtils.quoteIdentifier(schema)
           + "."
           + StringUtils.quoteIdentifier(TRIGGER_PREFIX + table);
   stat.execute("DROP TRIGGER IF EXISTS " + trigger);
   StringBuilder buff = new StringBuilder("CREATE TRIGGER IF NOT EXISTS ");
   // the trigger is also called on rollback because transaction rollback
   // will not undo the changes in the Lucene index
   buff.append(trigger)
       .append(" AFTER INSERT, UPDATE, DELETE, ROLLBACK ON ")
       .append(StringUtils.quoteIdentifier(schema))
       .append('.')
       .append(StringUtils.quoteIdentifier(table))
       .append(" FOR EACH ROW CALL \"")
       .append(FullTextLucene2.FullTextTrigger.class.getName())
       .append('\"');
   stat.execute(buff.toString());
 }
Example #22
0
  private void testPBKDF2() {
    // test vectors from StackOverflow (PBKDF2-HMAC-SHA2)
    assertEquals(
        "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b",
        StringUtils.convertBytesToHex(
            SHA256.getPBKDF2("password".getBytes(), "salt".getBytes(), 1, 32)));
    assertEquals(
        "ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43",
        StringUtils.convertBytesToHex(
            SHA256.getPBKDF2("password".getBytes(), "salt".getBytes(), 2, 32)));
    assertEquals(
        "c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a",
        StringUtils.convertBytesToHex(
            SHA256.getPBKDF2("password".getBytes(), "salt".getBytes(), 4096, 32)));
    // take a very long time to calculate
    // assertEquals(
    //         "cf81c66fe8cfc04d1f31ecb65dab4089f7f179e89b3b0bcb17ad10e3ac6eba46",
    //         StringUtils.convertBytesToHex(
    //         SHA256.getPBKDF2(
    //         "password".getBytes(),
    //         "salt".getBytes(), 16777216, 32)));
    assertEquals(
        "348c89dbcbd32b2f32d814b8116e84cf2b17347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9",
        StringUtils.convertBytesToHex(
            SHA256.getPBKDF2(
                ("password" + "PASSWORD" + "password").getBytes(),
                ("salt" + "SALT" + "salt" + "SALT" + "salt" + "SALT" + "salt" + "SALT" + "salt")
                    .getBytes(),
                4096,
                40)));
    assertEquals(
        "89b69d0516f829893c696226650a8687",
        StringUtils.convertBytesToHex(
            SHA256.getPBKDF2("pass\0word".getBytes(), "sa\0lt".getBytes(), 4096, 16)));

    // the password is filled with zeroes
    byte[] password = "******".getBytes();
    SHA256.getPBKDF2(password, "".getBytes(), 1, 16);
    assertEquals(new byte[4], password);
  }
Example #23
0
 @Override
 public String getPlanSQL() {
   StringBuilder buff = new StringBuilder();
   buff.append('(').append(left.getPlanSQL()).append(')');
   switch (unionType) {
     case UNION_ALL:
       buff.append("\nUNION ALL\n");
       break;
     case UNION:
       buff.append("\nUNION\n");
       break;
     case INTERSECT:
       buff.append("\nINTERSECT\n");
       break;
     case EXCEPT:
       buff.append("\nEXCEPT\n");
       break;
     default:
       DbException.throwInternalError("type=" + unionType);
   }
   buff.append('(').append(right.getPlanSQL()).append(')');
   Expression[] exprList = expressions.toArray(new Expression[expressions.size()]);
   if (sort != null) {
     buff.append("\nORDER BY ").append(sort.getSQL(exprList, exprList.length));
   }
   if (limitExpr != null) {
     buff.append("\nLIMIT ").append(StringUtils.unEnclose(limitExpr.getSQL()));
     if (offsetExpr != null) {
       buff.append("\nOFFSET ").append(StringUtils.unEnclose(offsetExpr.getSQL()));
     }
   }
   if (sampleSizeExpr != null) {
     buff.append("\nSAMPLE_SIZE ").append(StringUtils.unEnclose(sampleSizeExpr.getSQL()));
   }
   if (isForUpdate) {
     buff.append("\nFOR UPDATE");
   }
   return buff.toString();
 }
Example #24
0
 public String getCreateSQL() {
   StringBuilder buff = new StringBuilder("CREATE FORCE ALIAS ");
   buff.append(getSQL());
   if (deterministic) {
     buff.append(" DETERMINISTIC");
   }
   if (source != null) {
     buff.append(" AS ").append(StringUtils.quoteStringSQL(source));
   } else {
     buff.append(" FOR ").append(Parser.quoteIdentifier(className + "." + methodName));
   }
   return buff.toString();
 }
Example #25
0
 private void copy(File source, File target, boolean replaceFragments, boolean web)
     throws IOException {
   if (source.isDirectory()) {
     target.mkdirs();
     for (File f : source.listFiles()) {
       copy(f, new File(target, f.getName()), replaceFragments, web);
     }
   } else {
     String name = source.getName();
     if (name.endsWith("onePage.html") || name.startsWith("fragments")) {
       return;
     }
     if (web) {
       if (name.endsWith("main.html") || name.endsWith("main_ja.html")) {
         return;
       }
     } else {
       if (name.endsWith("mainWeb.html") || name.endsWith("mainWeb_ja.html")) {
         return;
       }
     }
     FileInputStream in = new FileInputStream(source);
     byte[] bytes = IOUtils.readBytesAndClose(in, 0);
     if (name.endsWith(".html")) {
       String page = new String(bytes, "UTF-8");
       if (web) {
         page = StringUtils.replaceAll(page, ANALYTICS_TAG, ANALYTICS_SCRIPT);
       }
       if (replaceFragments) {
         page = replaceFragments(name, page);
         page = StringUtils.replaceAll(page, "<a href=\"frame", "<a href=\"main");
         page = StringUtils.replaceAll(page, "html/frame.html", "html/main.html");
       }
       if (web) {
         page = StringUtils.replaceAll(page, TRANSLATE_START, "");
         page = StringUtils.replaceAll(page, TRANSLATE_END, "");
         page = StringUtils.replaceAll(page, "<pre>", "<pre class=\"notranslate\">");
         page = StringUtils.replaceAll(page, "<code>", "<code class=\"notranslate\">");
       }
       bytes = page.getBytes("UTF-8");
     }
     FileOutputStream out = new FileOutputStream(target);
     out.write(bytes);
     out.close();
     if (web) {
       if (name.endsWith("mainWeb.html")) {
         target.renameTo(new File(target.getParentFile(), "main.html"));
       } else if (name.endsWith("mainWeb_ja.html")) {
         target.renameTo(new File(target.getParentFile(), "main_ja.html"));
       }
     }
   }
 }
 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);
     }
   }
 }
Example #27
0
 @Override
 public String getCreateSQLForCopy(Table targetTable, String quotedName) {
   StringBuilder buff = new StringBuilder("CREATE ");
   buff.append(indexType.getSQL());
   buff.append(' ');
   if (table.isHidden()) {
     buff.append("IF NOT EXISTS ");
   }
   buff.append(quotedName);
   buff.append(" ON ").append(targetTable.getSQL());
   if (comment != null) {
     buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
   }
   buff.append('(').append(getColumnListSQL()).append(')');
   return buff.toString();
 }
Example #28
0
 @Override
 public String getString() {
   int len = precision > Integer.MAX_VALUE || precision == 0 ? Integer.MAX_VALUE : (int) precision;
   try {
     if (type == Value.CLOB) {
       if (small != null) {
         return new String(small, Constants.UTF8);
       }
       return IOUtils.readStringAndClose(getReader(), len);
     }
     byte[] buff;
     if (small != null) {
       buff = small;
     } else {
       buff = IOUtils.readBytesAndClose(getInputStream(), len);
     }
     return StringUtils.convertBytesToHex(buff);
   } catch (IOException e) {
     throw DbException.convertIOException(e, toString());
   }
 }
Example #29
0
  private void map(String key, ResultSet rs, boolean railroads) throws Exception {
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    while (rs.next()) {
      HashMap<String, String> map = new HashMap<String, String>();
      ResultSetMetaData meta = rs.getMetaData();
      for (int i = 0; i < meta.getColumnCount(); i++) {
        String k = StringUtils.toLowerEnglish(meta.getColumnLabel(i + 1));
        String value = rs.getString(i + 1);
        value = value.trim();
        map.put(k, PageParser.escapeHtml(value));
      }
      String topic = rs.getString("TOPIC");
      String syntax = rs.getString("SYNTAX").trim();
      if (railroads) {
        String railroad = bnf.getRailroadHtml(syntax);
        map.put("railroad", railroad);
      }
      syntax = bnf.getSyntaxHtml(syntax);
      map.put("syntax", syntax);

      // remove newlines in the regular text
      String text = map.get("text");
      if (text != null) {
        // text is enclosed in <p> .. </p> so this works.
        text = StringUtils.replaceAll(text, "<br /><br />", "</p><p>");
        text = StringUtils.replaceAll(text, "<br />", " ");
        map.put("text", text);
      }

      String link = topic.toLowerCase();
      link = StringUtils.replaceAll(link, " ", "_");
      // link = StringUtils.replaceAll(link, "_", "");
      link = StringUtils.replaceAll(link, "@", "_");
      map.put("link", StringUtils.urlEncode(link));
      list.add(map);
    }
    session.put(key, list);
    int div = 3;
    int part = (list.size() + div - 1) / div;
    for (int i = 0, start = 0; i < div; i++, start += part) {
      List<HashMap<String, String>> listThird =
          list.subList(start, Math.min(start + part, list.size()));
      session.put(key + "-" + i, listThird);
    }
    rs.close();
  }
Example #30
0
 private void parseAttributes(String s) {
   trace("data=" + s);
   while (s != null) {
     int idx = s.indexOf('=');
     if (idx >= 0) {
       String property = s.substring(0, idx);
       s = s.substring(idx + 1);
       idx = s.indexOf('&');
       String value;
       if (idx >= 0) {
         value = s.substring(0, idx);
         s = s.substring(idx + 1);
       } else {
         value = s;
       }
       String attr = StringUtils.urlDecode(value);
       attributes.put(property, attr);
     } else {
       break;
     }
   }
   trace(attributes.toString());
 }