index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/PlanItem.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import org.h2.index.Index;
/**
* The plan item describes the index to be used, and the estimated cost when
* using it.
*/
public class PlanItem {
/**
* The cost.
*/
double cost;
private int[] masks;
private Index index;
private PlanItem joinPlan;
private PlanItem nestedJoinPlan;
void setMasks(int[] masks) {
this.masks = masks;
}
int[] getMasks() {
return masks;
}
void setIndex(Index index) {
this.index = index;
}
public Index getIndex() {
return index;
}
PlanItem getJoinPlan() {
return joinPlan;
}
PlanItem getNestedJoinPlan() {
return nestedJoinPlan;
}
void setJoinPlan(PlanItem joinPlan) {
this.joinPlan = joinPlan;
}
void setNestedJoinPlan(PlanItem nestedJoinPlan) {
this.nestedJoinPlan = nestedJoinPlan;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/RangeTable.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.index.RangeIndex;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.schema.Schema;
import org.h2.value.Value;
/**
* The table SYSTEM_RANGE is a virtual table that generates incrementing numbers
* with a given start end end point.
*/
public class RangeTable extends Table {
/**
* The name of the range table.
*/
public static final String NAME = "SYSTEM_RANGE";
/**
* The PostgreSQL alias for the range table.
*/
public static final String ALIAS = "GENERATE_SERIES";
private Expression min, max, step;
private boolean optimized;
/**
* Create a new range with the given start and end expressions.
*
* @param schema the schema (always the main schema)
* @param min the start expression
* @param max the end expression
* @param noColumns whether this table has no columns
*/
public RangeTable(Schema schema, Expression min, Expression max,
boolean noColumns) {
super(schema, 0, NAME, true, true);
Column[] cols = noColumns ? new Column[0] : new Column[] { new Column(
"X", Value.LONG) };
this.min = min;
this.max = max;
setColumns(cols);
}
public RangeTable(Schema schema, Expression min, Expression max,
Expression step, boolean noColumns) {
this(schema, min, max, noColumns);
this.step = step;
}
@Override
public String getDropSQL() {
return null;
}
@Override
public String getCreateSQL() {
return null;
}
@Override
public String getSQL() {
String sql = NAME + "(" + min.getSQL() + ", " + max.getSQL();
if (step != null) {
sql += ", " + step.getSQL();
}
return sql + ")";
}
@Override
public boolean lock(Session session, boolean exclusive, boolean forceLockEvenInMvcc) {
// nothing to do
return false;
}
@Override
public void close(Session session) {
// nothing to do
}
@Override
public void unlock(Session s) {
// nothing to do
}
@Override
public boolean isLockedExclusively() {
return false;
}
@Override
public Index addIndex(Session session, String indexName,
int indexId, IndexColumn[] cols, IndexType indexType,
boolean create, String indexComment) {
throw DbException.getUnsupportedException("SYSTEM_RANGE");
}
@Override
public void removeRow(Session session, Row row) {
throw DbException.getUnsupportedException("SYSTEM_RANGE");
}
@Override
public void addRow(Session session, Row row) {
throw DbException.getUnsupportedException("SYSTEM_RANGE");
}
@Override
public void checkSupportAlter() {
throw DbException.getUnsupportedException("SYSTEM_RANGE");
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("SYSTEM_RANGE");
}
@Override
public boolean canGetRowCount() {
return true;
}
@Override
public boolean canDrop() {
return false;
}
@Override
public long getRowCount(Session session) {
long step = getStep(session);
if (step == 0L) {
throw DbException.get(ErrorCode.STEP_SIZE_MUST_NOT_BE_ZERO);
}
long delta = getMax(session) - getMin(session);
if (step > 0) {
if (delta < 0) {
return 0;
}
} else if (delta > 0) {
return 0;
}
return delta / step + 1;
}
@Override
public TableType getTableType() {
return TableType.SYSTEM_TABLE;
}
@Override
public Index getScanIndex(Session session) {
if (getStep(session) == 0) {
throw DbException.get(ErrorCode.STEP_SIZE_MUST_NOT_BE_ZERO);
}
return new RangeIndex(this, IndexColumn.wrap(columns));
}
/**
* Calculate and get the start value of this range.
*
* @param session the session
* @return the start value
*/
public long getMin(Session session) {
optimize(session);
return min.getValue(session).getLong();
}
/**
* Calculate and get the end value of this range.
*
* @param session the session
* @return the end value
*/
public long getMax(Session session) {
optimize(session);
return max.getValue(session).getLong();
}
/**
* Get the increment.
*
* @param session the session
* @return the increment (1 by default)
*/
public long getStep(Session session) {
optimize(session);
if (step == null) {
return 1;
}
return step.getValue(session).getLong();
}
private void optimize(Session s) {
if (!optimized) {
min = min.optimize(s);
max = max.optimize(s);
if (step != null) {
step = step.optimize(s);
}
optimized = true;
}
}
@Override
public ArrayList<Index> getIndexes() {
return null;
}
@Override
public void truncate(Session session) {
throw DbException.getUnsupportedException("SYSTEM_RANGE");
}
@Override
public long getMaxDataModificationId() {
return 0;
}
@Override
public Index getUniqueIndex() {
return null;
}
@Override
public long getRowCountApproximation() {
return 100;
}
@Override
public long getDiskSpaceUsed() {
return 0;
}
@Override
public boolean isDeterministic() {
return true;
}
@Override
public boolean canReference() {
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/RegularTable.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.h2.api.DatabaseEventListener;
import org.h2.api.ErrorCode;
import org.h2.command.ddl.CreateTableData;
import org.h2.constraint.Constraint;
import org.h2.constraint.ConstraintReferential;
import org.h2.engine.Constants;
import org.h2.engine.DbObject;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.index.Cursor;
import org.h2.index.HashIndex;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.index.MultiVersionIndex;
import org.h2.index.NonUniqueHashIndex;
import org.h2.index.PageBtreeIndex;
import org.h2.index.PageDataIndex;
import org.h2.index.PageDelegateIndex;
import org.h2.index.ScanIndex;
import org.h2.index.SpatialTreeIndex;
import org.h2.index.TreeIndex;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.Row;
import org.h2.result.SortOrder;
import org.h2.schema.SchemaObject;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.value.CompareMode;
import org.h2.value.DataType;
import org.h2.value.Value;
/**
* Most tables are an instance of this class. For this table, the data is stored
* in the database. The actual data is not kept here, instead it is kept in the
* indexes. There is at least one index, the scan index.
*/
public class RegularTable extends TableBase {
private Index scanIndex;
private long rowCount;
private volatile Session lockExclusiveSession;
private HashSet<Session> lockSharedSessions = new HashSet<>();
/**
* The queue of sessions waiting to lock the table. It is a FIFO queue to
* prevent starvation, since Java's synchronized locking is biased.
*/
private final ArrayDeque<Session> waitingSessions = new ArrayDeque<>();
private final Trace traceLock;
private final ArrayList<Index> indexes = New.arrayList();
private long lastModificationId;
private final boolean containsLargeObject;
private final PageDataIndex mainIndex;
private int changesSinceAnalyze;
private int nextAnalyze;
private Column rowIdColumn;
public RegularTable(CreateTableData data) {
super(data);
nextAnalyze = database.getSettings().analyzeAuto;
this.isHidden = data.isHidden;
boolean b = false;
for (Column col : getColumns()) {
if (DataType.isLargeObject(col.getType())) {
b = true;
break;
}
}
containsLargeObject = b;
if (data.persistData && database.isPersistent()) {
mainIndex = new PageDataIndex(this, data.id,
IndexColumn.wrap(getColumns()),
IndexType.createScan(data.persistData),
data.create, data.session);
scanIndex = mainIndex;
} else {
mainIndex = null;
scanIndex = new ScanIndex(this, data.id,
IndexColumn.wrap(getColumns()), IndexType.createScan(data.persistData));
}
indexes.add(scanIndex);
traceLock = database.getTrace(Trace.LOCK);
}
@Override
public void close(Session session) {
for (Index index : indexes) {
index.close(session);
}
}
@Override
public Row getRow(Session session, long key) {
return scanIndex.getRow(session, key);
}
@Override
public void addRow(Session session, Row row) {
lastModificationId = database.getNextModificationDataId();
if (database.isMultiVersion()) {
row.setSessionId(session.getId());
}
int i = 0;
try {
for (int size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
index.add(session, row);
checkRowCount(session, index, 1);
}
rowCount++;
} catch (Throwable e) {
try {
while (--i >= 0) {
Index index = indexes.get(i);
index.remove(session, row);
checkRowCount(session, index, 0);
}
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means there is something wrong
// with the database
trace.error(e2, "could not undo operation");
throw e2;
}
DbException de = DbException.convert(e);
if (de.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
for (Index index : indexes) {
if (index.getIndexType().isUnique() && index instanceof MultiVersionIndex) {
MultiVersionIndex mv = (MultiVersionIndex) index;
if (mv.isUncommittedFromOtherSession(session, row)) {
throw DbException.get(
ErrorCode.CONCURRENT_UPDATE_1, index.getName());
}
}
}
}
throw de;
}
analyzeIfRequired(session);
}
@Override
public void commit(short operation, Row row) {
lastModificationId = database.getNextModificationDataId();
for (Index index : indexes) {
index.commit(operation, row);
}
}
private void checkRowCount(Session session, Index index, int offset) {
if (SysProperties.CHECK && !database.isMultiVersion()) {
if (!(index instanceof PageDelegateIndex)) {
long rc = index.getRowCount(session);
if (rc != rowCount + offset) {
DbException.throwInternalError(
"rowCount expected " + (rowCount + offset) +
" got " + rc + " " + getName() + "." + index.getName());
}
}
}
}
@Override
public Index getScanIndex(Session session) {
return indexes.get(0);
}
@Override
public Index getUniqueIndex() {
for (Index idx : indexes) {
if (idx.getIndexType().isUnique()) {
return idx;
}
}
return null;
}
@Override
public ArrayList<Index> getIndexes() {
return indexes;
}
@Override
public Index addIndex(Session session, String indexName, int indexId,
IndexColumn[] cols, IndexType indexType, boolean create,
String indexComment) {
if (indexType.isPrimaryKey()) {
for (IndexColumn c : cols) {
Column column = c.column;
if (column.isNullable()) {
throw DbException.get(
ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName());
}
column.setPrimaryKey(true);
}
}
boolean isSessionTemporary = isTemporary() && !isGlobalTemporary();
if (!isSessionTemporary) {
database.lockMeta(session);
}
Index index;
if (isPersistIndexes() && indexType.isPersistent()) {
int mainIndexColumn;
if (database.isStarting() &&
database.getPageStore().getRootPageId(indexId) != 0) {
mainIndexColumn = -1;
} else if (!database.isStarting() && mainIndex.getRowCount(session) != 0) {
mainIndexColumn = -1;
} else {
mainIndexColumn = getMainIndexColumn(indexType, cols);
}
if (mainIndexColumn != -1) {
mainIndex.setMainIndexColumn(mainIndexColumn);
index = new PageDelegateIndex(this, indexId, indexName,
indexType, mainIndex, create, session);
} else if (indexType.isSpatial()) {
index = new SpatialTreeIndex(this, indexId, indexName, cols,
indexType, true, create, session);
} else {
index = new PageBtreeIndex(this, indexId, indexName, cols,
indexType, create, session);
}
} else {
if (indexType.isHash()) {
if (cols.length != 1) {
throw DbException.getUnsupportedException(
"hash indexes may index only one column");
}
if (indexType.isUnique()) {
index = new HashIndex(this, indexId, indexName, cols,
indexType);
} else {
index = new NonUniqueHashIndex(this, indexId, indexName,
cols, indexType);
}
} else if (indexType.isSpatial()) {
index = new SpatialTreeIndex(this, indexId, indexName, cols,
indexType, false, true, session);
} else {
index = new TreeIndex(this, indexId, indexName, cols, indexType);
}
}
if (database.isMultiVersion()) {
index = new MultiVersionIndex(index, this);
}
if (index.needRebuild() && rowCount > 0) {
try {
Index scan = getScanIndex(session);
long remaining = scan.getRowCount(session);
long total = remaining;
Cursor cursor = scan.find(session, null, null);
long i = 0;
int bufferSize = (int) Math.min(rowCount, database.getMaxMemoryRows());
ArrayList<Row> buffer = new ArrayList<>(bufferSize);
String n = getName() + ":" + index.getName();
int t = MathUtils.convertLongToInt(total);
while (cursor.next()) {
database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n,
MathUtils.convertLongToInt(i++), t);
Row row = cursor.get();
buffer.add(row);
if (buffer.size() >= bufferSize) {
addRowsToIndex(session, buffer, index);
}
remaining--;
}
addRowsToIndex(session, buffer, index);
if (SysProperties.CHECK && remaining != 0) {
DbException.throwInternalError("rowcount remaining=" +
remaining + " " + getName());
}
} catch (DbException e) {
getSchema().freeUniqueName(indexName);
try {
index.remove(session);
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means
// there is something wrong with the database
trace.error(e2, "could not remove index");
throw e2;
}
throw e;
}
}
index.setTemporary(isTemporary());
if (index.getCreateSQL() != null) {
index.setComment(indexComment);
if (isSessionTemporary) {
session.addLocalTempTableIndex(index);
} else {
database.addSchemaObject(session, index);
}
}
indexes.add(index);
setModified();
return index;
}
private int getMainIndexColumn(IndexType indexType, IndexColumn[] cols) {
if (mainIndex.getMainIndexColumn() != -1) {
return -1;
}
if (!indexType.isPrimaryKey() || cols.length != 1) {
return -1;
}
IndexColumn first = cols[0];
if (first.sortType != SortOrder.ASCENDING) {
return -1;
}
switch (first.column.getType()) {
case Value.BYTE:
case Value.SHORT:
case Value.INT:
case Value.LONG:
break;
default:
return -1;
}
return first.column.getColumnId();
}
@Override
public boolean canGetRowCount() {
return true;
}
private static void addRowsToIndex(Session session, ArrayList<Row> list,
Index index) {
final Index idx = index;
Collections.sort(list, new Comparator<Row>() {
@Override
public int compare(Row r1, Row r2) {
return idx.compareRows(r1, r2);
}
});
for (Row row : list) {
index.add(session, row);
}
list.clear();
}
@Override
public boolean canDrop() {
return true;
}
@Override
public long getRowCount(Session session) {
if (database.isMultiVersion()) {
return getScanIndex(session).getRowCount(session);
}
return rowCount;
}
@Override
public void removeRow(Session session, Row row) {
if (database.isMultiVersion()) {
if (row.isDeleted()) {
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, getName());
}
int old = row.getSessionId();
int newId = session.getId();
if (old == 0) {
row.setSessionId(newId);
} else if (old != newId) {
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, getName());
}
}
lastModificationId = database.getNextModificationDataId();
int i = indexes.size() - 1;
try {
for (; i >= 0; i--) {
Index index = indexes.get(i);
index.remove(session, row);
checkRowCount(session, index, -1);
}
rowCount--;
} catch (Throwable e) {
try {
while (++i < indexes.size()) {
Index index = indexes.get(i);
index.add(session, row);
checkRowCount(session, index, 0);
}
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means there is something wrong
// with the database
trace.error(e2, "could not undo operation");
throw e2;
}
throw DbException.convert(e);
}
analyzeIfRequired(session);
}
@Override
public void truncate(Session session) {
lastModificationId = database.getNextModificationDataId();
for (int i = indexes.size() - 1; i >= 0; i--) {
Index index = indexes.get(i);
index.truncate(session);
}
rowCount = 0;
changesSinceAnalyze = 0;
}
private void analyzeIfRequired(Session session) {
if (nextAnalyze == 0 || nextAnalyze > changesSinceAnalyze++) {
return;
}
changesSinceAnalyze = 0;
int n = 2 * nextAnalyze;
if (n > 0) {
nextAnalyze = n;
}
session.markTableForAnalyze(this);
}
@Override
public boolean isLockedExclusivelyBy(Session session) {
return lockExclusiveSession == session;
}
@Override
public boolean lock(Session session, boolean exclusive,
boolean forceLockEvenInMvcc) {
int lockMode = database.getLockMode();
if (lockMode == Constants.LOCK_MODE_OFF) {
return lockExclusiveSession != null;
}
if (!forceLockEvenInMvcc && database.isMultiVersion()) {
// MVCC: update, delete, and insert use a shared lock.
// Select doesn't lock except when using FOR UPDATE
if (exclusive) {
exclusive = false;
} else {
if (lockExclusiveSession == null) {
return false;
}
}
}
if (lockExclusiveSession == session) {
return true;
}
synchronized (database) {
if (lockExclusiveSession == session) {
return true;
}
if (!exclusive && lockSharedSessions.contains(session)) {
return true;
}
session.setWaitForLock(this, Thread.currentThread());
waitingSessions.addLast(session);
try {
doLock1(session, lockMode, exclusive);
} finally {
session.setWaitForLock(null, null);
waitingSessions.remove(session);
}
}
return false;
}
private void doLock1(Session session, int lockMode, boolean exclusive) {
traceLock(session, exclusive, "requesting for");
// don't get the current time unless necessary
long max = 0;
boolean checkDeadlock = false;
while (true) {
// if I'm the next one in the queue
if (waitingSessions.getFirst() == session) {
if (doLock2(session, lockMode, exclusive)) {
return;
}
}
if (checkDeadlock) {
ArrayList<Session> sessions = checkDeadlock(session, null, null);
if (sessions != null) {
throw DbException.get(ErrorCode.DEADLOCK_1,
getDeadlockDetails(sessions, exclusive));
}
} else {
// check for deadlocks from now on
checkDeadlock = true;
}
long now = System.nanoTime();
if (max == 0) {
// try at least one more time
max = now + TimeUnit.MILLISECONDS.toNanos(session.getLockTimeout());
} else if (now >= max) {
traceLock(session, exclusive, "timeout after " + session.getLockTimeout());
throw DbException.get(ErrorCode.LOCK_TIMEOUT_1, getName());
}
try {
traceLock(session, exclusive, "waiting for");
if (database.getLockMode() == Constants.LOCK_MODE_TABLE_GC) {
for (int i = 0; i < 20; i++) {
long free = Runtime.getRuntime().freeMemory();
System.gc();
long free2 = Runtime.getRuntime().freeMemory();
if (free == free2) {
break;
}
}
}
// don't wait too long so that deadlocks are detected early
long sleep = Math.min(Constants.DEADLOCK_CHECK,
TimeUnit.NANOSECONDS.toMillis(max - now));
if (sleep == 0) {
sleep = 1;
}
database.wait(sleep);
} catch (InterruptedException e) {
// ignore
}
}
}
private boolean doLock2(Session session, int lockMode, boolean exclusive) {
if (exclusive) {
if (lockExclusiveSession == null) {
if (lockSharedSessions.isEmpty()) {
traceLock(session, exclusive, "added for");
session.addLock(this);
lockExclusiveSession = session;
return true;
} else if (lockSharedSessions.size() == 1 &&
lockSharedSessions.contains(session)) {
traceLock(session, exclusive, "add (upgraded) for ");
lockExclusiveSession = session;
return true;
}
}
} else {
if (lockExclusiveSession == null) {
if (lockMode == Constants.LOCK_MODE_READ_COMMITTED) {
if (!database.isMultiThreaded() && !database.isMultiVersion()) {
// READ_COMMITTED: a read lock is acquired,
// but released immediately after the operation
// is complete.
// When allowing only one thread, no lock is
// required.
// Row level locks work like read committed.
return true;
}
}
if (!lockSharedSessions.contains(session)) {
traceLock(session, exclusive, "ok");
session.addLock(this);
lockSharedSessions.add(session);
}
return true;
}
}
return false;
}
private static String getDeadlockDetails(ArrayList<Session> sessions, boolean exclusive) {
// We add the thread details here to make it easier for customers to
// match up these error messages with their own logs.
StringBuilder buff = new StringBuilder();
for (Session s : sessions) {
Table lock = s.getWaitForLock();
Thread thread = s.getWaitForLockThread();
buff.append("\nSession ").
append(s.toString()).
append(" on thread ").
append(thread.getName()).
append(" is waiting to lock ").
append(lock.toString()).
append(exclusive ? " (exclusive)" : " (shared)").
append(" while locking ");
int i = 0;
for (Table t : s.getLocks()) {
if (i++ > 0) {
buff.append(", ");
}
buff.append(t.toString());
if (t instanceof RegularTable) {
if (((RegularTable) t).lockExclusiveSession == s) {
buff.append(" (exclusive)");
} else {
buff.append(" (shared)");
}
}
}
buff.append('.');
}
return buff.toString();
}
@Override
public ArrayList<Session> checkDeadlock(Session session, Session clash,
Set<Session> visited) {
// only one deadlock check at any given time
synchronized (RegularTable.class) {
if (clash == null) {
// verification is started
clash = session;
visited = new HashSet<>();
} else if (clash == session) {
// we found a circle where this session is involved
return New.arrayList();
} else if (visited.contains(session)) {
// we have already checked this session.
// there is a circle, but the sessions in the circle need to
// find it out themselves
return null;
}
visited.add(session);
ArrayList<Session> error = null;
for (Session s : lockSharedSessions) {
if (s == session) {
// it doesn't matter if we have locked the object already
continue;
}
Table t = s.getWaitForLock();
if (t != null) {
error = t.checkDeadlock(s, clash, visited);
if (error != null) {
error.add(session);
break;
}
}
}
if (error == null && lockExclusiveSession != null) {
Table t = lockExclusiveSession.getWaitForLock();
if (t != null) {
error = t.checkDeadlock(lockExclusiveSession, clash, visited);
if (error != null) {
error.add(session);
}
}
}
return error;
}
}
private void traceLock(Session session, boolean exclusive, String s) {
if (traceLock.isDebugEnabled()) {
traceLock.debug("{0} {1} {2} {3}", session.getId(),
exclusive ? "exclusive write lock" : "shared read lock", s, getName());
}
}
@Override
public boolean isLockedExclusively() {
return lockExclusiveSession != null;
}
@Override
public void unlock(Session s) {
if (database != null) {
traceLock(s, lockExclusiveSession == s, "unlock");
if (lockExclusiveSession == s) {
lockExclusiveSession = null;
}
synchronized (database) {
if (!lockSharedSessions.isEmpty()) {
lockSharedSessions.remove(s);
}
if (!waitingSessions.isEmpty()) {
database.notifyAll();
}
}
}
}
/**
* Set the row count of this table.
*
* @param count the row count
*/
public void setRowCount(long count) {
this.rowCount = count;
}
@Override
public void removeChildrenAndResources(Session session) {
if (containsLargeObject) {
// unfortunately, the data is gone on rollback
truncate(session);
database.getLobStorage().removeAllForTable(getId());
database.lockMeta(session);
}
super.removeChildrenAndResources(session);
// go backwards because database.removeIndex will call table.removeIndex
while (indexes.size() > 1) {
Index index = indexes.get(1);
if (index.getName() != null) {
database.removeSchemaObject(session, index);
}
// needed for session temporary indexes
indexes.remove(index);
}
if (SysProperties.CHECK) {
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.INDEX)) {
Index index = (Index) obj;
if (index.getTable() == this) {
DbException.throwInternalError("index not dropped: " + index.getName());
}
}
}
scanIndex.remove(session);
database.removeMeta(session, getId());
scanIndex = null;
lockExclusiveSession = null;
lockSharedSessions = null;
invalidate();
}
@Override
public String toString() {
return getSQL();
}
@Override
public void checkRename() {
// ok
}
@Override
public void checkSupportAlter() {
// ok
}
@Override
public boolean canTruncate() {
if (getCheckForeignKeyConstraints() && database.getReferentialIntegrity()) {
ArrayList<Constraint> constraints = getConstraints();
if (constraints != null) {
for (Constraint c : constraints) {
if (c.getConstraintType() != Constraint.Type.REFERENTIAL) {
continue;
}
ConstraintReferential ref = (ConstraintReferential) c;
if (ref.getRefTable() == this) {
return false;
}
}
}
}
return true;
}
@Override
public TableType getTableType() {
return TableType.TABLE;
}
@Override
public long getMaxDataModificationId() {
return lastModificationId;
}
public boolean getContainsLargeObject() {
return containsLargeObject;
}
@Override
public long getRowCountApproximation() {
return scanIndex.getRowCountApproximation();
}
@Override
public long getDiskSpaceUsed() {
return scanIndex.getDiskSpaceUsed();
}
public void setCompareMode(CompareMode compareMode) {
this.compareMode = compareMode;
}
@Override
public boolean isDeterministic() {
return true;
}
@Override
public Column getRowIdColumn() {
if (rowIdColumn == null) {
rowIdColumn = new Column(Column.ROWID, Value.LONG);
rowIdColumn.setTable(this, -1);
}
return rowIdColumn;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/SingleColumnResolver.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import org.h2.command.dml.Select;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.value.Value;
/**
* The single column resolver is like a table with exactly one row.
* It is used to parse a simple one-column check constraint.
*/
public class SingleColumnResolver implements ColumnResolver {
private final Column column;
private Value value;
SingleColumnResolver(Column column) {
this.column = column;
}
@Override
public String getTableAlias() {
return null;
}
void setValue(Value value) {
this.value = value;
}
@Override
public Value getValue(Column col) {
return value;
}
@Override
public Column[] getColumns() {
return new Column[] { column };
}
@Override
public String getDerivedColumnName(Column column) {
return null;
}
@Override
public String getSchemaName() {
return null;
}
@Override
public TableFilter getTableFilter() {
return null;
}
@Override
public Select getSelect() {
return null;
}
@Override
public Column[] getSystemColumns() {
return null;
}
@Override
public Column getRowIdColumn() {
return null;
}
@Override
public Expression optimize(ExpressionColumn expressionColumn, Column col) {
return expressionColumn;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/SubQueryInfo.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import org.h2.result.SortOrder;
/**
* Information about current sub-query being prepared.
*
* @author Sergi Vladykin
*/
public class SubQueryInfo {
private final int[] masks;
private final TableFilter[] filters;
private final int filter;
private final SortOrder sortOrder;
private final SubQueryInfo upper;
/**
* @param upper upper level sub-query if any
* @param masks index conditions masks
* @param filters table filters
* @param filter current filter
* @param sortOrder sort order
*/
public SubQueryInfo(SubQueryInfo upper, int[] masks, TableFilter[] filters, int filter,
SortOrder sortOrder) {
this.upper = upper;
this.masks = masks;
this.filters = filters;
this.filter = filter;
this.sortOrder = sortOrder;
}
public SubQueryInfo getUpper() {
return upper;
}
public int[] getMasks() {
return masks;
}
public TableFilter[] getFilters() {
return filters;
}
public int getFilter() {
return filter;
}
public SortOrder getSortOrder() {
return sortOrder;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/Table.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.Prepared;
import org.h2.constraint.Constraint;
import org.h2.engine.Constants;
import org.h2.engine.DbObject;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.engine.UndoLogRecord;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionVisitor;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.Row;
import org.h2.result.RowList;
import org.h2.result.SearchRow;
import org.h2.result.SimpleRow;
import org.h2.result.SimpleRowValue;
import org.h2.result.SortOrder;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObjectBase;
import org.h2.schema.Sequence;
import org.h2.schema.TriggerObject;
import org.h2.util.New;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* This is the base class for most tables.
* A table contains a list of columns and a list of rows.
*/
public abstract class Table extends SchemaObjectBase {
/**
* The table type that means this table is a regular persistent table.
*/
public static final int TYPE_CACHED = 0;
/**
* The table type that means this table is a regular persistent table.
*/
public static final int TYPE_MEMORY = 1;
/**
* The columns of this table.
*/
protected Column[] columns;
/**
* The compare mode used for this table.
*/
protected CompareMode compareMode;
/**
* Protected tables are not listed in the meta data and are excluded when
* using the SCRIPT command.
*/
protected boolean isHidden;
private final HashMap<String, Column> columnMap;
private final boolean persistIndexes;
private final boolean persistData;
private ArrayList<TriggerObject> triggers;
private ArrayList<Constraint> constraints;
private ArrayList<Sequence> sequences;
/**
* views that depend on this table
*/
private final CopyOnWriteArrayList<TableView> dependentViews = new CopyOnWriteArrayList<>();
private ArrayList<TableSynonym> synonyms;
private boolean checkForeignKeyConstraints = true;
private boolean onCommitDrop, onCommitTruncate;
private volatile Row nullRow;
private boolean tableExpression;
public Table(Schema schema, int id, String name, boolean persistIndexes,
boolean persistData) {
columnMap = schema.getDatabase().newStringMap();
initSchemaObjectBase(schema, id, name, Trace.TABLE);
this.persistIndexes = persistIndexes;
this.persistData = persistData;
compareMode = schema.getDatabase().getCompareMode();
}
@Override
public void rename(String newName) {
super.rename(newName);
if (constraints != null) {
for (Constraint constraint : constraints) {
constraint.rebuild();
}
}
}
public boolean isView() {
return false;
}
/**
* Lock the table for the given session.
* This method waits until the lock is granted.
*
* @param session the session
* @param exclusive true for write locks, false for read locks
* @param forceLockEvenInMvcc lock even in the MVCC mode
* @return true if the table was already exclusively locked by this session.
* @throws DbException if a lock timeout occurred
*/
public abstract boolean lock(Session session, boolean exclusive, boolean forceLockEvenInMvcc);
/**
* Close the table object and flush changes.
*
* @param session the session
*/
public abstract void close(Session session);
/**
* Release the lock for this session.
*
* @param s the session
*/
public abstract void unlock(Session s);
/**
* Create an index for this table
*
* @param session the session
* @param indexName the name of the index
* @param indexId the id
* @param cols the index columns
* @param indexType the index type
* @param create whether this is a new index
* @param indexComment the comment
* @return the index
*/
public abstract Index addIndex(Session session, String indexName,
int indexId, IndexColumn[] cols, IndexType indexType,
boolean create, String indexComment);
/**
* Get the given row.
*
* @param session the session
* @param key the primary key
* @return the row
*/
@SuppressWarnings("unused")
public Row getRow(Session session, long key) {
return null;
}
/**
* Remove a row from the table and all indexes.
*
* @param session the session
* @param row the row
*/
public abstract void removeRow(Session session, Row row);
/**
* Remove all rows from the table and indexes.
*
* @param session the session
*/
public abstract void truncate(Session session);
/**
* Add a row to the table and all indexes.
*
* @param session the session
* @param row the row
* @throws DbException if a constraint was violated
*/
public abstract void addRow(Session session, Row row);
/**
* Commit an operation (when using multi-version concurrency).
*
* @param operation the operation
* @param row the row
*/
@SuppressWarnings("unused")
public void commit(short operation, Row row) {
// nothing to do
}
/**
* Check if this table supports ALTER TABLE.
*
* @throws DbException if it is not supported
*/
public abstract void checkSupportAlter();
/**
* Get the table type name
*
* @return the table type name
*/
public abstract TableType getTableType();
/**
* Get the scan index to iterate through all rows.
*
* @param session the session
* @return the index
*/
public abstract Index getScanIndex(Session session);
/**
* Get the scan index for this table.
*
* @param session the session
* @param masks the search mask
* @param filters the table filters
* @param filter the filter index
* @param sortOrder the sort order
* @param allColumnsSet all columns
* @return the scan index
*/
@SuppressWarnings("unused")
public Index getScanIndex(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
return getScanIndex(session);
}
/**
* Get any unique index for this table if one exists.
*
* @return a unique index
*/
public abstract Index getUniqueIndex();
/**
* Get all indexes for this table.
*
* @return the list of indexes
*/
public abstract ArrayList<Index> getIndexes();
/**
* Get an index by name.
*
* @param indexName the index name to search for
* @return the found index
*/
public Index getIndex(String indexName) {
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
for (Index index : indexes) {
if (index.getName().equals(indexName)) {
return index;
}
}
}
throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1, indexName);
}
/**
* Check if this table is locked exclusively.
*
* @return true if it is.
*/
public abstract boolean isLockedExclusively();
/**
* Get the last data modification id.
*
* @return the modification id
*/
public abstract long getMaxDataModificationId();
/**
* Check if the table is deterministic.
*
* @return true if it is
*/
public abstract boolean isDeterministic();
/**
* Check if the row count can be retrieved quickly.
*
* @return true if it can
*/
public abstract boolean canGetRowCount();
/**
* Check if this table can be referenced.
*
* @return true if it can
*/
public boolean canReference() {
return true;
}
/**
* Check if this table can be dropped.
*
* @return true if it can
*/
public abstract boolean canDrop();
/**
* Get the row count for this table.
*
* @param session the session
* @return the row count
*/
public abstract long getRowCount(Session session);
/**
* Get the approximated row count for this table.
*
* @return the approximated row count
*/
public abstract long getRowCountApproximation();
public abstract long getDiskSpaceUsed();
/**
* Get the row id column if this table has one.
*
* @return the row id column, or null
*/
public Column getRowIdColumn() {
return null;
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
/**
* Check whether the table (or view) contains no columns that prevent index
* conditions to be used. For example, a view that contains the ROWNUM()
* pseudo-column prevents this.
*
* @return true if the table contains no query-comparable column
*/
public boolean isQueryComparable() {
return true;
}
/**
* Add all objects that this table depends on to the hash set.
*
* @param dependencies the current set of dependencies
*/
public void addDependencies(HashSet<DbObject> dependencies) {
if (dependencies.contains(this)) {
// avoid endless recursion
return;
}
if (sequences != null) {
dependencies.addAll(sequences);
}
ExpressionVisitor visitor = ExpressionVisitor.getDependenciesVisitor(
dependencies);
for (Column col : columns) {
col.isEverything(visitor);
}
if (constraints != null) {
for (Constraint c : constraints) {
c.isEverything(visitor);
}
}
dependencies.add(this);
}
@Override
public ArrayList<DbObject> getChildren() {
ArrayList<DbObject> children = New.arrayList();
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
children.addAll(indexes);
}
if (constraints != null) {
children.addAll(constraints);
}
if (triggers != null) {
children.addAll(triggers);
}
if (sequences != null) {
children.addAll(sequences);
}
children.addAll(dependentViews);
if (synonyms != null) {
children.addAll(synonyms);
}
ArrayList<Right> rights = database.getAllRights();
for (Right right : rights) {
if (right.getGrantedObject() == this) {
children.add(right);
}
}
return children;
}
protected void setColumns(Column[] columns) {
this.columns = columns;
if (columnMap.size() > 0) {
columnMap.clear();
}
for (int i = 0; i < columns.length; i++) {
Column col = columns[i];
int dataType = col.getType();
if (dataType == Value.UNKNOWN) {
throw DbException.get(
ErrorCode.UNKNOWN_DATA_TYPE_1, col.getSQL());
}
col.setTable(this, i);
String columnName = col.getName();
if (columnMap.get(columnName) != null) {
throw DbException.get(
ErrorCode.DUPLICATE_COLUMN_NAME_1, columnName);
}
columnMap.put(columnName, col);
}
}
/**
* Rename a column of this table.
*
* @param column the column to rename
* @param newName the new column name
*/
public void renameColumn(Column column, String newName) {
for (Column c : columns) {
if (c == column) {
continue;
}
if (c.getName().equals(newName)) {
throw DbException.get(
ErrorCode.DUPLICATE_COLUMN_NAME_1, newName);
}
}
columnMap.remove(column.getName());
column.rename(newName);
columnMap.put(newName, column);
}
/**
* Check if the table is exclusively locked by this session.
*
* @param session the session
* @return true if it is
*/
@SuppressWarnings("unused")
public boolean isLockedExclusivelyBy(Session session) {
return false;
}
/**
* Update a list of rows in this table.
*
* @param prepared the prepared statement
* @param session the session
* @param rows a list of row pairs of the form old row, new row, old row,
* new row,...
*/
public void updateRows(Prepared prepared, Session session, RowList rows) {
// in case we need to undo the update
Session.Savepoint rollback = session.setSavepoint();
// remove the old rows
int rowScanCount = 0;
for (rows.reset(); rows.hasNext();) {
if ((++rowScanCount & 127) == 0) {
prepared.checkCanceled();
}
Row o = rows.next();
rows.next();
try {
removeRow(session, o);
} catch (DbException e) {
if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) {
session.rollbackTo(rollback, false);
session.startStatementWithinTransaction();
rollback = session.setSavepoint();
}
throw e;
}
session.log(this, UndoLogRecord.DELETE, o);
}
// add the new rows
for (rows.reset(); rows.hasNext();) {
if ((++rowScanCount & 127) == 0) {
prepared.checkCanceled();
}
rows.next();
Row n = rows.next();
try {
addRow(session, n);
} catch (DbException e) {
if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) {
session.rollbackTo(rollback, false);
session.startStatementWithinTransaction();
rollback = session.setSavepoint();
}
throw e;
}
session.log(this, UndoLogRecord.INSERT, n);
}
}
public CopyOnWriteArrayList<TableView> getDependentViews() {
return dependentViews;
}
@Override
public void removeChildrenAndResources(Session session) {
while (!dependentViews.isEmpty()) {
TableView view = dependentViews.get(0);
dependentViews.remove(0);
database.removeSchemaObject(session, view);
}
while (synonyms != null && !synonyms.isEmpty()) {
TableSynonym synonym = synonyms.remove(0);
database.removeSchemaObject(session, synonym);
}
while (triggers != null && !triggers.isEmpty()) {
TriggerObject trigger = triggers.remove(0);
database.removeSchemaObject(session, trigger);
}
while (constraints != null && !constraints.isEmpty()) {
Constraint constraint = constraints.remove(0);
database.removeSchemaObject(session, constraint);
}
for (Right right : database.getAllRights()) {
if (right.getGrantedObject() == this) {
database.removeDatabaseObject(session, right);
}
}
database.removeMeta(session, getId());
// must delete sequences later (in case there is a power failure
// before removing the table object)
while (sequences != null && !sequences.isEmpty()) {
Sequence sequence = sequences.remove(0);
// only remove if no other table depends on this sequence
// this is possible when calling ALTER TABLE ALTER COLUMN
if (database.getDependentTable(sequence, this) == null) {
database.removeSchemaObject(session, sequence);
}
}
}
/**
* Check that these columns are not referenced by a multi-column constraint
* or multi-column index. If it is, an exception is thrown. Single-column
* references and indexes are dropped.
*
* @param session the session
* @param columnsToDrop the columns to drop
* @throws DbException if the column is referenced by multi-column
* constraints or indexes
*/
public void dropMultipleColumnsConstraintsAndIndexes(Session session,
ArrayList<Column> columnsToDrop) {
HashSet<Constraint> constraintsToDrop = new HashSet<>();
if (constraints != null) {
for (Column col : columnsToDrop) {
for (Constraint constraint : constraints) {
HashSet<Column> columns = constraint.getReferencedColumns(this);
if (!columns.contains(col)) {
continue;
}
if (columns.size() == 1) {
constraintsToDrop.add(constraint);
} else {
throw DbException.get(
ErrorCode.COLUMN_IS_REFERENCED_1, constraint.getSQL());
}
}
}
}
HashSet<Index> indexesToDrop = new HashSet<>();
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
for (Column col : columnsToDrop) {
for (Index index : indexes) {
if (index.getCreateSQL() == null) {
continue;
}
if (index.getColumnIndex(col) < 0) {
continue;
}
if (index.getColumns().length == 1) {
indexesToDrop.add(index);
} else {
throw DbException.get(
ErrorCode.COLUMN_IS_REFERENCED_1, index.getSQL());
}
}
}
}
for (Constraint c : constraintsToDrop) {
session.getDatabase().removeSchemaObject(session, c);
}
for (Index i : indexesToDrop) {
// the index may already have been dropped when dropping the
// constraint
if (getIndexes().contains(i)) {
session.getDatabase().removeSchemaObject(session, i);
}
}
}
public Row getTemplateRow() {
return database.createRow(new Value[columns.length], Row.MEMORY_CALCULATE);
}
/**
* Get a new simple row object.
*
* @param singleColumn if only one value need to be stored
* @return the simple row object
*/
public SearchRow getTemplateSimpleRow(boolean singleColumn) {
if (singleColumn) {
return new SimpleRowValue(columns.length);
}
return new SimpleRow(new Value[columns.length]);
}
Row getNullRow() {
Row row = nullRow;
if (row == null) {
// Here can be concurrently produced more than one row, but it must
// be ok.
Value[] values = new Value[columns.length];
Arrays.fill(values, ValueNull.INSTANCE);
nullRow = row = database.createRow(values, 1);
}
return row;
}
public Column[] getColumns() {
return columns;
}
@Override
public int getType() {
return DbObject.TABLE_OR_VIEW;
}
/**
* Get the column at the given index.
*
* @param index the column index (0, 1,...)
* @return the column
*/
public Column getColumn(int index) {
return columns[index];
}
/**
* Get the column with the given name.
*
* @param columnName the column name
* @return the column
* @throws DbException if the column was not found
*/
public Column getColumn(String columnName) {
Column column = columnMap.get(columnName);
if (column == null) {
throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, columnName);
}
return column;
}
/**
* Does the column with the given name exist?
*
* @param columnName the column name
* @return true if the column exists
*/
public boolean doesColumnExist(String columnName) {
return columnMap.containsKey(columnName);
}
/**
* Get the best plan for the given search mask.
*
* @param session the session
* @param masks per-column comparison bit masks, null means 'always false',
* see constants in IndexCondition
* @param filters all joined table filters
* @param filter the current table filter index
* @param sortOrder the sort order
* @param allColumnsSet the set of all columns
* @return the plan item
*/
public PlanItem getBestPlanItem(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
PlanItem item = new PlanItem();
item.setIndex(getScanIndex(session));
item.cost = item.getIndex().getCost(session, null, filters, filter, null, allColumnsSet);
Trace t = session.getTrace();
if (t.isDebugEnabled()) {
t.debug("Table : potential plan item cost {0} index {1}",
item.cost, item.getIndex().getPlanSQL());
}
ArrayList<Index> indexes = getIndexes();
IndexHints indexHints = getIndexHints(filters, filter);
if (indexes != null && masks != null) {
for (int i = 1, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
if (isIndexExcludedByHints(indexHints, index)) {
continue;
}
double cost = index.getCost(session, masks, filters, filter,
sortOrder, allColumnsSet);
if (t.isDebugEnabled()) {
t.debug("Table : potential plan item cost {0} index {1}",
cost, index.getPlanSQL());
}
if (cost < item.cost) {
item.cost = cost;
item.setIndex(index);
}
}
}
return item;
}
private static boolean isIndexExcludedByHints(IndexHints indexHints, Index index) {
return indexHints != null && !indexHints.allowIndex(index);
}
private static IndexHints getIndexHints(TableFilter[] filters, int filter) {
return filters == null ? null : filters[filter].getIndexHints();
}
/**
* Get the primary key index if there is one, or null if there is none.
*
* @return the primary key index or null
*/
public Index findPrimaryKey() {
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
for (Index idx : indexes) {
if (idx.getIndexType().isPrimaryKey()) {
return idx;
}
}
}
return null;
}
public Index getPrimaryKey() {
Index index = findPrimaryKey();
if (index != null) {
return index;
}
throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1,
Constants.PREFIX_PRIMARY_KEY);
}
/**
* Validate all values in this row, convert the values if required, and
* update the sequence values if required. This call will also set the
* default values if required and set the computed column if there are any.
*
* @param session the session
* @param row the row
*/
public void validateConvertUpdateSequence(Session session, Row row) {
for (int i = 0; i < columns.length; i++) {
Value value = row.getValue(i);
Column column = columns[i];
Value v2;
if (column.getComputed()) {
// force updating the value
value = null;
v2 = column.computeValue(session, row);
}
v2 = column.validateConvertUpdateSequence(session, value);
if (v2 != value) {
row.setValue(i, v2);
}
}
}
private static void remove(ArrayList<? extends DbObject> list, DbObject obj) {
if (list != null) {
list.remove(obj);
}
}
/**
* Remove the given index from the list.
*
* @param index the index to remove
*/
public void removeIndex(Index index) {
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
remove(indexes, index);
if (index.getIndexType().isPrimaryKey()) {
for (Column col : index.getColumns()) {
col.setPrimaryKey(false);
}
}
}
}
/**
* Remove the given view from the dependent views list.
*
* @param view the view to remove
*/
public void removeDependentView(TableView view) {
dependentViews.remove(view);
}
/**
* Remove the given view from the list.
*
* @param synonym the synonym to remove
*/
public void removeSynonym(TableSynonym synonym) {
remove(synonyms, synonym);
}
/**
* Remove the given constraint from the list.
*
* @param constraint the constraint to remove
*/
public void removeConstraint(Constraint constraint) {
remove(constraints, constraint);
}
/**
* Remove a sequence from the table. Sequences are used as identity columns.
*
* @param sequence the sequence to remove
*/
public final void removeSequence(Sequence sequence) {
remove(sequences, sequence);
}
/**
* Remove the given trigger from the list.
*
* @param trigger the trigger to remove
*/
public void removeTrigger(TriggerObject trigger) {
remove(triggers, trigger);
}
/**
* Add a view to this table.
*
* @param view the view to add
*/
public void addDependentView(TableView view) {
dependentViews.add(view);
}
/**
* Add a synonym to this table.
*
* @param synonym the synonym to add
*/
public void addSynonym(TableSynonym synonym) {
synonyms = add(synonyms, synonym);
}
/**
* Add a constraint to the table.
*
* @param constraint the constraint to add
*/
public void addConstraint(Constraint constraint) {
if (constraints == null || !constraints.contains(constraint)) {
constraints = add(constraints, constraint);
}
}
public ArrayList<Constraint> getConstraints() {
return constraints;
}
/**
* Add a sequence to this table.
*
* @param sequence the sequence to add
*/
public void addSequence(Sequence sequence) {
sequences = add(sequences, sequence);
}
/**
* Add a trigger to this table.
*
* @param trigger the trigger to add
*/
public void addTrigger(TriggerObject trigger) {
triggers = add(triggers, trigger);
}
private static <T> ArrayList<T> add(ArrayList<T> list, T obj) {
if (list == null) {
list = New.arrayList();
}
// self constraints are two entries in the list
list.add(obj);
return list;
}
/**
* Fire the triggers for this table.
*
* @param session the session
* @param type the trigger type
* @param beforeAction whether 'before' triggers should be called
*/
public void fire(Session session, int type, boolean beforeAction) {
if (triggers != null) {
for (TriggerObject trigger : triggers) {
trigger.fire(session, type, beforeAction);
}
}
}
/**
* Check whether this table has a select trigger.
*
* @return true if it has
*/
public boolean hasSelectTrigger() {
if (triggers != null) {
for (TriggerObject trigger : triggers) {
if (trigger.isSelectTrigger()) {
return true;
}
}
}
return false;
}
/**
* Check if row based triggers or constraints are defined.
* In this case the fire after and before row methods need to be called.
*
* @return if there are any triggers or rows defined
*/
public boolean fireRow() {
return (constraints != null && !constraints.isEmpty()) ||
(triggers != null && !triggers.isEmpty());
}
/**
* Fire all triggers that need to be called before a row is updated.
*
* @param session the session
* @param oldRow the old data or null for an insert
* @param newRow the new data or null for a delete
* @return true if no further action is required (for 'instead of' triggers)
*/
public boolean fireBeforeRow(Session session, Row oldRow, Row newRow) {
boolean done = fireRow(session, oldRow, newRow, true, false);
fireConstraints(session, oldRow, newRow, true);
return done;
}
private void fireConstraints(Session session, Row oldRow, Row newRow,
boolean before) {
if (constraints != null) {
// don't use enhanced for loop to avoid creating objects
for (Constraint constraint : constraints) {
if (constraint.isBefore() == before) {
constraint.checkRow(session, this, oldRow, newRow);
}
}
}
}
/**
* Fire all triggers that need to be called after a row is updated.
*
* @param session the session
* @param oldRow the old data or null for an insert
* @param newRow the new data or null for a delete
* @param rollback when the operation occurred within a rollback
*/
public void fireAfterRow(Session session, Row oldRow, Row newRow,
boolean rollback) {
fireRow(session, oldRow, newRow, false, rollback);
if (!rollback) {
fireConstraints(session, oldRow, newRow, false);
}
}
private boolean fireRow(Session session, Row oldRow, Row newRow,
boolean beforeAction, boolean rollback) {
if (triggers != null) {
for (TriggerObject trigger : triggers) {
boolean done = trigger.fireRow(session, this, oldRow, newRow, beforeAction, rollback);
if (done) {
return true;
}
}
}
return false;
}
public boolean isGlobalTemporary() {
return false;
}
/**
* Check if this table can be truncated.
*
* @return true if it can
*/
public boolean canTruncate() {
return false;
}
/**
* Enable or disable foreign key constraint checking for this table.
*
* @param session the session
* @param enabled true if checking should be enabled
* @param checkExisting true if existing rows must be checked during this
* call
*/
public void setCheckForeignKeyConstraints(Session session, boolean enabled,
boolean checkExisting) {
if (enabled && checkExisting) {
if (constraints != null) {
for (Constraint c : constraints) {
c.checkExistingData(session);
}
}
}
checkForeignKeyConstraints = enabled;
}
public boolean getCheckForeignKeyConstraints() {
return checkForeignKeyConstraints;
}
/**
* Get the index that has the given column as the first element.
* This method returns null if no matching index is found.
*
* @param column the column
* @param needGetFirstOrLast if the returned index must be able
* to do {@link Index#canGetFirstOrLast()}
* @param needFindNext if the returned index must be able to do
* {@link Index#findNext(Session, SearchRow, SearchRow)}
* @return the index or null
*/
public Index getIndexForColumn(Column column,
boolean needGetFirstOrLast, boolean needFindNext) {
ArrayList<Index> indexes = getIndexes();
Index result = null;
if (indexes != null) {
for (int i = 1, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
if (needGetFirstOrLast && !index.canGetFirstOrLast()) {
continue;
}
if (needFindNext && !index.canFindNext()) {
continue;
}
// choose the minimal covering index with the needed first
// column to work consistently with execution plan from
// Optimizer
if (index.isFirstColumn(column) && (result == null ||
result.getColumns().length > index.getColumns().length)) {
result = index;
}
}
}
return result;
}
public boolean getOnCommitDrop() {
return onCommitDrop;
}
public void setOnCommitDrop(boolean onCommitDrop) {
this.onCommitDrop = onCommitDrop;
}
public boolean getOnCommitTruncate() {
return onCommitTruncate;
}
public void setOnCommitTruncate(boolean onCommitTruncate) {
this.onCommitTruncate = onCommitTruncate;
}
/**
* If the index is still required by a constraint, transfer the ownership to
* it. Otherwise, the index is removed.
*
* @param session the session
* @param index the index that is no longer required
*/
public void removeIndexOrTransferOwnership(Session session, Index index) {
boolean stillNeeded = false;
if (constraints != null) {
for (Constraint cons : constraints) {
if (cons.usesIndex(index)) {
cons.setIndexOwner(index);
database.updateMeta(session, cons);
stillNeeded = true;
}
}
}
if (!stillNeeded) {
database.removeSchemaObject(session, index);
}
}
/**
* Check if a deadlock occurred. This method is called recursively. There is
* a circle if the session to be tested has already being visited. If this
* session is part of the circle (if it is the clash session), the method
* must return an empty object array. Once a deadlock has been detected, the
* methods must add the session to the list. If this session is not part of
* the circle, or if no deadlock is detected, this method returns null.
*
* @param session the session to be tested for
* @param clash set with sessions already visited, and null when starting
* verification
* @param visited set with sessions already visited, and null when starting
* verification
* @return an object array with the sessions involved in the deadlock, or
* null
*/
@SuppressWarnings("unused")
public ArrayList<Session> checkDeadlock(Session session, Session clash,
Set<Session> visited) {
return null;
}
public boolean isPersistIndexes() {
return persistIndexes;
}
public boolean isPersistData() {
return persistData;
}
/**
* Compare two values with the current comparison mode. The values may be of
* different type.
*
* @param a the first value
* @param b the second value
* @return 0 if both values are equal, -1 if the first value is smaller, and
* 1 otherwise
*/
public int compareTypeSafe(Value a, Value b) {
if (a == b) {
return 0;
}
int dataType = Value.getHigherOrder(a.getType(), b.getType());
a = a.convertTo(dataType);
b = b.convertTo(dataType);
return a.compareTypeSafe(b, compareMode);
}
public CompareMode getCompareMode() {
return compareMode;
}
/**
* Tests if the table can be written. Usually, this depends on the
* database.checkWritingAllowed method, but some tables (eg. TableLink)
* overwrite this default behaviour.
*/
public void checkWritingAllowed() {
database.checkWritingAllowed();
}
private static Value getGeneratedValue(Session session, Column column, Expression expression) {
Value v;
if (expression == null) {
v = column.validateConvertUpdateSequence(session, null);
} else {
v = expression.getValue(session);
}
return column.convert(v);
}
/**
* Get or generate a default value for the given column.
*
* @param session the session
* @param column the column
* @return the value
*/
public Value getDefaultValue(Session session, Column column) {
return getGeneratedValue(session, column, column.getDefaultExpression());
}
/**
* Generates on update value for the given column.
*
* @param session the session
* @param column the column
* @return the value
*/
public Value getOnUpdateValue(Session session, Column column) {
return getGeneratedValue(session, column, column.getOnUpdateExpression());
}
@Override
public boolean isHidden() {
return isHidden;
}
public void setHidden(boolean hidden) {
this.isHidden = hidden;
}
public boolean isMVStore() {
return false;
}
public void setTableExpression(boolean tableExpression) {
this.tableExpression = tableExpression;
}
public boolean isTableExpression() {
return tableExpression;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/TableBase.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.util.Collections;
import java.util.List;
import org.h2.command.ddl.CreateTableData;
import org.h2.engine.Database;
import org.h2.engine.DbSettings;
import org.h2.mvstore.db.MVTableEngine;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
/**
* The base class of a regular table, or a user defined table.
*
* @author Thomas Mueller
* @author Sergi Vladykin
*/
public abstract class TableBase extends Table {
/**
* The table engine used (null for regular tables).
*/
private final String tableEngine;
/** Provided table parameters */
private final List<String> tableEngineParams;
private final boolean globalTemporary;
public TableBase(CreateTableData data) {
super(data.schema, data.id, data.tableName,
data.persistIndexes, data.persistData);
this.tableEngine = data.tableEngine;
this.globalTemporary = data.globalTemporary;
if (data.tableEngineParams != null) {
this.tableEngineParams = data.tableEngineParams;
} else {
this.tableEngineParams = Collections.emptyList();
}
setTemporary(data.temporary);
Column[] cols = data.columns.toArray(new Column[0]);
setColumns(cols);
}
@Override
public String getDropSQL() {
return "DROP TABLE IF EXISTS " + getSQL() + " CASCADE";
}
@Override
public String getCreateSQL() {
Database db = getDatabase();
if (db == null) {
// closed
return null;
}
StatementBuilder buff = new StatementBuilder("CREATE ");
if (isTemporary()) {
if (isGlobalTemporary()) {
buff.append("GLOBAL ");
} else {
buff.append("LOCAL ");
}
buff.append("TEMPORARY ");
} else if (isPersistIndexes()) {
buff.append("CACHED ");
} else {
buff.append("MEMORY ");
}
buff.append("TABLE ");
if (isHidden) {
buff.append("IF NOT EXISTS ");
}
buff.append(getSQL());
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
buff.append("(\n ");
for (Column column : columns) {
buff.appendExceptFirst(",\n ");
buff.append(column.getCreateSQL());
}
buff.append("\n)");
if (tableEngine != null) {
DbSettings s = db.getSettings();
String d = s.defaultTableEngine;
if (d == null && s.mvStore) {
d = MVTableEngine.class.getName();
}
if (d == null || !tableEngine.endsWith(d)) {
buff.append("\nENGINE ");
buff.append(StringUtils.quoteIdentifier(tableEngine));
}
}
if (!tableEngineParams.isEmpty()) {
buff.append("\nWITH ");
buff.resetCount();
for (String parameter : tableEngineParams) {
buff.appendExceptFirst(", ");
buff.append(StringUtils.quoteIdentifier(parameter));
}
}
if (!isPersistIndexes() && !isPersistData()) {
buff.append("\nNOT PERSISTENT");
}
if (isHidden) {
buff.append("\nHIDDEN");
}
return buff.toString();
}
@Override
public boolean isGlobalTemporary() {
return globalTemporary;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/TableFilter.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.Parser;
import org.h2.command.dml.Select;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.engine.UndoLogRecord;
import org.h2.expression.Comparison;
import org.h2.expression.ConditionAndOr;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.index.Index;
import org.h2.index.IndexCondition;
import org.h2.index.IndexCursor;
import org.h2.index.IndexLookupBatch;
import org.h2.index.ViewIndex;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
/**
* A table filter represents a table that is used in a query. There is one such
* object whenever a table (or view) is used in a query. For example the
* following query has 2 table filters: SELECT * FROM TEST T1, TEST T2.
*/
public class TableFilter implements ColumnResolver {
private static final int BEFORE_FIRST = 0, FOUND = 1, AFTER_LAST = 2,
NULL_ROW = 3;
/**
* Whether this is a direct or indirect (nested) outer join
*/
protected boolean joinOuterIndirect;
private Session session;
private final Table table;
private final Select select;
private String alias;
private Index index;
private final IndexHints indexHints;
private int[] masks;
private int scanCount;
private boolean evaluatable;
/**
* Batched join support.
*/
private JoinBatch joinBatch;
private int joinFilterId = -1;
/**
* Indicates that this filter is used in the plan.
*/
private boolean used;
/**
* The filter used to walk through the index.
*/
private final IndexCursor cursor;
/**
* The index conditions used for direct index lookup (start or end).
*/
private final ArrayList<IndexCondition> indexConditions = New.arrayList();
/**
* Additional conditions that can't be used for index lookup, but for row
* filter for this table (ID=ID, NAME LIKE '%X%')
*/
private Expression filterCondition;
/**
* The complete join condition.
*/
private Expression joinCondition;
private SearchRow currentSearchRow;
private Row current;
private int state;
/**
* The joined table (if there is one).
*/
private TableFilter join;
/**
* Whether this is an outer join.
*/
private boolean joinOuter;
/**
* The nested joined table (if there is one).
*/
private TableFilter nestedJoin;
private ArrayList<Column> naturalJoinColumns;
private boolean foundOne;
private Expression fullCondition;
private final int hashCode;
private final int orderInFrom;
private HashMap<Column, String> derivedColumnMap;
/**
* Create a new table filter object.
*
* @param session the session
* @param table the table from where to read data
* @param alias the alias name
* @param rightsChecked true if rights are already checked
* @param select the select statement
* @param orderInFrom original order number (index) of this table filter in
* @param indexHints the index hints to be used by the query planner
*/
public TableFilter(Session session, Table table, String alias,
boolean rightsChecked, Select select, int orderInFrom, IndexHints indexHints) {
this.session = session;
this.table = table;
this.alias = alias;
this.select = select;
this.cursor = new IndexCursor(this);
if (!rightsChecked) {
session.getUser().checkRight(table, Right.SELECT);
}
hashCode = session.nextObjectId();
this.orderInFrom = orderInFrom;
this.indexHints = indexHints;
}
/**
* Get the order number (index) of this table filter in the "from" clause of
* the query.
*
* @return the index (0, 1, 2,...)
*/
public int getOrderInFrom() {
return orderInFrom;
}
public IndexCursor getIndexCursor() {
return cursor;
}
@Override
public Select getSelect() {
return select;
}
public Table getTable() {
return table;
}
/**
* Lock the table. This will also lock joined tables.
*
* @param s the session
* @param exclusive true if an exclusive lock is required
* @param forceLockEvenInMvcc lock even in the MVCC mode
*/
public void lock(Session s, boolean exclusive, boolean forceLockEvenInMvcc) {
table.lock(s, exclusive, forceLockEvenInMvcc);
if (join != null) {
join.lock(s, exclusive, forceLockEvenInMvcc);
}
}
/**
* Get the best plan item (index, cost) to use use for the current join
* order.
*
* @param s the session
* @param filters all joined table filters
* @param filter the current table filter index
* @param allColumnsSet the set of all columns
* @return the best plan item
*/
public PlanItem getBestPlanItem(Session s, TableFilter[] filters, int filter,
HashSet<Column> allColumnsSet) {
PlanItem item1 = null;
SortOrder sortOrder = null;
if (select != null) {
sortOrder = select.getSortOrder();
}
if (indexConditions.isEmpty()) {
item1 = new PlanItem();
item1.setIndex(table.getScanIndex(s, null, filters, filter,
sortOrder, allColumnsSet));
item1.cost = item1.getIndex().getCost(s, null, filters, filter,
sortOrder, allColumnsSet);
}
int len = table.getColumns().length;
int[] masks = new int[len];
for (IndexCondition condition : indexConditions) {
if (condition.isEvaluatable()) {
if (condition.isAlwaysFalse()) {
masks = null;
break;
}
int id = condition.getColumn().getColumnId();
if (id >= 0) {
masks[id] |= condition.getMask(indexConditions);
}
}
}
PlanItem item = table.getBestPlanItem(s, masks, filters, filter, sortOrder, allColumnsSet);
item.setMasks(masks);
// The more index conditions, the earlier the table.
// This is to ensure joins without indexes run quickly:
// x (x.a=10); y (x.b=y.b) - see issue 113
item.cost -= item.cost * indexConditions.size() / 100 / (filter + 1);
if (item1 != null && item1.cost < item.cost) {
item = item1;
}
if (nestedJoin != null) {
setEvaluatable(true);
item.setNestedJoinPlan(nestedJoin.getBestPlanItem(s, filters, filter, allColumnsSet));
// TODO optimizer: calculate cost of a join: should use separate
// expected row number and lookup cost
item.cost += item.cost * item.getNestedJoinPlan().cost;
}
if (join != null) {
setEvaluatable(true);
do {
filter++;
} while (filters[filter] != join);
item.setJoinPlan(join.getBestPlanItem(s, filters, filter, allColumnsSet));
// TODO optimizer: calculate cost of a join: should use separate
// expected row number and lookup cost
item.cost += item.cost * item.getJoinPlan().cost;
}
return item;
}
/**
* Set what plan item (index, cost, masks) to use.
*
* @param item the plan item
*/
public void setPlanItem(PlanItem item) {
if (item == null) {
// invalid plan, most likely because a column wasn't found
// this will result in an exception later on
return;
}
setIndex(item.getIndex());
masks = item.getMasks();
if (nestedJoin != null) {
if (item.getNestedJoinPlan() != null) {
nestedJoin.setPlanItem(item.getNestedJoinPlan());
} else {
nestedJoin.setScanIndexes();
}
}
if (join != null) {
if (item.getJoinPlan() != null) {
join.setPlanItem(item.getJoinPlan());
} else {
join.setScanIndexes();
}
}
}
/**
* Set all missing indexes to scan indexes recursively.
*/
private void setScanIndexes() {
if (index == null) {
setIndex(table.getScanIndex(session));
}
if (join != null) {
join.setScanIndexes();
}
if (nestedJoin != null) {
nestedJoin.setScanIndexes();
}
}
/**
* Prepare reading rows. This method will remove all index conditions that
* can not be used, and optimize the conditions.
*/
public void prepare() {
// forget all unused index conditions
// the indexConditions list may be modified here
for (int i = 0; i < indexConditions.size(); i++) {
IndexCondition condition = indexConditions.get(i);
if (!condition.isAlwaysFalse()) {
Column col = condition.getColumn();
if (col.getColumnId() >= 0) {
if (index.getColumnIndex(col) < 0) {
indexConditions.remove(i);
i--;
}
}
}
}
if (nestedJoin != null) {
if (SysProperties.CHECK && nestedJoin == this) {
DbException.throwInternalError("self join");
}
nestedJoin.prepare();
}
if (join != null) {
if (SysProperties.CHECK && join == this) {
DbException.throwInternalError("self join");
}
join.prepare();
}
if (filterCondition != null) {
filterCondition = filterCondition.optimize(session);
}
if (joinCondition != null) {
joinCondition = joinCondition.optimize(session);
}
}
/**
* Start the query. This will reset the scan counts.
*
* @param s the session
*/
public void startQuery(Session s) {
this.session = s;
scanCount = 0;
if (nestedJoin != null) {
nestedJoin.startQuery(s);
}
if (join != null) {
join.startQuery(s);
}
}
/**
* Reset to the current position.
*/
public void reset() {
if (joinBatch != null && joinFilterId == 0) {
// reset join batch only on top table filter
joinBatch.reset(true);
return;
}
if (nestedJoin != null) {
nestedJoin.reset();
}
if (join != null) {
join.reset();
}
state = BEFORE_FIRST;
foundOne = false;
}
private boolean isAlwaysTopTableFilter(int filter) {
if (filter != 0) {
return false;
}
// check if we are at the top table filters all the way up
SubQueryInfo info = session.getSubQueryInfo();
while (true) {
if (info == null) {
return true;
}
if (info.getFilter() != 0) {
return false;
}
info = info.getUpper();
}
}
/**
* Attempt to initialize batched join.
*
* @param jb join batch if it is already created
* @param filters the table filters
* @param filter the filter index (0, 1,...)
* @return join batch if query runs over index which supports batched
* lookups, {@code null} otherwise
*/
public JoinBatch prepareJoinBatch(JoinBatch jb, TableFilter[] filters, int filter) {
assert filters[filter] == this;
joinBatch = null;
joinFilterId = -1;
if (getTable().isView()) {
session.pushSubQueryInfo(masks, filters, filter, select.getSortOrder());
try {
((ViewIndex) index).getQuery().prepareJoinBatch();
} finally {
session.popSubQueryInfo();
}
}
// For globally top table filter we don't need to create lookup batch,
// because currently it will not be used (this will be shown in
// ViewIndex.getPlanSQL()). Probably later on it will make sense to
// create it to better support X IN (...) conditions, but this needs to
// be implemented separately. If isAlwaysTopTableFilter is false then we
// either not a top table filter or top table filter in a sub-query,
// which in turn is not top in outer query, thus we need to enable
// batching here to allow outer query run batched join against this
// sub-query.
IndexLookupBatch lookupBatch = null;
if (jb == null && select != null && !isAlwaysTopTableFilter(filter)) {
lookupBatch = index.createLookupBatch(filters, filter);
if (lookupBatch != null) {
jb = new JoinBatch(filter + 1, join);
}
}
if (jb != null) {
if (nestedJoin != null) {
throw DbException.throwInternalError();
}
joinBatch = jb;
joinFilterId = filter;
if (lookupBatch == null && !isAlwaysTopTableFilter(filter)) {
// createLookupBatch will be called at most once because jb can
// be created only if lookupBatch is already not null from the
// call above.
lookupBatch = index.createLookupBatch(filters, filter);
if (lookupBatch == null) {
// the index does not support lookup batching, need to fake
// it because we are not top
lookupBatch = JoinBatch.createFakeIndexLookupBatch(this);
}
}
jb.register(this, lookupBatch);
}
return jb;
}
public int getJoinFilterId() {
return joinFilterId;
}
public JoinBatch getJoinBatch() {
return joinBatch;
}
/**
* Check if there are more rows to read.
*
* @return true if there are
*/
public boolean next() {
if (joinBatch != null) {
// will happen only on topTableFilter since joinBatch.next() does
// not call join.next()
return joinBatch.next();
}
if (state == AFTER_LAST) {
return false;
} else if (state == BEFORE_FIRST) {
cursor.find(session, indexConditions);
if (!cursor.isAlwaysFalse()) {
if (nestedJoin != null) {
nestedJoin.reset();
}
if (join != null) {
join.reset();
}
}
} else {
// state == FOUND || NULL_ROW
// the last row was ok - try next row of the join
if (join != null && join.next()) {
return true;
}
}
while (true) {
// go to the next row
if (state == NULL_ROW) {
break;
}
if (cursor.isAlwaysFalse()) {
state = AFTER_LAST;
} else if (nestedJoin != null) {
if (state == BEFORE_FIRST) {
state = FOUND;
}
} else {
if ((++scanCount & 4095) == 0) {
checkTimeout();
}
if (cursor.next()) {
currentSearchRow = cursor.getSearchRow();
current = null;
state = FOUND;
} else {
state = AFTER_LAST;
}
}
if (nestedJoin != null && state == FOUND) {
if (!nestedJoin.next()) {
state = AFTER_LAST;
if (joinOuter && !foundOne) {
// possibly null row
} else {
continue;
}
}
}
// if no more rows found, try the null row (for outer joins only)
if (state == AFTER_LAST) {
if (joinOuter && !foundOne) {
setNullRow();
} else {
break;
}
}
if (!isOk(filterCondition)) {
continue;
}
boolean joinConditionOk = isOk(joinCondition);
if (state == FOUND) {
if (joinConditionOk) {
foundOne = true;
} else {
continue;
}
}
if (join != null) {
join.reset();
if (!join.next()) {
continue;
}
}
// check if it's ok
if (state == NULL_ROW || joinConditionOk) {
return true;
}
}
state = AFTER_LAST;
return false;
}
/**
* Set the state of this and all nested tables to the NULL row.
*/
protected void setNullRow() {
state = NULL_ROW;
current = table.getNullRow();
currentSearchRow = current;
if (nestedJoin != null) {
nestedJoin.visit(new TableFilterVisitor() {
@Override
public void accept(TableFilter f) {
f.setNullRow();
}
});
}
}
private void checkTimeout() {
session.checkCanceled();
}
/**
* Whether the current value of the condition is true, or there is no
* condition.
*
* @param condition the condition (null for no condition)
* @return true if yes
*/
boolean isOk(Expression condition) {
return condition == null || condition.getBooleanValue(session);
}
/**
* Get the current row.
*
* @return the current row, or null
*/
public Row get() {
if (current == null && currentSearchRow != null) {
current = cursor.get();
}
return current;
}
/**
* Set the current row.
*
* @param current the current row
*/
public void set(Row current) {
// this is currently only used so that check constraints work - to set
// the current (new) row
this.current = current;
this.currentSearchRow = current;
}
/**
* Get the table alias name. If no alias is specified, the table name is
* returned.
*
* @return the alias name
*/
@Override
public String getTableAlias() {
if (alias != null) {
return alias;
}
return table.getName();
}
/**
* Add an index condition.
*
* @param condition the index condition
*/
public void addIndexCondition(IndexCondition condition) {
indexConditions.add(condition);
}
/**
* Add a filter condition.
*
* @param condition the condition
* @param isJoin if this is in fact a join condition
*/
public void addFilterCondition(Expression condition, boolean isJoin) {
if (isJoin) {
if (joinCondition == null) {
joinCondition = condition;
} else {
joinCondition = new ConditionAndOr(ConditionAndOr.AND,
joinCondition, condition);
}
} else {
if (filterCondition == null) {
filterCondition = condition;
} else {
filterCondition = new ConditionAndOr(ConditionAndOr.AND,
filterCondition, condition);
}
}
}
/**
* Add a joined table.
*
* @param filter the joined table filter
* @param outer if this is an outer join
* @param on the join condition
*/
public void addJoin(TableFilter filter, boolean outer, Expression on) {
if (on != null) {
on.mapColumns(this, 0);
TableFilterVisitor visitor = new MapColumnsVisitor(on);
visit(visitor);
filter.visit(visitor);
}
if (join == null) {
join = filter;
filter.joinOuter = outer;
if (outer) {
filter.visit(new JOIVisitor());
}
if (on != null) {
filter.mapAndAddFilter(on);
}
} else {
join.addJoin(filter, outer, on);
}
}
/**
* Set a nested joined table.
*
* @param filter the joined table filter
*/
public void setNestedJoin(TableFilter filter) {
nestedJoin = filter;
}
/**
* Map the columns and add the join condition.
*
* @param on the condition
*/
public void mapAndAddFilter(Expression on) {
on.mapColumns(this, 0);
addFilterCondition(on, true);
on.createIndexConditions(session, this);
if (nestedJoin != null) {
on.mapColumns(nestedJoin, 0);
on.createIndexConditions(session, nestedJoin);
}
if (join != null) {
join.mapAndAddFilter(on);
}
}
public TableFilter getJoin() {
return join;
}
/**
* Whether this is an outer joined table.
*
* @return true if it is
*/
public boolean isJoinOuter() {
return joinOuter;
}
/**
* Whether this is indirectly an outer joined table (nested within an inner
* join).
*
* @return true if it is
*/
public boolean isJoinOuterIndirect() {
return joinOuterIndirect;
}
/**
* Get the query execution plan text to use for this table filter.
*
* @param isJoin if this is a joined table
* @return the SQL statement snippet
*/
public String getPlanSQL(boolean isJoin) {
StringBuilder buff = new StringBuilder();
if (isJoin) {
if (joinOuter) {
buff.append("LEFT OUTER JOIN ");
} else {
buff.append("INNER JOIN ");
}
}
if (nestedJoin != null) {
StringBuilder buffNested = new StringBuilder();
TableFilter n = nestedJoin;
do {
buffNested.append(n.getPlanSQL(n != nestedJoin));
buffNested.append('\n');
n = n.getJoin();
} while (n != null);
String nested = buffNested.toString();
boolean enclose = !nested.startsWith("(");
if (enclose) {
buff.append("(\n");
}
buff.append(StringUtils.indent(nested, 4, false));
if (enclose) {
buff.append(')');
}
if (isJoin) {
buff.append(" ON ");
if (joinCondition == null) {
// need to have a ON expression,
// otherwise the nesting is unclear
buff.append("1=1");
} else {
buff.append(StringUtils.unEnclose(joinCondition.getSQL()));
}
}
return buff.toString();
}
if (table.isView() && ((TableView) table).isRecursive()) {
buff.append(table.getName());
} else {
buff.append(table.getSQL());
}
if (table.isView() && ((TableView) table).isInvalid()) {
throw DbException.get(ErrorCode.VIEW_IS_INVALID_2, table.getName(), "not compiled");
}
if (alias != null) {
buff.append(' ').append(Parser.quoteIdentifier(alias));
}
if (indexHints != null) {
buff.append(" USE INDEX (");
boolean first = true;
for (String index : indexHints.getAllowedIndexes()) {
if (!first) {
buff.append(", ");
} else {
first = false;
}
buff.append(Parser.quoteIdentifier(index));
}
buff.append(")");
}
if (index != null) {
buff.append('\n');
StatementBuilder planBuff = new StatementBuilder();
if (joinBatch != null) {
IndexLookupBatch lookupBatch = joinBatch.getLookupBatch(joinFilterId);
if (lookupBatch == null) {
if (joinFilterId != 0) {
throw DbException.throwInternalError("" + joinFilterId);
}
} else {
planBuff.append("batched:");
String batchPlan = lookupBatch.getPlanSQL();
planBuff.append(batchPlan);
planBuff.append(" ");
}
}
planBuff.append(index.getPlanSQL());
if (!indexConditions.isEmpty()) {
planBuff.append(": ");
for (IndexCondition condition : indexConditions) {
planBuff.appendExceptFirst("\n AND ");
planBuff.append(condition.getSQL());
}
}
String plan = StringUtils.quoteRemarkSQL(planBuff.toString());
if (plan.indexOf('\n') >= 0) {
plan += "\n";
}
buff.append(StringUtils.indent("/* " + plan + " */", 4, false));
}
if (isJoin) {
buff.append("\n ON ");
if (joinCondition == null) {
// need to have a ON expression, otherwise the nesting is
// unclear
buff.append("1=1");
} else {
buff.append(StringUtils.unEnclose(joinCondition.getSQL()));
}
}
if (filterCondition != null) {
buff.append('\n');
String condition = StringUtils.unEnclose(filterCondition.getSQL());
condition = "/* WHERE " + StringUtils.quoteRemarkSQL(condition) + "\n*/";
buff.append(StringUtils.indent(condition, 4, false));
}
if (scanCount > 0) {
buff.append("\n /* scanCount: ").append(scanCount).append(" */");
}
return buff.toString();
}
/**
* Remove all index conditions that are not used by the current index.
*/
void removeUnusableIndexConditions() {
// the indexConditions list may be modified here
for (int i = 0; i < indexConditions.size(); i++) {
IndexCondition cond = indexConditions.get(i);
if (!cond.isEvaluatable()) {
indexConditions.remove(i--);
}
}
}
public int[] getMasks() {
return masks;
}
public ArrayList<IndexCondition> getIndexConditions() {
return indexConditions;
}
public Index getIndex() {
return index;
}
public void setIndex(Index index) {
this.index = index;
cursor.setIndex(index);
}
public void setUsed(boolean used) {
this.used = used;
}
public boolean isUsed() {
return used;
}
/**
* Set the session of this table filter.
*
* @param session the new session
*/
void setSession(Session session) {
this.session = session;
}
/**
* Remove the joined table
*/
public void removeJoin() {
this.join = null;
}
public Expression getJoinCondition() {
return joinCondition;
}
/**
* Remove the join condition.
*/
public void removeJoinCondition() {
this.joinCondition = null;
}
public Expression getFilterCondition() {
return filterCondition;
}
/**
* Remove the filter condition.
*/
public void removeFilterCondition() {
this.filterCondition = null;
}
public void setFullCondition(Expression condition) {
this.fullCondition = condition;
if (join != null) {
join.setFullCondition(condition);
}
}
/**
* Optimize the full condition. This will add the full condition to the
* filter condition.
*
* @param fromOuterJoin if this method was called from an outer joined table
*/
void optimizeFullCondition(boolean fromOuterJoin) {
if (fullCondition != null) {
fullCondition.addFilterConditions(this, fromOuterJoin || joinOuter);
if (nestedJoin != null) {
nestedJoin.optimizeFullCondition(fromOuterJoin || joinOuter);
}
if (join != null) {
join.optimizeFullCondition(fromOuterJoin || joinOuter);
}
}
}
/**
* Update the filter and join conditions of this and all joined tables with
* the information that the given table filter and all nested filter can now
* return rows or not.
*
* @param filter the table filter
* @param b the new flag
*/
public void setEvaluatable(TableFilter filter, boolean b) {
filter.setEvaluatable(b);
if (filterCondition != null) {
filterCondition.setEvaluatable(filter, b);
}
if (joinCondition != null) {
joinCondition.setEvaluatable(filter, b);
}
if (nestedJoin != null) {
// don't enable / disable the nested join filters
// if enabling a filter in a joined filter
if (this == filter) {
nestedJoin.setEvaluatable(nestedJoin, b);
}
}
if (join != null) {
join.setEvaluatable(filter, b);
}
}
public void setEvaluatable(boolean evaluatable) {
this.evaluatable = evaluatable;
}
@Override
public String getSchemaName() {
return table.getSchema().getName();
}
@Override
public Column[] getColumns() {
return table.getColumns();
}
@Override
public String getDerivedColumnName(Column column) {
HashMap<Column, String> map = derivedColumnMap;
return map != null ? map.get(column) : null;
}
/**
* Get the system columns that this table understands. This is used for
* compatibility with other databases. The columns are only returned if the
* current mode supports system columns.
*
* @return the system columns
*/
@Override
public Column[] getSystemColumns() {
if (!session.getDatabase().getMode().systemColumns) {
return null;
}
Column[] sys = new Column[3];
sys[0] = new Column("oid", Value.INT);
sys[0].setTable(table, 0);
sys[1] = new Column("ctid", Value.STRING);
sys[1].setTable(table, 0);
sys[2] = new Column("CTID", Value.STRING);
sys[2].setTable(table, 0);
return sys;
}
@Override
public Column getRowIdColumn() {
if (session.getDatabase().getSettings().rowId) {
return table.getRowIdColumn();
}
return null;
}
@Override
public Value getValue(Column column) {
if (joinBatch != null) {
return joinBatch.getValue(joinFilterId, column);
}
if (currentSearchRow == null) {
return null;
}
int columnId = column.getColumnId();
if (columnId == -1) {
return ValueLong.get(currentSearchRow.getKey());
}
if (current == null) {
Value v = currentSearchRow.getValue(columnId);
if (v != null) {
return v;
}
current = cursor.get();
if (current == null) {
return ValueNull.INSTANCE;
}
}
return current.getValue(columnId);
}
@Override
public TableFilter getTableFilter() {
return this;
}
public void setAlias(String alias) {
this.alias = alias;
}
/**
* Set derived column list.
*
* @param derivedColumnNames names of derived columns
*/
public void setDerivedColumns(ArrayList<String> derivedColumnNames) {
Column[] columns = getColumns();
int count = columns.length;
if (count != derivedColumnNames.size()) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
HashMap<Column, String> map = new HashMap<>(count);
for (int i = 0; i < count; i++) {
String alias = derivedColumnNames.get(i);
for (int j = 0; j < i; j++) {
if (alias.equals(derivedColumnNames.get(j))) {
throw DbException.get(ErrorCode.DUPLICATE_COLUMN_NAME_1, alias);
}
}
map.put(columns[i], alias);
}
this.derivedColumnMap = map;
}
@Override
public Expression optimize(ExpressionColumn expressionColumn, Column column) {
return expressionColumn;
}
@Override
public String toString() {
return alias != null ? alias : table.toString();
}
/**
* Add a column to the natural join key column list.
*
* @param c the column to add
*/
public void addNaturalJoinColumn(Column c) {
if (naturalJoinColumns == null) {
naturalJoinColumns = New.arrayList();
}
naturalJoinColumns.add(c);
}
/**
* Check if the given column is a natural join column.
*
* @param c the column to check
* @return true if this is a joined natural join column
*/
public boolean isNaturalJoinColumn(Column c) {
return naturalJoinColumns != null && naturalJoinColumns.contains(c);
}
@Override
public int hashCode() {
return hashCode;
}
/**
* Are there any index conditions that involve IN(...).
*
* @return whether there are IN(...) comparisons
*/
public boolean hasInComparisons() {
for (IndexCondition cond : indexConditions) {
int compareType = cond.getCompareType();
if (compareType == Comparison.IN_QUERY || compareType == Comparison.IN_LIST) {
return true;
}
}
return false;
}
/**
* Add the current row to the array, if there is a current row.
*
* @param rows the rows to lock
*/
public void lockRowAdd(ArrayList<Row> rows) {
if (state == FOUND) {
rows.add(get());
}
}
/**
* Lock the given rows.
*
* @param forUpdateRows the rows to lock
*/
public void lockRows(ArrayList<Row> forUpdateRows) {
for (Row row : forUpdateRows) {
Row newRow = row.getCopy();
table.removeRow(session, row);
session.log(table, UndoLogRecord.DELETE, row);
table.addRow(session, newRow);
session.log(table, UndoLogRecord.INSERT, newRow);
}
}
public TableFilter getNestedJoin() {
return nestedJoin;
}
/**
* Visit this and all joined or nested table filters.
*
* @param visitor the visitor
*/
public void visit(TableFilterVisitor visitor) {
TableFilter f = this;
do {
visitor.accept(f);
TableFilter n = f.nestedJoin;
if (n != null) {
n.visit(visitor);
}
f = f.join;
} while (f != null);
}
public boolean isEvaluatable() {
return evaluatable;
}
public Session getSession() {
return session;
}
public IndexHints getIndexHints() {
return indexHints;
}
/**
* A visitor for table filters.
*/
public interface TableFilterVisitor {
/**
* This method is called for each nested or joined table filter.
*
* @param f the filter
*/
void accept(TableFilter f);
}
/**
* A visitor that maps columns.
*/
private static final class MapColumnsVisitor implements TableFilterVisitor {
private final Expression on;
MapColumnsVisitor(Expression on) {
this.on = on;
}
@Override
public void accept(TableFilter f) {
on.mapColumns(f, 0);
}
}
/**
* A visitor that sets joinOuterIndirect to true.
*/
private static final class JOIVisitor implements TableFilterVisitor {
JOIVisitor() {
}
@Override
public void accept(TableFilter f) {
f.joinOuterIndirect = true;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/TableLink.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import org.h2.api.ErrorCode;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.engine.UndoLogRecord;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.index.LinkedIndex;
import org.h2.jdbc.JdbcSQLException;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.RowList;
import org.h2.schema.Schema;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueDate;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
/**
* A linked table contains connection information for a table accessible by
* JDBC. The table may be stored in a different database.
*/
public class TableLink extends Table {
private static final int MAX_RETRY = 2;
private static final long ROW_COUNT_APPROXIMATION = 100_000;
private final String originalSchema;
private String driver, url, user, password, originalTable, qualifiedTableName;
private TableLinkConnection conn;
private HashMap<String, PreparedStatement> preparedMap = new HashMap<>();
private final ArrayList<Index> indexes = New.arrayList();
private final boolean emitUpdates;
private LinkedIndex linkedIndex;
private DbException connectException;
private boolean storesLowerCase;
private boolean storesMixedCase;
private boolean storesMixedCaseQuoted;
private boolean supportsMixedCaseIdentifiers;
private boolean globalTemporary;
private boolean readOnly;
public TableLink(Schema schema, int id, String name, String driver,
String url, String user, String password, String originalSchema,
String originalTable, boolean emitUpdates, boolean force) {
super(schema, id, name, false, true);
this.driver = driver;
this.url = url;
this.user = user;
this.password = password;
this.originalSchema = originalSchema;
this.originalTable = originalTable;
this.emitUpdates = emitUpdates;
try {
connect();
} catch (DbException e) {
if (!force) {
throw e;
}
Column[] cols = { };
setColumns(cols);
linkedIndex = new LinkedIndex(this, id, IndexColumn.wrap(cols),
IndexType.createNonUnique(false));
indexes.add(linkedIndex);
}
}
private void connect() {
connectException = null;
for (int retry = 0;; retry++) {
try {
conn = database.getLinkConnection(driver, url, user, password);
synchronized (conn) {
try {
readMetaData();
return;
} catch (Exception e) {
// could be SQLException or RuntimeException
conn.close(true);
conn = null;
throw DbException.convert(e);
}
}
} catch (DbException e) {
if (retry >= MAX_RETRY) {
connectException = e;
throw e;
}
}
}
}
private void readMetaData() throws SQLException {
DatabaseMetaData meta = conn.getConnection().getMetaData();
storesLowerCase = meta.storesLowerCaseIdentifiers();
storesMixedCase = meta.storesMixedCaseIdentifiers();
storesMixedCaseQuoted = meta.storesMixedCaseQuotedIdentifiers();
supportsMixedCaseIdentifiers = meta.supportsMixedCaseIdentifiers();
ResultSet rs = meta.getTables(null, originalSchema, originalTable, null);
if (rs.next() && rs.next()) {
throw DbException.get(ErrorCode.SCHEMA_NAME_MUST_MATCH, originalTable);
}
rs.close();
rs = meta.getColumns(null, originalSchema, originalTable, null);
int i = 0;
ArrayList<Column> columnList = New.arrayList();
HashMap<String, Column> columnMap = new HashMap<>();
String catalog = null, schema = null;
while (rs.next()) {
String thisCatalog = rs.getString("TABLE_CAT");
if (catalog == null) {
catalog = thisCatalog;
}
String thisSchema = rs.getString("TABLE_SCHEM");
if (schema == null) {
schema = thisSchema;
}
if (!Objects.equals(catalog, thisCatalog) ||
!Objects.equals(schema, thisSchema)) {
// if the table exists in multiple schemas or tables,
// use the alternative solution
columnMap.clear();
columnList.clear();
break;
}
String n = rs.getString("COLUMN_NAME");
n = convertColumnName(n);
int sqlType = rs.getInt("DATA_TYPE");
String sqlTypeName = rs.getString("TYPE_NAME");
long precision = rs.getInt("COLUMN_SIZE");
precision = convertPrecision(sqlType, precision);
int scale = rs.getInt("DECIMAL_DIGITS");
scale = convertScale(sqlType, scale);
int displaySize = MathUtils.convertLongToInt(precision);
int type = DataType.convertSQLTypeToValueType(sqlType, sqlTypeName);
Column col = new Column(n, type, precision, scale, displaySize);
col.setTable(this, i++);
columnList.add(col);
columnMap.put(n, col);
}
rs.close();
if (originalTable.indexOf('.') < 0 && !StringUtils.isNullOrEmpty(schema)) {
qualifiedTableName = schema + "." + originalTable;
} else {
qualifiedTableName = originalTable;
}
// check if the table is accessible
try (Statement stat = conn.getConnection().createStatement()) {
rs = stat.executeQuery("SELECT * FROM " +
qualifiedTableName + " T WHERE 1=0");
if (columnList.isEmpty()) {
// alternative solution
ResultSetMetaData rsMeta = rs.getMetaData();
for (i = 0; i < rsMeta.getColumnCount();) {
String n = rsMeta.getColumnName(i + 1);
n = convertColumnName(n);
int sqlType = rsMeta.getColumnType(i + 1);
long precision = rsMeta.getPrecision(i + 1);
precision = convertPrecision(sqlType, precision);
int scale = rsMeta.getScale(i + 1);
scale = convertScale(sqlType, scale);
int displaySize = rsMeta.getColumnDisplaySize(i + 1);
int type = DataType.getValueTypeFromResultSet(rsMeta, i + 1);
Column col = new Column(n, type, precision, scale, displaySize);
col.setTable(this, i++);
columnList.add(col);
columnMap.put(n, col);
}
}
rs.close();
} catch (Exception e) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, e,
originalTable + "(" + e.toString() + ")");
}
Column[] cols = columnList.toArray(new Column[0]);
setColumns(cols);
int id = getId();
linkedIndex = new LinkedIndex(this, id, IndexColumn.wrap(cols),
IndexType.createNonUnique(false));
indexes.add(linkedIndex);
try {
rs = meta.getPrimaryKeys(null, originalSchema, originalTable);
} catch (Exception e) {
// Some ODBC bridge drivers don't support it:
// some combinations of "DataDirect SequeLink(R) for JDBC"
// http://www.datadirect.com/index.ssp
rs = null;
}
String pkName = "";
ArrayList<Column> list;
if (rs != null && rs.next()) {
// the problem is, the rows are not sorted by KEY_SEQ
list = New.arrayList();
do {
int idx = rs.getInt("KEY_SEQ");
if (pkName == null) {
pkName = rs.getString("PK_NAME");
}
while (list.size() < idx) {
list.add(null);
}
String col = rs.getString("COLUMN_NAME");
col = convertColumnName(col);
Column column = columnMap.get(col);
if (idx == 0) {
// workaround for a bug in the SQLite JDBC driver
list.add(column);
} else {
list.set(idx - 1, column);
}
} while (rs.next());
addIndex(list, IndexType.createPrimaryKey(false, false));
rs.close();
}
try {
rs = meta.getIndexInfo(null, originalSchema, originalTable, false, true);
} catch (Exception e) {
// Oracle throws an exception if the table is not found or is a
// SYNONYM
rs = null;
}
String indexName = null;
list = New.arrayList();
IndexType indexType = null;
if (rs != null) {
while (rs.next()) {
if (rs.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic) {
// ignore index statistics
continue;
}
String newIndex = rs.getString("INDEX_NAME");
if (pkName.equals(newIndex)) {
continue;
}
if (indexName != null && !indexName.equals(newIndex)) {
addIndex(list, indexType);
indexName = null;
}
if (indexName == null) {
indexName = newIndex;
list.clear();
}
boolean unique = !rs.getBoolean("NON_UNIQUE");
indexType = unique ? IndexType.createUnique(false, false) :
IndexType.createNonUnique(false);
String col = rs.getString("COLUMN_NAME");
col = convertColumnName(col);
Column column = columnMap.get(col);
list.add(column);
}
rs.close();
}
if (indexName != null) {
addIndex(list, indexType);
}
}
private static long convertPrecision(int sqlType, long precision) {
// workaround for an Oracle problem:
// for DATE columns, the reported precision is 7
// for DECIMAL columns, the reported precision is 0
switch (sqlType) {
case Types.DECIMAL:
case Types.NUMERIC:
if (precision == 0) {
precision = 65535;
}
break;
case Types.DATE:
precision = Math.max(ValueDate.PRECISION, precision);
break;
case Types.TIMESTAMP:
precision = Math.max(ValueTimestamp.MAXIMUM_PRECISION, precision);
break;
case Types.TIME:
precision = Math.max(ValueTime.MAXIMUM_PRECISION, precision);
break;
}
return precision;
}
private static int convertScale(int sqlType, int scale) {
// workaround for an Oracle problem:
// for DECIMAL columns, the reported precision is -127
switch (sqlType) {
case Types.DECIMAL:
case Types.NUMERIC:
if (scale < 0) {
scale = 32767;
}
break;
}
return scale;
}
private String convertColumnName(String columnName) {
if ((storesMixedCase || storesLowerCase) &&
columnName.equals(StringUtils.toLowerEnglish(columnName))) {
columnName = StringUtils.toUpperEnglish(columnName);
} else if (storesMixedCase && !supportsMixedCaseIdentifiers) {
// TeraData
columnName = StringUtils.toUpperEnglish(columnName);
} else if (storesMixedCase && storesMixedCaseQuoted) {
// MS SQL Server (identifiers are case insensitive even if quoted)
columnName = StringUtils.toUpperEnglish(columnName);
}
return columnName;
}
private void addIndex(List<Column> list, IndexType indexType) {
// bind the index to the leading recognized columns in the index
// (null columns might come from a function-based index)
int firstNull = list.indexOf(null);
if (firstNull == 0) {
trace.info("Omitting linked index - no recognized columns.");
return;
} else if (firstNull > 0) {
trace.info("Unrecognized columns in linked index. " +
"Registering the index against the leading {0} " +
"recognized columns of {1} total columns.", firstNull, list.size());
list = list.subList(0, firstNull);
}
Column[] cols = list.toArray(new Column[0]);
Index index = new LinkedIndex(this, 0, IndexColumn.wrap(cols), indexType);
indexes.add(index);
}
@Override
public String getDropSQL() {
return "DROP TABLE IF EXISTS " + getSQL();
}
@Override
public String getCreateSQL() {
StringBuilder buff = new StringBuilder("CREATE FORCE ");
if (isTemporary()) {
if (globalTemporary) {
buff.append("GLOBAL ");
} else {
buff.append("LOCAL ");
}
buff.append("TEMPORARY ");
}
buff.append("LINKED TABLE ").append(getSQL());
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
buff.append('(').
append(StringUtils.quoteStringSQL(driver)).
append(", ").
append(StringUtils.quoteStringSQL(url)).
append(", ").
append(StringUtils.quoteStringSQL(user)).
append(", ").
append(StringUtils.quoteStringSQL(password)).
append(", ").
append(StringUtils.quoteStringSQL(originalTable)).
append(')');
if (emitUpdates) {
buff.append(" EMIT UPDATES");
}
if (readOnly) {
buff.append(" READONLY");
}
buff.append(" /*").append(JdbcSQLException.HIDE_SQL).append("*/");
return buff.toString();
}
@Override
public Index addIndex(Session session, String indexName, int indexId,
IndexColumn[] cols, IndexType indexType, boolean create,
String indexComment) {
throw DbException.getUnsupportedException("LINK");
}
@Override
public boolean lock(Session session, boolean exclusive, boolean forceLockEvenInMvcc) {
// nothing to do
return false;
}
@Override
public boolean isLockedExclusively() {
return false;
}
@Override
public Index getScanIndex(Session session) {
return linkedIndex;
}
private void checkReadOnly() {
if (readOnly) {
throw DbException.get(ErrorCode.DATABASE_IS_READ_ONLY);
}
}
@Override
public void removeRow(Session session, Row row) {
checkReadOnly();
getScanIndex(session).remove(session, row);
}
@Override
public void addRow(Session session, Row row) {
checkReadOnly();
getScanIndex(session).add(session, row);
}
@Override
public void close(Session session) {
if (conn != null) {
try {
conn.close(false);
} finally {
conn = null;
}
}
}
@Override
public synchronized long getRowCount(Session session) {
//The foo alias is used to support the PostgreSQL syntax
String sql = "SELECT COUNT(*) FROM " + qualifiedTableName + " as foo";
try {
PreparedStatement prep = execute(sql, null, false);
ResultSet rs = prep.getResultSet();
rs.next();
long count = rs.getLong(1);
rs.close();
reusePreparedStatement(prep, sql);
return count;
} catch (Exception e) {
throw wrapException(sql, e);
}
}
/**
* Wrap a SQL exception that occurred while accessing a linked table.
*
* @param sql the SQL statement
* @param ex the exception from the remote database
* @return the wrapped exception
*/
public static DbException wrapException(String sql, Exception ex) {
SQLException e = DbException.toSQLException(ex);
return DbException.get(ErrorCode.ERROR_ACCESSING_LINKED_TABLE_2,
e, sql, e.toString());
}
public String getQualifiedTable() {
return qualifiedTableName;
}
/**
* Execute a SQL statement using the given parameters. Prepared
* statements are kept in a hash map to avoid re-creating them.
*
* @param sql the SQL statement
* @param params the parameters or null
* @param reusePrepared if the prepared statement can be re-used immediately
* @return the prepared statement, or null if it is re-used
*/
public PreparedStatement execute(String sql, ArrayList<Value> params,
boolean reusePrepared) {
if (conn == null) {
throw connectException;
}
for (int retry = 0;; retry++) {
try {
synchronized (conn) {
PreparedStatement prep = preparedMap.remove(sql);
if (prep == null) {
prep = conn.getConnection().prepareStatement(sql);
}
if (trace.isDebugEnabled()) {
StatementBuilder buff = new StatementBuilder();
buff.append(getName()).append(":\n").append(sql);
if (params != null && !params.isEmpty()) {
buff.append(" {");
int i = 1;
for (Value v : params) {
buff.appendExceptFirst(", ");
buff.append(i++).append(": ").append(v.getSQL());
}
buff.append('}');
}
buff.append(';');
trace.debug(buff.toString());
}
if (params != null) {
for (int i = 0, size = params.size(); i < size; i++) {
Value v = params.get(i);
v.set(prep, i + 1);
}
}
prep.execute();
if (reusePrepared) {
reusePreparedStatement(prep, sql);
return null;
}
return prep;
}
} catch (SQLException e) {
if (retry >= MAX_RETRY) {
throw DbException.convert(e);
}
conn.close(true);
connect();
}
}
}
@Override
public void unlock(Session s) {
// nothing to do
}
@Override
public void checkRename() {
// ok
}
@Override
public void checkSupportAlter() {
throw DbException.getUnsupportedException("LINK");
}
@Override
public void truncate(Session session) {
throw DbException.getUnsupportedException("LINK");
}
@Override
public boolean canGetRowCount() {
return true;
}
@Override
public boolean canDrop() {
return true;
}
@Override
public TableType getTableType() {
return TableType.TABLE_LINK;
}
@Override
public void removeChildrenAndResources(Session session) {
super.removeChildrenAndResources(session);
close(session);
database.removeMeta(session, getId());
driver = null;
url = user = password = originalTable = null;
preparedMap = null;
invalidate();
}
public boolean isOracle() {
return url.startsWith("jdbc:oracle:");
}
@Override
public ArrayList<Index> getIndexes() {
return indexes;
}
@Override
public long getMaxDataModificationId() {
// data may have been modified externally
return Long.MAX_VALUE;
}
@Override
public Index getUniqueIndex() {
for (Index idx : indexes) {
if (idx.getIndexType().isUnique()) {
return idx;
}
}
return null;
}
@Override
public void updateRows(Prepared prepared, Session session, RowList rows) {
boolean deleteInsert;
checkReadOnly();
if (emitUpdates) {
for (rows.reset(); rows.hasNext();) {
prepared.checkCanceled();
Row oldRow = rows.next();
Row newRow = rows.next();
linkedIndex.update(oldRow, newRow);
session.log(this, UndoLogRecord.DELETE, oldRow);
session.log(this, UndoLogRecord.INSERT, newRow);
}
deleteInsert = false;
} else {
deleteInsert = true;
}
if (deleteInsert) {
super.updateRows(prepared, session, rows);
}
}
public void setGlobalTemporary(boolean globalTemporary) {
this.globalTemporary = globalTemporary;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public long getRowCountApproximation() {
return ROW_COUNT_APPROXIMATION;
}
@Override
public long getDiskSpaceUsed() {
return 0;
}
/**
* Add this prepared statement to the list of cached statements.
*
* @param prep the prepared statement
* @param sql the SQL statement
*/
public void reusePreparedStatement(PreparedStatement prep, String sql) {
synchronized (conn) {
preparedMap.put(sql, prep);
}
}
@Override
public boolean isDeterministic() {
return false;
}
/**
* Linked tables don't know if they are readonly. This overwrites
* the default handling.
*/
@Override
public void checkWritingAllowed() {
// only the target database can verify this
}
/**
* Convert the values if required. Default values are not set (kept as
* null).
*
* @param session the session
* @param row the row
*/
@Override
public void validateConvertUpdateSequence(Session session, Row row) {
for (int i = 0; i < columns.length; i++) {
Value value = row.getValue(i);
if (value != null) {
// null means use the default value
Column column = columns[i];
Value v2 = column.validateConvertUpdateSequence(session, value);
if (v2 != value) {
row.setValue(i, v2);
}
}
}
}
/**
* Get or generate a default value for the given column. Default values are
* not set (kept as null).
*
* @param session the session
* @param column the column
* @return the value
*/
@Override
public Value getDefaultValue(Session session, Column column) {
return null;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/TableLinkConnection.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Objects;
import org.h2.message.DbException;
import org.h2.util.JdbcUtils;
/**
* A connection for a linked table. The same connection may be used for multiple
* tables, that means a connection may be shared.
*/
public class TableLinkConnection {
/**
* The map where the link is kept.
*/
private final HashMap<TableLinkConnection, TableLinkConnection> map;
/**
* The connection information.
*/
private final String driver, url, user, password;
/**
* The database connection.
*/
private Connection conn;
/**
* How many times the connection is used.
*/
private int useCounter;
private TableLinkConnection(
HashMap<TableLinkConnection, TableLinkConnection> map,
String driver, String url, String user, String password) {
this.map = map;
this.driver = driver;
this.url = url;
this.user = user;
this.password = password;
}
/**
* Open a new connection.
*
* @param map the map where the connection should be stored
* (if shared connections are enabled).
* @param driver the JDBC driver class name
* @param url the database URL
* @param user the user name
* @param password the password
* @param shareLinkedConnections if connections should be shared
* @return a connection
*/
public static TableLinkConnection open(
HashMap<TableLinkConnection, TableLinkConnection> map,
String driver, String url, String user, String password,
boolean shareLinkedConnections) {
TableLinkConnection t = new TableLinkConnection(map, driver, url,
user, password);
if (!shareLinkedConnections) {
t.open();
return t;
}
synchronized (map) {
TableLinkConnection result = map.get(t);
if (result == null) {
t.open();
// put the connection in the map after is has been opened,
// when we know it works
map.put(t, t);
result = t;
}
result.useCounter++;
return result;
}
}
private void open() {
try {
conn = JdbcUtils.getConnection(driver, url, user, password);
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
public int hashCode() {
return Objects.hashCode(driver)
^ Objects.hashCode(url)
^ Objects.hashCode(user)
^ Objects.hashCode(password);
}
@Override
public boolean equals(Object o) {
if (o instanceof TableLinkConnection) {
TableLinkConnection other = (TableLinkConnection) o;
return Objects.equals(driver, other.driver)
&& Objects.equals(url, other.url)
&& Objects.equals(user, other.user)
&& Objects.equals(password, other.password);
}
return false;
}
/**
* Get the connection.
* This method and methods on the statement must be
* synchronized on this object.
*
* @return the connection
*/
Connection getConnection() {
return conn;
}
/**
* Closes the connection if this is the last link to it.
*
* @param force if the connection needs to be closed even if it is still
* used elsewhere (for example, because the connection is broken)
*/
void close(boolean force) {
boolean actuallyClose = false;
synchronized (map) {
if (--useCounter <= 0 || force) {
actuallyClose = true;
map.remove(this);
}
}
if (actuallyClose) {
JdbcUtils.closeSilently(conn);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/TableSynonym.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import org.h2.command.ddl.CreateSynonymData;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObjectBase;
/**
* Synonym for an existing table or view. All DML requests are forwarded to the backing table.
* Adding indices to a synonym or altering the table is not supported.
*/
public class TableSynonym extends SchemaObjectBase {
private CreateSynonymData data;
/**
* The table the synonym is created for.
*/
private Table synonymFor;
public TableSynonym(CreateSynonymData data) {
initSchemaObjectBase(data.schema, data.id, data.synonymName, Trace.TABLE);
this.data = data;
}
/**
* @return the table this is a synonym for
*/
public Table getSynonymFor() {
return synonymFor;
}
/**
* Set (update) the data.
*
* @param data the new data
*/
public void updateData(CreateSynonymData data) {
this.data = data;
}
@Override
public int getType() {
return SYNONYM;
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
return synonymFor.getCreateSQLForCopy(table, quotedName);
}
@Override
public void rename(String newName) { throw DbException.getUnsupportedException("SYNONYM"); }
@Override
public void removeChildrenAndResources(Session session) {
synonymFor.removeSynonym(this);
database.removeMeta(session, getId());
}
@Override
public String getCreateSQL() {
return "CREATE SYNONYM " + getName() + " FOR " + data.synonymForSchema.getName() + "." + data.synonymFor;
}
@Override
public String getDropSQL() {
return "DROP SYNONYM " + getName();
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("SYNONYM");
}
/**
* @return the table this synonym is for
*/
public String getSynonymForName() {
return data.synonymFor;
}
/**
* @return the schema this synonym is for
*/
public Schema getSynonymForSchema() {
return data.synonymForSchema;
}
/**
* @return true if this synonym currently points to a real table
*/
public boolean isInvalid() {
return synonymFor.isValid();
}
/**
* Update the table that this is a synonym for, to know about this synonym.
*/
public void updateSynonymFor() {
if (synonymFor != null) {
synonymFor.removeSynonym(this);
}
synonymFor = data.synonymForSchema.getTableOrView(data.session, data.synonymFor);
synonymFor.addSynonym(this);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/TableType.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
/**
* The table types.
*/
public enum TableType {
/**
* The table type name for linked tables.
*/
TABLE_LINK,
/**
* The table type name for system tables. (aka. MetaTable)
*/
SYSTEM_TABLE,
/**
* The table type name for regular data tables.
*/
TABLE,
/**
* The table type name for views.
*/
VIEW,
/**
* The table type name for external table engines.
*/
EXTERNAL_TABLE_ENGINE;
@Override
public String toString() {
if (this == EXTERNAL_TABLE_ENGINE) {
return "EXTERNAL";
} else if (this == SYSTEM_TABLE) {
return "SYSTEM TABLE";
} else if (this == TABLE_LINK) {
return "TABLE LINK";
} else {
return super.toString();
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/table/TableView.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.h2.api.ErrorCode;
import org.h2.command.Prepared;
import org.h2.command.ddl.CreateTableData;
import org.h2.command.dml.Query;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Session;
import org.h2.engine.User;
import org.h2.expression.Alias;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.ExpressionVisitor;
import org.h2.expression.Parameter;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.index.ViewIndex;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.result.SortOrder;
import org.h2.schema.Schema;
import org.h2.util.ColumnNamer;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.Value;
/**
* A view is a virtual table that is defined by a query.
* @author Thomas Mueller
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class TableView extends Table {
private static final long ROW_COUNT_APPROXIMATION = 100;
private String querySQL;
private ArrayList<Table> tables;
private Column[] columnTemplates;
private Query viewQuery;
private ViewIndex index;
private boolean allowRecursive;
private DbException createException;
private long lastModificationCheck;
private long maxDataModificationId;
private User owner;
private Query topQuery;
private ResultInterface recursiveResult;
private boolean isRecursiveQueryDetected;
private boolean isTableExpression;
private boolean isPersistent;
public TableView(Schema schema, int id, String name, String querySQL,
ArrayList<Parameter> params, Column[] columnTemplates, Session session,
boolean allowRecursive, boolean literalsChecked, boolean isTableExpression, boolean isPersistent) {
super(schema, id, name, false, true);
init(querySQL, params, columnTemplates, session, allowRecursive, literalsChecked, isTableExpression,
isPersistent);
}
/**
* Try to replace the SQL statement of the view and re-compile this and all
* dependent views.
*
* @param querySQL the SQL statement
* @param newColumnTemplates the columns
* @param session the session
* @param recursive whether this is a recursive view
* @param force if errors should be ignored
* @param literalsChecked if literals have been checked
*/
public void replace(String querySQL, Column[] newColumnTemplates, Session session,
boolean recursive, boolean force, boolean literalsChecked) {
String oldQuerySQL = this.querySQL;
Column[] oldColumnTemplates = this.columnTemplates;
boolean oldRecursive = this.allowRecursive;
init(querySQL, null,
newColumnTemplates == null ? this.columnTemplates
: newColumnTemplates,
session, recursive, literalsChecked, isTableExpression, isPersistent);
DbException e = recompile(session, force, true);
if (e != null) {
init(oldQuerySQL, null, oldColumnTemplates, session, oldRecursive,
literalsChecked, isTableExpression, isPersistent);
recompile(session, true, false);
throw e;
}
}
private synchronized void init(String querySQL, ArrayList<Parameter> params,
Column[] columnTemplates, Session session, boolean allowRecursive, boolean literalsChecked,
boolean isTableExpression, boolean isPersistent) {
this.querySQL = querySQL;
this.columnTemplates = columnTemplates;
this.allowRecursive = allowRecursive;
this.isRecursiveQueryDetected = false;
this.isTableExpression = isTableExpression;
this.isPersistent = isPersistent;
index = new ViewIndex(this, querySQL, params, allowRecursive);
initColumnsAndTables(session, literalsChecked);
}
private Query compileViewQuery(Session session, String sql, boolean literalsChecked, String viewName) {
Prepared p;
session.setParsingCreateView(true, viewName);
try {
p = session.prepare(sql, false, literalsChecked);
} finally {
session.setParsingCreateView(false, viewName);
}
if (!(p instanceof Query)) {
throw DbException.getSyntaxError(sql, 0);
}
Query q = (Query) p;
// only potentially recursive cte queries need to be non-lazy
if (isTableExpression && allowRecursive) {
q.setNeverLazy(true);
}
return q;
}
/**
* Re-compile the view query and all views that depend on this object.
*
* @param session the session
* @param force if exceptions should be ignored
* @param clearIndexCache if we need to clear view index cache
* @return the exception if re-compiling this or any dependent view failed
* (only when force is disabled)
*/
public synchronized DbException recompile(Session session, boolean force,
boolean clearIndexCache) {
try {
compileViewQuery(session, querySQL, false, getName());
} catch (DbException e) {
if (!force) {
return e;
}
}
ArrayList<TableView> dependentViews = new ArrayList<>(getDependentViews());
initColumnsAndTables(session, false);
for (TableView v : dependentViews) {
DbException e = v.recompile(session, force, false);
if (e != null && !force) {
return e;
}
}
if (clearIndexCache) {
clearIndexCaches(database);
}
return force ? null : createException;
}
private void initColumnsAndTables(Session session, boolean literalsChecked) {
Column[] cols;
removeCurrentViewFromOtherTables();
setTableExpression(isTableExpression);
try {
Query compiledQuery = compileViewQuery(session, querySQL, literalsChecked, getName());
this.querySQL = compiledQuery.getPlanSQL();
tables = new ArrayList<>(compiledQuery.getTables());
ArrayList<Expression> expressions = compiledQuery.getExpressions();
ArrayList<Column> list = New.arrayList();
ColumnNamer columnNamer = new ColumnNamer(session);
for (int i = 0, count = compiledQuery.getColumnCount(); i < count; i++) {
Expression expr = expressions.get(i);
String name = null;
int type = Value.UNKNOWN;
if (columnTemplates != null && columnTemplates.length > i) {
name = columnTemplates[i].getName();
type = columnTemplates[i].getType();
}
if (name == null) {
name = expr.getAlias();
}
name = columnNamer.getColumnName(expr, i, name);
if (type == Value.UNKNOWN) {
type = expr.getType();
}
long precision = expr.getPrecision();
int scale = expr.getScale();
int displaySize = expr.getDisplaySize();
Column col = new Column(name, type, precision, scale, displaySize);
col.setTable(this, i);
// Fetch check constraint from view column source
ExpressionColumn fromColumn = null;
if (expr instanceof ExpressionColumn) {
fromColumn = (ExpressionColumn) expr;
} else if (expr instanceof Alias) {
Expression aliasExpr = expr.getNonAliasExpression();
if (aliasExpr instanceof ExpressionColumn) {
fromColumn = (ExpressionColumn) aliasExpr;
}
}
if (fromColumn != null) {
Expression checkExpression = fromColumn.getColumn()
.getCheckConstraint(session, name);
if (checkExpression != null) {
col.addCheckConstraint(session, checkExpression);
}
}
list.add(col);
}
cols = list.toArray(new Column[0]);
createException = null;
viewQuery = compiledQuery;
} catch (DbException e) {
e.addSQL(getCreateSQL());
createException = e;
// If it can't be compiled, then it's a 'zero column table'
// this avoids problems when creating the view when opening the
// database.
// If it can not be compiled - it could also be a recursive common
// table expression query.
if (isRecursiveQueryExceptionDetected(createException)) {
this.isRecursiveQueryDetected = true;
}
tables = New.arrayList();
cols = new Column[0];
if (allowRecursive && columnTemplates != null) {
cols = new Column[columnTemplates.length];
for (int i = 0; i < columnTemplates.length; i++) {
cols[i] = columnTemplates[i].getClone();
}
index.setRecursive(true);
createException = null;
}
}
setColumns(cols);
if (getId() != 0) {
addDependentViewToTables();
}
}
@Override
public boolean isView() {
return true;
}
/**
* Check if this view is currently invalid.
*
* @return true if it is
*/
public boolean isInvalid() {
return createException != null;
}
@Override
public PlanItem getBestPlanItem(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
final CacheKey cacheKey = new CacheKey(masks, this);
Map<Object, ViewIndex> indexCache = session.getViewIndexCache(topQuery != null);
ViewIndex i = indexCache.get(cacheKey);
if (i == null || i.isExpired()) {
i = new ViewIndex(this, index, session, masks, filters, filter, sortOrder);
indexCache.put(cacheKey, i);
}
PlanItem item = new PlanItem();
item.cost = i.getCost(session, masks, filters, filter, sortOrder, allColumnsSet);
item.setIndex(i);
return item;
}
@Override
public boolean isQueryComparable() {
if (!super.isQueryComparable()) {
return false;
}
for (Table t : tables) {
if (!t.isQueryComparable()) {
return false;
}
}
if (topQuery != null &&
!topQuery.isEverything(ExpressionVisitor.QUERY_COMPARABLE_VISITOR)) {
return false;
}
return true;
}
public Query getTopQuery() {
return topQuery;
}
@Override
public String getDropSQL() {
return "DROP VIEW IF EXISTS " + getSQL() + " CASCADE";
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
return getCreateSQL(false, true, quotedName);
}
@Override
public String getCreateSQL() {
return getCreateSQL(false, true);
}
/**
* 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) {
return getCreateSQL(orReplace, force, getSQL());
}
private String getCreateSQL(boolean orReplace, boolean force,
String quotedName) {
StatementBuilder buff = new StatementBuilder("CREATE ");
if (orReplace) {
buff.append("OR REPLACE ");
}
if (force) {
buff.append("FORCE ");
}
buff.append("VIEW ");
if (isTableExpression) {
buff.append("TABLE_EXPRESSION ");
}
buff.append(quotedName);
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
if (columns != null && columns.length > 0) {
buff.append('(');
for (Column c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(')');
} else if (columnTemplates != null) {
buff.append('(');
for (Column c : columnTemplates) {
buff.appendExceptFirst(", ");
buff.append(c.getName());
}
buff.append(')');
}
return buff.append(" AS\n").append(querySQL).toString();
}
@Override
public void checkRename() {
// ok
}
@Override
public boolean lock(Session session, boolean exclusive, boolean forceLockEvenInMvcc) {
// exclusive lock means: the view will be dropped
return false;
}
@Override
public void close(Session session) {
// nothing to do
}
@Override
public void unlock(Session s) {
// nothing to do
}
@Override
public boolean isLockedExclusively() {
return false;
}
@Override
public Index addIndex(Session session, String indexName, int indexId,
IndexColumn[] cols, IndexType indexType, boolean create,
String indexComment) {
throw DbException.getUnsupportedException("VIEW");
}
@Override
public void removeRow(Session session, Row row) {
throw DbException.getUnsupportedException("VIEW");
}
@Override
public void addRow(Session session, Row row) {
throw DbException.getUnsupportedException("VIEW");
}
@Override
public void checkSupportAlter() {
throw DbException.getUnsupportedException("VIEW");
}
@Override
public void truncate(Session session) {
throw DbException.getUnsupportedException("VIEW");
}
@Override
public long getRowCount(Session session) {
throw DbException.throwInternalError(toString());
}
@Override
public boolean canGetRowCount() {
// TODO view: could get the row count, but not that easy
return false;
}
@Override
public boolean canDrop() {
return true;
}
@Override
public TableType getTableType() {
return TableType.VIEW;
}
@Override
public void removeChildrenAndResources(Session session) {
removeCurrentViewFromOtherTables();
super.removeChildrenAndResources(session);
database.removeMeta(session, getId());
querySQL = null;
index = null;
clearIndexCaches(database);
invalidate();
}
/**
* Clear the cached indexes for all sessions.
*
* @param database the database
*/
public static void clearIndexCaches(Database database) {
for (Session s : database.getSessions(true)) {
s.clearViewIndexCache();
}
}
@Override
public String getSQL() {
if (isTemporary() && querySQL != null) {
return "(\n" + StringUtils.indent(querySQL) + ")";
}
return super.getSQL();
}
public String getQuery() {
return querySQL;
}
@Override
public Index getScanIndex(Session session) {
return getBestPlanItem(session, null, null, -1, null, null).getIndex();
}
@Override
public Index getScanIndex(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
if (createException != null) {
String msg = createException.getMessage();
throw DbException.get(ErrorCode.VIEW_IS_INVALID_2,
createException, getSQL(), msg);
}
PlanItem item = getBestPlanItem(session, masks, filters, filter, sortOrder, allColumnsSet);
return item.getIndex();
}
@Override
public boolean canReference() {
return false;
}
@Override
public ArrayList<Index> getIndexes() {
return null;
}
@Override
public long getMaxDataModificationId() {
if (createException != null) {
return Long.MAX_VALUE;
}
if (viewQuery == null) {
return Long.MAX_VALUE;
}
// if nothing was modified in the database since the last check, and the
// last is known, then we don't need to check again
// this speeds up nested views
long dbMod = database.getModificationDataId();
if (dbMod > lastModificationCheck && maxDataModificationId <= dbMod) {
maxDataModificationId = viewQuery.getMaxDataModificationId();
lastModificationCheck = dbMod;
}
return maxDataModificationId;
}
@Override
public Index getUniqueIndex() {
return null;
}
private void removeCurrentViewFromOtherTables() {
if (tables != null) {
for (Table t : tables) {
t.removeDependentView(this);
}
tables.clear();
}
}
private void addDependentViewToTables() {
for (Table t : tables) {
t.addDependentView(this);
}
}
private void setOwner(User owner) {
this.owner = owner;
}
public User getOwner() {
return owner;
}
/**
* Create a temporary view out of the given query.
*
* @param session the session
* @param owner the owner of the query
* @param name the view name
* @param query the query
* @param topQuery the top level query
* @return the view table
*/
public static TableView createTempView(Session session, User owner,
String name, Query query, Query topQuery) {
Schema mainSchema = session.getDatabase().getSchema(Constants.SCHEMA_MAIN);
String querySQL = query.getPlanSQL();
TableView v = new TableView(mainSchema, 0, name,
querySQL, query.getParameters(), null /* column templates */, session,
false/* allow recursive */, true /* literals have already been checked when parsing original query */,
false /* is table expression */, false/* is persistent*/);
if (v.createException != null) {
throw v.createException;
}
v.setTopQuery(topQuery);
v.setOwner(owner);
v.setTemporary(true);
return v;
}
private void setTopQuery(Query topQuery) {
this.topQuery = topQuery;
}
@Override
public long getRowCountApproximation() {
return ROW_COUNT_APPROXIMATION;
}
@Override
public long getDiskSpaceUsed() {
return 0;
}
/**
* Get the index of the first parameter.
*
* @param additionalParameters additional parameters
* @return the index of the first parameter
*/
public int getParameterOffset(ArrayList<Parameter> additionalParameters) {
int result = topQuery == null ? -1 : getMaxParameterIndex(topQuery.getParameters());
if (additionalParameters != null) {
result = Math.max(result, getMaxParameterIndex(additionalParameters));
}
return result + 1;
}
private static int getMaxParameterIndex(ArrayList<Parameter> parameters) {
int result = -1;
for (Parameter p : parameters) {
result = Math.max(result, p.getIndex());
}
return result;
}
public boolean isRecursive() {
return allowRecursive;
}
@Override
public boolean isDeterministic() {
if (allowRecursive || viewQuery == null) {
return false;
}
return viewQuery.isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR);
}
public void setRecursiveResult(ResultInterface value) {
if (recursiveResult != null) {
recursiveResult.close();
}
this.recursiveResult = value;
}
public ResultInterface getRecursiveResult() {
return recursiveResult;
}
@Override
public void addDependencies(HashSet<DbObject> dependencies) {
super.addDependencies(dependencies);
if (tables != null) {
for (Table t : tables) {
if (TableType.VIEW != t.getTableType()) {
t.addDependencies(dependencies);
}
}
}
}
/**
* The key of the index cache for views.
*/
private static final class CacheKey {
private final int[] masks;
private final TableView view;
CacheKey(int[] masks, TableView view) {
this.masks = masks;
this.view = view;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(masks);
result = prime * result + view.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CacheKey other = (CacheKey) obj;
if (view != other.view) {
return false;
}
return Arrays.equals(masks, other.masks);
}
}
/**
* Was query recursion detected during compiling.
*
* @return true if yes
*/
public boolean isRecursiveQueryDetected() {
return isRecursiveQueryDetected;
}
/**
* Does exception indicate query recursion?
*/
private boolean isRecursiveQueryExceptionDetected(DbException exception) {
if (exception == null) {
return false;
}
if (exception.getErrorCode() != ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1) {
return false;
}
return exception.getMessage().contains("\"" + this.getName() + "\"");
}
public List<Table> getTables() {
return tables;
}
public boolean isPersistent() {
return isPersistent;
}
/**
* Create a view.
*
* @param schema the schema
* @param id the view id
* @param name the view name
* @param querySQL the query
* @param parameters the parameters
* @param columnTemplates the columns
* @param session the session
* @param literalsChecked whether literals in the query are checked
* @param isTableExpression if this is a table expression
* @param isPersistent whether the view is persisted
* @param db the database
* @return the view
*/
public static TableView createTableViewMaybeRecursive(Schema schema, int id, String name, String querySQL,
ArrayList<Parameter> parameters, Column[] columnTemplates, Session session,
boolean literalsChecked, boolean isTableExpression, boolean isPersistent, Database db) {
Table recursiveTable = TableView.createShadowTableForRecursiveTableExpression(isPersistent, session, name,
schema, Arrays.asList(columnTemplates), db);
List<Column> columnTemplateList;
String[] querySQLOutput = {null};
ArrayList<String> columnNames = new ArrayList<>();
for (Column columnTemplate: columnTemplates) {
columnNames.add(columnTemplate.getName());
}
try {
Prepared withQuery = session.prepare(querySQL, false, false);
if (isPersistent) {
withQuery.setSession(session);
}
columnTemplateList = TableView.createQueryColumnTemplateList(columnNames.toArray(new String[1]),
(Query) withQuery, querySQLOutput);
} finally {
TableView.destroyShadowTableForRecursiveExpression(isPersistent, session, recursiveTable);
}
// build with recursion turned on
TableView view = new TableView(schema, id, name, querySQL,
parameters, columnTemplateList.toArray(columnTemplates), session,
true/* try recursive */, literalsChecked, isTableExpression, isPersistent);
// is recursion really detected ? if not - recreate it without recursion flag
// and no recursive index
if (!view.isRecursiveQueryDetected()) {
if (isPersistent) {
db.addSchemaObject(session, view);
view.lock(session, true, true);
session.getDatabase().removeSchemaObject(session, view);
// during database startup - this method does not normally get called - and it
// needs to be to correctly un-register the table which the table expression
// uses...
view.removeChildrenAndResources(session);
} else {
session.removeLocalTempTable(view);
}
view = new TableView(schema, id, name, querySQL, parameters,
columnTemplates, session,
false/* detected not recursive */, literalsChecked, isTableExpression, isPersistent);
}
return view;
}
/**
* Creates a list of column templates from a query (usually from WITH query,
* but could be any query)
*
* @param cols - an optional list of column names (can be specified by WITH
* clause overriding usual select names)
* @param theQuery - the query object we want the column list for
* @param querySQLOutput - array of length 1 to receive extra 'output' field
* in addition to return value - containing the SQL query of the
* Query object
* @return a list of column object returned by withQuery
*/
public static List<Column> createQueryColumnTemplateList(String[] cols,
Query theQuery, String[] querySQLOutput) {
List<Column> columnTemplateList = new ArrayList<>();
theQuery.prepare();
// String array of length 1 is to receive extra 'output' field in addition to
// return value
querySQLOutput[0] = StringUtils.cache(theQuery.getPlanSQL());
ColumnNamer columnNamer = new ColumnNamer(theQuery.getSession());
ArrayList<Expression> withExpressions = theQuery.getExpressions();
for (int i = 0; i < withExpressions.size(); ++i) {
Expression columnExp = withExpressions.get(i);
// use the passed in column name if supplied, otherwise use alias
// (if found) otherwise use column name derived from column
// expression
String columnName = columnNamer.getColumnName(columnExp, i, cols);
columnTemplateList.add(new Column(columnName,
columnExp.getType()));
}
return columnTemplateList;
}
/**
* Create a table for a recursive query.
*
* @param isPersistent whether the table is persisted
* @param targetSession the session
* @param cteViewName the name
* @param schema the schema
* @param columns the columns
* @param db the database
* @return the table
*/
public static Table createShadowTableForRecursiveTableExpression(boolean isPersistent, Session targetSession,
String cteViewName, Schema schema, List<Column> columns, Database db) {
// create table data object
CreateTableData recursiveTableData = new CreateTableData();
recursiveTableData.id = db.allocateObjectId();
recursiveTableData.columns = new ArrayList<>(columns);
recursiveTableData.tableName = cteViewName;
recursiveTableData.temporary = !isPersistent;
recursiveTableData.persistData = true;
recursiveTableData.persistIndexes = isPersistent;
recursiveTableData.create = true;
recursiveTableData.session = targetSession;
// this gets a meta table lock that is not released
Table recursiveTable = schema.createTable(recursiveTableData);
if (isPersistent) {
// this unlock is to prevent lock leak from schema.createTable()
db.unlockMeta(targetSession);
synchronized (targetSession) {
db.addSchemaObject(targetSession, recursiveTable);
}
} else {
targetSession.addLocalTempTable(recursiveTable);
}
return recursiveTable;
}
/**
* Remove a table for a recursive query.
*
* @param isPersistent whether the table is persisted
* @param targetSession the session
* @param recursiveTable the table
*/
public static void destroyShadowTableForRecursiveExpression(boolean isPersistent, Session targetSession,
Table recursiveTable) {
if (recursiveTable != null) {
if (isPersistent) {
recursiveTable.lock(targetSession, true, true);
targetSession.getDatabase().removeSchemaObject(targetSession, recursiveTable);
} else {
targetSession.removeLocalTempTable(recursiveTable);
}
// both removeSchemaObject and removeLocalTempTable hold meta locks - release them here
targetSession.getDatabase().unlockMeta(targetSession);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Backup.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.h2.command.dml.BackupCommand;
import org.h2.engine.Constants;
import org.h2.message.DbException;
import org.h2.store.FileLister;
import org.h2.store.fs.FileUtils;
import org.h2.util.IOUtils;
import org.h2.util.Tool;
/**
* Creates a backup of a database.
* <br />
* This tool copies all database files. The database must be closed before using
* this tool. To create a backup while the database is in use, run the BACKUP
* SQL statement. In an emergency, for example if the application is not
* responding, creating a backup using the Backup tool is possible by using the
* quiet mode. However, if the database is changed while the backup is running
* in quiet mode, the backup could be corrupt.
*
* @h2.resource
*/
public class Backup extends Tool {
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-file <filename>]</td>
* <td>The target file name (default: backup.zip)</td></tr>
* <tr><td>[-dir <dir>]</td>
* <td>The source directory (default: .)</td></tr>
* <tr><td>[-db <database>]</td>
* <td>Source database; not required if there is only one</td></tr>
* <tr><td>[-quiet]</td>
* <td>Do not print progress information</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new Backup().runTool(args);
}
@Override
public void runTool(String... args) throws SQLException {
String zipFileName = "backup.zip";
String dir = ".";
String db = null;
boolean quiet = false;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-dir")) {
dir = args[++i];
} else if (arg.equals("-db")) {
db = args[++i];
} else if (arg.equals("-quiet")) {
quiet = true;
} else if (arg.equals("-file")) {
zipFileName = args[++i];
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
try {
process(zipFileName, dir, db, quiet);
} catch (Exception e) {
throw DbException.toSQLException(e);
}
}
/**
* Backs up database files.
*
* @param zipFileName the name of the target backup file (including path)
* @param directory the source directory name
* @param db the source database name (null if there is only one database,
* and and empty string to backup all files in this directory)
* @param quiet don't print progress information
*/
public static void execute(String zipFileName, String directory, String db,
boolean quiet) throws SQLException {
try {
new Backup().process(zipFileName, directory, db, quiet);
} catch (Exception e) {
throw DbException.toSQLException(e);
}
}
private void process(String zipFileName, String directory, String db,
boolean quiet) throws SQLException {
List<String> list;
boolean allFiles = db != null && db.length() == 0;
if (allFiles) {
list = FileUtils.newDirectoryStream(directory);
} else {
list = FileLister.getDatabaseFiles(directory, db, true);
}
if (list.isEmpty()) {
if (!quiet) {
printNoDatabaseFilesFound(directory, db);
}
return;
}
if (!quiet) {
FileLister.tryUnlockDatabase(list, "backup");
}
zipFileName = FileUtils.toRealPath(zipFileName);
FileUtils.delete(zipFileName);
OutputStream fileOut = null;
try {
fileOut = FileUtils.newOutputStream(zipFileName, false);
try (ZipOutputStream zipOut = new ZipOutputStream(fileOut)) {
String base = "";
for (String fileName : list) {
if (allFiles ||
fileName.endsWith(Constants.SUFFIX_PAGE_FILE) ||
fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
base = FileUtils.getParent(fileName);
break;
}
}
for (String fileName : list) {
String f = FileUtils.toRealPath(fileName);
if (!f.startsWith(base)) {
DbException.throwInternalError(f + " does not start with " + base);
}
if (f.endsWith(zipFileName)) {
continue;
}
if (FileUtils.isDirectory(fileName)) {
continue;
}
f = f.substring(base.length());
f = BackupCommand.correctFileName(f);
ZipEntry entry = new ZipEntry(f);
zipOut.putNextEntry(entry);
InputStream in = null;
try {
in = FileUtils.newInputStream(fileName);
IOUtils.copyAndCloseInput(in, zipOut);
} catch (FileNotFoundException e) {
// the file could have been deleted in the meantime
// ignore this (in this case an empty file is created)
} finally {
IOUtils.closeSilently(in);
}
zipOut.closeEntry();
if (!quiet) {
out.println("Processed: " + fileName);
}
}
}
} catch (IOException e) {
throw DbException.convertIOException(e, zipFileName);
} finally {
IOUtils.closeSilently(fileOut);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/ChangeFileEncryption.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.h2.engine.Constants;
import org.h2.message.DbException;
import org.h2.security.SHA256;
import org.h2.store.FileLister;
import org.h2.store.FileStore;
import org.h2.store.fs.FileChannelInputStream;
import org.h2.store.fs.FileChannelOutputStream;
import org.h2.store.fs.FilePath;
import org.h2.store.fs.FilePathEncrypt;
import org.h2.store.fs.FileUtils;
import org.h2.util.Tool;
/**
* Allows changing the database file encryption password or algorithm.
* <br />
* This tool can not be used to change a password of a user.
* The database must be closed before using this tool.
* @h2.resource
*/
public class ChangeFileEncryption extends Tool {
private String directory;
private String cipherType;
private byte[] decrypt;
private byte[] encrypt;
private byte[] decryptKey;
private byte[] encryptKey;
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-cipher type]</td>
* <td>The encryption type (AES)</td></tr>
* <tr><td>[-dir <dir>]</td>
* <td>The database directory (default: .)</td></tr>
* <tr><td>[-db <database>]</td>
* <td>Database name (all databases if not set)</td></tr>
* <tr><td>[-decrypt <pwd>]</td>
* <td>The decryption password (if not set: not yet encrypted)</td></tr>
* <tr><td>[-encrypt <pwd>]</td>
* <td>The encryption password (if not set: do not encrypt)</td></tr>
* <tr><td>[-quiet]</td>
* <td>Do not print progress information</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new ChangeFileEncryption().runTool(args);
}
@Override
public void runTool(String... args) throws SQLException {
String dir = ".";
String cipher = null;
char[] decryptPassword = null;
char[] encryptPassword = null;
String db = null;
boolean quiet = false;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-dir")) {
dir = args[++i];
} else if (arg.equals("-cipher")) {
cipher = args[++i];
} else if (arg.equals("-db")) {
db = args[++i];
} else if (arg.equals("-decrypt")) {
decryptPassword = args[++i].toCharArray();
} else if (arg.equals("-encrypt")) {
encryptPassword = args[++i].toCharArray();
} else if (arg.equals("-quiet")) {
quiet = true;
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
if ((encryptPassword == null && decryptPassword == null) || cipher == null) {
showUsage();
throw new SQLException(
"Encryption or decryption password not set, or cipher not set");
}
try {
process(dir, db, cipher, decryptPassword, encryptPassword, quiet);
} catch (Exception e) {
throw DbException.toSQLException(e);
}
}
/**
* Get the file encryption key for a given password. The password must be
* supplied as char arrays and is cleaned in this method.
*
* @param password the password as a char array
* @return the encryption key
*/
private static byte[] getFileEncryptionKey(char[] password) {
if (password == null) {
return null;
}
return SHA256.getKeyPasswordHash("file", password);
}
/**
* Changes the password for a database. The passwords must be supplied as
* char arrays and are cleaned in this method. The database must be closed
* before calling this method.
*
* @param dir the directory (. for the current directory)
* @param db the database name (null for all databases)
* @param cipher the cipher (AES)
* @param decryptPassword the decryption password as a char array
* @param encryptPassword the encryption password as a char array
* @param quiet don't print progress information
*/
public static void execute(String dir, String db, String cipher,
char[] decryptPassword, char[] encryptPassword, boolean quiet)
throws SQLException {
try {
new ChangeFileEncryption().process(dir, db, cipher,
decryptPassword, encryptPassword, quiet);
} catch (Exception e) {
throw DbException.toSQLException(e);
}
}
private void process(String dir, String db, String cipher,
char[] decryptPassword, char[] encryptPassword, boolean quiet)
throws SQLException {
dir = FileLister.getDir(dir);
ChangeFileEncryption change = new ChangeFileEncryption();
if (encryptPassword != null) {
for (char c : encryptPassword) {
if (c == ' ') {
throw new SQLException("The file password may not contain spaces");
}
}
change.encryptKey = FilePathEncrypt.getPasswordBytes(encryptPassword);
change.encrypt = getFileEncryptionKey(encryptPassword);
}
if (decryptPassword != null) {
change.decryptKey = FilePathEncrypt.getPasswordBytes(decryptPassword);
change.decrypt = getFileEncryptionKey(decryptPassword);
}
change.out = out;
change.directory = dir;
change.cipherType = cipher;
ArrayList<String> files = FileLister.getDatabaseFiles(dir, db, true);
FileLister.tryUnlockDatabase(files, "encryption");
files = FileLister.getDatabaseFiles(dir, db, false);
if (files.isEmpty() && !quiet) {
printNoDatabaseFilesFound(dir, db);
}
// first, test only if the file can be renamed
// (to find errors with locked files early)
for (String fileName : files) {
String temp = dir + "/temp.db";
FileUtils.delete(temp);
FileUtils.move(fileName, temp);
FileUtils.move(temp, fileName);
}
// if this worked, the operation will (hopefully) be successful
// TODO changeFileEncryption: this is a workaround!
// make the operation atomic (all files or none)
for (String fileName : files) {
// don't process a lob directory, just the files in the directory.
if (!FileUtils.isDirectory(fileName)) {
change.process(fileName, quiet);
}
}
}
private void process(String fileName, boolean quiet) {
if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
try {
copy(fileName, quiet);
} catch (IOException e) {
throw DbException.convertIOException(e,
"Error encrypting / decrypting file " + fileName);
}
return;
}
FileStore in;
if (decrypt == null) {
in = FileStore.open(null, fileName, "r");
} else {
in = FileStore.open(null, fileName, "r", cipherType, decrypt);
}
try {
in.init();
copy(fileName, in, encrypt, quiet);
} finally {
in.closeSilently();
}
}
private void copy(String fileName, boolean quiet) throws IOException {
if (FileUtils.isDirectory(fileName)) {
return;
}
String temp = directory + "/temp.db";
try (FileChannel fileIn = getFileChannel(fileName, "r", decryptKey)){
try(InputStream inStream = new FileChannelInputStream(fileIn, true)) {
FileUtils.delete(temp);
try (OutputStream outStream = new FileChannelOutputStream(getFileChannel(temp, "rw", encryptKey),
true)) {
byte[] buffer = new byte[4 * 1024];
long remaining = fileIn.size();
long total = remaining;
long time = System.nanoTime();
while (remaining > 0) {
if (!quiet && System.nanoTime() - time > TimeUnit.SECONDS.toNanos(1)) {
out.println(fileName + ": " + (100 - 100 * remaining / total) + "%");
time = System.nanoTime();
}
int len = (int) Math.min(buffer.length, remaining);
len = inStream.read(buffer, 0, len);
outStream.write(buffer, 0, len);
remaining -= len;
}
}
}
}
FileUtils.delete(fileName);
FileUtils.move(temp, fileName);
}
private FileChannel getFileChannel(String fileName, String r, byte[] decryptKey) throws IOException {
FileChannel fileIn = FilePath.get(fileName).open(r);
if (decryptKey != null) {
fileIn = new FilePathEncrypt.FileEncrypt(fileName, decryptKey, fileIn);
}
return fileIn;
}
private void copy(String fileName, FileStore in, byte[] key, boolean quiet) {
if (FileUtils.isDirectory(fileName)) {
return;
}
String temp = directory + "/temp.db";
FileUtils.delete(temp);
FileStore fileOut;
if (key == null) {
fileOut = FileStore.open(null, temp, "rw");
} else {
fileOut = FileStore.open(null, temp, "rw", cipherType, key);
}
fileOut.init();
byte[] buffer = new byte[4 * 1024];
long remaining = in.length() - FileStore.HEADER_LENGTH;
long total = remaining;
in.seek(FileStore.HEADER_LENGTH);
fileOut.seek(FileStore.HEADER_LENGTH);
long time = System.nanoTime();
while (remaining > 0) {
if (!quiet && System.nanoTime() - time > TimeUnit.SECONDS.toNanos(1)) {
out.println(fileName + ": " + (100 - 100 * remaining / total) + "%");
time = System.nanoTime();
}
int len = (int) Math.min(buffer.length, remaining);
in.readFully(buffer, 0, len);
fileOut.write(buffer, 0, len);
remaining -= len;
}
in.close();
fileOut.close();
FileUtils.delete(fileName);
FileUtils.move(temp, fileName);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/CompressTool.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.InflaterInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.h2.api.ErrorCode;
import org.h2.compress.CompressDeflate;
import org.h2.compress.CompressLZF;
import org.h2.compress.CompressNo;
import org.h2.compress.Compressor;
import org.h2.compress.LZFInputStream;
import org.h2.compress.LZFOutputStream;
import org.h2.engine.Constants;
import org.h2.message.DbException;
import org.h2.util.Bits;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* A tool to losslessly compress data, and expand the compressed data again.
*/
public class CompressTool {
private static final int MAX_BUFFER_SIZE =
3 * Constants.IO_BUFFER_SIZE_COMPRESS;
private byte[] cachedBuffer;
private CompressTool() {
// don't allow construction
}
private byte[] getBuffer(int min) {
if (min > MAX_BUFFER_SIZE) {
return Utils.newBytes(min);
}
if (cachedBuffer == null || cachedBuffer.length < min) {
cachedBuffer = Utils.newBytes(min);
}
return cachedBuffer;
}
/**
* Get a new instance. Each instance uses a separate buffer, so multiple
* instances can be used concurrently. However each instance alone is not
* multithreading safe.
*
* @return a new instance
*/
public static CompressTool getInstance() {
return new CompressTool();
}
/**
* Compressed the data using the specified algorithm. If no algorithm is
* supplied, LZF is used
*
* @param in the byte array with the original data
* @param algorithm the algorithm (LZF, DEFLATE)
* @return the compressed data
*/
public byte[] compress(byte[] in, String algorithm) {
int len = in.length;
if (in.length < 5) {
algorithm = "NO";
}
Compressor compress = getCompressor(algorithm);
byte[] buff = getBuffer((len < 100 ? len + 100 : len) * 2);
int newLen = compress(in, in.length, compress, buff);
return Utils.copyBytes(buff, newLen);
}
private static int compress(byte[] in, int len, Compressor compress,
byte[] out) {
int newLen = 0;
out[0] = (byte) compress.getAlgorithm();
int start = 1 + writeVariableInt(out, 1, len);
newLen = compress.compress(in, len, out, start);
if (newLen > len + start || newLen <= 0) {
out[0] = Compressor.NO;
System.arraycopy(in, 0, out, start, len);
newLen = len + start;
}
return newLen;
}
/**
* Expands the compressed data.
*
* @param in the byte array with the compressed data
* @return the uncompressed data
*/
public byte[] expand(byte[] in) {
int algorithm = in[0];
Compressor compress = getCompressor(algorithm);
try {
int len = readVariableInt(in, 1);
int start = 1 + getVariableIntLength(len);
byte[] buff = Utils.newBytes(len);
compress.expand(in, start, in.length - start, buff, 0, len);
return buff;
} catch (Exception e) {
throw DbException.get(ErrorCode.COMPRESSION_ERROR, e);
}
}
/**
* INTERNAL
*/
public static void expand(byte[] in, byte[] out, int outPos) {
int algorithm = in[0];
Compressor compress = getCompressor(algorithm);
try {
int len = readVariableInt(in, 1);
int start = 1 + getVariableIntLength(len);
compress.expand(in, start, in.length - start, out, outPos, len);
} catch (Exception e) {
throw DbException.get(ErrorCode.COMPRESSION_ERROR, e);
}
}
/**
* Read a variable size integer using Rice coding.
*
* @param buff the buffer
* @param pos the position
* @return the integer
*/
public static int readVariableInt(byte[] buff, int pos) {
int x = buff[pos++] & 0xff;
if (x < 0x80) {
return x;
}
if (x < 0xc0) {
return ((x & 0x3f) << 8) + (buff[pos] & 0xff);
}
if (x < 0xe0) {
return ((x & 0x1f) << 16) +
((buff[pos++] & 0xff) << 8) +
(buff[pos] & 0xff);
}
if (x < 0xf0) {
return ((x & 0xf) << 24) +
((buff[pos++] & 0xff) << 16) +
((buff[pos++] & 0xff) << 8) +
(buff[pos] & 0xff);
}
return Bits.readInt(buff, pos);
}
/**
* Write a variable size integer using Rice coding.
* Negative values need 5 bytes.
*
* @param buff the buffer
* @param pos the position
* @param x the value
* @return the number of bytes written (0-5)
*/
public static int writeVariableInt(byte[] buff, int pos, int x) {
if (x < 0) {
buff[pos++] = (byte) 0xf0;
Bits.writeInt(buff, pos, x);
return 5;
} else if (x < 0x80) {
buff[pos] = (byte) x;
return 1;
} else if (x < 0x4000) {
buff[pos++] = (byte) (0x80 | (x >> 8));
buff[pos] = (byte) x;
return 2;
} else if (x < 0x20_0000) {
buff[pos++] = (byte) (0xc0 | (x >> 16));
buff[pos++] = (byte) (x >> 8);
buff[pos] = (byte) x;
return 3;
} else if (x < 0x1000_0000) {
Bits.writeInt(buff, pos, x | 0xe000_0000);
return 4;
} else {
buff[pos++] = (byte) 0xf0;
Bits.writeInt(buff, pos, x);
return 5;
}
}
/**
* Get a variable size integer length using Rice coding.
* Negative values need 5 bytes.
*
* @param x the value
* @return the number of bytes needed (0-5)
*/
public static int getVariableIntLength(int x) {
if (x < 0) {
return 5;
} else if (x < 0x80) {
return 1;
} else if (x < 0x4000) {
return 2;
} else if (x < 0x20_0000) {
return 3;
} else if (x < 0x1000_0000) {
return 4;
} else {
return 5;
}
}
private static Compressor getCompressor(String algorithm) {
if (algorithm == null) {
algorithm = "LZF";
}
int idx = algorithm.indexOf(' ');
String options = null;
if (idx > 0) {
options = algorithm.substring(idx + 1);
algorithm = algorithm.substring(0, idx);
}
int a = getCompressAlgorithm(algorithm);
Compressor compress = getCompressor(a);
compress.setOptions(options);
return compress;
}
/**
* INTERNAL
*/
public static int getCompressAlgorithm(String algorithm) {
algorithm = StringUtils.toUpperEnglish(algorithm);
if ("NO".equals(algorithm)) {
return Compressor.NO;
} else if ("LZF".equals(algorithm)) {
return Compressor.LZF;
} else if ("DEFLATE".equals(algorithm)) {
return Compressor.DEFLATE;
} else {
throw DbException.get(
ErrorCode.UNSUPPORTED_COMPRESSION_ALGORITHM_1,
algorithm);
}
}
private static Compressor getCompressor(int algorithm) {
switch (algorithm) {
case Compressor.NO:
return new CompressNo();
case Compressor.LZF:
return new CompressLZF();
case Compressor.DEFLATE:
return new CompressDeflate();
default:
throw DbException.get(
ErrorCode.UNSUPPORTED_COMPRESSION_ALGORITHM_1,
"" + algorithm);
}
}
/**
* INTERNAL
*/
public static OutputStream wrapOutputStream(OutputStream out,
String compressionAlgorithm, String entryName) {
try {
if ("GZIP".equals(compressionAlgorithm)) {
out = new GZIPOutputStream(out);
} else if ("ZIP".equals(compressionAlgorithm)) {
ZipOutputStream z = new ZipOutputStream(out);
z.putNextEntry(new ZipEntry(entryName));
out = z;
} else if ("DEFLATE".equals(compressionAlgorithm)) {
out = new DeflaterOutputStream(out);
} else if ("LZF".equals(compressionAlgorithm)) {
out = new LZFOutputStream(out);
} else if (compressionAlgorithm != null) {
throw DbException.get(
ErrorCode.UNSUPPORTED_COMPRESSION_ALGORITHM_1,
compressionAlgorithm);
}
return out;
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
/**
* INTERNAL
*/
public static InputStream wrapInputStream(InputStream in,
String compressionAlgorithm, String entryName) {
try {
if ("GZIP".equals(compressionAlgorithm)) {
in = new GZIPInputStream(in);
} else if ("ZIP".equals(compressionAlgorithm)) {
ZipInputStream z = new ZipInputStream(in);
while (true) {
ZipEntry entry = z.getNextEntry();
if (entry == null) {
return null;
}
if (entryName.equals(entry.getName())) {
break;
}
}
in = z;
} else if ("DEFLATE".equals(compressionAlgorithm)) {
in = new InflaterInputStream(in);
} else if ("LZF".equals(compressionAlgorithm)) {
in = new LZFInputStream(in);
} else if (compressionAlgorithm != null) {
throw DbException.get(
ErrorCode.UNSUPPORTED_COMPRESSION_ALGORITHM_1,
compressionAlgorithm);
}
return in;
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Console.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
//## AWT ##
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Label;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.PopupMenu;
import java.awt.SystemColor;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.h2.server.ShutdownHandler;
import org.h2.util.JdbcUtils;
import org.h2.util.Tool;
import org.h2.util.Utils;
/**
* Starts the H2 Console (web-) server, as well as the TCP and PG server.
* @h2.resource
*
* @author Thomas Mueller, Ridvan Agar
*/
public class Console extends Tool implements
//## AWT ##
ActionListener, MouseListener, WindowListener,
//*/
ShutdownHandler {
//## AWT ##
private Frame frame;
private boolean trayIconUsed;
private Font font;
private Button startBrowser;
private TextField urlText;
private Object tray;
private Object trayIcon;
//*/
private Server web, tcp, pg;
private boolean isWindows;
private long lastOpenNs;
/**
* When running without options, -tcp, -web, -browser and -pg are started.
* <br />
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-url]</td>
* <td>Start a browser and connect to this URL</td></tr>
* <tr><td>[-driver]</td>
* <td>Used together with -url: the driver</td></tr>
* <tr><td>[-user]</td>
* <td>Used together with -url: the user name</td></tr>
* <tr><td>[-password]</td>
* <td>Used together with -url: the password</td></tr>
* <tr><td>[-web]</td>
* <td>Start the web server with the H2 Console</td></tr>
* <tr><td>[-tool]</td>
* <td>Start the icon or window that allows to start a browser</td></tr>
* <tr><td>[-browser]</td>
* <td>Start a browser connecting to the web server</td></tr>
* <tr><td>[-tcp]</td>
* <td>Start the TCP server</td></tr>
* <tr><td>[-pg]</td>
* <td>Start the PG server</td></tr>
* </table>
* For each Server, additional options are available;
* for details, see the Server tool.<br />
* If a service can not be started, the program
* terminates with an exit code of 1.
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new Console().runTool(args);
}
/**
* This tool starts the H2 Console (web-) server, as well as the TCP and PG
* server. For JDK 1.6, a system tray icon is created, for platforms that
* support it. Otherwise, a small window opens.
*
* @param args the command line arguments
*/
@Override
public void runTool(String... args) throws SQLException {
isWindows = Utils.getProperty("os.name", "").startsWith("Windows");
boolean tcpStart = false, pgStart = false, webStart = false, toolStart = false;
boolean browserStart = false;
boolean startDefaultServers = true;
boolean printStatus = args != null && args.length > 0;
String driver = null, url = null, user = null, password = null;
boolean tcpShutdown = false, tcpShutdownForce = false;
String tcpPassword = "";
String tcpShutdownServer = "";
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg == null) {
} else if ("-?".equals(arg) || "-help".equals(arg)) {
showUsage();
return;
} else if ("-url".equals(arg)) {
startDefaultServers = false;
url = args[++i];
} else if ("-driver".equals(arg)) {
driver = args[++i];
} else if ("-user".equals(arg)) {
user = args[++i];
} else if ("-password".equals(arg)) {
password = args[++i];
} else if (arg.startsWith("-web")) {
if ("-web".equals(arg)) {
startDefaultServers = false;
webStart = true;
} else if ("-webAllowOthers".equals(arg)) {
// no parameters
} else if ("-webDaemon".equals(arg)) {
// no parameters
} else if ("-webSSL".equals(arg)) {
// no parameters
} else if ("-webPort".equals(arg)) {
i++;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
} else if ("-tool".equals(arg)) {
startDefaultServers = false;
webStart = true;
toolStart = true;
} else if ("-browser".equals(arg)) {
startDefaultServers = false;
webStart = true;
browserStart = true;
} else if (arg.startsWith("-tcp")) {
if ("-tcp".equals(arg)) {
startDefaultServers = false;
tcpStart = true;
} else if ("-tcpAllowOthers".equals(arg)) {
// no parameters
} else if ("-tcpDaemon".equals(arg)) {
// no parameters
} else if ("-tcpSSL".equals(arg)) {
// no parameters
} else if ("-tcpPort".equals(arg)) {
i++;
} else if ("-tcpPassword".equals(arg)) {
tcpPassword = args[++i];
} else if ("-tcpShutdown".equals(arg)) {
startDefaultServers = false;
tcpShutdown = true;
tcpShutdownServer = args[++i];
} else if ("-tcpShutdownForce".equals(arg)) {
tcpShutdownForce = true;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
} else if (arg.startsWith("-pg")) {
if ("-pg".equals(arg)) {
startDefaultServers = false;
pgStart = true;
} else if ("-pgAllowOthers".equals(arg)) {
// no parameters
} else if ("-pgDaemon".equals(arg)) {
// no parameters
} else if ("-pgPort".equals(arg)) {
i++;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
} else if ("-properties".equals(arg)) {
i++;
} else if ("-trace".equals(arg)) {
// no parameters
} else if ("-ifExists".equals(arg)) {
// no parameters
} else if ("-baseDir".equals(arg)) {
i++;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
if (startDefaultServers) {
webStart = true;
toolStart = true;
browserStart = true;
tcpStart = true;
pgStart = true;
}
if (tcpShutdown) {
out.println("Shutting down TCP Server at " + tcpShutdownServer);
Server.shutdownTcpServer(tcpShutdownServer,
tcpPassword, tcpShutdownForce, false);
}
SQLException startException = null;
boolean webRunning = false;
if (url != null) {
Connection conn = JdbcUtils.getConnection(driver, url, user, password);
Server.startWebServer(conn);
}
if (webStart) {
try {
web = Server.createWebServer(args);
web.setShutdownHandler(this);
web.start();
if (printStatus) {
out.println(web.getStatus());
}
webRunning = true;
} catch (SQLException e) {
printProblem(e, web);
startException = e;
}
}
//## AWT ##
if (toolStart && webRunning && !GraphicsEnvironment.isHeadless()) {
loadFont();
try {
if (!createTrayIcon()) {
showWindow();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//*/
// start browser in any case (even if the server is already running)
// because some people don't look at the output,
// but are wondering why nothing happens
if (browserStart && web != null) {
openBrowser(web.getURL());
}
if (tcpStart) {
try {
tcp = Server.createTcpServer(args);
tcp.start();
if (printStatus) {
out.println(tcp.getStatus());
}
tcp.setShutdownHandler(this);
} catch (SQLException e) {
printProblem(e, tcp);
if (startException == null) {
startException = e;
}
}
}
if (pgStart) {
try {
pg = Server.createPgServer(args);
pg.start();
if (printStatus) {
out.println(pg.getStatus());
}
} catch (SQLException e) {
printProblem(e, pg);
if (startException == null) {
startException = e;
}
}
}
if (startException != null) {
shutdown();
throw startException;
}
}
private void printProblem(Exception e, Server server) {
if (server == null) {
e.printStackTrace();
} else {
out.println(server.getStatus());
out.println("Root cause: " + e.getMessage());
}
}
private static Image loadImage(String name) {
try {
byte[] imageData = Utils.getResource(name);
if (imageData == null) {
return null;
}
return Toolkit.getDefaultToolkit().createImage(imageData);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* INTERNAL.
* Stop all servers that were started using the console.
*/
@Override
public void shutdown() {
if (web != null && web.isRunning(false)) {
web.stop();
web = null;
}
if (tcp != null && tcp.isRunning(false)) {
tcp.stop();
tcp = null;
}
if (pg != null && pg.isRunning(false)) {
pg.stop();
pg = null;
}
//## AWT ##
if (frame != null) {
frame.dispose();
frame = null;
}
if (trayIconUsed) {
try {
// tray.remove(trayIcon);
Utils.callMethod(tray, "remove", trayIcon);
} catch (Exception e) {
// ignore
} finally {
trayIcon = null;
tray = null;
trayIconUsed = false;
}
System.gc();
// Mac OS X: Console tool process did not stop on exit
String os = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (os.contains("mac")) {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().startsWith("AWT-")) {
t.interrupt();
}
}
}
Thread.currentThread().interrupt();
// throw new ThreadDeath();
}
//*/
}
//## AWT ##
private void loadFont() {
if (isWindows) {
font = new Font("Dialog", Font.PLAIN, 11);
} else {
font = new Font("Dialog", Font.PLAIN, 12);
}
}
private boolean createTrayIcon() {
try {
// SystemTray.isSupported();
boolean supported = (Boolean) Utils.callStaticMethod(
"java.awt.SystemTray.isSupported");
if (!supported) {
return false;
}
PopupMenu menuConsole = new PopupMenu();
MenuItem itemConsole = new MenuItem("H2 Console");
itemConsole.setActionCommand("console");
itemConsole.addActionListener(this);
itemConsole.setFont(font);
menuConsole.add(itemConsole);
MenuItem itemStatus = new MenuItem("Status");
itemStatus.setActionCommand("status");
itemStatus.addActionListener(this);
itemStatus.setFont(font);
menuConsole.add(itemStatus);
MenuItem itemExit = new MenuItem("Exit");
itemExit.setFont(font);
itemExit.setActionCommand("exit");
itemExit.addActionListener(this);
menuConsole.add(itemExit);
// tray = SystemTray.getSystemTray();
tray = Utils.callStaticMethod("java.awt.SystemTray.getSystemTray");
// Dimension d = tray.getTrayIconSize();
Dimension d = (Dimension) Utils.callMethod(tray, "getTrayIconSize");
String iconFile;
if (d.width >= 24 && d.height >= 24) {
iconFile = "/org/h2/res/h2-24.png";
} else if (d.width >= 22 && d.height >= 22) {
// for Mac OS X 10.8.1 with retina display:
// the reported resolution is 22 x 22, but the image
// is scaled and the real resolution is 44 x 44
iconFile = "/org/h2/res/h2-64-t.png";
// iconFile = "/org/h2/res/h2-22-t.png";
} else {
iconFile = "/org/h2/res/h2.png";
}
Image icon = loadImage(iconFile);
// trayIcon = new TrayIcon(image, "H2 Database Engine",
// menuConsole);
trayIcon = Utils.newInstance("java.awt.TrayIcon",
icon, "H2 Database Engine", menuConsole);
// trayIcon.addMouseListener(this);
Utils.callMethod(trayIcon, "addMouseListener", this);
// tray.add(trayIcon);
Utils.callMethod(tray, "add", trayIcon);
this.trayIconUsed = true;
return true;
} catch (Exception e) {
return false;
}
}
private void showWindow() {
if (frame != null) {
return;
}
frame = new Frame("H2 Console");
frame.addWindowListener(this);
Image image = loadImage("/org/h2/res/h2.png");
if (image != null) {
frame.setIconImage(image);
}
frame.setResizable(false);
frame.setBackground(SystemColor.control);
GridBagLayout layout = new GridBagLayout();
frame.setLayout(layout);
// the main panel keeps everything together
Panel mainPanel = new Panel(layout);
GridBagConstraints constraintsPanel = new GridBagConstraints();
constraintsPanel.gridx = 0;
constraintsPanel.weightx = 1.0D;
constraintsPanel.weighty = 1.0D;
constraintsPanel.fill = GridBagConstraints.BOTH;
constraintsPanel.insets = new Insets(0, 10, 0, 10);
constraintsPanel.gridy = 0;
GridBagConstraints constraintsButton = new GridBagConstraints();
constraintsButton.gridx = 0;
constraintsButton.gridwidth = 2;
constraintsButton.insets = new Insets(10, 0, 0, 0);
constraintsButton.gridy = 1;
constraintsButton.anchor = GridBagConstraints.EAST;
GridBagConstraints constraintsTextField = new GridBagConstraints();
constraintsTextField.fill = GridBagConstraints.HORIZONTAL;
constraintsTextField.gridy = 0;
constraintsTextField.weightx = 1.0;
constraintsTextField.insets = new Insets(0, 5, 0, 0);
constraintsTextField.gridx = 1;
GridBagConstraints constraintsLabel = new GridBagConstraints();
constraintsLabel.gridx = 0;
constraintsLabel.gridy = 0;
Label label = new Label("H2 Console URL:", Label.LEFT);
label.setFont(font);
mainPanel.add(label, constraintsLabel);
urlText = new TextField();
urlText.setEditable(false);
urlText.setFont(font);
urlText.setText(web.getURL());
if (isWindows) {
urlText.setFocusable(false);
}
mainPanel.add(urlText, constraintsTextField);
startBrowser = new Button("Start Browser");
startBrowser.setFocusable(false);
startBrowser.setActionCommand("console");
startBrowser.addActionListener(this);
startBrowser.setFont(font);
mainPanel.add(startBrowser, constraintsButton);
frame.add(mainPanel, constraintsPanel);
int width = 300, height = 120;
frame.setSize(width, height);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((screenSize.width - width) / 2,
(screenSize.height - height) / 2);
try {
frame.setVisible(true);
} catch (Throwable t) {
// ignore
// some systems don't support this method, for example IKVM
// however it still works
}
try {
// ensure this window is in front of the browser
frame.setAlwaysOnTop(true);
frame.setAlwaysOnTop(false);
} catch (Throwable t) {
// ignore
}
}
private void startBrowser() {
if (web != null) {
String url = web.getURL();
if (urlText != null) {
urlText.setText(url);
}
long now = System.nanoTime();
if (lastOpenNs == 0 || lastOpenNs + TimeUnit.MILLISECONDS.toNanos(100) < now) {
lastOpenNs = now;
openBrowser(url);
}
}
}
//*/
private void openBrowser(String url) {
try {
Server.openBrowser(url);
} catch (Exception e) {
out.println(e.getMessage());
}
}
/**
* INTERNAL
*/
//## AWT ##
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("exit".equals(command)) {
shutdown();
} else if ("console".equals(command)) {
startBrowser();
} else if ("status".equals(command)) {
showWindow();
} else if (startBrowser == e.getSource()) {
// for some reason, IKVM ignores setActionCommand
startBrowser();
}
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
startBrowser();
}
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void mouseEntered(MouseEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void mouseExited(MouseEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void mousePressed(MouseEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void mouseReleased(MouseEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void windowClosing(WindowEvent e) {
if (trayIconUsed) {
frame.dispose();
frame = null;
} else {
shutdown();
}
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void windowActivated(WindowEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void windowClosed(WindowEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void windowDeactivated(WindowEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void windowDeiconified(WindowEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void windowIconified(WindowEvent e) {
// nothing to do
}
//*/
/**
* INTERNAL
*/
//## AWT ##
@Override
public void windowOpened(WindowEvent e) {
// nothing to do
}
//*/
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/ConvertTraceFile.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
import org.h2.util.IOUtils;
import org.h2.util.StringUtils;
import org.h2.util.Tool;
/**
* Converts a .trace.db file to a SQL script and Java source code.
* <br />
* SQL statement statistics are listed as well.
* @h2.resource
*/
public class ConvertTraceFile extends Tool {
private final HashMap<String, Stat> stats = new HashMap<>();
private long timeTotal;
/**
* This class holds statistics about a SQL statement.
*/
static class Stat implements Comparable<Stat> {
String sql;
int executeCount;
long time;
long resultCount;
@Override
public int compareTo(Stat other) {
if (other == this) {
return 0;
}
int c = Long.compare(other.time, time);
if (c == 0) {
c = Integer.compare(other.executeCount, executeCount);
if (c == 0) {
c = sql.compareTo(other.sql);
}
}
return c;
}
}
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-traceFile <file>]</td>
* <td>The trace file name (default: test.trace.db)</td></tr>
* <tr><td>[-script <file>]</td>
* <td>The script file name (default: test.sql)</td></tr>
* <tr><td>[-javaClass <file>]</td>
* <td>The Java directory and class file name (default: Test)</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new ConvertTraceFile().runTool(args);
}
@Override
public void runTool(String... args) throws SQLException {
String traceFile = "test.trace.db";
String javaClass = "Test";
String script = "test.sql";
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-traceFile")) {
traceFile = args[++i];
} else if (arg.equals("-javaClass")) {
javaClass = args[++i];
} else if (arg.equals("-script")) {
script = args[++i];
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
try {
convertFile(traceFile, javaClass, script);
} catch (IOException e) {
throw DbException.convertIOException(e, traceFile);
}
}
/**
* Converts a trace file to a Java class file and a script file.
*/
private void convertFile(String traceFileName, String javaClassName,
String script) throws IOException {
LineNumberReader reader = new LineNumberReader(
IOUtils.getBufferedReader(
FileUtils.newInputStream(traceFileName)));
PrintWriter javaWriter = new PrintWriter(
IOUtils.getBufferedWriter(
FileUtils.newOutputStream(javaClassName + ".java", false)));
PrintWriter scriptWriter = new PrintWriter(
IOUtils.getBufferedWriter(
FileUtils.newOutputStream(script, false)));
javaWriter.println("import java.io.*;");
javaWriter.println("import java.sql.*;");
javaWriter.println("import java.math.*;");
javaWriter.println("import java.util.Calendar;");
String cn = javaClassName.replace('\\', '/');
int idx = cn.lastIndexOf('/');
if (idx > 0) {
cn = cn.substring(idx + 1);
}
javaWriter.println("public class " + cn + " {");
javaWriter.println(" public static void main(String... args) " +
"throws Exception {");
javaWriter.println(" Class.forName(\"org.h2.Driver\");");
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
if (line.startsWith("/**/")) {
line = " " + line.substring(4);
javaWriter.println(line);
} else if (line.startsWith("/*SQL")) {
int end = line.indexOf("*/");
String sql = line.substring(end + "*/".length());
sql = StringUtils.javaDecode(sql);
line = line.substring("/*SQL".length(), end);
if (line.length() > 0) {
String statement = sql;
int count = 0;
long time = 0;
line = line.trim();
if (line.length() > 0) {
StringTokenizer tk = new StringTokenizer(line, " :");
while (tk.hasMoreElements()) {
String token = tk.nextToken();
if ("l".equals(token)) {
int len = Integer.parseInt(tk.nextToken());
statement = sql.substring(0, len) + ";";
} else if ("#".equals(token)) {
count = Integer.parseInt(tk.nextToken());
} else if ("t".equals(token)) {
time = Long.parseLong(tk.nextToken());
}
}
}
addToStats(statement, count, time);
}
scriptWriter.println(sql);
}
}
javaWriter.println(" }");
javaWriter.println('}');
reader.close();
javaWriter.close();
if (stats.size() > 0) {
scriptWriter.println("-----------------------------------------");
scriptWriter.println("-- SQL Statement Statistics");
scriptWriter.println("-- time: total time in milliseconds (accumulated)");
scriptWriter.println("-- count: how many times the statement ran");
scriptWriter.println("-- result: total update count or row count");
scriptWriter.println("-----------------------------------------");
scriptWriter.println("-- self accu time count result sql");
int accumTime = 0;
ArrayList<Stat> list = new ArrayList<>(stats.values());
Collections.sort(list);
if (timeTotal == 0) {
timeTotal = 1;
}
for (Stat stat : list) {
accumTime += stat.time;
StringBuilder buff = new StringBuilder(100);
buff.append("-- ").
append(padNumberLeft(100 * stat.time / timeTotal, 3)).
append("% ").
append(padNumberLeft(100 * accumTime / timeTotal, 3)).
append('%').
append(padNumberLeft(stat.time, 8)).
append(padNumberLeft(stat.executeCount, 8)).
append(padNumberLeft(stat.resultCount, 8)).
append(' ').
append(removeNewlines(stat.sql));
scriptWriter.println(buff.toString());
}
}
scriptWriter.close();
}
private static String removeNewlines(String s) {
return s == null ? s : s.replace('\r', ' ').replace('\n', ' ');
}
private static String padNumberLeft(long number, int digits) {
return StringUtils.pad(String.valueOf(number), digits, " ", false);
}
private void addToStats(String sql, int resultCount, long time) {
Stat stat = stats.get(sql);
if (stat == null) {
stat = new Stat();
stat.sql = sql;
stats.put(sql, stat);
}
stat.executeCount++;
stat.resultCount += resultCount;
stat.time += time;
timeTotal += time;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/CreateCluster.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.h2.util.Tool;
/**
* Creates a cluster from a stand-alone database.
* <br />
* Copies a database to another location if required.
* @h2.resource
*/
public class CreateCluster extends Tool {
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-urlSource "<url>"]</td>
* <td>The database URL of the source database (jdbc:h2:...)</td></tr>
* <tr><td>[-urlTarget "<url>"]</td>
* <td>The database URL of the target database (jdbc:h2:...)</td></tr>
* <tr><td>[-user <user>]</td>
* <td>The user name (default: sa)</td></tr>
* <tr><td>[-password <pwd>]</td>
* <td>The password</td></tr>
* <tr><td>[-serverList <list>]</td>
* <td>The comma separated list of host names or IP addresses</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new CreateCluster().runTool(args);
}
@Override
public void runTool(String... args) throws SQLException {
String urlSource = null;
String urlTarget = null;
String user = "";
String password = "";
String serverList = null;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-urlSource")) {
urlSource = args[++i];
} else if (arg.equals("-urlTarget")) {
urlTarget = args[++i];
} else if (arg.equals("-user")) {
user = args[++i];
} else if (arg.equals("-password")) {
password = args[++i];
} else if (arg.equals("-serverList")) {
serverList = args[++i];
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
if (urlSource == null || urlTarget == null || serverList == null) {
showUsage();
throw new SQLException("Source URL, target URL, or server list not set");
}
process(urlSource, urlTarget, user, password, serverList);
}
/**
* Creates a cluster.
*
* @param urlSource the database URL of the original database
* @param urlTarget the database URL of the copy
* @param user the user name
* @param password the password
* @param serverList the server list
*/
public void execute(String urlSource, String urlTarget,
String user, String password, String serverList) throws SQLException {
process(urlSource, urlTarget, user, password, serverList);
}
private static void process(String urlSource, String urlTarget,
String user, String password, String serverList) throws SQLException {
org.h2.Driver.load();
// use cluster='' so connecting is possible
// even if the cluster is enabled
try (Connection connSource = DriverManager.getConnection(urlSource + ";CLUSTER=''", user, password);
Statement statSource = connSource.createStatement()) {
// enable the exclusive mode and close other connections,
// so that data can't change while restoring the second database
statSource.execute("SET EXCLUSIVE 2");
try {
performTransfer(statSource, urlTarget, user, password, serverList);
} finally {
// switch back to the regular mode
statSource.execute("SET EXCLUSIVE FALSE");
}
}
}
private static void performTransfer(Statement statSource, String urlTarget, String user, String password,
String serverList) throws SQLException {
// Delete the target database first.
try (Connection connTarget = DriverManager.getConnection(urlTarget + ";CLUSTER=''", user, password);
Statement statTarget = connTarget.createStatement()) {
statTarget.execute("DROP ALL OBJECTS DELETE FILES");
}
try (PipedReader pipeReader = new PipedReader()) {
Future<?> threadFuture = startWriter(pipeReader, statSource);
// Read data from pipe reader, restore on target.
try (Connection connTarget = DriverManager.getConnection(urlTarget, user, password);
Statement statTarget = connTarget.createStatement()) {
RunScript.execute(connTarget, pipeReader);
// Check if the writer encountered any exception
try {
threadFuture.get();
} catch (ExecutionException ex) {
throw new SQLException(ex.getCause());
} catch (InterruptedException ex) {
throw new SQLException(ex);
}
// set the cluster to the serverList on both databases
statSource.executeUpdate("SET CLUSTER '" + serverList + "'");
statTarget.executeUpdate("SET CLUSTER '" + serverList + "'");
}
} catch (IOException ex) {
throw new SQLException(ex);
}
}
private static Future<?> startWriter(final PipedReader pipeReader,
final Statement statSource) {
final ExecutorService thread = Executors.newFixedThreadPool(1);
// Since exceptions cannot be thrown across thread boundaries, return
// the task's future so we can check manually
Future<?> threadFuture = thread.submit(new Runnable() {
@Override
public void run() {
// If the creation of the piped writer fails, the reader will
// throw an IOException as soon as read() is called: IOException
// - if the pipe is broken, unconnected, closed, or an I/O error
// occurs. The reader's IOException will then trigger the
// finally{} that releases exclusive mode on the source DB.
try (final PipedWriter pipeWriter = new PipedWriter(pipeReader);
final ResultSet rs = statSource.executeQuery("SCRIPT")) {
while (rs.next()) {
pipeWriter.write(rs.getString(1) + "\n");
}
} catch (SQLException | IOException ex) {
throw new IllegalStateException("Producing script from the source DB is failing.", ex);
}
}
});
thread.shutdown();
return threadFuture;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Csv.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
import org.h2.util.IOUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.New;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* A facility to read from and write to CSV (comma separated values) files. When
* reading, the BOM (the byte-order-mark) character 0xfeff at the beginning of
* the file is ignored.
*
* @author Thomas Mueller, Sylvain Cuaz
*/
public class Csv implements SimpleRowSource {
private String[] columnNames;
private String characterSet = SysProperties.FILE_ENCODING;
private char escapeCharacter = '\"';
private char fieldDelimiter = '\"';
private char fieldSeparatorRead = ',';
private String fieldSeparatorWrite = ",";
private boolean caseSensitiveColumnNames;
private boolean preserveWhitespace;
private boolean writeColumnHeader = true;
private char lineComment;
private String lineSeparator = SysProperties.LINE_SEPARATOR;
private String nullString = "";
private String fileName;
private Reader input;
private char[] inputBuffer;
private int inputBufferPos;
private int inputBufferStart = -1;
private int inputBufferEnd;
private Writer output;
private boolean endOfLine, endOfFile;
private int writeResultSet(ResultSet rs) throws SQLException {
try {
int rows = 0;
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
String[] row = new String[columnCount];
int[] sqlTypes = new int[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = meta.getColumnLabel(i + 1);
sqlTypes[i] = meta.getColumnType(i + 1);
}
if (writeColumnHeader) {
writeRow(row);
}
while (rs.next()) {
for (int i = 0; i < columnCount; i++) {
Object o;
switch (sqlTypes[i]) {
case Types.DATE:
o = rs.getDate(i + 1);
break;
case Types.TIME:
o = rs.getTime(i + 1);
break;
case Types.TIMESTAMP:
o = rs.getTimestamp(i + 1);
break;
default:
o = rs.getString(i + 1);
}
row[i] = o == null ? null : o.toString();
}
writeRow(row);
rows++;
}
output.close();
return rows;
} catch (IOException e) {
throw DbException.convertIOException(e, null);
} finally {
close();
JdbcUtils.closeSilently(rs);
}
}
/**
* Writes the result set to a file in the CSV format.
*
* @param writer the writer
* @param rs the result set
* @return the number of rows written
*/
public int write(Writer writer, ResultSet rs) throws SQLException {
this.output = writer;
return writeResultSet(rs);
}
/**
* Writes the result set to a file in the CSV format. The result set is read
* using the following loop:
*
* <pre>
* while (rs.next()) {
* writeRow(row);
* }
* </pre>
*
* @param outputFileName the name of the csv file
* @param rs the result set - the result set must be positioned before the
* first row.
* @param charset the charset or null to use the system default charset
* (see system property file.encoding)
* @return the number of rows written
*/
public int write(String outputFileName, ResultSet rs, String charset)
throws SQLException {
init(outputFileName, charset);
try {
initWrite();
return writeResultSet(rs);
} catch (IOException e) {
throw convertException("IOException writing " + outputFileName, e);
}
}
/**
* Writes the result set of a query to a file in the CSV format.
*
* @param conn the connection
* @param outputFileName the file name
* @param sql the query
* @param charset the charset or null to use the system default charset
* (see system property file.encoding)
* @return the number of rows written
*/
public int write(Connection conn, String outputFileName, String sql,
String charset) throws SQLException {
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(sql);
int rows = write(outputFileName, rs, charset);
stat.close();
return rows;
}
/**
* Reads from the CSV file and returns a result set. The rows in the result
* set are created on demand, that means the file is kept open until all
* rows are read or the result set is closed.
* <br />
* If the columns are read from the CSV file, then the following rules are
* used: columns names that start with a letter or '_', and only
* contain letters, '_', and digits, are considered case insensitive
* and are converted to uppercase. Other column names are considered
* case sensitive (that means they need to be quoted when accessed).
*
* @param inputFileName the file name
* @param colNames or null if the column names should be read from the CSV
* file
* @param charset the charset or null to use the system default charset
* (see system property file.encoding)
* @return the result set
*/
public ResultSet read(String inputFileName, String[] colNames,
String charset) throws SQLException {
init(inputFileName, charset);
try {
return readResultSet(colNames);
} catch (IOException e) {
throw convertException("IOException reading " + inputFileName, e);
}
}
/**
* Reads CSV data from a reader and returns a result set. The rows in the
* result set are created on demand, that means the reader is kept open
* until all rows are read or the result set is closed.
*
* @param reader the reader
* @param colNames or null if the column names should be read from the CSV
* file
* @return the result set
*/
public ResultSet read(Reader reader, String[] colNames) throws IOException {
init(null, null);
this.input = reader;
return readResultSet(colNames);
}
private ResultSet readResultSet(String[] colNames) throws IOException {
this.columnNames = colNames;
initRead();
SimpleResultSet result = new SimpleResultSet(this);
makeColumnNamesUnique();
for (String columnName : columnNames) {
result.addColumn(columnName, Types.VARCHAR, Integer.MAX_VALUE, 0);
}
return result;
}
private void makeColumnNamesUnique() {
for (int i = 0; i < columnNames.length; i++) {
StringBuilder buff = new StringBuilder();
String n = columnNames[i];
if (n == null || n.length() == 0) {
buff.append('C').append(i + 1);
} else {
buff.append(n);
}
for (int j = 0; j < i; j++) {
String y = columnNames[j];
if (buff.toString().equals(y)) {
buff.append('1');
j = -1;
}
}
columnNames[i] = buff.toString();
}
}
private void init(String newFileName, String charset) {
this.fileName = newFileName;
if (charset != null) {
this.characterSet = charset;
}
}
private void initWrite() throws IOException {
if (output == null) {
try {
OutputStream out = FileUtils.newOutputStream(fileName, false);
out = new BufferedOutputStream(out, Constants.IO_BUFFER_SIZE);
output = new BufferedWriter(new OutputStreamWriter(out, characterSet));
} catch (Exception e) {
close();
throw DbException.convertToIOException(e);
}
}
}
private void writeRow(String[] values) throws IOException {
for (int i = 0; i < values.length; i++) {
if (i > 0) {
if (fieldSeparatorWrite != null) {
output.write(fieldSeparatorWrite);
}
}
String s = values[i];
if (s != null) {
if (escapeCharacter != 0) {
if (fieldDelimiter != 0) {
output.write(fieldDelimiter);
}
output.write(escape(s));
if (fieldDelimiter != 0) {
output.write(fieldDelimiter);
}
} else {
output.write(s);
}
} else if (nullString != null && nullString.length() > 0) {
output.write(nullString);
}
}
output.write(lineSeparator);
}
private String escape(String data) {
if (data.indexOf(fieldDelimiter) < 0) {
if (escapeCharacter == fieldDelimiter || data.indexOf(escapeCharacter) < 0) {
return data;
}
}
int length = data.length();
StringBuilder buff = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char ch = data.charAt(i);
if (ch == fieldDelimiter || ch == escapeCharacter) {
buff.append(escapeCharacter);
}
buff.append(ch);
}
return buff.toString();
}
private void initRead() throws IOException {
if (input == null) {
try {
InputStream in = FileUtils.newInputStream(fileName);
in = new BufferedInputStream(in, Constants.IO_BUFFER_SIZE);
input = new InputStreamReader(in, characterSet);
} catch (IOException e) {
close();
throw e;
}
}
if (!input.markSupported()) {
input = new BufferedReader(input);
}
input.mark(1);
int bom = input.read();
if (bom != 0xfeff) {
// Microsoft Excel compatibility
// ignore pseudo-BOM
input.reset();
}
inputBuffer = new char[Constants.IO_BUFFER_SIZE * 2];
if (columnNames == null) {
readHeader();
}
}
private void readHeader() throws IOException {
ArrayList<String> list = New.arrayList();
while (true) {
String v = readValue();
if (v == null) {
if (endOfLine) {
if (endOfFile || !list.isEmpty()) {
break;
}
} else {
v = "COLUMN" + list.size();
list.add(v);
}
} else {
if (v.length() == 0) {
v = "COLUMN" + list.size();
} else if (!caseSensitiveColumnNames && isSimpleColumnName(v)) {
v = StringUtils.toUpperEnglish(v);
}
list.add(v);
if (endOfLine) {
break;
}
}
}
columnNames = list.toArray(new String[0]);
}
private static boolean isSimpleColumnName(String columnName) {
for (int i = 0, length = columnName.length(); i < length; i++) {
char ch = columnName.charAt(i);
if (i == 0) {
if (ch != '_' && !Character.isLetter(ch)) {
return false;
}
} else {
if (ch != '_' && !Character.isLetterOrDigit(ch)) {
return false;
}
}
}
return columnName.length() != 0;
}
private void pushBack() {
inputBufferPos--;
}
private int readChar() throws IOException {
if (inputBufferPos >= inputBufferEnd) {
return readBuffer();
}
return inputBuffer[inputBufferPos++];
}
private int readBuffer() throws IOException {
if (endOfFile) {
return -1;
}
int keep;
if (inputBufferStart >= 0) {
keep = inputBufferPos - inputBufferStart;
if (keep > 0) {
char[] src = inputBuffer;
if (keep + Constants.IO_BUFFER_SIZE > src.length) {
inputBuffer = new char[src.length * 2];
}
System.arraycopy(src, inputBufferStart, inputBuffer, 0, keep);
}
inputBufferStart = 0;
} else {
keep = 0;
}
inputBufferPos = keep;
int len = input.read(inputBuffer, keep, Constants.IO_BUFFER_SIZE);
if (len == -1) {
// ensure bufferPos > bufferEnd
// even after pushBack
inputBufferEnd = -1024;
endOfFile = true;
// ensure the right number of characters are read
// in case the input buffer is still used
inputBufferPos++;
return -1;
}
inputBufferEnd = keep + len;
return inputBuffer[inputBufferPos++];
}
private String readValue() throws IOException {
endOfLine = false;
inputBufferStart = inputBufferPos;
while (true) {
int ch = readChar();
if (ch == fieldDelimiter) {
// delimited value
boolean containsEscape = false;
inputBufferStart = inputBufferPos;
int sep;
while (true) {
ch = readChar();
if (ch == fieldDelimiter) {
ch = readChar();
if (ch != fieldDelimiter) {
sep = 2;
break;
}
containsEscape = true;
} else if (ch == escapeCharacter) {
ch = readChar();
if (ch < 0) {
sep = 1;
break;
}
containsEscape = true;
} else if (ch < 0) {
sep = 1;
break;
}
}
String s = new String(inputBuffer,
inputBufferStart, inputBufferPos - inputBufferStart - sep);
if (containsEscape) {
s = unEscape(s);
}
inputBufferStart = -1;
while (true) {
if (ch == fieldSeparatorRead) {
break;
} else if (ch == '\n' || ch < 0 || ch == '\r') {
endOfLine = true;
break;
} else if (ch == ' ' || ch == '\t') {
// ignore
} else {
pushBack();
break;
}
ch = readChar();
}
return s;
} else if (ch == '\n' || ch < 0 || ch == '\r') {
endOfLine = true;
return null;
} else if (ch == fieldSeparatorRead) {
// null
return null;
} else if (ch <= ' ') {
// ignore spaces
} else if (lineComment != 0 && ch == lineComment) {
// comment until end of line
inputBufferStart = -1;
do {
ch = readChar();
} while (ch != '\n' && ch >= 0 && ch != '\r');
endOfLine = true;
return null;
} else {
// un-delimited value
while (true) {
ch = readChar();
if (ch == fieldSeparatorRead) {
break;
} else if (ch == '\n' || ch < 0 || ch == '\r') {
endOfLine = true;
break;
}
}
String s = new String(inputBuffer,
inputBufferStart, inputBufferPos - inputBufferStart - 1);
if (!preserveWhitespace) {
s = s.trim();
}
inputBufferStart = -1;
// check un-delimited value for nullString
return readNull(s);
}
}
}
private String readNull(String s) {
return s.equals(nullString) ? null : s;
}
private String unEscape(String s) {
StringBuilder buff = new StringBuilder(s.length());
int start = 0;
char[] chars = null;
while (true) {
int idx = s.indexOf(escapeCharacter, start);
if (idx < 0) {
idx = s.indexOf(fieldDelimiter, start);
if (idx < 0) {
break;
}
}
if (chars == null) {
chars = s.toCharArray();
}
buff.append(chars, start, idx - start);
if (idx == s.length() - 1) {
start = s.length();
break;
}
buff.append(chars[idx + 1]);
start = idx + 2;
}
buff.append(s, start, s.length());
return buff.toString();
}
/**
* INTERNAL
*/
@Override
public Object[] readRow() throws SQLException {
if (input == null) {
return null;
}
String[] row = new String[columnNames.length];
try {
int i = 0;
while (true) {
String v = readValue();
if (v == null) {
if (endOfLine) {
if (i == 0) {
if (endOfFile) {
return null;
}
// empty line
continue;
}
break;
}
}
if (i < row.length) {
row[i++] = v;
}
if (endOfLine) {
break;
}
}
} catch (IOException e) {
throw convertException("IOException reading from " + fileName, e);
}
return row;
}
private static SQLException convertException(String message, Exception e) {
return DbException.get(ErrorCode.IO_EXCEPTION_1, e, message).getSQLException();
}
/**
* INTERNAL
*/
@Override
public void close() {
IOUtils.closeSilently(input);
input = null;
IOUtils.closeSilently(output);
output = null;
}
/**
* INTERNAL
*/
@Override
public void reset() throws SQLException {
throw new SQLException("Method is not supported", "CSV");
}
/**
* Override the field separator for writing. The default is ",".
*
* @param fieldSeparatorWrite the field separator
*/
public void setFieldSeparatorWrite(String fieldSeparatorWrite) {
this.fieldSeparatorWrite = fieldSeparatorWrite;
}
/**
* Get the current field separator for writing.
*
* @return the field separator
*/
public String getFieldSeparatorWrite() {
return fieldSeparatorWrite;
}
/**
* Override the case sensitive column names setting. The default is false.
* If enabled, the case of all column names is always preserved.
*
* @param caseSensitiveColumnNames whether column names are case sensitive
*/
public void setCaseSensitiveColumnNames(boolean caseSensitiveColumnNames) {
this.caseSensitiveColumnNames = caseSensitiveColumnNames;
}
/**
* Get the current case sensitive column names setting.
*
* @return whether column names are case sensitive
*/
public boolean getCaseSensitiveColumnNames() {
return caseSensitiveColumnNames;
}
/**
* Override the field separator for reading. The default is ','.
*
* @param fieldSeparatorRead the field separator
*/
public void setFieldSeparatorRead(char fieldSeparatorRead) {
this.fieldSeparatorRead = fieldSeparatorRead;
}
/**
* Get the current field separator for reading.
*
* @return the field separator
*/
public char getFieldSeparatorRead() {
return fieldSeparatorRead;
}
/**
* Set the line comment character. The default is character code 0 (line
* comments are disabled).
*
* @param lineCommentCharacter the line comment character
*/
public void setLineCommentCharacter(char lineCommentCharacter) {
this.lineComment = lineCommentCharacter;
}
/**
* Get the line comment character.
*
* @return the line comment character, or 0 if disabled
*/
public char getLineCommentCharacter() {
return lineComment;
}
/**
* Set the field delimiter. The default is " (a double quote).
* The value 0 means no field delimiter is used.
*
* @param fieldDelimiter the field delimiter
*/
public void setFieldDelimiter(char fieldDelimiter) {
this.fieldDelimiter = fieldDelimiter;
}
/**
* Get the current field delimiter.
*
* @return the field delimiter
*/
public char getFieldDelimiter() {
return fieldDelimiter;
}
/**
* Set the escape character. The escape character is used to escape the
* field delimiter. This is needed if the data contains the field delimiter.
* The default escape character is " (a double quote), which is the same as
* the field delimiter. If the field delimiter and the escape character are
* both " (double quote), and the data contains a double quote, then an
* additional double quote is added. Example:
* <pre>
* Data: He said "Hello".
* Escape character: "
* Field delimiter: "
* CSV file: "He said ""Hello""."
* </pre>
* If the field delimiter is a double quote and the escape character is a
* backslash, then escaping is done similar to Java (however, only the field
* delimiter is escaped). Example:
* <pre>
* Data: He said "Hello".
* Escape character: \
* Field delimiter: "
* CSV file: "He said \"Hello\"."
* </pre>
* The value 0 means no escape character is used.
*
* @param escapeCharacter the escape character
*/
public void setEscapeCharacter(char escapeCharacter) {
this.escapeCharacter = escapeCharacter;
}
/**
* Get the current escape character.
*
* @return the escape character
*/
public char getEscapeCharacter() {
return escapeCharacter;
}
/**
* Set the line separator used for writing. This is usually a line feed (\n
* or \r\n depending on the system settings). The line separator is written
* after each row (including the last row), so this option can include an
* end-of-row marker if needed.
*
* @param lineSeparator the line separator
*/
public void setLineSeparator(String lineSeparator) {
this.lineSeparator = lineSeparator;
}
/**
* Get the line separator used for writing.
*
* @return the line separator
*/
public String getLineSeparator() {
return lineSeparator;
}
/**
* Set the value that represents NULL. It is only used for non-delimited
* values.
*
* @param nullString the null
*/
public void setNullString(String nullString) {
this.nullString = nullString;
}
/**
* Get the current null string.
*
* @return the null string.
*/
public String getNullString() {
return nullString;
}
/**
* Enable or disable preserving whitespace in unquoted text.
*
* @param value the new value for the setting
*/
public void setPreserveWhitespace(boolean value) {
this.preserveWhitespace = value;
}
/**
* Whether whitespace in unquoted text is preserved.
*
* @return the current value for the setting
*/
public boolean getPreserveWhitespace() {
return preserveWhitespace;
}
/**
* Enable or disable writing the column header.
*
* @param value the new value for the setting
*/
public void setWriteColumnHeader(boolean value) {
this.writeColumnHeader = value;
}
/**
* Whether the column header is written.
*
* @return the current value for the setting
*/
public boolean getWriteColumnHeader() {
return writeColumnHeader;
}
/**
* INTERNAL.
* Parse and set the CSV options.
*
* @param options the the options
* @return the character set
*/
public String setOptions(String options) {
String charset = null;
String[] keyValuePairs = StringUtils.arraySplit(options, ' ', false);
for (String pair : keyValuePairs) {
if (pair.length() == 0) {
continue;
}
int index = pair.indexOf('=');
String key = StringUtils.trim(pair.substring(0, index), true, true, " ");
String value = pair.substring(index + 1);
char ch = value.length() == 0 ? 0 : value.charAt(0);
if (isParam(key, "escape", "esc", "escapeCharacter")) {
setEscapeCharacter(ch);
} else if (isParam(key, "fieldDelimiter", "fieldDelim")) {
setFieldDelimiter(ch);
} else if (isParam(key, "fieldSeparator", "fieldSep")) {
setFieldSeparatorRead(ch);
setFieldSeparatorWrite(value);
} else if (isParam(key, "lineComment", "lineCommentCharacter")) {
setLineCommentCharacter(ch);
} else if (isParam(key, "lineSeparator", "lineSep")) {
setLineSeparator(value);
} else if (isParam(key, "null", "nullString")) {
setNullString(value);
} else if (isParam(key, "charset", "characterSet")) {
charset = value;
} else if (isParam(key, "preserveWhitespace")) {
setPreserveWhitespace(Utils.parseBoolean(value, false, false));
} else if (isParam(key, "writeColumnHeader")) {
setWriteColumnHeader(Utils.parseBoolean(value, true, false));
} else if (isParam(key, "caseSensitiveColumnNames")) {
setCaseSensitiveColumnNames(Utils.parseBoolean(value, false, false));
} else {
throw DbException.getUnsupportedException(key);
}
}
return charset;
}
private static boolean isParam(String key, String... values) {
for (String v : values) {
if (key.equalsIgnoreCase(v)) {
return true;
}
}
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/DeleteDbFiles.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.sql.SQLException;
import java.util.ArrayList;
import org.h2.engine.Constants;
import org.h2.store.FileLister;
import org.h2.store.fs.FileUtils;
import org.h2.util.Tool;
/**
* Deletes all files belonging to a database.
* <br />
* The database must be closed before calling this tool.
* @h2.resource
*/
public class DeleteDbFiles extends Tool {
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-dir <dir>]</td>
* <td>The directory (default: .)</td></tr>
* <tr><td>[-db <database>]</td>
* <td>The database name</td></tr>
* <tr><td>[-quiet]</td>
* <td>Do not print progress information</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new DeleteDbFiles().runTool(args);
}
@Override
public void runTool(String... args) throws SQLException {
String dir = ".";
String db = null;
boolean quiet = false;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-dir")) {
dir = args[++i];
} else if (arg.equals("-db")) {
db = args[++i];
} else if (arg.equals("-quiet")) {
quiet = true;
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
process(dir, db, quiet);
}
/**
* Deletes the database files.
*
* @param dir the directory
* @param db the database name (null for all databases)
* @param quiet don't print progress information
*/
public static void execute(String dir, String db, boolean quiet) {
new DeleteDbFiles().process(dir, db, quiet);
}
/**
* Deletes the database files.
*
* @param dir the directory
* @param db the database name (null for all databases)
* @param quiet don't print progress information
*/
private void process(String dir, String db, boolean quiet) {
ArrayList<String> files = FileLister.getDatabaseFiles(dir, db, true);
if (files.isEmpty() && !quiet) {
printNoDatabaseFilesFound(dir, db);
}
for (String fileName : files) {
process(fileName, quiet);
if (!quiet) {
out.println("Processed: " + fileName);
}
}
}
private static void process(String fileName, boolean quiet) {
if (FileUtils.isDirectory(fileName)) {
// only delete empty directories
FileUtils.tryDelete(fileName);
} else if (quiet || fileName.endsWith(Constants.SUFFIX_TEMP_FILE) ||
fileName.endsWith(Constants.SUFFIX_TRACE_FILE)) {
FileUtils.tryDelete(fileName);
} else {
FileUtils.delete(fileName);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/MultiDimension.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.h2.util.New;
import org.h2.util.StringUtils;
/**
* A tool to help an application execute multi-dimensional range queries.
* The algorithm used is database independent, the only requirement
* is that the engine supports a range index (for example b-tree).
*/
public class MultiDimension implements Comparator<long[]> {
private static final MultiDimension INSTANCE = new MultiDimension();
protected MultiDimension() {
// don't allow construction by normal code
// but allow tests
}
/**
* Get the singleton.
*
* @return the singleton
*/
public static MultiDimension getInstance() {
return INSTANCE;
}
/**
* Normalize a value so that it is between the minimum and maximum for the
* given number of dimensions.
*
* @param dimensions the number of dimensions
* @param value the value (must be in the range min..max)
* @param min the minimum value
* @param max the maximum value (must be larger than min)
* @return the normalized value in the range 0..getMaxValue(dimensions)
*/
public int normalize(int dimensions, double value, double min, double max) {
if (value < min || value > max) {
throw new IllegalArgumentException(min + "<" + value + "<" + max);
}
double x = (value - min) / (max - min);
return (int) (x * getMaxValue(dimensions));
}
/**
* Get the maximum value for the given dimension count. For two dimensions,
* each value must contain at most 32 bit, for 3: 21 bit, 4: 16 bit, 5: 12
* bit, 6: 10 bit, 7: 9 bit, 8: 8 bit.
*
* @param dimensions the number of dimensions
* @return the maximum value
*/
public int getMaxValue(int dimensions) {
if (dimensions < 2 || dimensions > 32) {
throw new IllegalArgumentException("" + dimensions);
}
int bitsPerValue = getBitsPerValue(dimensions);
return (int) ((1L << bitsPerValue) - 1);
}
private static int getBitsPerValue(int dimensions) {
return Math.min(31, 64 / dimensions);
}
/**
* Convert the multi-dimensional value into a one-dimensional (scalar)
* value. This is done by interleaving the bits of the values. Each values
* must be between 0 (including) and the maximum value for the given number
* of dimensions (getMaxValue, excluding). To normalize values to this
* range, use the normalize function.
*
* @param values the multi-dimensional value
* @return the scalar value
*/
public long interleave(int... values) {
int dimensions = values.length;
long max = getMaxValue(dimensions);
int bitsPerValue = getBitsPerValue(dimensions);
long x = 0;
for (int i = 0; i < dimensions; i++) {
long k = values[i];
if (k < 0 || k > max) {
throw new IllegalArgumentException(0 + "<" + k + "<" + max);
}
for (int b = 0; b < bitsPerValue; b++) {
x |= (k & (1L << b)) << (i + (dimensions - 1) * b);
}
}
return x;
}
/**
* Convert the two-dimensional value into a one-dimensional (scalar) value.
* This is done by interleaving the bits of the values.
* Each values must be between 0 (including) and the maximum value
* for the given number of dimensions (getMaxValue, excluding).
* To normalize values to this range, use the normalize function.
*
* @param x the value of the first dimension, normalized
* @param y the value of the second dimension, normalized
* @return the scalar value
*/
public long interleave(int x, int y) {
if (x < 0) {
throw new IllegalArgumentException(0 + "<" + x);
}
if (y < 0) {
throw new IllegalArgumentException(0 + "<" + y);
}
long z = 0;
for (int i = 0; i < 32; i++) {
z |= (x & (1L << i)) << i;
z |= (y & (1L << i)) << (i + 1);
}
return z;
}
/**
* Gets one of the original multi-dimensional values from a scalar value.
*
* @param dimensions the number of dimensions
* @param scalar the scalar value
* @param dim the dimension of the returned value (starting from 0)
* @return the value
*/
public int deinterleave(int dimensions, long scalar, int dim) {
int bitsPerValue = getBitsPerValue(dimensions);
int value = 0;
for (int i = 0; i < bitsPerValue; i++) {
value |= (scalar >> (dim + (dimensions - 1) * i)) & (1L << i);
}
return value;
}
/**
* Generates an optimized multi-dimensional range query. The query contains
* parameters. It can only be used with the H2 database.
*
* @param table the table name
* @param columns the list of columns
* @param scalarColumn the column name of the computed scalar column
* @return the query
*/
public String generatePreparedQuery(String table, String scalarColumn,
String[] columns) {
StringBuilder buff = new StringBuilder("SELECT D.* FROM ");
buff.append(StringUtils.quoteIdentifier(table)).
append(" D, TABLE(_FROM_ BIGINT=?, _TO_ BIGINT=?) WHERE ").
append(StringUtils.quoteIdentifier(scalarColumn)).
append(" BETWEEN _FROM_ AND _TO_");
for (String col : columns) {
buff.append(" AND ").append(StringUtils.quoteIdentifier(col)).
append("+1 BETWEEN ?+1 AND ?+1");
}
return buff.toString();
}
/**
* Executes a prepared query that was generated using generatePreparedQuery.
*
* @param prep the prepared statement
* @param min the lower values
* @param max the upper values
* @return the result set
*/
public ResultSet getResult(PreparedStatement prep, int[] min, int[] max)
throws SQLException {
long[][] ranges = getMortonRanges(min, max);
int len = ranges.length;
Long[] from = new Long[len];
Long[] to = new Long[len];
for (int i = 0; i < len; i++) {
from[i] = ranges[i][0];
to[i] = ranges[i][1];
}
prep.setObject(1, from);
prep.setObject(2, to);
len = min.length;
for (int i = 0, idx = 3; i < len; i++) {
prep.setInt(idx++, min[i]);
prep.setInt(idx++, max[i]);
}
return prep.executeQuery();
}
/**
* Gets a list of ranges to be searched for a multi-dimensional range query
* where min <= value <= max. In most cases, the ranges will be larger
* than required in order to combine smaller ranges into one. Usually, about
* double as many points will be included in the resulting range.
*
* @param min the minimum value
* @param max the maximum value
* @return the list of ranges (low, high pairs)
*/
private long[][] getMortonRanges(int[] min, int[] max) {
int len = min.length;
if (max.length != len) {
throw new IllegalArgumentException(len + "=" + max.length);
}
for (int i = 0; i < len; i++) {
if (min[i] > max[i]) {
int temp = min[i];
min[i] = max[i];
max[i] = temp;
}
}
int total = getSize(min, max, len);
ArrayList<long[]> list = New.arrayList();
addMortonRanges(list, min, max, len, 0);
combineEntries(list, total);
return list.toArray(new long[0][]);
}
private static int getSize(int[] min, int[] max, int len) {
int size = 1;
for (int i = 0; i < len; i++) {
int diff = max[i] - min[i];
size *= diff + 1;
}
return size;
}
/**
* Combine entries if the size of the list is too large.
*
* @param list list of pairs(low, high)
* @param total product of the gap lengths
*/
private void combineEntries(ArrayList<long[]> list, int total) {
Collections.sort(list, this);
for (int minGap = 10; minGap < total; minGap += minGap / 2) {
for (int i = 0; i < list.size() - 1; i++) {
long[] current = list.get(i);
long[] next = list.get(i + 1);
if (current[1] + minGap >= next[0]) {
current[1] = next[1];
list.remove(i + 1);
i--;
}
}
int searched = 0;
for (long[] range : list) {
searched += range[1] - range[0] + 1;
}
if (searched > 2 * total || list.size() < 100) {
break;
}
}
}
@Override
public int compare(long[] a, long[] b) {
return a[0] > b[0] ? 1 : -1;
}
private void addMortonRanges(ArrayList<long[]> list, int[] min, int[] max,
int len, int level) {
if (level > 100) {
throw new IllegalArgumentException("" + level);
}
int largest = 0, largestDiff = 0;
long size = 1;
for (int i = 0; i < len; i++) {
int diff = max[i] - min[i];
if (diff < 0) {
throw new IllegalArgumentException(""+ diff);
}
size *= diff + 1;
if (size < 0) {
throw new IllegalArgumentException("" + size);
}
if (diff > largestDiff) {
largestDiff = diff;
largest = i;
}
}
long low = interleave(min), high = interleave(max);
if (high < low) {
throw new IllegalArgumentException(high + "<" + low);
}
long range = high - low + 1;
if (range == size) {
long[] item = { low, high };
list.add(item);
} else {
int middle = findMiddle(min[largest], max[largest]);
int temp = max[largest];
max[largest] = middle;
addMortonRanges(list, min, max, len, level + 1);
max[largest] = temp;
temp = min[largest];
min[largest] = middle + 1;
addMortonRanges(list, min, max, len, level + 1);
min[largest] = temp;
}
}
private static int roundUp(int x, int blockSizePowerOf2) {
return (x + blockSizePowerOf2 - 1) & (-blockSizePowerOf2);
}
private static int findMiddle(int a, int b) {
int diff = b - a - 1;
if (diff == 0) {
return a;
}
if (diff == 1) {
return a + 1;
}
int scale = 0;
while ((1 << scale) < diff) {
scale++;
}
scale--;
int m = roundUp(a + 2, 1 << scale) - 1;
if (m <= a || m >= b) {
throw new IllegalArgumentException(a + "<" + m + "<" + b);
}
return m;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Recover.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.SequenceInputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.CRC32;
import org.h2.api.ErrorCode;
import org.h2.api.JavaObjectSerializer;
import org.h2.compress.CompressLZF;
import org.h2.engine.Constants;
import org.h2.engine.DbObject;
import org.h2.engine.MetaRecord;
import org.h2.jdbc.JdbcConnection;
import org.h2.message.DbException;
import org.h2.mvstore.MVMap;
import org.h2.mvstore.MVStore;
import org.h2.mvstore.MVStoreTool;
import org.h2.mvstore.StreamStore;
import org.h2.mvstore.db.TransactionStore;
import org.h2.mvstore.db.TransactionStore.TransactionMap;
import org.h2.mvstore.db.ValueDataType;
import org.h2.result.Row;
import org.h2.result.RowFactory;
import org.h2.result.SimpleRow;
import org.h2.security.SHA256;
import org.h2.store.Data;
import org.h2.store.DataHandler;
import org.h2.store.DataReader;
import org.h2.store.FileLister;
import org.h2.store.FileStore;
import org.h2.store.FileStoreInputStream;
import org.h2.store.LobStorageBackend;
import org.h2.store.LobStorageFrontend;
import org.h2.store.LobStorageMap;
import org.h2.store.Page;
import org.h2.store.PageFreeList;
import org.h2.store.PageLog;
import org.h2.store.PageStore;
import org.h2.store.fs.FileUtils;
import org.h2.util.BitField;
import org.h2.util.IOUtils;
import org.h2.util.IntArray;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.SmallLRUCache;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.util.TempFileDeleter;
import org.h2.util.Tool;
import org.h2.util.Utils;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueLob;
import org.h2.value.ValueLobDb;
import org.h2.value.ValueLong;
/**
* Helps recovering a corrupted database.
* @h2.resource
*/
public class Recover extends Tool implements DataHandler {
private String databaseName;
private int storageId;
private String storageName;
private int recordLength;
private int valueId;
private boolean trace;
private boolean transactionLog;
private ArrayList<MetaRecord> schema;
private HashSet<Integer> objectIdSet;
private HashMap<Integer, String> tableMap;
private HashMap<String, String> columnTypeMap;
private boolean remove;
private int pageSize;
private FileStore store;
private int[] parents;
private Stats stat;
private boolean lobMaps;
/**
* Statistic data
*/
static class Stats {
/**
* The empty space in bytes in a data leaf pages.
*/
long pageDataEmpty;
/**
* The number of bytes used for data.
*/
long pageDataRows;
/**
* The number of bytes used for the page headers.
*/
long pageDataHead;
/**
* The count per page type.
*/
final int[] pageTypeCount = new int[Page.TYPE_STREAM_DATA + 2];
/**
* The number of free pages.
*/
int free;
}
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-dir <dir>]</td>
* <td>The directory (default: .)</td></tr>
* <tr><td>[-db <database>]</td>
* <td>The database name (all databases if not set)</td></tr>
* <tr><td>[-trace]</td>
* <td>Print additional trace information</td></tr>
* <tr><td>[-transactionLog]</td>
* <td>Print the transaction log</td></tr>
* </table>
* Encrypted databases need to be decrypted first.
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new Recover().runTool(args);
}
/**
* Dumps the contents of a database file to a human readable text file. This
* text file can be used to recover most of the data. This tool does not
* open the database and can be used even if the database files are
* corrupted. A database can get corrupted if there is a bug in the database
* engine or file system software, or if an application writes into the
* database file that doesn't understand the the file format, or if there is
* a hardware problem.
*
* @param args the command line arguments
*/
@Override
public void runTool(String... args) throws SQLException {
String dir = ".";
String db = null;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if ("-dir".equals(arg)) {
dir = args[++i];
} else if ("-db".equals(arg)) {
db = args[++i];
} else if ("-removePassword".equals(arg)) {
remove = true;
} else if ("-trace".equals(arg)) {
trace = true;
} else if ("-transactionLog".equals(arg)) {
transactionLog = true;
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
process(dir, db);
}
/**
* INTERNAL
*/
public static Reader readClob(String fileName) throws IOException {
return new BufferedReader(new InputStreamReader(readBlob(fileName),
StandardCharsets.UTF_8));
}
/**
* INTERNAL
*/
public static InputStream readBlob(String fileName) throws IOException {
return new BufferedInputStream(FileUtils.newInputStream(fileName));
}
/**
* INTERNAL
*/
public static Value.ValueBlob readBlobDb(Connection conn, long lobId,
long precision) {
DataHandler h = ((JdbcConnection) conn).getSession().getDataHandler();
verifyPageStore(h);
ValueLobDb lob = ValueLobDb.create(Value.BLOB, h, LobStorageFrontend.TABLE_TEMP,
lobId, null, precision);
lob.setRecoveryReference(true);
return lob;
}
private static void verifyPageStore(DataHandler h) {
if (h.getLobStorage() instanceof LobStorageMap) {
throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1,
"Restore page store recovery SQL script " +
"can only be restored to a PageStore file");
}
}
/**
* INTERNAL
*/
public static Value.ValueClob readClobDb(Connection conn, long lobId,
long precision) {
DataHandler h = ((JdbcConnection) conn).getSession().getDataHandler();
verifyPageStore(h);
ValueLobDb lob = ValueLobDb.create(Value.CLOB, h, LobStorageFrontend.TABLE_TEMP,
lobId, null, precision);
lob.setRecoveryReference(true);
return lob;
}
/**
* INTERNAL
*/
public static InputStream readBlobMap(Connection conn, long lobId,
long precision) throws SQLException {
final PreparedStatement prep = conn.prepareStatement(
"SELECT DATA FROM INFORMATION_SCHEMA.LOB_BLOCKS " +
"WHERE LOB_ID = ? AND SEQ = ? AND ? > 0");
prep.setLong(1, lobId);
// precision is currently not really used,
// it is just to improve readability of the script
prep.setLong(3, precision);
return new SequenceInputStream(
new Enumeration<InputStream>() {
private int seq;
private byte[] data = fetch();
private byte[] fetch() {
try {
prep.setInt(2, seq++);
ResultSet rs = prep.executeQuery();
if (rs.next()) {
return rs.getBytes(1);
}
return null;
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
public boolean hasMoreElements() {
return data != null;
}
@Override
public InputStream nextElement() {
ByteArrayInputStream in = new ByteArrayInputStream(data);
data = fetch();
return in;
}
}
);
}
/**
* INTERNAL
*/
public static Reader readClobMap(Connection conn, long lobId, long precision)
throws Exception {
InputStream in = readBlobMap(conn, lobId, precision);
return new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
}
private void trace(String message) {
if (trace) {
out.println(message);
}
}
private void traceError(String message, Throwable t) {
out.println(message + ": " + t.toString());
if (trace) {
t.printStackTrace(out);
}
}
/**
* Dumps the contents of a database to a SQL script file.
*
* @param dir the directory
* @param db the database name (null for all databases)
*/
public static void execute(String dir, String db) throws SQLException {
try {
new Recover().process(dir, db);
} catch (DbException e) {
throw DbException.toSQLException(e);
}
}
private void process(String dir, String db) {
ArrayList<String> list = FileLister.getDatabaseFiles(dir, db, true);
if (list.isEmpty()) {
printNoDatabaseFilesFound(dir, db);
}
for (String fileName : list) {
if (fileName.endsWith(Constants.SUFFIX_PAGE_FILE)) {
dumpPageStore(fileName);
} else if (fileName.endsWith(Constants.SUFFIX_LOB_FILE)) {
dumpLob(fileName, false);
} else if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
String f = fileName.substring(0, fileName.length() -
Constants.SUFFIX_PAGE_FILE.length());
PrintWriter writer;
writer = getWriter(fileName, ".txt");
MVStoreTool.dump(fileName, writer, true);
MVStoreTool.info(fileName, writer);
writer.close();
writer = getWriter(f + ".h2.db", ".sql");
dumpMVStoreFile(writer, fileName);
writer.close();
}
}
}
private PrintWriter getWriter(String fileName, String suffix) {
fileName = fileName.substring(0, fileName.length() - 3);
String outputFile = fileName + suffix;
trace("Created file: " + outputFile);
try {
return new PrintWriter(IOUtils.getBufferedWriter(
FileUtils.newOutputStream(outputFile, false)));
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
private void writeDataError(PrintWriter writer, String error, byte[] data) {
writer.println("-- ERROR: " + error + " storageId: "
+ storageId + " recordLength: " + recordLength + " valueId: " + valueId);
StringBuilder sb = new StringBuilder();
for (byte aData1 : data) {
int x = aData1 & 0xff;
if (x >= ' ' && x < 128) {
sb.append((char) x);
} else {
sb.append('?');
}
}
writer.println("-- dump: " + sb.toString());
sb = new StringBuilder();
for (byte aData : data) {
int x = aData & 0xff;
sb.append(' ');
if (x < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(x));
}
writer.println("-- dump: " + sb.toString());
}
private void dumpLob(String fileName, boolean lobCompression) {
OutputStream fileOut = null;
FileStore fileStore = null;
long size = 0;
String n = fileName + (lobCompression ? ".comp" : "") + ".txt";
InputStream in = null;
try {
fileOut = FileUtils.newOutputStream(n, false);
fileStore = FileStore.open(null, fileName, "r");
fileStore.init();
in = new FileStoreInputStream(fileStore, this, lobCompression, false);
size = IOUtils.copy(in, fileOut);
} catch (Throwable e) {
// this is usually not a problem, because we try both compressed and
// uncompressed
} finally {
IOUtils.closeSilently(fileOut);
IOUtils.closeSilently(in);
closeSilently(fileStore);
}
if (size == 0) {
try {
FileUtils.delete(n);
} catch (Exception e) {
traceError(n, e);
}
}
}
private String getSQL(String column, Value v) {
if (v instanceof ValueLob) {
ValueLob lob = (ValueLob) v;
byte[] small = lob.getSmall();
if (small == null) {
String file = lob.getFileName();
String type = lob.getType() == Value.BLOB ? "BLOB" : "CLOB";
if (lob.isCompressed()) {
dumpLob(file, true);
file += ".comp";
}
return "READ_" + type + "('" + file + ".txt')";
}
} else if (v instanceof ValueLobDb) {
ValueLobDb lob = (ValueLobDb) v;
byte[] small = lob.getSmall();
if (small == null) {
int type = lob.getType();
long id = lob.getLobId();
long precision = lob.getPrecision();
String m;
String columnType;
if (type == Value.BLOB) {
columnType = "BLOB";
m = "READ_BLOB";
} else {
columnType = "CLOB";
m = "READ_CLOB";
}
if (lobMaps) {
m += "_MAP";
} else {
m += "_DB";
}
columnTypeMap.put(column, columnType);
return m + "(" + id + ", " + precision + ")";
}
}
return v.getSQL();
}
private void setDatabaseName(String name) {
databaseName = name;
}
private void dumpPageStore(String fileName) {
setDatabaseName(fileName.substring(0, fileName.length() -
Constants.SUFFIX_PAGE_FILE.length()));
PrintWriter writer = null;
stat = new Stats();
try {
writer = getWriter(fileName, ".sql");
writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB FOR \"" +
this.getClass().getName() + ".readBlob\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB FOR \"" +
this.getClass().getName() + ".readClob\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB_DB FOR \"" +
this.getClass().getName() + ".readBlobDb\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB_DB FOR \"" +
this.getClass().getName() + ".readClobDb\";");
resetSchema();
store = FileStore.open(null, fileName, remove ? "rw" : "r");
long length = store.length();
try {
store.init();
} catch (Exception e) {
writeError(writer, e);
}
Data s = Data.create(this, 128);
seek(0);
store.readFully(s.getBytes(), 0, 128);
s.setPos(48);
pageSize = s.readInt();
int writeVersion = s.readByte();
int readVersion = s.readByte();
writer.println("-- pageSize: " + pageSize +
" writeVersion: " + writeVersion +
" readVersion: " + readVersion);
if (pageSize < PageStore.PAGE_SIZE_MIN ||
pageSize > PageStore.PAGE_SIZE_MAX) {
pageSize = Constants.DEFAULT_PAGE_SIZE;
writer.println("-- ERROR: page size; using " + pageSize);
}
long pageCount = length / pageSize;
parents = new int[(int) pageCount];
s = Data.create(this, pageSize);
for (long i = 3; i < pageCount; i++) {
s.reset();
seek(i);
store.readFully(s.getBytes(), 0, 32);
s.readByte();
s.readShortInt();
parents[(int) i] = s.readInt();
}
int logKey = 0, logFirstTrunkPage = 0, logFirstDataPage = 0;
s = Data.create(this, pageSize);
for (long i = 1;; i++) {
if (i == 3) {
break;
}
s.reset();
seek(i);
store.readFully(s.getBytes(), 0, pageSize);
CRC32 crc = new CRC32();
crc.update(s.getBytes(), 4, pageSize - 4);
int expected = (int) crc.getValue();
int got = s.readInt();
long writeCounter = s.readLong();
int key = s.readInt();
int firstTrunkPage = s.readInt();
int firstDataPage = s.readInt();
if (expected == got) {
logKey = key;
logFirstTrunkPage = firstTrunkPage;
logFirstDataPage = firstDataPage;
}
writer.println("-- head " + i +
": writeCounter: " + writeCounter +
" log " + key + ":" + firstTrunkPage + "/" + firstDataPage +
" crc " + got + " (" + (expected == got ?
"ok" : ("expected: " + expected)) + ")");
}
writer.println("-- log " + logKey + ":" + logFirstTrunkPage +
"/" + logFirstDataPage);
PrintWriter devNull = new PrintWriter(new OutputStream() {
@Override
public void write(int b) {
// ignore
}
});
dumpPageStore(devNull, pageCount);
stat = new Stats();
schema.clear();
objectIdSet = new HashSet<>();
dumpPageStore(writer, pageCount);
writeSchema(writer);
try {
dumpPageLogStream(writer, logKey, logFirstTrunkPage,
logFirstDataPage, pageCount);
} catch (IOException e) {
// ignore
}
writer.println("---- Statistics ----");
writer.println("-- page count: " + pageCount + ", free: " + stat.free);
long total = Math.max(1, stat.pageDataRows +
stat.pageDataEmpty + stat.pageDataHead);
writer.println("-- page data bytes: head " + stat.pageDataHead +
", empty " + stat.pageDataEmpty +
", rows " + stat.pageDataRows +
" (" + (100 - 100L * stat.pageDataEmpty / total) + "% full)");
for (int i = 0; i < stat.pageTypeCount.length; i++) {
int count = stat.pageTypeCount[i];
if (count > 0) {
writer.println("-- " + getPageType(i) + " " +
(100 * count / pageCount) + "%, " + count + " page(s)");
}
}
writer.close();
} catch (Throwable e) {
writeError(writer, e);
} finally {
IOUtils.closeSilently(writer);
closeSilently(store);
}
}
private void dumpMVStoreFile(PrintWriter writer, String fileName) {
writer.println("-- MVStore");
writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB FOR \"" +
this.getClass().getName() + ".readBlob\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB FOR \"" +
this.getClass().getName() + ".readClob\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB_DB FOR \"" +
this.getClass().getName() + ".readBlobDb\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB_DB FOR \"" +
this.getClass().getName() + ".readClobDb\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB_MAP FOR \"" +
this.getClass().getName() + ".readBlobMap\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB_MAP FOR \"" +
this.getClass().getName() + ".readClobMap\";");
resetSchema();
setDatabaseName(fileName.substring(0, fileName.length() -
Constants.SUFFIX_MV_FILE.length()));
MVStore mv = new MVStore.Builder().
fileName(fileName).readOnly().open();
dumpLobMaps(writer, mv);
writer.println("-- Meta");
dumpMeta(writer, mv);
writer.println("-- Tables");
TransactionStore store = new TransactionStore(mv);
try {
store.init();
} catch (Throwable e) {
writeError(writer, e);
}
try {
for (String mapName : mv.getMapNames()) {
if (!mapName.startsWith("table.")) {
continue;
}
String tableId = mapName.substring("table.".length());
ValueDataType keyType = new ValueDataType(
null, this, null);
ValueDataType valueType = new ValueDataType(
null, this, null);
TransactionMap<Value, Value> dataMap = store.begin().openMap(
mapName, keyType, valueType);
Iterator<Value> dataIt = dataMap.keyIterator(null);
boolean init = false;
while (dataIt.hasNext()) {
Value rowId = dataIt.next();
Value[] values = ((ValueArray) dataMap.get(rowId)).getList();
recordLength = values.length;
if (!init) {
setStorage(Integer.parseInt(tableId));
// init the column types
for (valueId = 0; valueId < recordLength; valueId++) {
String columnName = storageName + "." + valueId;
getSQL(columnName, values[valueId]);
}
createTemporaryTable(writer);
init = true;
}
StringBuilder buff = new StringBuilder();
buff.append("INSERT INTO O_").append(tableId)
.append(" VALUES(");
for (valueId = 0; valueId < recordLength; valueId++) {
if (valueId > 0) {
buff.append(", ");
}
String columnName = storageName + "." + valueId;
buff.append(getSQL(columnName, values[valueId]));
}
buff.append(");");
writer.println(buff.toString());
if (storageId == 0) {
try {
SimpleRow r = new SimpleRow(values);
MetaRecord meta = new MetaRecord(r);
schema.add(meta);
if (meta.getObjectType() == DbObject.TABLE_OR_VIEW) {
String sql = values[3].getString();
String name = extractTableOrViewName(sql);
tableMap.put(meta.getId(), name);
}
} catch (Throwable t) {
writeError(writer, t);
}
}
}
}
writeSchema(writer);
writer.println("DROP ALIAS READ_BLOB_MAP;");
writer.println("DROP ALIAS READ_CLOB_MAP;");
writer.println("DROP TABLE IF EXISTS INFORMATION_SCHEMA.LOB_BLOCKS;");
} catch (Throwable e) {
writeError(writer, e);
} finally {
mv.close();
}
}
private static void dumpMeta(PrintWriter writer, MVStore mv) {
MVMap<String, String> meta = mv.getMetaMap();
for (Entry<String, String> e : meta.entrySet()) {
writer.println("-- " + e.getKey() + " = " + e.getValue());
}
}
private void dumpLobMaps(PrintWriter writer, MVStore mv) {
lobMaps = mv.hasMap("lobData");
if (!lobMaps) {
return;
}
MVMap<Long, byte[]> lobData = mv.openMap("lobData");
StreamStore streamStore = new StreamStore(lobData);
MVMap<Long, Object[]> lobMap = mv.openMap("lobMap");
writer.println("-- LOB");
writer.println("CREATE TABLE IF NOT EXISTS " +
"INFORMATION_SCHEMA.LOB_BLOCKS(" +
"LOB_ID BIGINT, SEQ INT, DATA BINARY, " +
"PRIMARY KEY(LOB_ID, SEQ));");
boolean hasErrors = false;
for (Entry<Long, Object[]> e : lobMap.entrySet()) {
long lobId = e.getKey();
Object[] value = e.getValue();
byte[] streamStoreId = (byte[]) value[0];
InputStream in = streamStore.get(streamStoreId);
int len = 8 * 1024;
byte[] block = new byte[len];
try {
for (int seq = 0;; seq++) {
int l = IOUtils.readFully(in, block, block.length);
String x = StringUtils.convertBytesToHex(block, l);
if (l > 0) {
writer.println("INSERT INTO INFORMATION_SCHEMA.LOB_BLOCKS " +
"VALUES(" + lobId + ", " + seq + ", '" + x + "');");
}
if (l != len) {
break;
}
}
} catch (IOException ex) {
writeError(writer, ex);
hasErrors = true;
}
}
writer.println("-- lobMap.size: " + lobMap.sizeAsLong());
writer.println("-- lobData.size: " + lobData.sizeAsLong());
if (hasErrors) {
writer.println("-- lobMap");
for (Long k : lobMap.keyList()) {
Object[] value = lobMap.get(k);
byte[] streamStoreId = (byte[]) value[0];
writer.println("-- " + k + " " + StreamStore.toString(streamStoreId));
}
writer.println("-- lobData");
for (Long k : lobData.keyList()) {
writer.println("-- " + k + " len " + lobData.get(k).length);
}
}
}
private static String getPageType(int type) {
switch (type) {
case 0:
return "free";
case Page.TYPE_DATA_LEAF:
return "data leaf";
case Page.TYPE_DATA_NODE:
return "data node";
case Page.TYPE_DATA_OVERFLOW:
return "data overflow";
case Page.TYPE_BTREE_LEAF:
return "btree leaf";
case Page.TYPE_BTREE_NODE:
return "btree node";
case Page.TYPE_FREE_LIST:
return "free list";
case Page.TYPE_STREAM_TRUNK:
return "stream trunk";
case Page.TYPE_STREAM_DATA:
return "stream data";
}
return "[" + type + "]";
}
private void dumpPageStore(PrintWriter writer, long pageCount) {
Data s = Data.create(this, pageSize);
for (long page = 3; page < pageCount; page++) {
s = Data.create(this, pageSize);
seek(page);
store.readFully(s.getBytes(), 0, pageSize);
dumpPage(writer, s, page, pageCount);
}
}
private void dumpPage(PrintWriter writer, Data s, long page, long pageCount) {
try {
int type = s.readByte();
switch (type) {
case Page.TYPE_EMPTY:
stat.pageTypeCount[type]++;
return;
}
boolean last = (type & Page.FLAG_LAST) != 0;
type &= ~Page.FLAG_LAST;
if (!PageStore.checksumTest(s.getBytes(), (int) page, pageSize)) {
writeDataError(writer, "checksum mismatch type: " + type, s.getBytes());
}
s.readShortInt();
switch (type) {
// type 1
case Page.TYPE_DATA_LEAF: {
stat.pageTypeCount[type]++;
int parentPageId = s.readInt();
setStorage(s.readVarInt());
int columnCount = s.readVarInt();
int entries = s.readShortInt();
writer.println("-- page " + page + ": data leaf " +
(last ? "(last) " : "") + "parent: " + parentPageId +
" table: " + storageId + " entries: " + entries +
" columns: " + columnCount);
dumpPageDataLeaf(writer, s, last, page, columnCount, entries);
break;
}
// type 2
case Page.TYPE_DATA_NODE: {
stat.pageTypeCount[type]++;
int parentPageId = s.readInt();
setStorage(s.readVarInt());
int rowCount = s.readInt();
int entries = s.readShortInt();
writer.println("-- page " + page + ": data node " +
(last ? "(last) " : "") + "parent: " + parentPageId +
" table: " + storageId + " entries: " + entries +
" rowCount: " + rowCount);
dumpPageDataNode(writer, s, page, entries);
break;
}
// type 3
case Page.TYPE_DATA_OVERFLOW:
stat.pageTypeCount[type]++;
writer.println("-- page " + page + ": data overflow " +
(last ? "(last) " : ""));
break;
// type 4
case Page.TYPE_BTREE_LEAF: {
stat.pageTypeCount[type]++;
int parentPageId = s.readInt();
setStorage(s.readVarInt());
int entries = s.readShortInt();
writer.println("-- page " + page + ": b-tree leaf " +
(last ? "(last) " : "") + "parent: " + parentPageId +
" index: " + storageId + " entries: " + entries);
if (trace) {
dumpPageBtreeLeaf(writer, s, entries, !last);
}
break;
}
// type 5
case Page.TYPE_BTREE_NODE:
stat.pageTypeCount[type]++;
int parentPageId = s.readInt();
setStorage(s.readVarInt());
writer.println("-- page " + page + ": b-tree node " +
(last ? "(last) " : "") + "parent: " + parentPageId +
" index: " + storageId);
dumpPageBtreeNode(writer, s, page, !last);
break;
// type 6
case Page.TYPE_FREE_LIST:
stat.pageTypeCount[type]++;
writer.println("-- page " + page + ": free list " + (last ? "(last)" : ""));
stat.free += dumpPageFreeList(writer, s, page, pageCount);
break;
// type 7
case Page.TYPE_STREAM_TRUNK:
stat.pageTypeCount[type]++;
writer.println("-- page " + page + ": log trunk");
break;
// type 8
case Page.TYPE_STREAM_DATA:
stat.pageTypeCount[type]++;
writer.println("-- page " + page + ": log data");
break;
default:
writer.println("-- ERROR page " + page + " unknown type " + type);
break;
}
} catch (Exception e) {
writeError(writer, e);
}
}
private void dumpPageLogStream(PrintWriter writer, int logKey,
int logFirstTrunkPage, int logFirstDataPage, long pageCount)
throws IOException {
Data s = Data.create(this, pageSize);
DataReader in = new DataReader(
new PageInputStream(writer, this, store, logKey,
logFirstTrunkPage, logFirstDataPage, pageSize)
);
writer.println("---- Transaction log ----");
CompressLZF compress = new CompressLZF();
while (true) {
int x = in.readByte();
if (x < 0) {
break;
}
if (x == PageLog.NOOP) {
// ignore
} else if (x == PageLog.UNDO) {
int pageId = in.readVarInt();
int size = in.readVarInt();
byte[] data = new byte[pageSize];
if (size == 0) {
in.readFully(data, pageSize);
} else if (size == 1) {
// empty
} else {
byte[] compressBuffer = new byte[size];
in.readFully(compressBuffer, size);
try {
compress.expand(compressBuffer, 0, size, data, 0, pageSize);
} catch (ArrayIndexOutOfBoundsException e) {
throw DbException.convertToIOException(e);
}
}
String typeName = "";
int type = data[0];
boolean last = (type & Page.FLAG_LAST) != 0;
type &= ~Page.FLAG_LAST;
switch (type) {
case Page.TYPE_EMPTY:
typeName = "empty";
break;
case Page.TYPE_DATA_LEAF:
typeName = "data leaf " + (last ? "(last)" : "");
break;
case Page.TYPE_DATA_NODE:
typeName = "data node " + (last ? "(last)" : "");
break;
case Page.TYPE_DATA_OVERFLOW:
typeName = "data overflow " + (last ? "(last)" : "");
break;
case Page.TYPE_BTREE_LEAF:
typeName = "b-tree leaf " + (last ? "(last)" : "");
break;
case Page.TYPE_BTREE_NODE:
typeName = "b-tree node " + (last ? "(last)" : "");
break;
case Page.TYPE_FREE_LIST:
typeName = "free list " + (last ? "(last)" : "");
break;
case Page.TYPE_STREAM_TRUNK:
typeName = "log trunk";
break;
case Page.TYPE_STREAM_DATA:
typeName = "log data";
break;
default:
typeName = "ERROR: unknown type " + type;
break;
}
writer.println("-- undo page " + pageId + " " + typeName);
if (trace) {
Data d = Data.create(null, data);
dumpPage(writer, d, pageId, pageCount);
}
} else if (x == PageLog.ADD) {
int sessionId = in.readVarInt();
setStorage(in.readVarInt());
Row row = PageLog.readRow(RowFactory.DEFAULT, in, s);
writer.println("-- session " + sessionId +
" table " + storageId +
" + " + row.toString());
if (transactionLog) {
if (storageId == 0 && row.getColumnCount() >= 4) {
int tableId = (int) row.getKey();
String sql = row.getValue(3).getString();
String name = extractTableOrViewName(sql);
if (row.getValue(2).getInt() == DbObject.TABLE_OR_VIEW) {
tableMap.put(tableId, name);
}
writer.println(sql + ";");
} else {
String tableName = tableMap.get(storageId);
if (tableName != null) {
StatementBuilder buff = new StatementBuilder();
buff.append("INSERT INTO ").append(tableName).
append(" VALUES(");
for (int i = 0; i < row.getColumnCount(); i++) {
buff.appendExceptFirst(", ");
buff.append(row.getValue(i).getSQL());
}
buff.append(");");
writer.println(buff.toString());
}
}
}
} else if (x == PageLog.REMOVE) {
int sessionId = in.readVarInt();
setStorage(in.readVarInt());
long key = in.readVarLong();
writer.println("-- session " + sessionId +
" table " + storageId +
" - " + key);
if (transactionLog) {
if (storageId == 0) {
int tableId = (int) key;
String tableName = tableMap.get(tableId);
if (tableName != null) {
writer.println("DROP TABLE IF EXISTS " + tableName + ";");
}
} else {
String tableName = tableMap.get(storageId);
if (tableName != null) {
String sql = "DELETE FROM " + tableName +
" WHERE _ROWID_ = " + key + ";";
writer.println(sql);
}
}
}
} else if (x == PageLog.TRUNCATE) {
int sessionId = in.readVarInt();
setStorage(in.readVarInt());
writer.println("-- session " + sessionId +
" table " + storageId +
" truncate");
if (transactionLog) {
writer.println("TRUNCATE TABLE " + storageId);
}
} else if (x == PageLog.COMMIT) {
int sessionId = in.readVarInt();
writer.println("-- commit " + sessionId);
} else if (x == PageLog.ROLLBACK) {
int sessionId = in.readVarInt();
writer.println("-- rollback " + sessionId);
} else if (x == PageLog.PREPARE_COMMIT) {
int sessionId = in.readVarInt();
String transaction = in.readString();
writer.println("-- prepare commit " + sessionId + " " + transaction);
} else if (x == PageLog.NOOP) {
// nothing to do
} else if (x == PageLog.CHECKPOINT) {
writer.println("-- checkpoint");
} else if (x == PageLog.FREE_LOG) {
int size = in.readVarInt();
StringBuilder buff = new StringBuilder("-- free");
for (int i = 0; i < size; i++) {
buff.append(' ').append(in.readVarInt());
}
writer.println(buff);
} else {
writer.println("-- ERROR: unknown operation " + x);
break;
}
}
}
private String setStorage(int storageId) {
this.storageId = storageId;
this.storageName = "O_" + String.valueOf(storageId).replace('-', 'M');
return storageName;
}
/**
* An input stream that reads the data from a page store.
*/
static class PageInputStream extends InputStream {
private final PrintWriter writer;
private final FileStore store;
private final Data page;
private final int pageSize;
private long trunkPage;
private long nextTrunkPage;
private long dataPage;
private final IntArray dataPages = new IntArray();
private boolean endOfFile;
private int remaining;
private int logKey;
public PageInputStream(PrintWriter writer, DataHandler handler,
FileStore store, int logKey, long firstTrunkPage,
long firstDataPage, int pageSize) {
this.writer = writer;
this.store = store;
this.pageSize = pageSize;
this.logKey = logKey - 1;
this.nextTrunkPage = firstTrunkPage;
this.dataPage = firstDataPage;
page = Data.create(handler, pageSize);
}
@Override
public int read() {
byte[] b = { 0 };
int len = read(b);
return len < 0 ? -1 : (b[0] & 255);
}
@Override
public int read(byte[] b) {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) {
if (len == 0) {
return 0;
}
int read = 0;
while (len > 0) {
int r = readBlock(b, off, len);
if (r < 0) {
break;
}
read += r;
off += r;
len -= r;
}
return read == 0 ? -1 : read;
}
private int readBlock(byte[] buff, int off, int len) {
fillBuffer();
if (endOfFile) {
return -1;
}
int l = Math.min(remaining, len);
page.read(buff, off, l);
remaining -= l;
return l;
}
private void fillBuffer() {
if (remaining > 0 || endOfFile) {
return;
}
while (dataPages.size() == 0) {
if (nextTrunkPage == 0) {
endOfFile = true;
return;
}
trunkPage = nextTrunkPage;
store.seek(trunkPage * pageSize);
store.readFully(page.getBytes(), 0, pageSize);
page.reset();
if (!PageStore.checksumTest(page.getBytes(), (int) trunkPage, pageSize)) {
writer.println("-- ERROR: checksum mismatch page: " +trunkPage);
endOfFile = true;
return;
}
int t = page.readByte();
page.readShortInt();
if (t != Page.TYPE_STREAM_TRUNK) {
writer.println("-- log eof " + trunkPage + " type: " + t +
" expected type: " + Page.TYPE_STREAM_TRUNK);
endOfFile = true;
return;
}
page.readInt();
int key = page.readInt();
logKey++;
if (key != logKey) {
writer.println("-- log eof " + trunkPage +
" type: " + t + " expected key: " + logKey + " got: " + key);
}
nextTrunkPage = page.readInt();
writer.println("-- log " + key + ":" + trunkPage +
" next: " + nextTrunkPage);
int pageCount = page.readShortInt();
for (int i = 0; i < pageCount; i++) {
int d = page.readInt();
if (dataPage != 0) {
if (d == dataPage) {
dataPage = 0;
} else {
// ignore the pages before the starting page
continue;
}
}
dataPages.add(d);
}
}
if (dataPages.size() > 0) {
page.reset();
long nextPage = dataPages.get(0);
dataPages.remove(0);
store.seek(nextPage * pageSize);
store.readFully(page.getBytes(), 0, pageSize);
page.reset();
int t = page.readByte();
if (t != 0 && !PageStore.checksumTest(page.getBytes(),
(int) nextPage, pageSize)) {
writer.println("-- ERROR: checksum mismatch page: " +nextPage);
endOfFile = true;
return;
}
page.readShortInt();
int p = page.readInt();
int k = page.readInt();
writer.println("-- log " + k + ":" + trunkPage + "/" + nextPage);
if (t != Page.TYPE_STREAM_DATA) {
writer.println("-- log eof " +nextPage+ " type: " + t + " parent: " + p +
" expected type: " + Page.TYPE_STREAM_DATA);
endOfFile = true;
return;
} else if (k != logKey) {
writer.println("-- log eof " +nextPage+ " type: " + t + " parent: " + p +
" expected key: " + logKey + " got: " + k);
endOfFile = true;
return;
}
remaining = pageSize - page.length();
}
}
}
private void dumpPageBtreeNode(PrintWriter writer, Data s, long pageId,
boolean positionOnly) {
int rowCount = s.readInt();
int entryCount = s.readShortInt();
int[] children = new int[entryCount + 1];
int[] offsets = new int[entryCount];
children[entryCount] = s.readInt();
checkParent(writer, pageId, children, entryCount);
int empty = Integer.MAX_VALUE;
for (int i = 0; i < entryCount; i++) {
children[i] = s.readInt();
checkParent(writer, pageId, children, i);
int off = s.readShortInt();
empty = Math.min(off, empty);
offsets[i] = off;
}
empty = empty - s.length();
if (!trace) {
return;
}
writer.println("-- empty: " + empty);
for (int i = 0; i < entryCount; i++) {
int off = offsets[i];
s.setPos(off);
long key = s.readVarLong();
Value data;
if (positionOnly) {
data = ValueLong.get(key);
} else {
try {
data = s.readValue();
} catch (Throwable e) {
writeDataError(writer, "exception " + e, s.getBytes());
continue;
}
}
writer.println("-- [" + i + "] child: " + children[i] +
" key: " + key + " data: " + data);
}
writer.println("-- [" + entryCount + "] child: " +
children[entryCount] + " rowCount: " + rowCount);
}
private int dumpPageFreeList(PrintWriter writer, Data s, long pageId,
long pageCount) {
int pagesAddressed = PageFreeList.getPagesAddressed(pageSize);
BitField used = new BitField();
for (int i = 0; i < pagesAddressed; i += 8) {
int x = s.readByte() & 255;
for (int j = 0; j < 8; j++) {
if ((x & (1 << j)) != 0) {
used.set(i + j);
}
}
}
int free = 0;
for (long i = 0, j = pageId; i < pagesAddressed && j < pageCount; i++, j++) {
if (i == 0 || j % 100 == 0) {
if (i > 0) {
writer.println();
}
writer.print("-- " + j + " ");
} else if (j % 20 == 0) {
writer.print(" - ");
} else if (j % 10 == 0) {
writer.print(' ');
}
writer.print(used.get((int) i) ? '1' : '0');
if (!used.get((int) i)) {
free++;
}
}
writer.println();
return free;
}
private void dumpPageBtreeLeaf(PrintWriter writer, Data s, int entryCount,
boolean positionOnly) {
int[] offsets = new int[entryCount];
int empty = Integer.MAX_VALUE;
for (int i = 0; i < entryCount; i++) {
int off = s.readShortInt();
empty = Math.min(off, empty);
offsets[i] = off;
}
empty = empty - s.length();
writer.println("-- empty: " + empty);
for (int i = 0; i < entryCount; i++) {
int off = offsets[i];
s.setPos(off);
long key = s.readVarLong();
Value data;
if (positionOnly) {
data = ValueLong.get(key);
} else {
try {
data = s.readValue();
} catch (Throwable e) {
writeDataError(writer, "exception " + e, s.getBytes());
continue;
}
}
writer.println("-- [" + i + "] key: " + key + " data: " + data);
}
}
private void checkParent(PrintWriter writer, long pageId, int[] children,
int index) {
int child = children[index];
if (child < 0 || child >= parents.length) {
writer.println("-- ERROR [" + pageId + "] child[" +
index + "]: " + child + " >= page count: " + parents.length);
} else if (parents[child] != pageId) {
writer.println("-- ERROR [" + pageId + "] child[" +
index + "]: " + child + " parent: " + parents[child]);
}
}
private void dumpPageDataNode(PrintWriter writer, Data s, long pageId,
int entryCount) {
int[] children = new int[entryCount + 1];
long[] keys = new long[entryCount];
children[entryCount] = s.readInt();
checkParent(writer, pageId, children, entryCount);
for (int i = 0; i < entryCount; i++) {
children[i] = s.readInt();
checkParent(writer, pageId, children, i);
keys[i] = s.readVarLong();
}
if (!trace) {
return;
}
for (int i = 0; i < entryCount; i++) {
writer.println("-- [" + i + "] child: " + children[i] + " key: " + keys[i]);
}
writer.println("-- [" + entryCount + "] child: " + children[entryCount]);
}
private void dumpPageDataLeaf(PrintWriter writer, Data s, boolean last,
long pageId, int columnCount, int entryCount) {
long[] keys = new long[entryCount];
int[] offsets = new int[entryCount];
long next = 0;
if (!last) {
next = s.readInt();
writer.println("-- next: " + next);
}
int empty = pageSize;
for (int i = 0; i < entryCount; i++) {
keys[i] = s.readVarLong();
int off = s.readShortInt();
empty = Math.min(off, empty);
offsets[i] = off;
}
stat.pageDataRows += pageSize - empty;
empty = empty - s.length();
stat.pageDataHead += s.length();
stat.pageDataEmpty += empty;
if (trace) {
writer.println("-- empty: " + empty);
}
if (!last) {
Data s2 = Data.create(this, pageSize);
s.setPos(pageSize);
long parent = pageId;
while (true) {
checkParent(writer, parent, new int[]{(int) next}, 0);
parent = next;
seek(next);
store.readFully(s2.getBytes(), 0, pageSize);
s2.reset();
int type = s2.readByte();
s2.readShortInt();
s2.readInt();
if (type == (Page.TYPE_DATA_OVERFLOW | Page.FLAG_LAST)) {
int size = s2.readShortInt();
writer.println("-- chain: " + next +
" type: " + type + " size: " + size);
s.checkCapacity(size);
s.write(s2.getBytes(), s2.length(), size);
break;
} else if (type == Page.TYPE_DATA_OVERFLOW) {
next = s2.readInt();
if (next == 0) {
writeDataError(writer, "next:0", s2.getBytes());
break;
}
int size = pageSize - s2.length();
writer.println("-- chain: " + next + " type: " + type +
" size: " + size + " next: " + next);
s.checkCapacity(size);
s.write(s2.getBytes(), s2.length(), size);
} else {
writeDataError(writer, "type: " + type, s2.getBytes());
break;
}
}
}
for (int i = 0; i < entryCount; i++) {
long key = keys[i];
int off = offsets[i];
if (trace) {
writer.println("-- [" + i + "] storage: " + storageId +
" key: " + key + " off: " + off);
}
s.setPos(off);
Value[] data = createRecord(writer, s, columnCount);
if (data != null) {
createTemporaryTable(writer);
writeRow(writer, s, data);
if (remove && storageId == 0) {
String sql = data[3].getString();
if (sql.startsWith("CREATE USER ")) {
int saltIndex = Utils.indexOf(s.getBytes(), "SALT ".getBytes(), off);
if (saltIndex >= 0) {
String userName = sql.substring("CREATE USER ".length(),
sql.indexOf("SALT ") - 1);
if (userName.startsWith("IF NOT EXISTS ")) {
userName = userName.substring("IF NOT EXISTS ".length());
}
if (userName.startsWith("\"")) {
// TODO doesn't work for all cases ("" inside
// user name)
userName = userName.substring(1, userName.length() - 1);
}
byte[] userPasswordHash = SHA256.getKeyPasswordHash(
userName, "".toCharArray());
byte[] salt = MathUtils.secureRandomBytes(Constants.SALT_LEN);
byte[] passwordHash = SHA256.getHashWithSalt(
userPasswordHash, salt);
StringBuilder buff = new StringBuilder();
buff.append("SALT '").
append(StringUtils.convertBytesToHex(salt)).
append("' HASH '").
append(StringUtils.convertBytesToHex(passwordHash)).
append('\'');
byte[] replacement = buff.toString().getBytes();
System.arraycopy(replacement, 0, s.getBytes(),
saltIndex, replacement.length);
seek(pageId);
store.write(s.getBytes(), 0, pageSize);
if (trace) {
out.println("User: " + userName);
}
remove = false;
}
}
}
}
}
}
private void seek(long page) {
// page is long to avoid integer overflow
store.seek(page * pageSize);
}
private Value[] createRecord(PrintWriter writer, Data s, int columnCount) {
recordLength = columnCount;
if (columnCount <= 0) {
writeDataError(writer, "columnCount<0", s.getBytes());
return null;
}
Value[] data;
try {
data = new Value[columnCount];
} catch (OutOfMemoryError e) {
writeDataError(writer, "out of memory", s.getBytes());
return null;
}
return data;
}
private void writeRow(PrintWriter writer, Data s, Value[] data) {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(storageName).append(" VALUES(");
for (valueId = 0; valueId < recordLength; valueId++) {
try {
Value v = s.readValue();
data[valueId] = v;
if (valueId > 0) {
sb.append(", ");
}
String columnName = storageName + "." + valueId;
sb.append(getSQL(columnName, v));
} catch (Exception e) {
writeDataError(writer, "exception " + e, s.getBytes());
} catch (OutOfMemoryError e) {
writeDataError(writer, "out of memory", s.getBytes());
}
}
sb.append(");");
writer.println(sb.toString());
if (storageId == 0) {
try {
SimpleRow r = new SimpleRow(data);
MetaRecord meta = new MetaRecord(r);
schema.add(meta);
if (meta.getObjectType() == DbObject.TABLE_OR_VIEW) {
String sql = data[3].getString();
String name = extractTableOrViewName(sql);
tableMap.put(meta.getId(), name);
}
} catch (Throwable t) {
writeError(writer, t);
}
}
}
private void resetSchema() {
schema = New.arrayList();
objectIdSet = new HashSet<>();
tableMap = new HashMap<>();
columnTypeMap = new HashMap<>();
}
private void writeSchema(PrintWriter writer) {
writer.println("---- Schema ----");
Collections.sort(schema);
for (MetaRecord m : schema) {
if (!isSchemaObjectTypeDelayed(m)) {
// create, but not referential integrity constraints and so on
// because they could fail on duplicate keys
String sql = m.getSQL();
writer.println(sql + ";");
}
}
// first, copy the lob storage (if there is any)
// must occur before copying data,
// otherwise the lob storage may be overwritten
boolean deleteLobs = false;
for (Map.Entry<Integer, String> entry : tableMap.entrySet()) {
Integer objectId = entry.getKey();
String name = entry.getValue();
if (objectIdSet.contains(objectId)) {
if (name.startsWith("INFORMATION_SCHEMA.LOB")) {
setStorage(objectId);
writer.println("DELETE FROM " + name + ";");
writer.println("INSERT INTO " + name + " SELECT * FROM " + storageName + ";");
if (name.startsWith("INFORMATION_SCHEMA.LOBS")) {
writer.println("UPDATE " + name + " SET TABLE = " +
LobStorageFrontend.TABLE_TEMP + ";");
deleteLobs = true;
}
}
}
}
for (Map.Entry<Integer, String> entry : tableMap.entrySet()) {
Integer objectId = entry.getKey();
String name = entry.getValue();
if (objectIdSet.contains(objectId)) {
setStorage(objectId);
if (name.startsWith("INFORMATION_SCHEMA.LOB")) {
continue;
}
writer.println("INSERT INTO " + name + " SELECT * FROM " + storageName + ";");
}
}
for (Integer objectId : objectIdSet) {
setStorage(objectId);
writer.println("DROP TABLE " + storageName + ";");
}
writer.println("DROP ALIAS READ_BLOB;");
writer.println("DROP ALIAS READ_CLOB;");
writer.println("DROP ALIAS READ_BLOB_DB;");
writer.println("DROP ALIAS READ_CLOB_DB;");
if (deleteLobs) {
writer.println("DELETE FROM INFORMATION_SCHEMA.LOBS WHERE TABLE = " +
LobStorageFrontend.TABLE_TEMP + ";");
}
for (MetaRecord m : schema) {
if (isSchemaObjectTypeDelayed(m)) {
String sql = m.getSQL();
writer.println(sql + ";");
}
}
}
private static boolean isSchemaObjectTypeDelayed(MetaRecord m) {
switch (m.getObjectType()) {
case DbObject.INDEX:
case DbObject.CONSTRAINT:
case DbObject.TRIGGER:
return true;
}
return false;
}
private void createTemporaryTable(PrintWriter writer) {
if (!objectIdSet.contains(storageId)) {
objectIdSet.add(storageId);
StatementBuilder buff = new StatementBuilder("CREATE TABLE ");
buff.append(storageName).append('(');
for (int i = 0; i < recordLength; i++) {
buff.appendExceptFirst(", ");
buff.append('C').append(i).append(' ');
String columnType = columnTypeMap.get(storageName + "." + i);
if (columnType == null) {
buff.append("VARCHAR");
} else {
buff.append(columnType);
}
}
writer.println(buff.append(");").toString());
writer.flush();
}
}
private static String extractTableOrViewName(String sql) {
int indexTable = sql.indexOf(" TABLE ");
int indexView = sql.indexOf(" VIEW ");
if (indexTable > 0 && indexView > 0) {
if (indexTable < indexView) {
indexView = -1;
} else {
indexTable = -1;
}
}
if (indexView > 0) {
sql = sql.substring(indexView + " VIEW ".length());
} else if (indexTable > 0) {
sql = sql.substring(indexTable + " TABLE ".length());
} else {
return "UNKNOWN";
}
if (sql.startsWith("IF NOT EXISTS ")) {
sql = sql.substring("IF NOT EXISTS ".length());
}
boolean ignore = false;
// sql is modified in the loop
for (int i = 0; i < sql.length(); i++) {
char ch = sql.charAt(i);
if (ch == '\"') {
ignore = !ignore;
} else if (!ignore && (ch <= ' ' || ch == '(')) {
sql = sql.substring(0, i);
return sql;
}
}
return "UNKNOWN";
}
private static void closeSilently(FileStore fileStore) {
if (fileStore != null) {
fileStore.closeSilently();
}
}
private void writeError(PrintWriter writer, Throwable e) {
if (writer != null) {
writer.println("// error: " + e);
}
traceError("Error", e);
}
/**
* INTERNAL
*/
@Override
public String getDatabasePath() {
return databaseName;
}
/**
* INTERNAL
*/
@Override
public FileStore openFile(String name, String mode, boolean mustExist) {
return FileStore.open(this, name, "rw");
}
/**
* INTERNAL
*/
@Override
public void checkPowerOff() {
// nothing to do
}
/**
* INTERNAL
*/
@Override
public void checkWritingAllowed() {
// nothing to do
}
/**
* INTERNAL
*/
@Override
public int getMaxLengthInplaceLob() {
throw DbException.throwInternalError();
}
/**
* INTERNAL
*/
@Override
public String getLobCompressionAlgorithm(int type) {
return null;
}
/**
* INTERNAL
*/
@Override
public Object getLobSyncObject() {
return this;
}
/**
* INTERNAL
*/
@Override
public SmallLRUCache<String, String[]> getLobFileListCache() {
return null;
}
/**
* INTERNAL
*/
@Override
public TempFileDeleter getTempFileDeleter() {
return TempFileDeleter.getInstance();
}
/**
* INTERNAL
*/
@Override
public LobStorageBackend getLobStorage() {
return null;
}
/**
* INTERNAL
*/
@Override
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff,
int off, int length) {
throw DbException.throwInternalError();
}
@Override
public JavaObjectSerializer getJavaObjectSerializer() {
return null;
}
@Override
public CompareMode getCompareMode() {
return CompareMode.getInstance(null, 0);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Restore.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
import org.h2.util.IOUtils;
import org.h2.util.Tool;
/**
* Restores a H2 database by extracting the database files from a .zip file.
* @h2.resource
*/
public class Restore extends Tool {
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-file <filename>]</td>
* <td>The source file name (default: backup.zip)</td></tr>
* <tr><td>[-dir <dir>]</td>
* <td>The target directory (default: .)</td></tr>
* <tr><td>[-db <database>]</td>
* <td>The target database name (as stored if not set)</td></tr>
* <tr><td>[-quiet]</td>
* <td>Do not print progress information</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new Restore().runTool(args);
}
@Override
public void runTool(String... args) throws SQLException {
String zipFileName = "backup.zip";
String dir = ".";
String db = null;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-dir")) {
dir = args[++i];
} else if (arg.equals("-file")) {
zipFileName = args[++i];
} else if (arg.equals("-db")) {
db = args[++i];
} else if (arg.equals("-quiet")) {
// ignore
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
execute(zipFileName, dir, db);
}
private static String getOriginalDbName(String fileName, String db)
throws IOException {
try (InputStream in = FileUtils.newInputStream(fileName)) {
ZipInputStream zipIn = new ZipInputStream(in);
String originalDbName = null;
boolean multiple = false;
while (true) {
ZipEntry entry = zipIn.getNextEntry();
if (entry == null) {
break;
}
String entryName = entry.getName();
zipIn.closeEntry();
String name = getDatabaseNameFromFileName(entryName);
if (name != null) {
if (db.equals(name)) {
originalDbName = name;
// we found the correct database
break;
} else if (originalDbName == null) {
originalDbName = name;
// we found a database, but maybe another one
} else {
// we have found multiple databases, but not the correct
// one
multiple = true;
}
}
}
zipIn.close();
if (multiple && !db.equals(originalDbName)) {
throw new IOException("Multiple databases found, but not " + db);
}
return originalDbName;
}
}
/**
* Extract the name of the database from a given file name.
* Only files ending with .h2.db are considered, all others return null.
*
* @param fileName the file name (without directory)
* @return the database name or null
*/
private static String getDatabaseNameFromFileName(String fileName) {
if (fileName.endsWith(Constants.SUFFIX_PAGE_FILE)) {
return fileName.substring(0,
fileName.length() - Constants.SUFFIX_PAGE_FILE.length());
}
if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
return fileName.substring(0,
fileName.length() - Constants.SUFFIX_MV_FILE.length());
}
return null;
}
/**
* Restores database files.
*
* @param zipFileName the name of the backup file
* @param directory the directory name
* @param db the database name (null for all databases)
* @throws DbException if there is an IOException
*/
public static void execute(String zipFileName, String directory, String db) {
InputStream in = null;
try {
if (!FileUtils.exists(zipFileName)) {
throw new IOException("File not found: " + zipFileName);
}
String originalDbName = null;
int originalDbLen = 0;
if (db != null) {
originalDbName = getOriginalDbName(zipFileName, db);
if (originalDbName == null) {
throw new IOException("No database named " + db + " found");
}
if (originalDbName.startsWith(SysProperties.FILE_SEPARATOR)) {
originalDbName = originalDbName.substring(1);
}
originalDbLen = originalDbName.length();
}
in = FileUtils.newInputStream(zipFileName);
try (ZipInputStream zipIn = new ZipInputStream(in)) {
while (true) {
ZipEntry entry = zipIn.getNextEntry();
if (entry == null) {
break;
}
String fileName = entry.getName();
// restoring windows backups on linux and vice versa
fileName = fileName.replace('\\', SysProperties.FILE_SEPARATOR.charAt(0));
fileName = fileName.replace('/', SysProperties.FILE_SEPARATOR.charAt(0));
if (fileName.startsWith(SysProperties.FILE_SEPARATOR)) {
fileName = fileName.substring(1);
}
boolean copy = false;
if (db == null) {
copy = true;
} else if (fileName.startsWith(originalDbName + ".")) {
fileName = db + fileName.substring(originalDbLen);
copy = true;
}
if (copy) {
OutputStream o = null;
try {
o = FileUtils.newOutputStream(
directory + SysProperties.FILE_SEPARATOR + fileName, false);
IOUtils.copy(zipIn, o);
o.close();
} finally {
IOUtils.closeSilently(o);
}
}
zipIn.closeEntry();
}
zipIn.closeEntry();
}
} catch (IOException e) {
throw DbException.convertIOException(e, zipFileName);
} finally {
IOUtils.closeSilently(in);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/RunScript.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.TimeUnit;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
import org.h2.util.IOUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.ScriptReader;
import org.h2.util.StringUtils;
import org.h2.util.Tool;
/**
* Runs a SQL script against a database.
* @h2.resource
*/
public class RunScript extends Tool {
private boolean showResults;
private boolean checkResults;
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-url "<url>"]</td>
* <td>The database URL (jdbc:...)</td></tr>
* <tr><td>[-user <user>]</td>
* <td>The user name (default: sa)</td></tr>
* <tr><td>[-password <pwd>]</td>
* <td>The password</td></tr>
* <tr><td>[-script <file>]</td>
* <td>The script file to run (default: backup.sql)</td></tr>
* <tr><td>[-driver <class>]</td>
* <td>The JDBC driver class to use (not required in most cases)</td></tr>
* <tr><td>[-showResults]</td>
* <td>Show the statements and the results of queries</td></tr>
* <tr><td>[-checkResults]</td>
* <td>Check if the query results match the expected results</td></tr>
* <tr><td>[-continueOnError]</td>
* <td>Continue even if the script contains errors</td></tr>
* <tr><td>[-options ...]</td>
* <td>RUNSCRIPT options (embedded H2; -*Results not supported)</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new RunScript().runTool(args);
}
/**
* Executes the contents of a SQL script file against a database.
* This tool is usually used to create a database from script.
* It can also be used to analyze performance problems by running
* the tool using Java profiler settings such as:
* <pre>
* java -Xrunhprof:cpu=samples,depth=16 ...
* </pre>
* To include local files when using remote databases, use the special
* syntax:
* <pre>
* @INCLUDE fileName
* </pre>
* This syntax is only supported by this tool. Embedded RUNSCRIPT SQL
* statements will be executed by the database.
*
* @param args the command line arguments
*/
@Override
public void runTool(String... args) throws SQLException {
String url = null;
String user = "";
String password = "";
String script = "backup.sql";
String options = null;
boolean continueOnError = false;
boolean showTime = false;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-url")) {
url = args[++i];
} else if (arg.equals("-user")) {
user = args[++i];
} else if (arg.equals("-password")) {
password = args[++i];
} else if (arg.equals("-continueOnError")) {
continueOnError = true;
} else if (arg.equals("-checkResults")) {
checkResults = true;
} else if (arg.equals("-showResults")) {
showResults = true;
} else if (arg.equals("-script")) {
script = args[++i];
} else if (arg.equals("-time")) {
showTime = true;
} else if (arg.equals("-driver")) {
String driver = args[++i];
JdbcUtils.loadUserClass(driver);
} else if (arg.equals("-options")) {
StringBuilder buff = new StringBuilder();
i++;
for (; i < args.length; i++) {
buff.append(' ').append(args[i]);
}
options = buff.toString();
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
if (url == null) {
showUsage();
throw new SQLException("URL not set");
}
long time = System.nanoTime();
if (options != null) {
processRunscript(url, user, password, script, options);
} else {
process(url, user, password, script, null, continueOnError);
}
if (showTime) {
time = System.nanoTime() - time;
out.println("Done in " + TimeUnit.NANOSECONDS.toMillis(time) + " ms");
}
}
/**
* Executes the SQL commands read from the reader against a database.
*
* @param conn the connection to a database
* @param reader the reader
* @return the last result set
*/
public static ResultSet execute(Connection conn, Reader reader)
throws SQLException {
// can not close the statement because we return a result set from it
Statement stat = conn.createStatement();
ResultSet rs = null;
ScriptReader r = new ScriptReader(reader);
while (true) {
String sql = r.readStatement();
if (sql == null) {
break;
}
if (sql.trim().length() == 0) {
continue;
}
boolean resultSet = stat.execute(sql);
if (resultSet) {
if (rs != null) {
rs.close();
rs = null;
}
rs = stat.getResultSet();
}
}
return rs;
}
private void process(Connection conn, String fileName,
boolean continueOnError, Charset charset) throws SQLException,
IOException {
InputStream in = FileUtils.newInputStream(fileName);
String path = FileUtils.getParent(fileName);
try {
in = new BufferedInputStream(in, Constants.IO_BUFFER_SIZE);
Reader reader = new InputStreamReader(in, charset);
process(conn, continueOnError, path, reader, charset);
} finally {
IOUtils.closeSilently(in);
}
}
private void process(Connection conn, boolean continueOnError, String path,
Reader reader, Charset charset) throws SQLException, IOException {
Statement stat = conn.createStatement();
ScriptReader r = new ScriptReader(reader);
while (true) {
String sql = r.readStatement();
if (sql == null) {
break;
}
String trim = sql.trim();
if (trim.length() == 0) {
continue;
}
if (trim.startsWith("@") && StringUtils.toUpperEnglish(trim).
startsWith("@INCLUDE")) {
sql = trim;
sql = sql.substring("@INCLUDE".length()).trim();
if (!FileUtils.isAbsolute(sql)) {
sql = path + SysProperties.FILE_SEPARATOR + sql;
}
process(conn, sql, continueOnError, charset);
} else {
try {
if (showResults && !trim.startsWith("-->")) {
out.print(sql + ";");
}
if (showResults || checkResults) {
boolean query = stat.execute(sql);
if (query) {
ResultSet rs = stat.getResultSet();
int columns = rs.getMetaData().getColumnCount();
StringBuilder buff = new StringBuilder();
while (rs.next()) {
buff.append("\n-->");
for (int i = 0; i < columns; i++) {
String s = rs.getString(i + 1);
if (s != null) {
s = StringUtils.replaceAll(s, "\r\n", "\n");
s = StringUtils.replaceAll(s, "\n", "\n--> ");
s = StringUtils.replaceAll(s, "\r", "\r--> ");
}
buff.append(' ').append(s);
}
}
buff.append("\n;");
String result = buff.toString();
if (showResults) {
out.print(result);
}
if (checkResults) {
String expected = r.readStatement() + ";";
expected = StringUtils.replaceAll(expected, "\r\n", "\n");
expected = StringUtils.replaceAll(expected, "\r", "\n");
if (!expected.equals(result)) {
expected = StringUtils.replaceAll(expected, " ", "+");
result = StringUtils.replaceAll(result, " ", "+");
throw new SQLException(
"Unexpected output for:\n" + sql.trim() +
"\nGot:\n" + result + "\nExpected:\n" + expected);
}
}
}
} else {
stat.execute(sql);
}
} catch (Exception e) {
if (continueOnError) {
e.printStackTrace(out);
} else {
throw DbException.toSQLException(e);
}
}
}
}
}
private static void processRunscript(String url, String user, String password,
String fileName, String options) throws SQLException {
Connection conn = null;
Statement stat = null;
try {
org.h2.Driver.load();
conn = DriverManager.getConnection(url, user, password);
stat = conn.createStatement();
String sql = "RUNSCRIPT FROM '" + fileName + "' " + options;
stat.execute(sql);
} finally {
JdbcUtils.closeSilently(stat);
JdbcUtils.closeSilently(conn);
}
}
/**
* Executes the SQL commands in a script file against a database.
*
* @param url the database URL
* @param user the user name
* @param password the password
* @param fileName the script file
* @param charset the character set or null for UTF-8
* @param continueOnError if execution should be continued if an error
* occurs
*/
public static void execute(String url, String user, String password,
String fileName, Charset charset, boolean continueOnError)
throws SQLException {
new RunScript().process(url, user, password, fileName, charset,
continueOnError);
}
/**
* Executes the SQL commands in a script file against a database.
*
* @param url the database URL
* @param user the user name
* @param password the password
* @param fileName the script file
* @param charset the character set or null for UTF-8
* @param continueOnError if execution should be continued if an error
* occurs
*/
void process(String url, String user, String password,
String fileName, Charset charset,
boolean continueOnError) throws SQLException {
try {
org.h2.Driver.load();
if (charset == null) {
charset = StandardCharsets.UTF_8;
}
try (Connection conn = DriverManager.getConnection(url, user, password)) {
process(conn, fileName, continueOnError, charset);
}
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Script.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils;
import org.h2.util.Tool;
/**
* Creates a SQL script file by extracting the schema and data of a database.
* @h2.resource
*/
public class Script extends Tool {
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-url "<url>"]</td>
* <td>The database URL (jdbc:...)</td></tr>
* <tr><td>[-user <user>]</td>
* <td>The user name (default: sa)</td></tr>
* <tr><td>[-password <pwd>]</td>
* <td>The password</td></tr>
* <tr><td>[-script <file>]</td>
* <td>The target script file name (default: backup.sql)</td></tr>
* <tr><td>[-options ...]</td>
* <td>A list of options (only for embedded H2, see SCRIPT)</td></tr>
* <tr><td>[-quiet]</td>
* <td>Do not print progress information</td></tr>
* </table>
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new Script().runTool(args);
}
@Override
public void runTool(String... args) throws SQLException {
String url = null;
String user = "";
String password = "";
String file = "backup.sql";
String options1 = "";
String options2 = "";
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-url")) {
url = args[++i];
} else if (arg.equals("-user")) {
user = args[++i];
} else if (arg.equals("-password")) {
password = args[++i];
} else if (arg.equals("-script")) {
file = args[++i];
} else if (arg.equals("-options")) {
StringBuilder buff1 = new StringBuilder();
StringBuilder buff2 = new StringBuilder();
i++;
for (; i < args.length; i++) {
String a = args[i];
String upper = StringUtils.toUpperEnglish(a);
if ("SIMPLE".equals(upper) || upper.startsWith("NO") || "DROP".equals(upper)) {
buff1.append(' ');
buff1.append(args[i]);
} else if ("BLOCKSIZE".equals(upper)) {
buff1.append(' ');
buff1.append(args[i]);
i++;
buff1.append(' ');
buff1.append(args[i]);
} else {
buff2.append(' ');
buff2.append(args[i]);
}
}
options1 = buff1.toString();
options2 = buff2.toString();
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
if (url == null) {
showUsage();
throw new SQLException("URL not set");
}
process(url, user, password, file, options1, options2);
}
/**
* Backs up a database to a stream.
*
* @param url the database URL
* @param user the user name
* @param password the password
* @param fileName the target file name
* @param options1 the options before the file name (may be an empty string)
* @param options2 the options after the file name (may be an empty string)
*/
public static void process(String url, String user, String password,
String fileName, String options1, String options2) throws SQLException {
Connection conn = null;
try {
org.h2.Driver.load();
conn = DriverManager.getConnection(url, user, password);
process(conn, fileName, options1, options2);
} finally {
JdbcUtils.closeSilently(conn);
}
}
/**
* Backs up a database to a stream. The stream is not closed.
* The connection is not closed.
*
* @param conn the connection
* @param fileName the target file name
* @param options1 the options before the file name
* @param options2 the options after the file name
*/
public static void process(Connection conn,
String fileName, String options1, String options2) throws SQLException {
try (Statement stat = conn.createStatement()) {
String sql = "SCRIPT " + options1 + " TO '" + fileName + "' " + options2;
stat.execute(sql);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Server.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.net.URI;
import java.sql.Connection;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.server.Service;
import org.h2.server.ShutdownHandler;
import org.h2.server.TcpServer;
import org.h2.server.pg.PgServer;
import org.h2.server.web.WebServer;
import org.h2.util.StringUtils;
import org.h2.util.Tool;
import org.h2.util.Utils;
/**
* Starts the H2 Console (web-) server, TCP, and PG server.
* @h2.resource
*/
public class Server extends Tool implements Runnable, ShutdownHandler {
private final Service service;
private Server web, tcp, pg;
private ShutdownHandler shutdownHandler;
private boolean started;
public Server() {
// nothing to do
this.service = null;
}
/**
* Create a new server for the given service.
*
* @param service the service
* @param args the command line arguments
*/
public Server(Service service, String... args) throws SQLException {
verifyArgs(args);
this.service = service;
try {
service.init(args);
} catch (Exception e) {
throw DbException.toSQLException(e);
}
}
/**
* When running without options, -tcp, -web, -browser and -pg are started.
* <br />
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-web]</td>
* <td>Start the web server with the H2 Console</td></tr>
* <tr><td>[-webAllowOthers]</td>
* <td>Allow other computers to connect - see below</td></tr>
* <tr><td>[-webDaemon]</td>
* <td>Use a daemon thread</td></tr>
* <tr><td>[-webPort <port>]</td>
* <td>The port (default: 8082)</td></tr>
* <tr><td>[-webSSL]</td>
* <td>Use encrypted (HTTPS) connections</td></tr>
* <tr><td>[-browser]</td>
* <td>Start a browser connecting to the web server</td></tr>
* <tr><td>[-tcp]</td>
* <td>Start the TCP server</td></tr>
* <tr><td>[-tcpAllowOthers]</td>
* <td>Allow other computers to connect - see below</td></tr>
* <tr><td>[-tcpDaemon]</td>
* <td>Use a daemon thread</td></tr>
* <tr><td>[-tcpPort <port>]</td>
* <td>The port (default: 9092)</td></tr>
* <tr><td>[-tcpSSL]</td>
* <td>Use encrypted (SSL) connections</td></tr>
* <tr><td>[-tcpPassword <pwd>]</td>
* <td>The password for shutting down a TCP server</td></tr>
* <tr><td>[-tcpShutdown "<url>"]</td>
* <td>Stop the TCP server; example: tcp://localhost</td></tr>
* <tr><td>[-tcpShutdownForce]</td>
* <td>Do not wait until all connections are closed</td></tr>
* <tr><td>[-pg]</td>
* <td>Start the PG server</td></tr>
* <tr><td>[-pgAllowOthers]</td>
* <td>Allow other computers to connect - see below</td></tr>
* <tr><td>[-pgDaemon]</td>
* <td>Use a daemon thread</td></tr>
* <tr><td>[-pgPort <port>]</td>
* <td>The port (default: 5435)</td></tr>
* <tr><td>[-properties "<dir>"]</td>
* <td>Server properties (default: ~, disable: null)</td></tr>
* <tr><td>[-baseDir <dir>]</td>
* <td>The base directory for H2 databases (all servers)</td></tr>
* <tr><td>[-ifExists]</td>
* <td>Only existing databases may be opened (all servers)</td></tr>
* <tr><td>[-trace]</td>
* <td>Print additional trace information (all servers)</td></tr>
* <tr><td>[-key <from> <to>]</td>
* <td>Allows to map a database name to another (all servers)</td></tr>
* </table>
* The options -xAllowOthers are potentially risky.
* <br />
* For details, see Advanced Topics / Protection against Remote Access.
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new Server().runTool(args);
}
private void verifyArgs(String... args) throws SQLException {
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg == null) {
} else if ("-?".equals(arg) || "-help".equals(arg)) {
// ok
} else if (arg.startsWith("-web")) {
if ("-web".equals(arg)) {
// ok
} else if ("-webAllowOthers".equals(arg)) {
// no parameters
} else if ("-webDaemon".equals(arg)) {
// no parameters
} else if ("-webSSL".equals(arg)) {
// no parameters
} else if ("-webPort".equals(arg)) {
i++;
} else {
throwUnsupportedOption(arg);
}
} else if ("-browser".equals(arg)) {
// ok
} else if (arg.startsWith("-tcp")) {
if ("-tcp".equals(arg)) {
// ok
} else if ("-tcpAllowOthers".equals(arg)) {
// no parameters
} else if ("-tcpDaemon".equals(arg)) {
// no parameters
} else if ("-tcpSSL".equals(arg)) {
// no parameters
} else if ("-tcpPort".equals(arg)) {
i++;
} else if ("-tcpPassword".equals(arg)) {
i++;
} else if ("-tcpShutdown".equals(arg)) {
i++;
} else if ("-tcpShutdownForce".equals(arg)) {
// ok
} else {
throwUnsupportedOption(arg);
}
} else if (arg.startsWith("-pg")) {
if ("-pg".equals(arg)) {
// ok
} else if ("-pgAllowOthers".equals(arg)) {
// no parameters
} else if ("-pgDaemon".equals(arg)) {
// no parameters
} else if ("-pgPort".equals(arg)) {
i++;
} else {
throwUnsupportedOption(arg);
}
} else if (arg.startsWith("-ftp")) {
if ("-ftpPort".equals(arg)) {
i++;
} else if ("-ftpDir".equals(arg)) {
i++;
} else if ("-ftpRead".equals(arg)) {
i++;
} else if ("-ftpWrite".equals(arg)) {
i++;
} else if ("-ftpWritePassword".equals(arg)) {
i++;
} else if ("-ftpTask".equals(arg)) {
// no parameters
} else {
throwUnsupportedOption(arg);
}
} else if ("-properties".equals(arg)) {
i++;
} else if ("-trace".equals(arg)) {
// no parameters
} else if ("-ifExists".equals(arg)) {
// no parameters
} else if ("-baseDir".equals(arg)) {
i++;
} else if ("-key".equals(arg)) {
i += 2;
} else if ("-tool".equals(arg)) {
// no parameters
} else {
throwUnsupportedOption(arg);
}
}
}
@Override
public void runTool(String... args) throws SQLException {
boolean tcpStart = false, pgStart = false, webStart = false;
boolean browserStart = false;
boolean tcpShutdown = false, tcpShutdownForce = false;
String tcpPassword = "";
String tcpShutdownServer = "";
boolean startDefaultServers = true;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg == null) {
} else if ("-?".equals(arg) || "-help".equals(arg)) {
showUsage();
return;
} else if (arg.startsWith("-web")) {
if ("-web".equals(arg)) {
startDefaultServers = false;
webStart = true;
} else if ("-webAllowOthers".equals(arg)) {
// no parameters
} else if ("-webDaemon".equals(arg)) {
// no parameters
} else if ("-webSSL".equals(arg)) {
// no parameters
} else if ("-webPort".equals(arg)) {
i++;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
} else if ("-browser".equals(arg)) {
startDefaultServers = false;
browserStart = true;
} else if (arg.startsWith("-tcp")) {
if ("-tcp".equals(arg)) {
startDefaultServers = false;
tcpStart = true;
} else if ("-tcpAllowOthers".equals(arg)) {
// no parameters
} else if ("-tcpDaemon".equals(arg)) {
// no parameters
} else if ("-tcpSSL".equals(arg)) {
// no parameters
} else if ("-tcpPort".equals(arg)) {
i++;
} else if ("-tcpPassword".equals(arg)) {
tcpPassword = args[++i];
} else if ("-tcpShutdown".equals(arg)) {
startDefaultServers = false;
tcpShutdown = true;
tcpShutdownServer = args[++i];
} else if ("-tcpShutdownForce".equals(arg)) {
tcpShutdownForce = true;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
} else if (arg.startsWith("-pg")) {
if ("-pg".equals(arg)) {
startDefaultServers = false;
pgStart = true;
} else if ("-pgAllowOthers".equals(arg)) {
// no parameters
} else if ("-pgDaemon".equals(arg)) {
// no parameters
} else if ("-pgPort".equals(arg)) {
i++;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
} else if ("-properties".equals(arg)) {
i++;
} else if ("-trace".equals(arg)) {
// no parameters
} else if ("-ifExists".equals(arg)) {
// no parameters
} else if ("-baseDir".equals(arg)) {
i++;
} else if ("-key".equals(arg)) {
i += 2;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
verifyArgs(args);
if (startDefaultServers) {
tcpStart = true;
pgStart = true;
webStart = true;
browserStart = true;
}
// TODO server: maybe use one single properties file?
if (tcpShutdown) {
out.println("Shutting down TCP Server at " + tcpShutdownServer);
shutdownTcpServer(tcpShutdownServer, tcpPassword,
tcpShutdownForce, false);
}
try {
if (tcpStart) {
tcp = createTcpServer(args);
tcp.start();
out.println(tcp.getStatus());
tcp.setShutdownHandler(this);
}
if (pgStart) {
pg = createPgServer(args);
pg.start();
out.println(pg.getStatus());
}
if (webStart) {
web = createWebServer(args);
web.setShutdownHandler(this);
SQLException result = null;
try {
web.start();
} catch (Exception e) {
result = DbException.toSQLException(e);
}
out.println(web.getStatus());
// start browser in any case (even if the server is already
// running) because some people don't look at the output, but
// are wondering why nothing happens
if (browserStart) {
try {
openBrowser(web.getURL());
} catch (Exception e) {
out.println(e.getMessage());
}
}
if (result != null) {
throw result;
}
} else if (browserStart) {
out.println("The browser can only start if a web server is started (-web)");
}
} catch (SQLException e) {
stopAll();
throw e;
}
}
/**
* Shutdown one or all TCP server. If force is set to false, the server will
* not allow new connections, but not kill existing connections, instead it
* will stop if the last connection is closed. If force is set to true,
* existing connections are killed. After calling the method with
* force=false, it is not possible to call it again with force=true because
* new connections are not allowed. Example:
*
* <pre>
* Server.shutdownTcpServer("tcp://localhost:9094",
* password, true, false);
* </pre>
*
* @param url example: tcp://localhost:9094
* @param password the password to use ("" for no password)
* @param force the shutdown (don't wait)
* @param all whether all TCP servers that are running in the JVM should be
* stopped
*/
public static void shutdownTcpServer(String url, String password,
boolean force, boolean all) throws SQLException {
TcpServer.shutdown(url, password, force, all);
}
/**
* Get the status of this server.
*
* @return the status
*/
public String getStatus() {
StringBuilder buff = new StringBuilder();
if (!started) {
buff.append("Not started");
} else if (isRunning(false)) {
buff.append(service.getType()).
append(" server running at ").
append(service.getURL()).
append(" (");
if (service.getAllowOthers()) {
buff.append("others can connect");
} else {
buff.append("only local connections");
}
buff.append(')');
} else {
buff.append("The ").
append(service.getType()).
append(" server could not be started. " +
"Possible cause: another server is already running at ").
append(service.getURL());
}
return buff.toString();
}
/**
* Create a new web server, but does not start it yet. Example:
*
* <pre>
* Server server = Server.createWebServer("-trace").start();
* </pre>
* Supported options are:
* -webPort, -webSSL, -webAllowOthers, -webDaemon,
* -trace, -ifExists, -baseDir, -properties.
* See the main method for details.
*
* @param args the argument list
* @return the server
*/
public static Server createWebServer(String... args) throws SQLException {
WebServer service = new WebServer();
Server server = new Server(service, args);
service.setShutdownHandler(server);
return server;
}
/**
* Create a new TCP server, but does not start it yet. Example:
*
* <pre>
* Server server = Server.createTcpServer(
* "-tcpPort", "9123", "-tcpAllowOthers").start();
* </pre>
* Supported options are:
* -tcpPort, -tcpSSL, -tcpPassword, -tcpAllowOthers, -tcpDaemon,
* -trace, -ifExists, -baseDir, -key.
* See the main method for details.
* <p>
* If no port is specified, the default port is used if possible,
* and if this port is already used, a random port is used.
* Use getPort() or getURL() after starting to retrieve the port.
* </p>
*
* @param args the argument list
* @return the server
*/
public static Server createTcpServer(String... args) throws SQLException {
TcpServer service = new TcpServer();
Server server = new Server(service, args);
service.setShutdownHandler(server);
return server;
}
/**
* Create a new PG server, but does not start it yet.
* Example:
* <pre>
* Server server =
* Server.createPgServer("-pgAllowOthers").start();
* </pre>
* Supported options are:
* -pgPort, -pgAllowOthers, -pgDaemon,
* -trace, -ifExists, -baseDir, -key.
* See the main method for details.
* <p>
* If no port is specified, the default port is used if possible,
* and if this port is already used, a random port is used.
* Use getPort() or getURL() after starting to retrieve the port.
* </p>
*
* @param args the argument list
* @return the server
*/
public static Server createPgServer(String... args) throws SQLException {
return new Server(new PgServer(), args);
}
/**
* Tries to start the server.
* @return the server if successful
* @throws SQLException if the server could not be started
*/
public Server start() throws SQLException {
try {
started = true;
service.start();
String name = service.getName() + " (" + service.getURL() + ")";
Thread t = new Thread(this, name);
t.setDaemon(service.isDaemon());
t.start();
for (int i = 1; i < 64; i += i) {
wait(i);
if (isRunning(false)) {
return this;
}
}
if (isRunning(true)) {
return this;
}
throw DbException.get(ErrorCode.EXCEPTION_OPENING_PORT_2,
name, "timeout; " +
"please check your network configuration, specially the file /etc/hosts");
} catch (DbException e) {
throw DbException.toSQLException(e);
}
}
private static void wait(int i) {
try {
// sleep at most 4096 ms
long sleep = (long) i * (long) i;
Thread.sleep(sleep);
} catch (InterruptedException e) {
// ignore
}
}
private void stopAll() {
Server s = web;
if (s != null && s.isRunning(false)) {
s.stop();
web = null;
}
s = tcp;
if (s != null && s.isRunning(false)) {
s.stop();
tcp = null;
}
s = pg;
if (s != null && s.isRunning(false)) {
s.stop();
pg = null;
}
}
/**
* Checks if the server is running.
*
* @param traceError if errors should be written
* @return if the server is running
*/
public boolean isRunning(boolean traceError) {
return service.isRunning(traceError);
}
/**
* Stops the server.
*/
public void stop() {
started = false;
if (service != null) {
service.stop();
}
}
/**
* Gets the URL of this server.
*
* @return the url
*/
public String getURL() {
return service.getURL();
}
/**
* Gets the port this server is listening on.
*
* @return the port
*/
public int getPort() {
return service.getPort();
}
/**
* INTERNAL
*/
@Override
public void run() {
try {
service.listen();
} catch (Exception e) {
DbException.traceThrowable(e);
}
}
/**
* INTERNAL
*/
public void setShutdownHandler(ShutdownHandler shutdownHandler) {
this.shutdownHandler = shutdownHandler;
}
/**
* INTERNAL
*/
@Override
public void shutdown() {
if (shutdownHandler != null) {
shutdownHandler.shutdown();
} else {
stopAll();
}
}
/**
* Get the service attached to this server.
*
* @return the service
*/
public Service getService() {
return service;
}
/**
* Open a new browser tab or window with the given URL.
*
* @param url the URL to open
*/
public static void openBrowser(String url) throws Exception {
try {
String osName = StringUtils.toLowerEnglish(
Utils.getProperty("os.name", "linux"));
Runtime rt = Runtime.getRuntime();
String browser = Utils.getProperty(SysProperties.H2_BROWSER, null);
if (browser == null) {
// under Linux, this will point to the default system browser
try {
browser = System.getenv("BROWSER");
} catch (SecurityException se) {
// ignore
}
}
if (browser != null) {
if (browser.startsWith("call:")) {
browser = browser.substring("call:".length());
Utils.callStaticMethod(browser, url);
} else if (browser.contains("%url")) {
String[] args = StringUtils.arraySplit(browser, ',', false);
for (int i = 0; i < args.length; i++) {
args[i] = StringUtils.replaceAll(args[i], "%url", url);
}
rt.exec(args);
} else if (osName.contains("windows")) {
rt.exec(new String[] { "cmd.exe", "/C", browser, url });
} else {
rt.exec(new String[] { browser, url });
}
return;
}
try {
Class<?> desktopClass = Class.forName("java.awt.Desktop");
// Desktop.isDesktopSupported()
Boolean supported = (Boolean) desktopClass.
getMethod("isDesktopSupported").
invoke(null, new Object[0]);
URI uri = new URI(url);
if (supported) {
// Desktop.getDesktop();
Object desktop = desktopClass.getMethod("getDesktop").
invoke(null);
// desktop.browse(uri);
desktopClass.getMethod("browse", URI.class).
invoke(desktop, uri);
return;
}
} catch (Exception e) {
// ignore
}
if (osName.contains("windows")) {
rt.exec(new String[] { "rundll32", "url.dll,FileProtocolHandler", url });
} else if (osName.contains("mac") || osName.contains("darwin")) {
// Mac OS: to open a page with Safari, use "open -a Safari"
Runtime.getRuntime().exec(new String[] { "open", url });
} else {
String[] browsers = { "xdg-open", "chromium", "google-chrome",
"firefox", "mozilla-firefox", "mozilla", "konqueror",
"netscape", "opera", "midori" };
boolean ok = false;
for (String b : browsers) {
try {
rt.exec(new String[] { b, url });
ok = true;
break;
} catch (Exception e) {
// ignore and try the next
}
}
if (!ok) {
// No success in detection.
throw new Exception(
"Browser detection failed and system property " +
SysProperties.H2_BROWSER + " not set");
}
}
} catch (Exception e) {
throw new Exception(
"Failed to start a browser to open the URL " +
url + ": " + e.getMessage());
}
}
/**
* Start a web server and a browser that uses the given connection. The
* current transaction is preserved. This is specially useful to manually
* inspect the database when debugging. This method return as soon as the
* user has disconnected.
*
* @param conn the database connection (the database must be open)
*/
public static void startWebServer(Connection conn) throws SQLException {
startWebServer(conn, false);
}
/**
* Start a web server and a browser that uses the given connection. The
* current transaction is preserved. This is specially useful to manually
* inspect the database when debugging. This method return as soon as the
* user has disconnected.
*
* @param conn the database connection (the database must be open)
* @param ignoreProperties if {@code true} properties from
* {@code .h2.server.properties} will be ignored
*/
public static void startWebServer(Connection conn, boolean ignoreProperties) throws SQLException {
WebServer webServer = new WebServer();
String[] args;
if (ignoreProperties) {
args = new String[] { "-webPort", "0", "-properties", "null"};
} else {
args = new String[] { "-webPort", "0" };
}
Server web = new Server(webServer, args);
web.start();
Server server = new Server();
server.web = web;
webServer.setShutdownHandler(server);
String url = webServer.addSession(conn);
try {
Server.openBrowser(url);
while (!webServer.isStopped()) {
Thread.sleep(1000);
}
} catch (Exception e) {
// ignore
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/Shell.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.h2.engine.Constants;
import org.h2.server.web.ConnectionInfo;
import org.h2.util.JdbcUtils;
import org.h2.util.New;
import org.h2.util.ScriptReader;
import org.h2.util.SortedProperties;
import org.h2.util.StringUtils;
import org.h2.util.Tool;
import org.h2.util.Utils;
/**
* Interactive command line tool to access a database using JDBC.
* @h2.resource
*/
public class Shell extends Tool implements Runnable {
private static final int MAX_ROW_BUFFER = 5000;
private static final int HISTORY_COUNT = 20;
// Windows: '\u00b3';
private static final char BOX_VERTICAL = '|';
private PrintStream err = System.err;
private InputStream in = System.in;
private BufferedReader reader;
private Connection conn;
private Statement stat;
private boolean listMode;
private int maxColumnSize = 100;
private final ArrayList<String> history = New.arrayList();
private boolean stopHide;
private String serverPropertiesDir = Constants.SERVER_PROPERTIES_DIR;
/**
* Options are case sensitive. Supported options are:
* <table>
* <tr><td>[-help] or [-?]</td>
* <td>Print the list of options</td></tr>
* <tr><td>[-url "<url>"]</td>
* <td>The database URL (jdbc:h2:...)</td></tr>
* <tr><td>[-user <user>]</td>
* <td>The user name</td></tr>
* <tr><td>[-password <pwd>]</td>
* <td>The password</td></tr>
* <tr><td>[-driver <class>]</td>
* <td>The JDBC driver class to use (not required in most cases)</td></tr>
* <tr><td>[-sql "<statements>"]</td>
* <td>Execute the SQL statements and exit</td></tr>
* <tr><td>[-properties "<dir>"]</td>
* <td>Load the server properties from this directory</td></tr>
* </table>
* If special characters don't work as expected, you may need to use
* -Dfile.encoding=UTF-8 (Mac OS X) or CP850 (Windows).
* @h2.resource
*
* @param args the command line arguments
*/
public static void main(String... args) throws SQLException {
new Shell().runTool(args);
}
/**
* Sets the standard error stream.
*
* @param err the new standard error stream
*/
public void setErr(PrintStream err) {
this.err = err;
}
/**
* Redirects the standard input. By default, System.in is used.
*
* @param in the input stream to use
*/
public void setIn(InputStream in) {
this.in = in;
}
/**
* Redirects the standard input. By default, System.in is used.
*
* @param reader the input stream reader to use
*/
public void setInReader(BufferedReader reader) {
this.reader = reader;
}
/**
* Run the shell tool with the given command line settings.
*
* @param args the command line settings
*/
@Override
public void runTool(String... args) throws SQLException {
String url = null;
String user = "";
String password = "";
String sql = null;
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg.equals("-url")) {
url = args[++i];
} else if (arg.equals("-user")) {
user = args[++i];
} else if (arg.equals("-password")) {
password = args[++i];
} else if (arg.equals("-driver")) {
String driver = args[++i];
JdbcUtils.loadUserClass(driver);
} else if (arg.equals("-sql")) {
sql = args[++i];
} else if (arg.equals("-properties")) {
serverPropertiesDir = args[++i];
} else if (arg.equals("-help") || arg.equals("-?")) {
showUsage();
return;
} else if (arg.equals("-list")) {
listMode = true;
} else {
showUsageAndThrowUnsupportedOption(arg);
}
}
if (url != null) {
org.h2.Driver.load();
conn = DriverManager.getConnection(url, user, password);
stat = conn.createStatement();
}
if (sql == null) {
promptLoop();
} else {
ScriptReader r = new ScriptReader(new StringReader(sql));
while (true) {
String s = r.readStatement();
if (s == null) {
break;
}
execute(s);
}
if (conn != null) {
conn.close();
}
}
}
/**
* Run the shell tool with the given connection and command line settings.
* The connection will be closed when the shell exits.
* This is primary used to integrate the Shell into another application.
* <p>
* Note: using the "-url" option in {@code args} doesn't make much sense
* since it will override the {@code conn} parameter.
* </p>
*
* @param conn the connection
* @param args the command line settings
*/
public void runTool(Connection conn, String... args) throws SQLException {
this.conn = conn;
this.stat = conn.createStatement();
runTool(args);
}
private void showHelp() {
println("Commands are case insensitive; SQL statements end with ';'");
println("help or ? Display this help");
println("list Toggle result list / stack trace mode");
println("maxwidth Set maximum column width (default is 100)");
println("autocommit Enable or disable autocommit");
println("history Show the last 20 statements");
println("quit or exit Close the connection and exit");
println("");
}
private void promptLoop() {
println("");
println("Welcome to H2 Shell " + Constants.getFullVersion());
println("Exit with Ctrl+C");
if (conn != null) {
showHelp();
}
String statement = null;
if (reader == null) {
reader = new BufferedReader(new InputStreamReader(in));
}
while (true) {
try {
if (conn == null) {
connect();
showHelp();
}
if (statement == null) {
print("sql> ");
} else {
print("...> ");
}
String line = readLine();
if (line == null) {
break;
}
String trimmed = line.trim();
if (trimmed.length() == 0) {
continue;
}
boolean end = trimmed.endsWith(";");
if (end) {
line = line.substring(0, line.lastIndexOf(';'));
trimmed = trimmed.substring(0, trimmed.length() - 1);
}
String lower = StringUtils.toLowerEnglish(trimmed);
if ("exit".equals(lower) || "quit".equals(lower)) {
break;
} else if ("help".equals(lower) || "?".equals(lower)) {
showHelp();
} else if ("list".equals(lower)) {
listMode = !listMode;
println("Result list mode is now " + (listMode ? "on" : "off"));
} else if ("history".equals(lower)) {
for (int i = 0, size = history.size(); i < size; i++) {
String s = history.get(i);
s = s.replace('\n', ' ').replace('\r', ' ');
println("#" + (1 + i) + ": " + s);
}
if (!history.isEmpty()) {
println("To re-run a statement, type the number and press and enter");
} else {
println("No history");
}
} else if (lower.startsWith("autocommit")) {
lower = lower.substring("autocommit".length()).trim();
if ("true".equals(lower)) {
conn.setAutoCommit(true);
} else if ("false".equals(lower)) {
conn.setAutoCommit(false);
} else {
println("Usage: autocommit [true|false]");
}
println("Autocommit is now " + conn.getAutoCommit());
} else if (lower.startsWith("maxwidth")) {
lower = lower.substring("maxwidth".length()).trim();
try {
maxColumnSize = Integer.parseInt(lower);
} catch (NumberFormatException e) {
println("Usage: maxwidth <integer value>");
}
println("Maximum column width is now " + maxColumnSize);
} else {
boolean addToHistory = true;
if (statement == null) {
if (StringUtils.isNumber(line)) {
int pos = Integer.parseInt(line);
if (pos == 0 || pos > history.size()) {
println("Not found");
} else {
statement = history.get(pos - 1);
addToHistory = false;
println(statement);
end = true;
}
} else {
statement = line;
}
} else {
statement += "\n" + line;
}
if (end) {
if (addToHistory) {
history.add(0, statement);
if (history.size() > HISTORY_COUNT) {
history.remove(HISTORY_COUNT);
}
}
execute(statement);
statement = null;
}
}
} catch (SQLException e) {
println("SQL Exception: " + e.getMessage());
statement = null;
} catch (IOException e) {
println(e.getMessage());
break;
} catch (Exception e) {
println("Exception: " + e.toString());
e.printStackTrace(err);
break;
}
}
if (conn != null) {
try {
conn.close();
println("Connection closed");
} catch (SQLException e) {
println("SQL Exception: " + e.getMessage());
e.printStackTrace(err);
}
}
}
private void connect() throws IOException, SQLException {
String url = "jdbc:h2:~/test";
String user = "";
String driver = null;
try {
Properties prop;
if ("null".equals(serverPropertiesDir)) {
prop = new Properties();
} else {
prop = SortedProperties.loadProperties(
serverPropertiesDir + "/" + Constants.SERVER_PROPERTIES_NAME);
}
String data = null;
boolean found = false;
for (int i = 0;; i++) {
String d = prop.getProperty(String.valueOf(i));
if (d == null) {
break;
}
found = true;
data = d;
}
if (found) {
ConnectionInfo info = new ConnectionInfo(data);
url = info.url;
user = info.user;
driver = info.driver;
}
} catch (IOException e) {
// ignore
}
println("[Enter] " + url);
print("URL ");
url = readLine(url).trim();
if (driver == null) {
driver = JdbcUtils.getDriver(url);
}
if (driver != null) {
println("[Enter] " + driver);
}
print("Driver ");
driver = readLine(driver).trim();
println("[Enter] " + user);
print("User ");
user = readLine(user);
println("[Enter] Hide");
print("Password ");
String password = readLine();
if (password.length() == 0) {
password = readPassword();
}
conn = JdbcUtils.getConnection(driver, url, user, password);
stat = conn.createStatement();
println("Connected");
}
/**
* Print the string without newline, and flush.
*
* @param s the string to print
*/
protected void print(String s) {
out.print(s);
out.flush();
}
private void println(String s) {
out.println(s);
out.flush();
}
private String readPassword() throws IOException {
try {
Object console = Utils.callStaticMethod("java.lang.System.console");
print("Password ");
char[] password = (char[]) Utils.callMethod(console, "readPassword");
return password == null ? null : new String(password);
} catch (Exception e) {
// ignore, use the default solution
}
Thread passwordHider = new Thread(this, "Password hider");
stopHide = false;
passwordHider.start();
print("Password > ");
String p = readLine();
stopHide = true;
try {
passwordHider.join();
} catch (InterruptedException e) {
// ignore
}
print("\b\b");
return p;
}
/**
* INTERNAL.
* Hides the password by repeatedly printing
* backspace, backspace, >, <.
*/
@Override
public void run() {
while (!stopHide) {
print("\b\b><");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// ignore
}
}
}
private String readLine(String defaultValue) throws IOException {
String s = readLine();
return s.length() == 0 ? defaultValue : s;
}
private String readLine() throws IOException {
String line = reader.readLine();
if (line == null) {
throw new IOException("Aborted");
}
return line;
}
private void execute(String sql) {
if (sql.trim().length() == 0) {
return;
}
long time = System.nanoTime();
try {
ResultSet rs = null;
try {
if (stat.execute(sql)) {
rs = stat.getResultSet();
int rowCount = printResult(rs, listMode);
time = System.nanoTime() - time;
println("(" + rowCount + (rowCount == 1 ?
" row, " : " rows, ") + TimeUnit.NANOSECONDS.toMillis(time) + " ms)");
} else {
int updateCount = stat.getUpdateCount();
time = System.nanoTime() - time;
println("(Update count: " + updateCount + ", " +
TimeUnit.NANOSECONDS.toMillis(time) + " ms)");
}
} finally {
JdbcUtils.closeSilently(rs);
}
} catch (SQLException e) {
println("Error: " + e.toString());
if (listMode) {
e.printStackTrace(err);
}
}
}
private int printResult(ResultSet rs, boolean asList) throws SQLException {
if (asList) {
return printResultAsList(rs);
}
return printResultAsTable(rs);
}
private int printResultAsTable(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int len = meta.getColumnCount();
boolean truncated = false;
ArrayList<String[]> rows = New.arrayList();
// buffer the header
String[] columns = new String[len];
for (int i = 0; i < len; i++) {
String s = meta.getColumnLabel(i + 1);
columns[i] = s == null ? "" : s;
}
rows.add(columns);
int rowCount = 0;
while (rs.next()) {
rowCount++;
truncated |= loadRow(rs, len, rows);
if (rowCount > MAX_ROW_BUFFER) {
printRows(rows, len);
rows.clear();
}
}
printRows(rows, len);
rows.clear();
if (truncated) {
println("(data is partially truncated)");
}
return rowCount;
}
private boolean loadRow(ResultSet rs, int len, ArrayList<String[]> rows)
throws SQLException {
boolean truncated = false;
String[] row = new String[len];
for (int i = 0; i < len; i++) {
String s = rs.getString(i + 1);
if (s == null) {
s = "null";
}
// only truncate if more than one column
if (len > 1 && s.length() > maxColumnSize) {
s = s.substring(0, maxColumnSize);
truncated = true;
}
row[i] = s;
}
rows.add(row);
return truncated;
}
private int[] printRows(ArrayList<String[]> rows, int len) {
int[] columnSizes = new int[len];
for (int i = 0; i < len; i++) {
int max = 0;
for (String[] row : rows) {
max = Math.max(max, row[i].length());
}
if (len > 1) {
Math.min(maxColumnSize, max);
}
columnSizes[i] = max;
}
for (String[] row : rows) {
StringBuilder buff = new StringBuilder();
for (int i = 0; i < len; i++) {
if (i > 0) {
buff.append(' ').append(BOX_VERTICAL).append(' ');
}
String s = row[i];
buff.append(s);
if (i < len - 1) {
for (int j = s.length(); j < columnSizes[i]; j++) {
buff.append(' ');
}
}
}
println(buff.toString());
}
return columnSizes;
}
private int printResultAsList(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int longestLabel = 0;
int len = meta.getColumnCount();
String[] columns = new String[len];
for (int i = 0; i < len; i++) {
String s = meta.getColumnLabel(i + 1);
columns[i] = s;
longestLabel = Math.max(longestLabel, s.length());
}
StringBuilder buff = new StringBuilder();
int rowCount = 0;
while (rs.next()) {
rowCount++;
buff.setLength(0);
if (rowCount > 1) {
println("");
}
for (int i = 0; i < len; i++) {
if (i > 0) {
buff.append('\n');
}
String label = columns[i];
buff.append(label);
for (int j = label.length(); j < longestLabel; j++) {
buff.append(' ');
}
buff.append(": ").append(rs.getString(i + 1));
}
println(buff.toString());
}
if (rowCount == 0) {
for (int i = 0; i < len; i++) {
if (i > 0) {
buff.append('\n');
}
String label = columns[i];
buff.append(label);
}
println(buff.toString());
}
return rowCount;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/SimpleResultSet.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;
import org.h2.api.ErrorCode;
import org.h2.jdbc.JdbcResultSetBackwardsCompat;
import org.h2.message.DbException;
import org.h2.util.Bits;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.Utils;
import org.h2.value.DataType;
/**
* This class is a simple result set and meta data implementation.
* It can be used in Java functions that return a result set.
* Only the most basic methods are implemented, the others throw an exception.
* This implementation is standalone, and only relies on standard classes.
* It can be extended easily if required.
*
* An application can create a result set using the following code:
*
* <pre>
* SimpleResultSet rs = new SimpleResultSet();
* rs.addColumn("ID", Types.INTEGER, 10, 0);
* rs.addColumn("NAME", Types.VARCHAR, 255, 0);
* rs.addRow(0, "Hello" });
* rs.addRow(1, "World" });
* </pre>
*
*/
public class SimpleResultSet implements ResultSet, ResultSetMetaData,
JdbcResultSetBackwardsCompat {
private ArrayList<Object[]> rows;
private Object[] currentRow;
private int rowId = -1;
private boolean wasNull;
private SimpleRowSource source;
private ArrayList<Column> columns = New.arrayList();
private boolean autoClose = true;
/**
* This constructor is used if the result set is later populated with
* addRow.
*/
public SimpleResultSet() {
rows = New.arrayList();
}
/**
* This constructor is used if the result set should retrieve the rows using
* the specified row source object.
*
* @param source the row source
*/
public SimpleResultSet(SimpleRowSource source) {
this.source = source;
}
/**
* Adds a column to the result set.
* All columns must be added before adding rows.
* This method uses the default SQL type names.
*
* @param name null is replaced with C1, C2,...
* @param sqlType the value returned in getColumnType(..)
* @param precision the precision
* @param scale the scale
*/
public void addColumn(String name, int sqlType, int precision, int scale) {
int valueType = DataType.convertSQLTypeToValueType(sqlType);
addColumn(name, sqlType, DataType.getDataType(valueType).name,
precision, scale);
}
/**
* Adds a column to the result set.
* All columns must be added before adding rows.
*
* @param name null is replaced with C1, C2,...
* @param sqlType the value returned in getColumnType(..)
* @param sqlTypeName the type name return in getColumnTypeName(..)
* @param precision the precision
* @param scale the scale
*/
public void addColumn(String name, int sqlType, String sqlTypeName,
int precision, int scale) {
if (rows != null && !rows.isEmpty()) {
throw new IllegalStateException(
"Cannot add a column after adding rows");
}
if (name == null) {
name = "C" + (columns.size() + 1);
}
Column column = new Column();
column.name = name;
column.sqlType = sqlType;
column.precision = precision;
column.scale = scale;
column.sqlTypeName = sqlTypeName;
columns.add(column);
}
/**
* Add a new row to the result set.
* Do not use this method when using a RowSource.
*
* @param row the row as an array of objects
*/
public void addRow(Object... row) {
if (rows == null) {
throw new IllegalStateException(
"Cannot add a row when using RowSource");
}
rows.add(row);
}
/**
* Returns ResultSet.CONCUR_READ_ONLY.
*
* @return CONCUR_READ_ONLY
*/
@Override
public int getConcurrency() {
return ResultSet.CONCUR_READ_ONLY;
}
/**
* Returns ResultSet.FETCH_FORWARD.
*
* @return FETCH_FORWARD
*/
@Override
public int getFetchDirection() {
return ResultSet.FETCH_FORWARD;
}
/**
* Returns 0.
*
* @return 0
*/
@Override
public int getFetchSize() {
return 0;
}
/**
* Returns the row number (1, 2,...) or 0 for no row.
*
* @return 0
*/
@Override
public int getRow() {
return currentRow == null ? 0 : rowId + 1;
}
/**
* Returns the result set type. This is ResultSet.TYPE_FORWARD_ONLY for
* auto-close result sets, and ResultSet.TYPE_SCROLL_INSENSITIVE for others.
*
* @return TYPE_FORWARD_ONLY or TYPE_SCROLL_INSENSITIVE
*/
@Override
public int getType() {
if (autoClose) {
return ResultSet.TYPE_FORWARD_ONLY;
}
return ResultSet.TYPE_SCROLL_INSENSITIVE;
}
/**
* Closes the result set and releases the resources.
*/
@Override
public void close() {
currentRow = null;
rows = null;
columns = null;
rowId = -1;
if (source != null) {
source.close();
source = null;
}
}
/**
* Moves the cursor to the next row of the result set.
*
* @return true if successful, false if there are no more rows
*/
@Override
public boolean next() throws SQLException {
if (source != null) {
rowId++;
currentRow = source.readRow();
if (currentRow != null) {
return true;
}
} else if (rows != null && rowId < rows.size()) {
rowId++;
if (rowId < rows.size()) {
currentRow = rows.get(rowId);
return true;
}
currentRow = null;
}
if (autoClose) {
close();
}
return false;
}
/**
* Moves the current position to before the first row, that means the result
* set is reset.
*/
@Override
public void beforeFirst() throws SQLException {
if (autoClose) {
throw DbException.get(ErrorCode.RESULT_SET_NOT_SCROLLABLE);
}
rowId = -1;
if (source != null) {
source.reset();
}
}
/**
* Returns whether the last column accessed was null.
*
* @return true if the last column accessed was null
*/
@Override
public boolean wasNull() {
return wasNull;
}
/**
* Searches for a specific column in the result set. A case-insensitive
* search is made.
*
* @param columnLabel the column label
* @return the column index (1,2,...)
* @throws SQLException if the column is not found or if the result set is
* closed
*/
@Override
public int findColumn(String columnLabel) throws SQLException {
if (columnLabel != null && columns != null) {
for (int i = 0, size = columns.size(); i < size; i++) {
if (columnLabel.equalsIgnoreCase(getColumn(i).name)) {
return i + 1;
}
}
}
throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, columnLabel)
.getSQLException();
}
/**
* Returns a reference to itself.
*
* @return this
*/
@Override
public ResultSetMetaData getMetaData() {
return this;
}
/**
* Returns null.
*
* @return null
*/
@Override
public SQLWarning getWarnings() {
return null;
}
/**
* Returns null.
*
* @return null
*/
@Override
public Statement getStatement() {
return null;
}
/**
* INTERNAL
*/
@Override
public void clearWarnings() {
// nothing to do
}
// ---- get ---------------------------------------------
/**
* Returns the value as a java.sql.Array.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Array getArray(int columnIndex) throws SQLException {
Object[] o = (Object[]) get(columnIndex);
return o == null ? null : new SimpleArray(o);
}
/**
* Returns the value as a java.sql.Array.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Array getArray(String columnLabel) throws SQLException {
return getArray(findColumn(columnLabel));
}
/**
* INTERNAL
*/
@Override
public InputStream getAsciiStream(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public InputStream getAsciiStream(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
/**
* Returns the value as a java.math.BigDecimal.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o != null && !(o instanceof BigDecimal)) {
o = new BigDecimal(o.toString());
}
return (BigDecimal) o;
}
/**
* Returns the value as a java.math.BigDecimal.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public BigDecimal getBigDecimal(String columnLabel) throws SQLException {
return getBigDecimal(findColumn(columnLabel));
}
/**
* @deprecated INTERNAL
*/
@Deprecated
@Override
public BigDecimal getBigDecimal(int columnIndex, int scale)
throws SQLException {
throw getUnsupportedException();
}
/**
* @deprecated INTERNAL
*/
@Deprecated
@Override
public BigDecimal getBigDecimal(String columnLabel, int scale)
throws SQLException {
throw getUnsupportedException();
}
/**
* Returns the value as a java.io.InputStream.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public InputStream getBinaryStream(int columnIndex) throws SQLException {
return asInputStream(get(columnIndex));
}
private static InputStream asInputStream(Object o) throws SQLException {
if (o == null) {
return null;
} else if (o instanceof Blob) {
return ((Blob) o).getBinaryStream();
}
return (InputStream) o;
}
/**
* Returns the value as a java.io.InputStream.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public InputStream getBinaryStream(String columnLabel) throws SQLException {
return getBinaryStream(findColumn(columnLabel));
}
/**
* Returns the value as a java.sql.Blob.
* This is only supported if the
* result set was created using a Blob object.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Blob getBlob(int columnIndex) throws SQLException {
return (Blob) get(columnIndex);
}
/**
* Returns the value as a java.sql.Blob.
* This is only supported if the
* result set was created using a Blob object.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Blob getBlob(String columnLabel) throws SQLException {
return getBlob(findColumn(columnLabel));
}
/**
* Returns the value as a boolean.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public boolean getBoolean(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o == null) {
return false;
}
if (o instanceof Boolean) {
return (Boolean) o;
}
if (o instanceof Number) {
Number n = (Number) o;
if (n instanceof Double || n instanceof Float) {
return n.doubleValue() != 0;
}
if (n instanceof BigDecimal) {
return ((BigDecimal) n).signum() != 0;
}
if (n instanceof BigInteger) {
return ((BigInteger) n).signum() != 0;
}
return n.longValue() != 0;
}
return Utils.parseBoolean(o.toString(), false, true);
}
/**
* Returns the value as a boolean.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public boolean getBoolean(String columnLabel) throws SQLException {
return getBoolean(findColumn(columnLabel));
}
/**
* Returns the value as a byte.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public byte getByte(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o != null && !(o instanceof Number)) {
o = Byte.decode(o.toString());
}
return o == null ? 0 : ((Number) o).byteValue();
}
/**
* Returns the value as a byte.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public byte getByte(String columnLabel) throws SQLException {
return getByte(findColumn(columnLabel));
}
/**
* Returns the value as a byte array.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public byte[] getBytes(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o == null || o instanceof byte[]) {
return (byte[]) o;
}
if (o instanceof UUID) {
return Bits.uuidToBytes((UUID) o);
}
return JdbcUtils.serialize(o, null);
}
/**
* Returns the value as a byte array.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public byte[] getBytes(String columnLabel) throws SQLException {
return getBytes(findColumn(columnLabel));
}
/**
* Returns the value as a java.io.Reader.
* This is only supported if the
* result set was created using a Clob or Reader object.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Reader getCharacterStream(int columnIndex) throws SQLException {
return asReader(get(columnIndex));
}
private static Reader asReader(Object o) throws SQLException {
if (o == null) {
return null;
} else if (o instanceof Clob) {
return ((Clob) o).getCharacterStream();
}
return (Reader) o;
}
/**
* Returns the value as a java.io.Reader.
* This is only supported if the
* result set was created using a Clob or Reader object.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Reader getCharacterStream(String columnLabel) throws SQLException {
return getCharacterStream(findColumn(columnLabel));
}
/**
* Returns the value as a java.sql.Clob.
* This is only supported if the
* result set was created using a Clob object.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Clob getClob(int columnIndex) throws SQLException {
Clob c = (Clob) get(columnIndex);
return c == null ? null : c;
}
/**
* Returns the value as a java.sql.Clob.
* This is only supported if the
* result set was created using a Clob object.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Clob getClob(String columnLabel) throws SQLException {
return getClob(findColumn(columnLabel));
}
/**
* Returns the value as an java.sql.Date.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Date getDate(int columnIndex) throws SQLException {
return (Date) get(columnIndex);
}
/**
* Returns the value as a java.sql.Date.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Date getDate(String columnLabel) throws SQLException {
return getDate(findColumn(columnLabel));
}
/**
* INTERNAL
*/
@Override
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Date getDate(String columnLabel, Calendar cal) throws SQLException {
throw getUnsupportedException();
}
/**
* Returns the value as an double.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public double getDouble(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o != null && !(o instanceof Number)) {
return Double.parseDouble(o.toString());
}
return o == null ? 0 : ((Number) o).doubleValue();
}
/**
* Returns the value as a double.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public double getDouble(String columnLabel) throws SQLException {
return getDouble(findColumn(columnLabel));
}
/**
* Returns the value as a float.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public float getFloat(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o != null && !(o instanceof Number)) {
return Float.parseFloat(o.toString());
}
return o == null ? 0 : ((Number) o).floatValue();
}
/**
* Returns the value as a float.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public float getFloat(String columnLabel) throws SQLException {
return getFloat(findColumn(columnLabel));
}
/**
* Returns the value as an int.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public int getInt(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o != null && !(o instanceof Number)) {
o = Integer.decode(o.toString());
}
return o == null ? 0 : ((Number) o).intValue();
}
/**
* Returns the value as an int.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public int getInt(String columnLabel) throws SQLException {
return getInt(findColumn(columnLabel));
}
/**
* Returns the value as a long.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public long getLong(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o != null && !(o instanceof Number)) {
o = Long.decode(o.toString());
}
return o == null ? 0 : ((Number) o).longValue();
}
/**
* Returns the value as a long.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public long getLong(String columnLabel) throws SQLException {
return getLong(findColumn(columnLabel));
}
/**
* INTERNAL
*/
@Override
public Reader getNCharacterStream(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Reader getNCharacterStream(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public NClob getNClob(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public NClob getNClob(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public String getNString(int columnIndex) throws SQLException {
return getString(columnIndex);
}
/**
* INTERNAL
*/
@Override
public String getNString(String columnLabel) throws SQLException {
return getString(columnLabel);
}
/**
* Returns the value as an Object.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Object getObject(int columnIndex) throws SQLException {
return get(columnIndex);
}
/**
* Returns the value as an Object.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Object getObject(String columnLabel) throws SQLException {
return getObject(findColumn(columnLabel));
}
/**
* Returns the value as an Object of the specified type.
*
* @param columnIndex the column index (1, 2, ...)
* @param type the class of the returned value
* @return the value
*/
@Override
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
if (wasNull()) {
return null;
}
if (type == BigDecimal.class) {
return type.cast(getBigDecimal(columnIndex));
} else if (type == BigInteger.class) {
return type.cast(getBigDecimal(columnIndex).toBigInteger());
} else if (type == String.class) {
return type.cast(getString(columnIndex));
} else if (type == Boolean.class) {
return type.cast(getBoolean(columnIndex));
} else if (type == Byte.class) {
return type.cast(getByte(columnIndex));
} else if (type == Short.class) {
return type.cast(getShort(columnIndex));
} else if (type == Integer.class) {
return type.cast(getInt(columnIndex));
} else if (type == Long.class) {
return type.cast(getLong(columnIndex));
} else if (type == Float.class) {
return type.cast(getFloat(columnIndex));
} else if (type == Double.class) {
return type.cast(getDouble(columnIndex));
} else if (type == Date.class) {
return type.cast(getDate(columnIndex));
} else if (type == Time.class) {
return type.cast(getTime(columnIndex));
} else if (type == Timestamp.class) {
return type.cast(getTimestamp(columnIndex));
} else if (type == UUID.class) {
return type.cast(getObject(columnIndex));
} else if (type == byte[].class) {
return type.cast(getBytes(columnIndex));
} else if (type == java.sql.Array.class) {
return type.cast(getArray(columnIndex));
} else if (type == Blob.class) {
return type.cast(getBlob(columnIndex));
} else if (type == Clob.class) {
return type.cast(getClob(columnIndex));
} else {
throw getUnsupportedException();
}
}
/**
* Returns the value as an Object of the specified type.
*
* @param columnName the column name
* @param type the class of the returned value
* @return the value
*/
@Override
public <T> T getObject(String columnName, Class<T> type) throws SQLException {
return getObject(findColumn(columnName), type);
}
/**
* INTERNAL
*/
@Override
public Object getObject(int columnIndex, Map<String, Class<?>> map)
throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Object getObject(String columnLabel, Map<String, Class<?>> map)
throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Ref getRef(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Ref getRef(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public RowId getRowId(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public RowId getRowId(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
/**
* Returns the value as a short.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public short getShort(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o != null && !(o instanceof Number)) {
o = Short.decode(o.toString());
}
return o == null ? 0 : ((Number) o).shortValue();
}
/**
* Returns the value as a short.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public short getShort(String columnLabel) throws SQLException {
return getShort(findColumn(columnLabel));
}
/**
* INTERNAL
*/
@Override
public SQLXML getSQLXML(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public SQLXML getSQLXML(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
/**
* Returns the value as a String.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public String getString(int columnIndex) throws SQLException {
Object o = get(columnIndex);
if (o == null) {
return null;
}
switch (columns.get(columnIndex - 1).sqlType) {
case Types.CLOB:
Clob c = (Clob) o;
return c.getSubString(1, MathUtils.convertLongToInt(c.length()));
}
return o.toString();
}
/**
* Returns the value as a String.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public String getString(String columnLabel) throws SQLException {
return getString(findColumn(columnLabel));
}
/**
* Returns the value as an java.sql.Time.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Time getTime(int columnIndex) throws SQLException {
return (Time) get(columnIndex);
}
/**
* Returns the value as a java.sql.Time.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Time getTime(String columnLabel) throws SQLException {
return getTime(findColumn(columnLabel));
}
/**
* INTERNAL
*/
@Override
public Time getTime(int columnIndex, Calendar cal) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Time getTime(String columnLabel, Calendar cal) throws SQLException {
throw getUnsupportedException();
}
/**
* Returns the value as an java.sql.Timestamp.
*
* @param columnIndex (1,2,...)
* @return the value
*/
@Override
public Timestamp getTimestamp(int columnIndex) throws SQLException {
return (Timestamp) get(columnIndex);
}
/**
* Returns the value as a java.sql.Timestamp.
*
* @param columnLabel the column label
* @return the value
*/
@Override
public Timestamp getTimestamp(String columnLabel) throws SQLException {
return getTimestamp(findColumn(columnLabel));
}
/**
* INTERNAL
*/
@Override
public Timestamp getTimestamp(int columnIndex, Calendar cal)
throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Timestamp getTimestamp(String columnLabel, Calendar cal)
throws SQLException {
throw getUnsupportedException();
}
/**
* @deprecated INTERNAL
*/
@Deprecated
@Override
public InputStream getUnicodeStream(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* @deprecated INTERNAL
*/
@Deprecated
@Override
public InputStream getUnicodeStream(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public URL getURL(int columnIndex) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public URL getURL(String columnLabel) throws SQLException {
throw getUnsupportedException();
}
// ---- update ---------------------------------------------
/**
* INTERNAL
*/
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateArray(String columnLabel, Array x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateAsciiStream(int columnIndex, InputStream x)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateAsciiStream(String columnLabel, InputStream x)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateAsciiStream(int columnIndex, InputStream x, int length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateAsciiStream(String columnLabel, InputStream x, int length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateAsciiStream(int columnIndex, InputStream x, long length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateAsciiStream(String columnLabel, InputStream x, long length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBigDecimal(int columnIndex, BigDecimal x)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBigDecimal(String columnLabel, BigDecimal x)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBinaryStream(int columnIndex, InputStream x)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBinaryStream(String columnLabel, InputStream x)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBinaryStream(int columnIndex, InputStream x, int length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBinaryStream(String columnLabel, InputStream x, int length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBinaryStream(int columnIndex, InputStream x, long length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBinaryStream(String columnLabel, InputStream x, long length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBlob(int columnIndex, Blob x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBlob(String columnLabel, Blob x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBlob(int columnIndex, InputStream x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBlob(String columnLabel, InputStream x)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBlob(int columnIndex, InputStream x, long length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBlob(String columnLabel, InputStream x, long length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBoolean(int columnIndex, boolean x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBoolean(String columnLabel, boolean x)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateByte(int columnIndex, byte x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateByte(String columnLabel, byte x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateBytes(int columnIndex, byte[] x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateBytes(String columnLabel, byte[] x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateCharacterStream(int columnIndex, Reader x)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateCharacterStream(String columnLabel, Reader x)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateCharacterStream(int columnIndex, Reader x, int length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateCharacterStream(String columnLabel, Reader x, int length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateCharacterStream(int columnIndex, Reader x, long length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateCharacterStream(String columnLabel, Reader x, long length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateClob(String columnLabel, Clob x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateClob(int columnIndex, Reader x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateClob(String columnLabel, Reader x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateClob(int columnIndex, Reader x, long length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateClob(String columnLabel, Reader x, long length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateDate(int columnIndex, Date x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateDate(String columnLabel, Date x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateDouble(int columnIndex, double x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateDouble(String columnLabel, double x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateFloat(int columnIndex, float x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateFloat(String columnLabel, float x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateInt(int columnIndex, int x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateInt(String columnLabel, int x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateLong(int columnIndex, long x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateLong(String columnLabel, long x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateNCharacterStream(int columnIndex, Reader x)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateNCharacterStream(String columnLabel, Reader x)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateNCharacterStream(int columnIndex, Reader x, long length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateNCharacterStream(String columnLabel, Reader x, long length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateNClob(int columnIndex, NClob x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateNClob(String columnLabel, NClob x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateNClob(int columnIndex, Reader x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateNClob(String columnLabel, Reader x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateNClob(int columnIndex, Reader x, long length)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateNClob(String columnLabel, Reader x, long length)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateNString(int columnIndex, String x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateNString(String columnLabel, String x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateNull(int columnIndex) throws SQLException {
update(columnIndex, null);
}
/**
* INTERNAL
*/
@Override
public void updateNull(String columnLabel) throws SQLException {
update(columnLabel, null);
}
/**
* INTERNAL
*/
@Override
public void updateObject(int columnIndex, Object x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateObject(String columnLabel, Object x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateObject(int columnIndex, Object x, int scale)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateObject(String columnLabel, Object x, int scale)
throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateRef(int columnIndex, Ref x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateRef(String columnLabel, Ref x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateRowId(int columnIndex, RowId x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateRowId(String columnLabel, RowId x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateShort(int columnIndex, short x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateShort(String columnLabel, short x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateSQLXML(int columnIndex, SQLXML x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateSQLXML(String columnLabel, SQLXML x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateString(int columnIndex, String x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateString(String columnLabel, String x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateTime(int columnIndex, Time x) throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateTime(String columnLabel, Time x) throws SQLException {
update(columnLabel, x);
}
/**
* INTERNAL
*/
@Override
public void updateTimestamp(int columnIndex, Timestamp x)
throws SQLException {
update(columnIndex, x);
}
/**
* INTERNAL
*/
@Override
public void updateTimestamp(String columnLabel, Timestamp x)
throws SQLException {
update(columnLabel, x);
}
// ---- result set meta data ---------------------------------------------
/**
* Returns the column count.
*
* @return the column count
*/
@Override
public int getColumnCount() {
return columns.size();
}
/**
* Returns 15.
*
* @param columnIndex (1,2,...)
* @return 15
*/
@Override
public int getColumnDisplaySize(int columnIndex) {
return 15;
}
/**
* Returns the SQL type.
*
* @param columnIndex (1,2,...)
* @return the SQL type
*/
@Override
public int getColumnType(int columnIndex) throws SQLException {
return getColumn(columnIndex - 1).sqlType;
}
/**
* Returns the precision.
*
* @param columnIndex (1,2,...)
* @return the precision
*/
@Override
public int getPrecision(int columnIndex) throws SQLException {
return getColumn(columnIndex - 1).precision;
}
/**
* Returns the scale.
*
* @param columnIndex (1,2,...)
* @return the scale
*/
@Override
public int getScale(int columnIndex) throws SQLException {
return getColumn(columnIndex - 1).scale;
}
/**
* Returns ResultSetMetaData.columnNullableUnknown.
*
* @param columnIndex (1,2,...)
* @return columnNullableUnknown
*/
@Override
public int isNullable(int columnIndex) {
return ResultSetMetaData.columnNullableUnknown;
}
/**
* Returns false.
*
* @param columnIndex (1,2,...)
* @return false
*/
@Override
public boolean isAutoIncrement(int columnIndex) {
return false;
}
/**
* Returns true.
*
* @param columnIndex (1,2,...)
* @return true
*/
@Override
public boolean isCaseSensitive(int columnIndex) {
return true;
}
/**
* Returns false.
*
* @param columnIndex (1,2,...)
* @return false
*/
@Override
public boolean isCurrency(int columnIndex) {
return false;
}
/**
* Returns false.
*
* @param columnIndex (1,2,...)
* @return false
*/
@Override
public boolean isDefinitelyWritable(int columnIndex) {
return false;
}
/**
* Returns true.
*
* @param columnIndex (1,2,...)
* @return true
*/
@Override
public boolean isReadOnly(int columnIndex) {
return true;
}
/**
* Returns true.
*
* @param columnIndex (1,2,...)
* @return true
*/
@Override
public boolean isSearchable(int columnIndex) {
return true;
}
/**
* Returns true.
*
* @param columnIndex (1,2,...)
* @return true
*/
@Override
public boolean isSigned(int columnIndex) {
return true;
}
/**
* Returns false.
*
* @param columnIndex (1,2,...)
* @return false
*/
@Override
public boolean isWritable(int columnIndex) {
return false;
}
/**
* Returns null.
*
* @param columnIndex (1,2,...)
* @return null
*/
@Override
public String getCatalogName(int columnIndex) {
return null;
}
/**
* Returns the Java class name if this column.
*
* @param columnIndex (1,2,...)
* @return the class name
*/
@Override
public String getColumnClassName(int columnIndex) throws SQLException {
int type = DataType.getValueTypeFromResultSet(this, columnIndex);
return DataType.getTypeClassName(type);
}
/**
* Returns the column label.
*
* @param columnIndex (1,2,...)
* @return the column label
*/
@Override
public String getColumnLabel(int columnIndex) throws SQLException {
return getColumn(columnIndex - 1).name;
}
/**
* Returns the column name.
*
* @param columnIndex (1,2,...)
* @return the column name
*/
@Override
public String getColumnName(int columnIndex) throws SQLException {
return getColumnLabel(columnIndex);
}
/**
* Returns the data type name of a column.
*
* @param columnIndex (1,2,...)
* @return the type name
*/
@Override
public String getColumnTypeName(int columnIndex) throws SQLException {
return getColumn(columnIndex - 1).sqlTypeName;
}
/**
* Returns null.
*
* @param columnIndex (1,2,...)
* @return null
*/
@Override
public String getSchemaName(int columnIndex) {
return null;
}
/**
* Returns null.
*
* @param columnIndex (1,2,...)
* @return null
*/
@Override
public String getTableName(int columnIndex) {
return null;
}
// ---- unsupported / result set -----------------------------------
/**
* INTERNAL
*/
@Override
public void afterLast() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void cancelRowUpdates() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void deleteRow() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void insertRow() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void moveToCurrentRow() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void moveToInsertRow() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void refreshRow() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void updateRow() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean first() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean isAfterLast() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean isBeforeFirst() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean isFirst() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean isLast() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean last() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean previous() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean rowDeleted() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean rowInserted() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean rowUpdated() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void setFetchDirection(int direction) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void setFetchSize(int rows) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean absolute(int row) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean relative(int offset) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public String getCursorName() throws SQLException {
throw getUnsupportedException();
}
// --- private -----------------------------
private void update(int columnIndex, Object obj) throws SQLException {
checkColumnIndex(columnIndex);
this.currentRow[columnIndex - 1] = obj;
}
private void update(String columnLabel, Object obj) throws SQLException {
this.currentRow[findColumn(columnLabel) - 1] = obj;
}
/**
* INTERNAL
*/
static SQLException getUnsupportedException() {
return DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1).
getSQLException();
}
private void checkColumnIndex(int columnIndex) throws SQLException {
if (columnIndex < 1 || columnIndex > columns.size()) {
throw DbException.getInvalidValueException(
"columnIndex", columnIndex).getSQLException();
}
}
private Object get(int columnIndex) throws SQLException {
if (currentRow == null) {
throw DbException.get(ErrorCode.NO_DATA_AVAILABLE).
getSQLException();
}
checkColumnIndex(columnIndex);
columnIndex--;
Object o = columnIndex < currentRow.length ?
currentRow[columnIndex] : null;
wasNull = o == null;
return o;
}
private Column getColumn(int i) throws SQLException {
checkColumnIndex(i + 1);
return columns.get(i);
}
/**
* Returns the current result set holdability.
*
* @return the holdability
*/
@Override
public int getHoldability() {
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
/**
* Returns whether this result set has been closed.
*
* @return true if the result set was closed
*/
@Override
public boolean isClosed() {
return rows == null && source == null;
}
/**
* INTERNAL
*/
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
throw getUnsupportedException();
}
/**
* Set the auto-close behavior. If enabled (the default), the result set is
* closed after reading the last row.
*
* @param autoClose the new value
*/
public void setAutoClose(boolean autoClose) {
this.autoClose = autoClose;
}
/**
* Get the current auto-close behavior.
*
* @return the auto-close value
*/
public boolean getAutoClose() {
return autoClose;
}
/**
* This class holds the data of a result column.
*/
static class Column {
/**
* The column label.
*/
String name;
/**
* The column type Name
*/
String sqlTypeName;
/**
* The SQL type.
*/
int sqlType;
/**
* The precision.
*/
int precision;
/**
* The scale.
*/
int scale;
}
/**
* A simple array implementation,
* backed by an object array
*/
public static class SimpleArray implements Array {
private final Object[] value;
SimpleArray(Object[] value) {
this.value = value;
}
/**
* Get the object array.
*
* @return the object array
*/
@Override
public Object getArray() {
return value;
}
/**
* INTERNAL
*/
@Override
public Object getArray(Map<String, Class<?>> map) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Object getArray(long index, int count) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public Object getArray(long index, int count, Map<String, Class<?>> map)
throws SQLException {
throw getUnsupportedException();
}
/**
* Get the base type of this array.
*
* @return Types.NULL
*/
@Override
public int getBaseType() {
return Types.NULL;
}
/**
* Get the base type name of this array.
*
* @return "NULL"
*/
@Override
public String getBaseTypeName() {
return "NULL";
}
/**
* INTERNAL
*/
@Override
public ResultSet getResultSet() throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public ResultSet getResultSet(Map<String, Class<?>> map)
throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public ResultSet getResultSet(long index, int count)
throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public ResultSet getResultSet(long index, int count,
Map<String, Class<?>> map) throws SQLException {
throw getUnsupportedException();
}
/**
* INTERNAL
*/
@Override
public void free() {
// nothing to do
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/SimpleRowSource.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.sql.SQLException;
/**
* This interface is for classes that create rows on demand.
* It is used together with SimpleResultSet to create a dynamic result set.
*/
public interface SimpleRowSource {
/**
* Get the next row. Must return null if no more rows are available.
*
* @return the row or null
*/
Object[] readRow() throws SQLException;
/**
* Close the row source.
*/
void close();
/**
* Reset the position (before the first row).
*
* @throws SQLException if this operation is not supported
*/
void reset() throws SQLException;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/tools/TriggerAdapter.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.tools;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.h2.api.Trigger;
/**
* An adapter for the trigger interface that allows to use the ResultSet
* interface instead of a row array.
*/
public abstract class TriggerAdapter implements Trigger {
/**
* The schema name.
*/
protected String schemaName;
/**
* The name of the trigger.
*/
protected String triggerName;
/**
* The name of the table.
*/
protected String tableName;
/**
* Whether the fire method is called before or after the operation is
* performed.
*/
protected boolean before;
/**
* The trigger type: INSERT, UPDATE, DELETE, SELECT, or a combination (a bit
* field).
*/
protected int type;
private SimpleResultSet oldResultSet, newResultSet;
private TriggerRowSource oldSource, newSource;
/**
* This method is called by the database engine once when initializing the
* trigger. It is called when the trigger is created, as well as when the
* database is opened. The default implementation initialized the result
* sets.
*
* @param conn a connection to the database
* @param schemaName the name of the schema
* @param triggerName the name of the trigger used in the CREATE TRIGGER
* statement
* @param tableName the name of the table
* @param before whether the fire method is called before or after the
* operation is performed
* @param type the operation type: INSERT, UPDATE, DELETE, SELECT, or a
* combination (this parameter is a bit field)
*/
@Override
public void init(Connection conn, String schemaName,
String triggerName, String tableName,
boolean before, int type) throws SQLException {
ResultSet rs = conn.getMetaData().getColumns(
null, schemaName, tableName, null);
oldSource = new TriggerRowSource();
newSource = new TriggerRowSource();
oldResultSet = new SimpleResultSet(oldSource);
newResultSet = new SimpleResultSet(newSource);
while (rs.next()) {
String column = rs.getString("COLUMN_NAME");
int dataType = rs.getInt("DATA_TYPE");
int precision = rs.getInt("COLUMN_SIZE");
int scale = rs.getInt("DECIMAL_DIGITS");
oldResultSet.addColumn(column, dataType, precision, scale);
newResultSet.addColumn(column, dataType, precision, scale);
}
this.schemaName = schemaName;
this.triggerName = triggerName;
this.tableName = tableName;
this.before = before;
this.type = type;
}
/**
* A row source that allows to set the next row.
*/
static class TriggerRowSource implements SimpleRowSource {
private Object[] row;
void setRow(Object[] row) {
this.row = row;
}
@Override
public Object[] readRow() {
return row;
}
@Override
public void close() {
// ignore
}
@Override
public void reset() {
// ignore
}
}
/**
* This method is called for each triggered action. The method is called
* immediately when the operation occurred (before it is committed). A
* transaction rollback will also rollback the operations that were done
* within the trigger, if the operations occurred within the same database.
* If the trigger changes state outside the database, a rollback trigger
* should be used.
* <p>
* The row arrays contain all columns of the table, in the same order
* as defined in the table.
* </p>
* <p>
* The default implementation calls the fire method with the ResultSet
* parameters.
* </p>
*
* @param conn a connection to the database
* @param oldRow the old row, or null if no old row is available (for
* INSERT)
* @param newRow the new row, or null if no new row is available (for
* DELETE)
* @throws SQLException if the operation must be undone
*/
@Override
public void fire(Connection conn, Object[] oldRow, Object[] newRow)
throws SQLException {
fire(conn, wrap(oldResultSet, oldSource, oldRow),
wrap(newResultSet, newSource, newRow));
}
/**
* This method is called for each triggered action by the default
* fire(Connection conn, Object[] oldRow, Object[] newRow) method.
* ResultSet.next does not need to be called (and calling it has no effect;
* it will always return true).
* <p>
* For "before" triggers, the new values of the new row may be changed
* using the ResultSet.updateX methods.
* </p>
*
* @param conn a connection to the database
* @param oldRow the old row, or null if no old row is available (for
* INSERT)
* @param newRow the new row, or null if no new row is available (for
* DELETE)
* @throws SQLException if the operation must be undone
*/
public abstract void fire(Connection conn, ResultSet oldRow,
ResultSet newRow) throws SQLException;
private static SimpleResultSet wrap(SimpleResultSet rs,
TriggerRowSource source, Object[] row) throws SQLException {
if (row == null) {
return null;
}
source.setRow(row);
rs.next();
return rs;
}
/**
* This method is called when the database is closed.
* If the method throws an exception, it will be logged, but
* closing the database will continue.
* The default implementation does nothing.
*/
@Override
public void remove() throws SQLException {
// do nothing by default
}
/**
* This method is called when the trigger is dropped.
* The default implementation does nothing.
*/
@Override
public void close() throws SQLException {
// do nothing by default
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/upgrade/DbUpgrade.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.upgrade;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.UUID;
import org.h2.engine.ConnectionInfo;
import org.h2.engine.Constants;
import org.h2.jdbc.JdbcConnection;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* This class starts the conversion from older database versions to the current
* version if the respective classes are found.
*/
public class DbUpgrade {
private static final boolean UPGRADE_CLASSES_PRESENT;
private static boolean scriptInTempDir;
private static boolean deleteOldDb;
static {
UPGRADE_CLASSES_PRESENT = Utils.isClassPresent("org.h2.upgrade.v1_1.Driver");
}
/**
* If the upgrade classes are present, upgrade the database, or connect
* using the old version (if the parameter NO_UPGRADE is set to true). If
* the database is upgraded, or if no upgrade is possible or needed, this
* methods returns null.
*
* @param url the database URL
* @param info the properties
* @return the connection if connected with the old version (NO_UPGRADE)
*/
public static Connection connectOrUpgrade(String url, Properties info)
throws SQLException {
if (!UPGRADE_CLASSES_PRESENT) {
return null;
}
Properties i2 = new Properties();
i2.putAll(info);
// clone so that the password (if set as a char array) is not cleared
Object o = info.get("password");
if (o instanceof char[]) {
i2.put("password", StringUtils.cloneCharArray((char[]) o));
}
info = i2;
ConnectionInfo ci = new ConnectionInfo(url, info);
if (ci.isRemote() || !ci.isPersistent()) {
return null;
}
String name = ci.getName();
if (FileUtils.exists(name + Constants.SUFFIX_PAGE_FILE)) {
return null;
}
if (!FileUtils.exists(name + Constants.SUFFIX_OLD_DATABASE_FILE)) {
return null;
}
if (ci.removeProperty("NO_UPGRADE", false)) {
return connectWithOldVersion(url, info);
}
synchronized (DbUpgrade.class) {
upgrade(ci, info);
return null;
}
}
/**
* The conversion script file will per default be created in the db
* directory. Use this method to change the directory to the temp
* directory.
*
* @param scriptInTempDir true if the conversion script should be
* located in the temp directory.
*/
public static void setScriptInTempDir(boolean scriptInTempDir) {
DbUpgrade.scriptInTempDir = scriptInTempDir;
}
/**
* Old files will be renamed to .backup after a successful conversion. To
* delete them after the conversion, use this method with the parameter
* 'true'.
*
* @param deleteOldDb if true, the old db files will be deleted.
*/
public static void setDeleteOldDb(boolean deleteOldDb) {
DbUpgrade.deleteOldDb = deleteOldDb;
}
private static Connection connectWithOldVersion(String url, Properties info)
throws SQLException {
url = "jdbc:h2v1_1:" + url.substring("jdbc:h2:".length()) +
";IGNORE_UNKNOWN_SETTINGS=TRUE";
return DriverManager.getConnection(url, info);
}
private static void upgrade(ConnectionInfo ci, Properties info)
throws SQLException {
String name = ci.getName();
String data = name + Constants.SUFFIX_OLD_DATABASE_FILE;
String index = name + ".index.db";
String lobs = name + ".lobs.db";
String backupData = data + ".backup";
String backupIndex = index + ".backup";
String backupLobs = lobs + ".backup";
String script = null;
try {
if (scriptInTempDir) {
new File(Utils.getProperty("java.io.tmpdir", ".")).mkdirs();
script = File.createTempFile(
"h2dbmigration", "backup.sql").getAbsolutePath();
} else {
script = name + ".script.sql";
}
String oldUrl = "jdbc:h2v1_1:" + name +
";UNDO_LOG=0;LOG=0;LOCK_MODE=0";
String cipher = ci.getProperty("CIPHER", null);
if (cipher != null) {
oldUrl += ";CIPHER=" + cipher;
}
Connection conn = DriverManager.getConnection(oldUrl, info);
Statement stat = conn.createStatement();
String uuid = UUID.randomUUID().toString();
if (cipher != null) {
stat.execute("script to '" + script +
"' cipher aes password '" + uuid + "' --hide--");
} else {
stat.execute("script to '" + script + "'");
}
conn.close();
FileUtils.move(data, backupData);
FileUtils.move(index, backupIndex);
if (FileUtils.exists(lobs)) {
FileUtils.move(lobs, backupLobs);
}
ci.removeProperty("IFEXISTS", false);
conn = new JdbcConnection(ci, true);
stat = conn.createStatement();
if (cipher != null) {
stat.execute("runscript from '" + script +
"' cipher aes password '" + uuid + "' --hide--");
} else {
stat.execute("runscript from '" + script + "'");
}
stat.execute("analyze");
stat.execute("shutdown compact");
stat.close();
conn.close();
if (deleteOldDb) {
FileUtils.delete(backupData);
FileUtils.delete(backupIndex);
FileUtils.deleteRecursive(backupLobs, false);
}
} catch (Exception e) {
if (FileUtils.exists(backupData)) {
FileUtils.move(backupData, data);
}
if (FileUtils.exists(backupIndex)) {
FileUtils.move(backupIndex, index);
}
if (FileUtils.exists(backupLobs)) {
FileUtils.move(backupLobs, lobs);
}
FileUtils.delete(name + ".h2.db");
throw DbException.toSQLException(e);
} finally {
if (script != null) {
FileUtils.delete(script);
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/AbbaDetector.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Utility to detect AB-BA deadlocks.
*/
public class AbbaDetector {
private static final boolean TRACE = false;
private static final ThreadLocal<Deque<Object>> STACK =
new ThreadLocal<Deque<Object>>() {
@Override protected Deque<Object> initialValue() {
return new ArrayDeque<>();
}
};
/**
* Map of (object A) -> (
* map of (object locked before object A) ->
* (stack trace where locked) )
*/
private static final Map<Object, Map<Object, Exception>> LOCK_ORDERING =
new WeakHashMap<>();
private static final Set<String> KNOWN_DEADLOCKS = new HashSet<>();
/**
* This method is called just before or just after an object is
* synchronized.
*
* @param o the object, or null for the current class
* @return the object that was passed
*/
public static Object begin(Object o) {
if (o == null) {
o = new SecurityManager() {
Class<?> clazz = getClassContext()[2];
}.clazz;
}
Deque<Object> stack = STACK.get();
if (!stack.isEmpty()) {
// Ignore locks which are locked multiple times in succession -
// Java locks are recursive
if (stack.contains(o)) {
// already synchronized on this
return o;
}
while (!stack.isEmpty()) {
Object last = stack.peek();
if (Thread.holdsLock(last)) {
break;
}
stack.pop();
}
}
if (TRACE) {
String thread = "[thread " + Thread.currentThread().getId() + "]";
String indent = new String(new char[stack.size() * 2]).replace((char) 0, ' ');
System.out.println(thread + " " + indent +
"sync " + getObjectName(o));
}
if (!stack.isEmpty()) {
markHigher(o, stack);
}
stack.push(o);
return o;
}
private static Object getTest(Object o) {
// return o.getClass();
return o;
}
private static String getObjectName(Object o) {
return o.getClass().getSimpleName() + "@" + System.identityHashCode(o);
}
private static synchronized void markHigher(Object o, Deque<Object> older) {
Object test = getTest(o);
Map<Object, Exception> map = LOCK_ORDERING.get(test);
if (map == null) {
map = new WeakHashMap<>();
LOCK_ORDERING.put(test, map);
}
Exception oldException = null;
for (Object old : older) {
Object oldTest = getTest(old);
if (oldTest == test) {
continue;
}
Map<Object, Exception> oldMap = LOCK_ORDERING.get(oldTest);
if (oldMap != null) {
Exception e = oldMap.get(test);
if (e != null) {
String deadlockType = test.getClass() + " " + oldTest.getClass();
if (!KNOWN_DEADLOCKS.contains(deadlockType)) {
String message = getObjectName(test) +
" synchronized after \n " + getObjectName(oldTest) +
", but in the past before";
RuntimeException ex = new RuntimeException(message);
ex.initCause(e);
ex.printStackTrace(System.out);
// throw ex;
KNOWN_DEADLOCKS.add(deadlockType);
}
}
}
if (!map.containsKey(oldTest)) {
if (oldException == null) {
oldException = new Exception("Before");
}
map.put(oldTest, oldException);
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/AbbaLockingDetector.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, Version
* 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html). Initial Developer: H2 Group
*/
package org.h2.util;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Utility to detect AB-BA deadlocks.
*/
public class AbbaLockingDetector implements Runnable {
private final int tickIntervalMs = 2;
private volatile boolean stop;
private final ThreadMXBean threadMXBean =
ManagementFactory.getThreadMXBean();
private Thread thread;
/**
* Map of (object A) -> ( map of (object locked before object A) ->
* (stack trace where locked) )
*/
private final Map<String, Map<String, String>> lockOrdering =
new WeakHashMap<>();
private final Set<String> knownDeadlocks = new HashSet<>();
/**
* Start collecting locking data.
*
* @return this
*/
public AbbaLockingDetector startCollecting() {
thread = new Thread(this, "AbbaLockingDetector");
thread.setDaemon(true);
thread.start();
return this;
}
/**
* Reset the state.
*/
public synchronized void reset() {
lockOrdering.clear();
knownDeadlocks.clear();
}
/**
* Stop collecting.
*
* @return this
*/
public AbbaLockingDetector stopCollecting() {
stop = true;
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
thread = null;
}
return this;
}
@Override
public void run() {
while (!stop) {
try {
tick();
} catch (Throwable t) {
break;
}
}
}
private void tick() {
if (tickIntervalMs > 0) {
try {
Thread.sleep(tickIntervalMs);
} catch (InterruptedException ex) {
// ignore
}
}
ThreadInfo[] list = threadMXBean.dumpAllThreads(
// lockedMonitors
true,
// lockedSynchronizers
false);
processThreadList(list);
}
private void processThreadList(ThreadInfo[] threadInfoList) {
final List<String> lockOrder = new ArrayList<>();
for (ThreadInfo threadInfo : threadInfoList) {
lockOrder.clear();
generateOrdering(lockOrder, threadInfo);
if (lockOrder.size() > 1) {
markHigher(lockOrder, threadInfo);
}
}
}
/**
* We cannot simply call getLockedMonitors because it is not guaranteed to
* return the locks in the correct order.
*/
private static void generateOrdering(final List<String> lockOrder,
ThreadInfo info) {
final MonitorInfo[] lockedMonitors = info.getLockedMonitors();
Arrays.sort(lockedMonitors, new Comparator<MonitorInfo>() {
@Override
public int compare(MonitorInfo a, MonitorInfo b) {
return b.getLockedStackDepth() - a.getLockedStackDepth();
}
});
for (MonitorInfo mi : lockedMonitors) {
String lockName = getObjectName(mi);
if (lockName.equals("sun.misc.Launcher$AppClassLoader")) {
// ignore, it shows up everywhere
continue;
}
// Ignore locks which are locked multiple times in
// succession - Java locks are recursive.
if (!lockOrder.contains(lockName)) {
lockOrder.add(lockName);
}
}
}
private synchronized void markHigher(List<String> lockOrder,
ThreadInfo threadInfo) {
String topLock = lockOrder.get(lockOrder.size() - 1);
Map<String, String> map = lockOrdering.get(topLock);
if (map == null) {
map = new WeakHashMap<>();
lockOrdering.put(topLock, map);
}
String oldException = null;
for (int i = 0; i < lockOrder.size() - 1; i++) {
String olderLock = lockOrder.get(i);
Map<String, String> oldMap = lockOrdering.get(olderLock);
boolean foundDeadLock = false;
if (oldMap != null) {
String e = oldMap.get(topLock);
if (e != null) {
foundDeadLock = true;
String deadlockType = topLock + " " + olderLock;
if (!knownDeadlocks.contains(deadlockType)) {
System.out.println(topLock + " synchronized after \n " + olderLock
+ ", but in the past before\n" + "AFTER\n" +
getStackTraceForThread(threadInfo)
+ "BEFORE\n" + e);
knownDeadlocks.add(deadlockType);
}
}
}
if (!foundDeadLock && !map.containsKey(olderLock)) {
if (oldException == null) {
oldException = getStackTraceForThread(threadInfo);
}
map.put(olderLock, oldException);
}
}
}
/**
* Dump data in the same format as {@link ThreadInfo#toString()}, but with
* some modifications (no stack frame limit, and removal of uninteresting
* stack frames)
*/
private static String getStackTraceForThread(ThreadInfo info) {
StringBuilder sb = new StringBuilder().append('"')
.append(info.getThreadName()).append("\"" + " Id=")
.append(info.getThreadId()).append(' ').append(info.getThreadState());
if (info.getLockName() != null) {
sb.append(" on ").append(info.getLockName());
}
if (info.getLockOwnerName() != null) {
sb.append(" owned by \"").append(info.getLockOwnerName())
.append("\" Id=").append(info.getLockOwnerId());
}
if (info.isSuspended()) {
sb.append(" (suspended)");
}
if (info.isInNative()) {
sb.append(" (in native)");
}
sb.append('\n');
final StackTraceElement[] stackTrace = info.getStackTrace();
final MonitorInfo[] lockedMonitors = info.getLockedMonitors();
boolean startDumping = false;
for (int i = 0; i < stackTrace.length; i++) {
StackTraceElement e = stackTrace[i];
if (startDumping) {
dumpStackTraceElement(info, sb, i, e);
}
for (MonitorInfo mi : lockedMonitors) {
if (mi.getLockedStackDepth() == i) {
// Only start dumping the stack from the first time we lock
// something.
// Removes a lot of unnecessary noise from the output.
if (!startDumping) {
dumpStackTraceElement(info, sb, i, e);
startDumping = true;
}
sb.append("\t- locked ").append(mi);
sb.append('\n');
}
}
}
return sb.toString();
}
private static void dumpStackTraceElement(ThreadInfo info,
StringBuilder sb, int i, StackTraceElement e) {
sb.append('\t').append("at ").append(e)
.append('\n');
if (i == 0 && info.getLockInfo() != null) {
Thread.State ts = info.getThreadState();
switch (ts) {
case BLOCKED:
sb.append("\t- blocked on ")
.append(info.getLockInfo())
.append('\n');
break;
case WAITING:
sb.append("\t- waiting on ")
.append(info.getLockInfo())
.append('\n');
break;
case TIMED_WAITING:
sb.append("\t- waiting on ")
.append(info.getLockInfo())
.append('\n');
break;
default:
}
}
}
private static String getObjectName(MonitorInfo info) {
return info.getClassName() + "@" +
Integer.toHexString(info.getIdentityHashCode());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/BitField.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.Arrays;
/**
* A list of bits.
*/
public final class BitField {
private static final int ADDRESS_BITS = 6;
private static final int BITS = 64;
private static final int ADDRESS_MASK = BITS - 1;
private long[] data;
private int maxLength;
public BitField() {
this(64);
}
public BitField(int capacity) {
data = new long[capacity >>> 3];
}
/**
* Get the index of the next bit that is not set.
*
* @param fromIndex where to start searching
* @return the index of the next disabled bit
*/
public int nextClearBit(int fromIndex) {
int i = fromIndex >> ADDRESS_BITS;
int max = data.length;
for (; i < max; i++) {
if (data[i] == -1) {
continue;
}
int j = Math.max(fromIndex, i << ADDRESS_BITS);
for (int end = j + 64; j < end; j++) {
if (!get(j)) {
return j;
}
}
}
return max << ADDRESS_BITS;
}
/**
* Get the bit at the given index.
*
* @param i the index
* @return true if the bit is enabled
*/
public boolean get(int i) {
int addr = i >> ADDRESS_BITS;
if (addr >= data.length) {
return false;
}
return (data[addr] & getBitMask(i)) != 0;
}
/**
* Get the next 8 bits at the given index.
* The index must be a multiple of 8.
*
* @param i the index
* @return the next 8 bits
*/
public int getByte(int i) {
int addr = i >> ADDRESS_BITS;
if (addr >= data.length) {
return 0;
}
return (int) (data[addr] >>> (i & (7 << 3)) & 255);
}
/**
* Combine the next 8 bits at the given index with OR.
* The index must be a multiple of 8.
*
* @param i the index
* @param x the next 8 bits (0 - 255)
*/
public void setByte(int i, int x) {
int addr = i >> ADDRESS_BITS;
checkCapacity(addr);
data[addr] |= ((long) x) << (i & (7 << 3));
if (maxLength < i && x != 0) {
maxLength = i + 7;
}
}
/**
* Set bit at the given index to 'true'.
*
* @param i the index
*/
public void set(int i) {
int addr = i >> ADDRESS_BITS;
checkCapacity(addr);
data[addr] |= getBitMask(i);
if (maxLength < i) {
maxLength = i;
}
}
/**
* Set bit at the given index to 'false'.
*
* @param i the index
*/
public void clear(int i) {
int addr = i >> ADDRESS_BITS;
if (addr >= data.length) {
return;
}
data[addr] &= ~getBitMask(i);
}
private static long getBitMask(int i) {
return 1L << (i & ADDRESS_MASK);
}
private void checkCapacity(int size) {
if (size >= data.length) {
expandCapacity(size);
}
}
private void expandCapacity(int size) {
while (size >= data.length) {
int newSize = data.length == 0 ? 1 : data.length * 2;
data = Arrays.copyOf(data, newSize);
}
}
/**
* Enable or disable a number of bits.
*
* @param fromIndex the index of the first bit to enable or disable
* @param toIndex one plus the index of the last bit to enable or disable
* @param value the new value
*/
public void set(int fromIndex, int toIndex, boolean value) {
// go backwards so that OutOfMemory happens
// before some bytes are modified
for (int i = toIndex - 1; i >= fromIndex; i--) {
set(i, value);
}
if (value) {
if (toIndex > maxLength) {
maxLength = toIndex;
}
} else {
if (toIndex >= maxLength) {
maxLength = fromIndex;
}
}
}
private void set(int i, boolean value) {
if (value) {
set(i);
} else {
clear(i);
}
}
/**
* Get the index of the highest set bit plus one, or 0 if no bits are set.
*
* @return the length of the bit field
*/
public int length() {
int m = maxLength >> ADDRESS_BITS;
while (m > 0 && data[m] == 0) {
m--;
}
maxLength = (m << ADDRESS_BITS) +
(64 - Long.numberOfLeadingZeros(data[m]));
return maxLength;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/Bits.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.UUID;
/**
* Manipulations with bytes and arrays. This class can be overridden in
* multi-release JAR with more efficient implementation for a newer versions of
* Java.
*/
public final class Bits {
/*
* Signatures of methods should match with
* h2/src/java9/src/org/h2/util/Bits.java and precompiled
* h2/src/java9/precompiled/org/h2/util/Bits.class.
*/
/**
* Compare the contents of two byte arrays. If the content or length of the
* first array is smaller than the second array, -1 is returned. If the content
* or length of the second array is smaller than the first array, 1 is returned.
* If the contents and lengths are the same, 0 is returned.
*
* <p>
* This method interprets bytes as signed.
* </p>
*
* @param data1
* the first byte array (must not be null)
* @param data2
* the second byte array (must not be null)
* @return the result of the comparison (-1, 1 or 0)
*/
public static int compareNotNullSigned(byte[] data1, byte[] data2) {
if (data1 == data2) {
return 0;
}
int len = Math.min(data1.length, data2.length);
for (int i = 0; i < len; i++) {
byte b = data1[i];
byte b2 = data2[i];
if (b != b2) {
return b > b2 ? 1 : -1;
}
}
return Integer.signum(data1.length - data2.length);
}
/**
* Compare the contents of two byte arrays. If the content or length of the
* first array is smaller than the second array, -1 is returned. If the content
* or length of the second array is smaller than the first array, 1 is returned.
* If the contents and lengths are the same, 0 is returned.
*
* <p>
* This method interprets bytes as unsigned.
* </p>
*
* @param data1
* the first byte array (must not be null)
* @param data2
* the second byte array (must not be null)
* @return the result of the comparison (-1, 1 or 0)
*/
public static int compareNotNullUnsigned(byte[] data1, byte[] data2) {
if (data1 == data2) {
return 0;
}
int len = Math.min(data1.length, data2.length);
for (int i = 0; i < len; i++) {
int b = data1[i] & 0xff;
int b2 = data2[i] & 0xff;
if (b != b2) {
return b > b2 ? 1 : -1;
}
}
return Integer.signum(data1.length - data2.length);
}
/**
* Reads a int value from the byte array at the given position in big-endian
* order.
*
* @param buff
* the byte array
* @param pos
* the position
* @return the value
*/
public static int readInt(byte[] buff, int pos) {
return (buff[pos++] << 24) + ((buff[pos++] & 0xff) << 16) + ((buff[pos++] & 0xff) << 8) + (buff[pos] & 0xff);
}
/**
* Reads a long value from the byte array at the given position in big-endian
* order.
*
* @param buff
* the byte array
* @param pos
* the position
* @return the value
*/
public static long readLong(byte[] buff, int pos) {
return (((long) readInt(buff, pos)) << 32) + (readInt(buff, pos + 4) & 0xffffffffL);
}
/**
* Converts UUID value to byte array in big-endian order.
*
* @param msb
* most significant part of UUID
* @param lsb
* least significant part of UUID
* @return byte array representation
*/
public static byte[] uuidToBytes(long msb, long lsb) {
byte[] buff = new byte[16];
for (int i = 0; i < 8; i++) {
buff[i] = (byte) ((msb >> (8 * (7 - i))) & 0xff);
buff[8 + i] = (byte) ((lsb >> (8 * (7 - i))) & 0xff);
}
return buff;
}
/**
* Converts UUID value to byte array in big-endian order.
*
* @param uuid
* UUID value
* @return byte array representation
*/
public static byte[] uuidToBytes(UUID uuid) {
return uuidToBytes(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
}
/**
* Writes a int value to the byte array at the given position in big-endian
* order.
*
* @param buff
* the byte array
* @param pos
* the position
* @param x
* the value to write
*/
public static void writeInt(byte[] buff, int pos, int x) {
buff[pos++] = (byte) (x >> 24);
buff[pos++] = (byte) (x >> 16);
buff[pos++] = (byte) (x >> 8);
buff[pos] = (byte) x;
}
/**
* Writes a long value to the byte array at the given position in big-endian
* order.
*
* @param buff
* the byte array
* @param pos
* the position
* @param x
* the value to write
*/
public static void writeLong(byte[] buff, int pos, long x) {
writeInt(buff, pos, (int) (x >> 32));
writeInt(buff, pos + 4, (int) x);
}
private Bits() {
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/Cache.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.ArrayList;
/**
* The cache keeps frequently used objects in the main memory.
*/
public interface Cache {
/**
* Get all objects in the cache that have been changed.
*
* @return the list of objects
*/
ArrayList<CacheObject> getAllChanged();
/**
* Clear the cache.
*/
void clear();
/**
* Get an element in the cache if it is available.
* This will move the item to the front of the list.
*
* @param pos the unique key of the element
* @return the element or null
*/
CacheObject get(int pos);
/**
* Add an element to the cache. Other items may fall out of the cache
* because of this. It is not allowed to add the same record twice.
*
* @param r the object
*/
void put(CacheObject r);
/**
* Update an element in the cache.
* This will move the item to the front of the list.
*
* @param pos the unique key of the element
* @param record the element
* @return the element
*/
CacheObject update(int pos, CacheObject record);
/**
* Remove an object from the cache.
*
* @param pos the unique key of the element
* @return true if the key was in the cache
*/
boolean remove(int pos);
/**
* Get an element from the cache if it is available.
* This will not move the item to the front of the list.
*
* @param pos the unique key of the element
* @return the element or null
*/
CacheObject find(int pos);
/**
* Set the maximum memory to be used by this cache.
*
* @param size the maximum size in KB
*/
void setMaxMemory(int size);
/**
* Get the maximum memory to be used.
*
* @return the maximum size in KB
*/
int getMaxMemory();
/**
* Get the used size in KB.
*
* @return the current size in KB
*/
int getMemory();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/CacheHead.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
/**
* The head element of the linked list.
*/
public class CacheHead extends CacheObject {
@Override
public boolean canRemove() {
return false;
}
@Override
public int getMemory() {
return 0;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/CacheLRU.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
/**
* A cache implementation based on the last recently used (LRU) algorithm.
*/
public class CacheLRU implements Cache {
static final String TYPE_NAME = "LRU";
private final CacheWriter writer;
/**
* Use First-In-First-Out (don't move recently used items to the front of
* the queue).
*/
private final boolean fifo;
private final CacheObject head = new CacheHead();
private final int mask;
private CacheObject[] values;
private int recordCount;
/**
* The number of cache buckets.
*/
private final int len;
/**
* The maximum memory, in words (4 bytes each).
*/
private long maxMemory;
/**
* The current memory used in this cache, in words (4 bytes each).
*/
private long memory;
CacheLRU(CacheWriter writer, int maxMemoryKb, boolean fifo) {
this.writer = writer;
this.fifo = fifo;
this.setMaxMemory(maxMemoryKb);
try {
// Since setMaxMemory() ensures that maxMemory is >=0,
// we don't have to worry about an underflow.
long tmpLen = maxMemory / 64;
if (tmpLen > Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
this.len = MathUtils.nextPowerOf2((int) tmpLen);
} catch (IllegalArgumentException e) {
throw new IllegalStateException("This much cache memory is not supported: " + maxMemoryKb + "kb", e);
}
this.mask = len - 1;
clear();
}
/**
* Create a cache of the given type and size.
*
* @param writer the cache writer
* @param cacheType the cache type
* @param cacheSize the size
* @return the cache object
*/
public static Cache getCache(CacheWriter writer, String cacheType,
int cacheSize) {
Map<Integer, CacheObject> secondLevel = null;
if (cacheType.startsWith("SOFT_")) {
secondLevel = new SoftHashMap<>();
cacheType = cacheType.substring("SOFT_".length());
}
Cache cache;
if (CacheLRU.TYPE_NAME.equals(cacheType)) {
cache = new CacheLRU(writer, cacheSize, false);
} else if (CacheTQ.TYPE_NAME.equals(cacheType)) {
cache = new CacheTQ(writer, cacheSize);
} else {
throw DbException.getInvalidValueException("CACHE_TYPE", cacheType);
}
if (secondLevel != null) {
cache = new CacheSecondLevel(cache, secondLevel);
}
return cache;
}
@Override
public void clear() {
head.cacheNext = head.cachePrevious = head;
// first set to null - avoiding out of memory
values = null;
values = new CacheObject[len];
recordCount = 0;
memory = len * (long)Constants.MEMORY_POINTER;
}
@Override
public void put(CacheObject rec) {
if (SysProperties.CHECK) {
int pos = rec.getPos();
CacheObject old = find(pos);
if (old != null) {
DbException
.throwInternalError("try to add a record twice at pos " +
pos);
}
}
int index = rec.getPos() & mask;
rec.cacheChained = values[index];
values[index] = rec;
recordCount++;
memory += rec.getMemory();
addToFront(rec);
removeOldIfRequired();
}
@Override
public CacheObject update(int pos, CacheObject rec) {
CacheObject old = find(pos);
if (old == null) {
put(rec);
} else {
if (SysProperties.CHECK) {
if (old != rec) {
DbException.throwInternalError("old!=record pos:" + pos +
" old:" + old + " new:" + rec);
}
}
if (!fifo) {
removeFromLinkedList(rec);
addToFront(rec);
}
}
return old;
}
private void removeOldIfRequired() {
// a small method, to allow inlining
if (memory >= maxMemory) {
removeOld();
}
}
private void removeOld() {
int i = 0;
ArrayList<CacheObject> changed = New.arrayList();
long mem = memory;
int rc = recordCount;
boolean flushed = false;
CacheObject next = head.cacheNext;
while (true) {
if (rc <= Constants.CACHE_MIN_RECORDS) {
break;
}
if (changed.isEmpty()) {
if (mem <= maxMemory) {
break;
}
} else {
if (mem * 4 <= maxMemory * 3) {
break;
}
}
CacheObject check = next;
next = check.cacheNext;
i++;
if (i >= recordCount) {
if (!flushed) {
writer.flushLog();
flushed = true;
i = 0;
} else {
// can't remove any record, because the records can not be
// removed hopefully this does not happen frequently, but it
// can happen
writer.getTrace()
.info("cannot remove records, cache size too small? records:" +
recordCount + " memory:" + memory);
break;
}
}
if (SysProperties.CHECK && check == head) {
DbException.throwInternalError("try to remove head");
}
// we are not allowed to remove it if the log is not yet written
// (because we need to log before writing the data)
// also, can't write it if the record is pinned
if (!check.canRemove()) {
removeFromLinkedList(check);
addToFront(check);
continue;
}
rc--;
mem -= check.getMemory();
if (check.isChanged()) {
changed.add(check);
} else {
remove(check.getPos());
}
}
if (!changed.isEmpty()) {
if (!flushed) {
writer.flushLog();
}
Collections.sort(changed);
long max = maxMemory;
int size = changed.size();
try {
// temporary disable size checking,
// to avoid stack overflow
maxMemory = Long.MAX_VALUE;
for (i = 0; i < size; i++) {
CacheObject rec = changed.get(i);
writer.writeBack(rec);
}
} finally {
maxMemory = max;
}
for (i = 0; i < size; i++) {
CacheObject rec = changed.get(i);
remove(rec.getPos());
if (SysProperties.CHECK) {
if (rec.cacheNext != null) {
throw DbException.throwInternalError();
}
}
}
}
}
private void addToFront(CacheObject rec) {
if (SysProperties.CHECK && rec == head) {
DbException.throwInternalError("try to move head");
}
rec.cacheNext = head;
rec.cachePrevious = head.cachePrevious;
rec.cachePrevious.cacheNext = rec;
head.cachePrevious = rec;
}
private void removeFromLinkedList(CacheObject rec) {
if (SysProperties.CHECK && rec == head) {
DbException.throwInternalError("try to remove head");
}
rec.cachePrevious.cacheNext = rec.cacheNext;
rec.cacheNext.cachePrevious = rec.cachePrevious;
// TODO cache: mystery: why is this required? needs more memory if we
// don't do this
rec.cacheNext = null;
rec.cachePrevious = null;
}
@Override
public boolean remove(int pos) {
int index = pos & mask;
CacheObject rec = values[index];
if (rec == null) {
return false;
}
if (rec.getPos() == pos) {
values[index] = rec.cacheChained;
} else {
CacheObject last;
do {
last = rec;
rec = rec.cacheChained;
if (rec == null) {
return false;
}
} while (rec.getPos() != pos);
last.cacheChained = rec.cacheChained;
}
recordCount--;
memory -= rec.getMemory();
removeFromLinkedList(rec);
if (SysProperties.CHECK) {
rec.cacheChained = null;
CacheObject o = find(pos);
if (o != null) {
DbException.throwInternalError("not removed: " + o);
}
}
return true;
}
@Override
public CacheObject find(int pos) {
CacheObject rec = values[pos & mask];
while (rec != null && rec.getPos() != pos) {
rec = rec.cacheChained;
}
return rec;
}
@Override
public CacheObject get(int pos) {
CacheObject rec = find(pos);
if (rec != null) {
if (!fifo) {
removeFromLinkedList(rec);
addToFront(rec);
}
}
return rec;
}
// private void testConsistency() {
// int s = size;
// HashSet set = new HashSet();
// for(int i=0; i<values.length; i++) {
// Record rec = values[i];
// if(rec == null) {
// continue;
// }
// set.add(rec);
// while(rec.chained != null) {
// rec = rec.chained;
// set.add(rec);
// }
// }
// Record rec = head.next;
// while(rec != head) {
// set.add(rec);
// rec = rec.next;
// }
// rec = head.previous;
// while(rec != head) {
// set.add(rec);
// rec = rec.previous;
// }
// if(set.size() != size) {
// System.out.println("size="+size+" but el.size="+set.size());
// }
// }
@Override
public ArrayList<CacheObject> getAllChanged() {
// if(Database.CHECK) {
// testConsistency();
// }
ArrayList<CacheObject> list = New.arrayList();
CacheObject rec = head.cacheNext;
while (rec != head) {
if (rec.isChanged()) {
list.add(rec);
}
rec = rec.cacheNext;
}
return list;
}
@Override
public void setMaxMemory(int maxKb) {
long newSize = maxKb * 1024L / 4;
maxMemory = newSize < 0 ? 0 : newSize;
// can not resize, otherwise existing records are lost
// resize(maxSize);
removeOldIfRequired();
}
@Override
public int getMaxMemory() {
return (int) (maxMemory * 4L / 1024);
}
@Override
public int getMemory() {
// CacheObject rec = head.cacheNext;
// while (rec != head) {
// System.out.println(rec.getMemory() + " " +
// MemoryFootprint.getObjectSize(rec) + " " + rec);
// rec = rec.cacheNext;
// }
return (int) (memory * 4L / 1024);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/CacheObject.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
/**
* The base object for all cached objects.
*/
public abstract class CacheObject implements Comparable<CacheObject> {
/**
* The previous element in the LRU linked list. If the previous element is
* the head, then this element is the most recently used object.
*/
public CacheObject cachePrevious;
/**
* The next element in the LRU linked list. If the next element is the head,
* then this element is the least recently used object.
*/
public CacheObject cacheNext;
/**
* The next element in the hash chain.
*/
public CacheObject cacheChained;
private int pos;
private boolean changed;
/**
* Check if the object can be removed from the cache.
* For example pinned objects can not be removed.
*
* @return true if it can be removed
*/
public abstract boolean canRemove();
/**
* Get the estimated used memory.
*
* @return number of words (one word is 4 bytes)
*/
public abstract int getMemory();
public void setPos(int pos) {
if (SysProperties.CHECK) {
if (cachePrevious != null || cacheNext != null || cacheChained != null) {
DbException.throwInternalError("setPos too late");
}
}
this.pos = pos;
}
public int getPos() {
return pos;
}
/**
* Check if this cache object has been changed and thus needs to be written
* back to the storage.
*
* @return if it has been changed
*/
public boolean isChanged() {
return changed;
}
public void setChanged(boolean b) {
changed = b;
}
@Override
public int compareTo(CacheObject other) {
return Integer.compare(getPos(), other.getPos());
}
public boolean isStream() {
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/CacheSecondLevel.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: Jan Kotek
*/
package org.h2.util;
import java.util.ArrayList;
import java.util.Map;
/**
* Cache which wraps another cache (proxy pattern) and adds caching using map.
* This is useful for WeakReference, SoftReference or hard reference cache.
*/
class CacheSecondLevel implements Cache {
private final Cache baseCache;
private final Map<Integer, CacheObject> map;
CacheSecondLevel(Cache cache, Map<Integer, CacheObject> map) {
this.baseCache = cache;
this.map = map;
}
@Override
public void clear() {
map.clear();
baseCache.clear();
}
@Override
public CacheObject find(int pos) {
CacheObject ret = baseCache.find(pos);
if (ret == null) {
ret = map.get(pos);
}
return ret;
}
@Override
public CacheObject get(int pos) {
CacheObject ret = baseCache.get(pos);
if (ret == null) {
ret = map.get(pos);
}
return ret;
}
@Override
public ArrayList<CacheObject> getAllChanged() {
return baseCache.getAllChanged();
}
@Override
public int getMaxMemory() {
return baseCache.getMaxMemory();
}
@Override
public int getMemory() {
return baseCache.getMemory();
}
@Override
public void put(CacheObject r) {
baseCache.put(r);
map.put(r.getPos(), r);
}
@Override
public boolean remove(int pos) {
boolean result = baseCache.remove(pos);
result |= map.remove(pos) != null;
return result;
}
@Override
public void setMaxMemory(int size) {
baseCache.setMaxMemory(size);
}
@Override
public CacheObject update(int pos, CacheObject record) {
CacheObject oldRec = baseCache.update(pos, record);
map.put(pos, record);
return oldRec;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/CacheTQ.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.ArrayList;
/**
* An alternative cache implementation. This implementation uses two caches: a
* LRU cache and a FIFO cache. Entries are first kept in the FIFO cache, and if
* referenced again then marked in a hash set. If referenced again, they are
* moved to the LRU cache. Stream pages are never added to the LRU cache. It is
* supposed to be more or less scan resistant, and it doesn't cache large rows
* in the LRU cache.
*/
public class CacheTQ implements Cache {
static final String TYPE_NAME = "TQ";
private final Cache lru;
private final Cache fifo;
private final SmallLRUCache<Integer, Object> recentlyUsed =
SmallLRUCache.newInstance(1024);
private int lastUsed = -1;
private int maxMemory;
CacheTQ(CacheWriter writer, int maxMemoryKb) {
this.maxMemory = maxMemoryKb;
lru = new CacheLRU(writer, (int) (maxMemoryKb * 0.8), false);
fifo = new CacheLRU(writer, (int) (maxMemoryKb * 0.2), true);
setMaxMemory(4 * maxMemoryKb);
}
@Override
public void clear() {
lru.clear();
fifo.clear();
recentlyUsed.clear();
lastUsed = -1;
}
@Override
public CacheObject find(int pos) {
CacheObject r = lru.find(pos);
if (r == null) {
r = fifo.find(pos);
}
return r;
}
@Override
public CacheObject get(int pos) {
CacheObject r = lru.find(pos);
if (r != null) {
return r;
}
r = fifo.find(pos);
if (r != null && !r.isStream()) {
if (recentlyUsed.get(pos) != null) {
if (lastUsed != pos) {
fifo.remove(pos);
lru.put(r);
}
} else {
recentlyUsed.put(pos, this);
}
lastUsed = pos;
}
return r;
}
@Override
public ArrayList<CacheObject> getAllChanged() {
ArrayList<CacheObject> changed = New.arrayList();
changed.addAll(lru.getAllChanged());
changed.addAll(fifo.getAllChanged());
return changed;
}
@Override
public int getMaxMemory() {
return maxMemory;
}
@Override
public int getMemory() {
return lru.getMemory() + fifo.getMemory();
}
@Override
public void put(CacheObject r) {
if (r.isStream()) {
fifo.put(r);
} else if (recentlyUsed.get(r.getPos()) != null) {
lru.put(r);
} else {
fifo.put(r);
lastUsed = r.getPos();
}
}
@Override
public boolean remove(int pos) {
boolean result = lru.remove(pos);
if (!result) {
result = fifo.remove(pos);
}
recentlyUsed.remove(pos);
return result;
}
@Override
public void setMaxMemory(int maxMemoryKb) {
this.maxMemory = maxMemoryKb;
lru.setMaxMemory((int) (maxMemoryKb * 0.8));
fifo.setMaxMemory((int) (maxMemoryKb * 0.2));
recentlyUsed.setMaxSize(4 * maxMemoryKb);
}
@Override
public CacheObject update(int pos, CacheObject record) {
if (lru.find(pos) != null) {
return lru.update(pos, record);
}
return fifo.update(pos, record);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/CacheWriter.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import org.h2.message.Trace;
/**
* The cache writer is called by the cache to persist changed data that needs to
* be removed from the cache.
*/
public interface CacheWriter {
/**
* Persist a record.
*
* @param entry the cache entry
*/
void writeBack(CacheObject entry);
/**
* Flush the transaction log, so that entries can be removed from the cache.
* This is only required if the cache is full and contains data that is not
* yet written to the log. It is required to write the log entries to the
* log first, because the log is 'write ahead'.
*/
void flushLog();
/**
* Get the trace writer.
*
* @return the trace writer
*/
Trace getTrace();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/CloseWatcher.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
* Iso8601:
* Initial Developer: Robert Rathsack (firstName dot lastName at gmx dot de)
*/
package org.h2.util;
import java.io.Closeable;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* A phantom reference to watch for unclosed objects.
*/
public class CloseWatcher extends PhantomReference<Object> {
/**
* The queue (might be set to null at any time).
*/
private static ReferenceQueue<Object> queue = new ReferenceQueue<>();
/**
* The reference set. Must keep it, otherwise the references are garbage
* collected first and thus never enqueued.
*/
private static Set<CloseWatcher> refs = createSet();
/**
* The stack trace of when the object was created. It is converted to a
* string early on to avoid classloader problems (a classloader can't be
* garbage collected if there is a static reference to one of its classes).
*/
private String openStackTrace;
/**
* The closeable object.
*/
private Closeable closeable;
public CloseWatcher(Object referent, ReferenceQueue<Object> q,
Closeable closeable) {
super(referent, q);
this.closeable = closeable;
}
private static Set<CloseWatcher> createSet() {
return Collections.synchronizedSet(new HashSet<CloseWatcher>());
}
/**
* Check for an collected object.
*
* @return the first watcher
*/
public static CloseWatcher pollUnclosed() {
ReferenceQueue<Object> q = queue;
if (q == null) {
return null;
}
while (true) {
CloseWatcher cw = (CloseWatcher) q.poll();
if (cw == null) {
return null;
}
if (refs != null) {
refs.remove(cw);
}
if (cw.closeable != null) {
return cw;
}
}
}
/**
* Register an object. Before calling this method, pollUnclosed() should be
* called in a loop to remove old references.
*
* @param o the object
* @param closeable the object to close
* @param stackTrace whether the stack trace should be registered (this is
* relatively slow)
* @return the close watcher
*/
public static CloseWatcher register(Object o, Closeable closeable,
boolean stackTrace) {
ReferenceQueue<Object> q = queue;
if (q == null) {
q = new ReferenceQueue<>();
queue = q;
}
CloseWatcher cw = new CloseWatcher(o, q, closeable);
if (stackTrace) {
Exception e = new Exception("Open Stack Trace");
StringWriter s = new StringWriter();
e.printStackTrace(new PrintWriter(s));
cw.openStackTrace = s.toString();
}
if (refs == null) {
refs = createSet();
}
refs.add(cw);
return cw;
}
/**
* Unregister an object, so it is no longer tracked.
*
* @param w the reference
*/
public static void unregister(CloseWatcher w) {
w.closeable = null;
refs.remove(w);
}
/**
* Get the open stack trace or null if none.
*
* @return the open stack trace
*/
public String getOpenStackTrace() {
return openStackTrace;
}
public Closeable getCloseable() {
return closeable;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ColumnNamer.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
*/
package org.h2.util;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import org.h2.engine.Session;
import org.h2.expression.Expression;
/**
* A factory for column names.
*/
public class ColumnNamer {
private static final String DEFAULT_COLUMN_NAME = "DEFAULT";
private final ColumnNamerConfiguration configuration;
private final Session session;
private final Set<String> existingColumnNames = new HashSet<>();
public ColumnNamer(Session session) {
this.session = session;
if (this.session != null && this.session.getColumnNamerConfiguration() != null) {
// use original from session
this.configuration = this.session.getColumnNamerConfiguration();
} else {
// detached namer, create new
this.configuration = ColumnNamerConfiguration.getDefault();
if (session != null) {
session.setColumnNamerConfiguration(this.configuration);
}
}
}
/**
* Create a standardized column name that isn't null and doesn't have a CR/LF in it.
* @param columnExp the column expression
* @param indexOfColumn index of column in below array
* @param columnNameOverides array of overriding column names
* @return the new column name
*/
public String getColumnName(Expression columnExp, int indexOfColumn, String[] columnNameOverides) {
String columnNameOverride = null;
if (columnNameOverides != null && columnNameOverides.length > indexOfColumn) {
columnNameOverride = columnNameOverides[indexOfColumn];
}
return getColumnName(columnExp, indexOfColumn, columnNameOverride);
}
/**
* Create a standardized column name that isn't null and doesn't have a CR/LF in it.
* @param columnExp the column expression
* @param indexOfColumn index of column in below array
* @param columnNameOverride single overriding column name
* @return the new column name
*/
public String getColumnName(Expression columnExp, int indexOfColumn, String columnNameOverride) {
// try a name from the column name override
String columnName = null;
if (columnNameOverride != null) {
columnName = columnNameOverride;
if (!isAllowableColumnName(columnName)) {
columnName = fixColumnName(columnName);
}
if (!isAllowableColumnName(columnName)) {
columnName = null;
}
}
// try a name from the column alias
if (columnName == null && columnExp.getAlias() != null && !DEFAULT_COLUMN_NAME.equals(columnExp.getAlias())) {
columnName = columnExp.getAlias();
if (!isAllowableColumnName(columnName)) {
columnName = fixColumnName(columnName);
}
if (!isAllowableColumnName(columnName)) {
columnName = null;
}
}
// try a name derived from the column expression SQL
if (columnName == null && columnExp.getColumnName() != null
&& !DEFAULT_COLUMN_NAME.equals(columnExp.getColumnName())) {
columnName = columnExp.getColumnName();
if (!isAllowableColumnName(columnName)) {
columnName = fixColumnName(columnName);
}
if (!isAllowableColumnName(columnName)) {
columnName = null;
}
}
// try a name derived from the column expression plan SQL
if (columnName == null && columnExp.getSQL() != null && !DEFAULT_COLUMN_NAME.equals(columnExp.getSQL())) {
columnName = columnExp.getSQL();
if (!isAllowableColumnName(columnName)) {
columnName = fixColumnName(columnName);
}
if (!isAllowableColumnName(columnName)) {
columnName = null;
}
}
// go with a innocuous default name pattern
if (columnName == null) {
columnName = configuration.getDefaultColumnNamePattern().replace("$$", "" + (indexOfColumn + 1));
}
if (existingColumnNames.contains(columnName) && configuration.isGenerateUniqueColumnNames()) {
columnName = generateUniqueName(columnName);
}
existingColumnNames.add(columnName);
return columnName;
}
private String generateUniqueName(String columnName) {
String newColumnName = columnName;
int loopCount = 2;
while (existingColumnNames.contains(newColumnName)) {
String loopCountString = "_" + loopCount;
newColumnName = columnName.substring(0,
Math.min(columnName.length(), configuration.getMaxIdentiferLength() - loopCountString.length()))
+ loopCountString;
loopCount++;
}
return newColumnName;
}
private boolean isAllowableColumnName(String proposedName) {
// check null
if (proposedName == null) {
return false;
}
// check size limits
if (proposedName.length() > configuration.getMaxIdentiferLength() || proposedName.length() == 0) {
return false;
}
Matcher match = configuration.getCompiledRegularExpressionMatchAllowed().matcher(proposedName);
return match.matches();
}
private String fixColumnName(String proposedName) {
Matcher match = configuration.getCompiledRegularExpressionMatchDisallowed().matcher(proposedName);
proposedName = match.replaceAll("");
// check size limits - then truncate
if (proposedName.length() > configuration.getMaxIdentiferLength()) {
proposedName = proposedName.substring(0, configuration.getMaxIdentiferLength());
}
return proposedName;
}
public ColumnNamerConfiguration getConfiguration() {
return configuration;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ColumnNamerConfiguration.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
*/
package org.h2.util;
import java.util.regex.Pattern;
import org.h2.engine.Mode.ModeEnum;
import static org.h2.engine.Mode.ModeEnum.*;
import org.h2.message.DbException;
/**
* The configuration for the allowed column names.
*/
public class ColumnNamerConfiguration {
private static final String DEFAULT_COMMAND = "DEFAULT";
private static final String REGULAR_EXPRESSION_MATCH_DISALLOWED = "REGULAR_EXPRESSION_MATCH_DISALLOWED = ";
private static final String REGULAR_EXPRESSION_MATCH_ALLOWED = "REGULAR_EXPRESSION_MATCH_ALLOWED = ";
private static final String DEFAULT_COLUMN_NAME_PATTERN = "DEFAULT_COLUMN_NAME_PATTERN = ";
private static final String MAX_IDENTIFIER_LENGTH = "MAX_IDENTIFIER_LENGTH = ";
private static final String EMULATE_COMMAND = "EMULATE = ";
private static final String GENERATE_UNIQUE_COLUMN_NAMES = "GENERATE_UNIQUE_COLUMN_NAMES = ";
private int maxIdentiferLength;
private String regularExpressionMatchAllowed;
private String regularExpressionMatchDisallowed;
private String defaultColumnNamePattern;
private boolean generateUniqueColumnNames;
private Pattern compiledRegularExpressionMatchAllowed;
private Pattern compiledRegularExpressionMatchDisallowed;
public ColumnNamerConfiguration(int maxIdentiferLength, String regularExpressionMatchAllowed,
String regularExpressionMatchDisallowed, String defaultColumnNamePattern,
boolean generateUniqueColumnNames) {
this.maxIdentiferLength = maxIdentiferLength;
this.regularExpressionMatchAllowed = regularExpressionMatchAllowed;
this.regularExpressionMatchDisallowed = regularExpressionMatchDisallowed;
this.defaultColumnNamePattern = defaultColumnNamePattern;
this.generateUniqueColumnNames = generateUniqueColumnNames;
compiledRegularExpressionMatchAllowed = Pattern.compile(regularExpressionMatchAllowed);
compiledRegularExpressionMatchDisallowed = Pattern.compile(regularExpressionMatchDisallowed);
}
public int getMaxIdentiferLength() {
return maxIdentiferLength;
}
public void setMaxIdentiferLength(int maxIdentiferLength) {
this.maxIdentiferLength = Math.max(30, maxIdentiferLength);
if (maxIdentiferLength != getMaxIdentiferLength()) {
throw DbException.getInvalidValueException("Illegal value (<30) in SET COLUMN_NAME_RULES",
"MAX_IDENTIFIER_LENGTH=" + maxIdentiferLength);
}
}
public String getRegularExpressionMatchAllowed() {
return regularExpressionMatchAllowed;
}
public void setRegularExpressionMatchAllowed(String regularExpressionMatchAllowed) {
this.regularExpressionMatchAllowed = regularExpressionMatchAllowed;
}
public String getRegularExpressionMatchDisallowed() {
return regularExpressionMatchDisallowed;
}
public void setRegularExpressionMatchDisallowed(String regularExpressionMatchDisallowed) {
this.regularExpressionMatchDisallowed = regularExpressionMatchDisallowed;
}
public String getDefaultColumnNamePattern() {
return defaultColumnNamePattern;
}
public void setDefaultColumnNamePattern(String defaultColumnNamePattern) {
this.defaultColumnNamePattern = defaultColumnNamePattern;
}
public Pattern getCompiledRegularExpressionMatchAllowed() {
return compiledRegularExpressionMatchAllowed;
}
public void setCompiledRegularExpressionMatchAllowed(Pattern compiledRegularExpressionMatchAllowed) {
this.compiledRegularExpressionMatchAllowed = compiledRegularExpressionMatchAllowed;
}
public Pattern getCompiledRegularExpressionMatchDisallowed() {
return compiledRegularExpressionMatchDisallowed;
}
public void setCompiledRegularExpressionMatchDisallowed(Pattern compiledRegularExpressionMatchDisallowed) {
this.compiledRegularExpressionMatchDisallowed = compiledRegularExpressionMatchDisallowed;
}
/**
* Configure the column namer.
*
* @param stringValue the configuration
*/
public void configure(String stringValue) {
try {
if (stringValue.equalsIgnoreCase(DEFAULT_COMMAND)) {
configure(REGULAR);
} else if (stringValue.startsWith(EMULATE_COMMAND)) {
configure(ModeEnum.valueOf(unquoteString(stringValue.substring(EMULATE_COMMAND.length()))));
} else if (stringValue.startsWith(MAX_IDENTIFIER_LENGTH)) {
int maxLength = Integer.parseInt(stringValue.substring(MAX_IDENTIFIER_LENGTH.length()));
setMaxIdentiferLength(maxLength);
} else if (stringValue.startsWith(GENERATE_UNIQUE_COLUMN_NAMES)) {
setGenerateUniqueColumnNames(
Integer.parseInt(stringValue.substring(GENERATE_UNIQUE_COLUMN_NAMES.length())) == 1);
} else if (stringValue.startsWith(DEFAULT_COLUMN_NAME_PATTERN)) {
setDefaultColumnNamePattern(
unquoteString(stringValue.substring(DEFAULT_COLUMN_NAME_PATTERN.length())));
} else if (stringValue.startsWith(REGULAR_EXPRESSION_MATCH_ALLOWED)) {
setRegularExpressionMatchAllowed(
unquoteString(stringValue.substring(REGULAR_EXPRESSION_MATCH_ALLOWED.length())));
} else if (stringValue.startsWith(REGULAR_EXPRESSION_MATCH_DISALLOWED)) {
setRegularExpressionMatchDisallowed(
unquoteString(stringValue.substring(REGULAR_EXPRESSION_MATCH_DISALLOWED.length())));
} else {
throw DbException.getInvalidValueException("SET COLUMN_NAME_RULES: unknown id:" + stringValue,
stringValue);
}
recompilePatterns();
}
// Including NumberFormatException|PatternSyntaxException
catch (RuntimeException e) {
throw DbException.getInvalidValueException("SET COLUMN_NAME_RULES:" + e.getMessage(), stringValue);
}
}
private void recompilePatterns() {
try {
// recompile RE patterns
setCompiledRegularExpressionMatchAllowed(Pattern.compile(getRegularExpressionMatchAllowed()));
setCompiledRegularExpressionMatchDisallowed(Pattern.compile(getRegularExpressionMatchDisallowed()));
} catch (Exception e) {
configure(REGULAR);
throw e;
}
}
public static ColumnNamerConfiguration getDefault() {
return new ColumnNamerConfiguration(Integer.MAX_VALUE, "(?m)(?s).+", "(?m)(?s)[\\x00]", "_UNNAMED_$$", false);
}
private static String unquoteString(String s) {
if (s.startsWith("'") && s.endsWith("'")) {
s = s.substring(1, s.length() - 1);
return s;
}
return s;
}
public boolean isGenerateUniqueColumnNames() {
return generateUniqueColumnNames;
}
public void setGenerateUniqueColumnNames(boolean generateUniqueColumnNames) {
this.generateUniqueColumnNames = generateUniqueColumnNames;
}
/**
* Configure the rules.
*
* @param modeEnum the mode
*/
public void configure(ModeEnum modeEnum) {
switch (modeEnum) {
case Oracle:
// Nonquoted identifiers can contain only alphanumeric characters
// from your database character set and the underscore (_), dollar
// sign ($), and pound sign (#).
setMaxIdentiferLength(128);
setRegularExpressionMatchAllowed("(?m)(?s)\"?[A-Za-z0-9_\\$#]+\"?");
setRegularExpressionMatchDisallowed("(?m)(?s)[^A-Za-z0-9_\"\\$#]");
setDefaultColumnNamePattern("_UNNAMED_$$");
setGenerateUniqueColumnNames(false);
break;
case MSSQLServer:
// https://docs.microsoft.com/en-us/sql/sql-server/maximum-capacity-specifications-for-sql-server
setMaxIdentiferLength(128);
// allows [] around names
setRegularExpressionMatchAllowed("(?m)(?s)[A-Za-z0-9_\\[\\]]+");
setRegularExpressionMatchDisallowed("(?m)(?s)[^A-Za-z0-9_\\[\\]]");
setDefaultColumnNamePattern("_UNNAMED_$$");
setGenerateUniqueColumnNames(false);
break;
case PostgreSQL:
// this default can be changed to 128 by postgres config
setMaxIdentiferLength(63);
setRegularExpressionMatchAllowed("(?m)(?s)[A-Za-z0-9_\\$]+");
setRegularExpressionMatchDisallowed("(?m)(?s)[^A-Za-z0-9_\\$]");
setDefaultColumnNamePattern("_UNNAMED_$$");
setGenerateUniqueColumnNames(false);
break;
case MySQL:
// https://dev.mysql.com/doc/refman/5.7/en/identifiers.html
setMaxIdentiferLength(64);
setRegularExpressionMatchAllowed("(?m)(?s)`?[A-Za-z0-9_`\\$]+`?");
setRegularExpressionMatchDisallowed("(?m)(?s)[^A-Za-z0-9_`\\$]");
setDefaultColumnNamePattern("_UNNAMED_$$");
setGenerateUniqueColumnNames(false);
break;
case REGULAR:
case DB2:
case Derby:
case HSQLDB:
case Ignite:
default:
setMaxIdentiferLength(Integer.MAX_VALUE);
setRegularExpressionMatchAllowed("(?m)(?s).+");
setRegularExpressionMatchDisallowed("(?m)(?s)[\\x00]");
setDefaultColumnNamePattern("_UNNAMED_$$");
setGenerateUniqueColumnNames(false);
break;
}
recompilePatterns();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/DateTimeFunctions.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import static org.h2.expression.Function.CENTURY;
import static org.h2.expression.Function.DAY_OF_MONTH;
import static org.h2.expression.Function.DAY_OF_WEEK;
import static org.h2.expression.Function.DAY_OF_YEAR;
import static org.h2.expression.Function.DECADE;
import static org.h2.expression.Function.EPOCH;
import static org.h2.expression.Function.HOUR;
import static org.h2.expression.Function.ISO_DAY_OF_WEEK;
import static org.h2.expression.Function.ISO_WEEK;
import static org.h2.expression.Function.ISO_YEAR;
import static org.h2.expression.Function.MICROSECOND;
import static org.h2.expression.Function.MILLENNIUM;
import static org.h2.expression.Function.MILLISECOND;
import static org.h2.expression.Function.MINUTE;
import static org.h2.expression.Function.MONTH;
import static org.h2.expression.Function.NANOSECOND;
import static org.h2.expression.Function.QUARTER;
import static org.h2.expression.Function.SECOND;
import static org.h2.expression.Function.TIMEZONE_HOUR;
import static org.h2.expression.Function.TIMEZONE_MINUTE;
import static org.h2.expression.Function.WEEK;
import static org.h2.expression.Function.YEAR;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import org.h2.api.ErrorCode;
import org.h2.expression.Function;
import org.h2.message.DbException;
import org.h2.value.Value;
import org.h2.value.ValueDate;
import org.h2.value.ValueDecimal;
import org.h2.value.ValueInt;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueTimestampTimeZone;
/**
* Date and time functions.
*/
public final class DateTimeFunctions {
private static final HashMap<String, Integer> DATE_PART = new HashMap<>();
/**
* English names of months and week days.
*/
private static volatile String[][] MONTHS_AND_WEEKS;
static {
// DATE_PART
DATE_PART.put("SQL_TSI_YEAR", YEAR);
DATE_PART.put("YEAR", YEAR);
DATE_PART.put("YYYY", YEAR);
DATE_PART.put("YY", YEAR);
DATE_PART.put("SQL_TSI_MONTH", MONTH);
DATE_PART.put("MONTH", MONTH);
DATE_PART.put("MM", MONTH);
DATE_PART.put("M", MONTH);
DATE_PART.put("QUARTER", QUARTER);
DATE_PART.put("SQL_TSI_WEEK", WEEK);
DATE_PART.put("WW", WEEK);
DATE_PART.put("WK", WEEK);
DATE_PART.put("WEEK", WEEK);
DATE_PART.put("ISO_WEEK", ISO_WEEK);
DATE_PART.put("DAY", DAY_OF_MONTH);
DATE_PART.put("DD", DAY_OF_MONTH);
DATE_PART.put("D", DAY_OF_MONTH);
DATE_PART.put("SQL_TSI_DAY", DAY_OF_MONTH);
DATE_PART.put("DAY_OF_WEEK", DAY_OF_WEEK);
DATE_PART.put("DAYOFWEEK", DAY_OF_WEEK);
DATE_PART.put("DOW", DAY_OF_WEEK);
DATE_PART.put("ISO_DAY_OF_WEEK", ISO_DAY_OF_WEEK);
DATE_PART.put("DAYOFYEAR", DAY_OF_YEAR);
DATE_PART.put("DAY_OF_YEAR", DAY_OF_YEAR);
DATE_PART.put("DY", DAY_OF_YEAR);
DATE_PART.put("DOY", DAY_OF_YEAR);
DATE_PART.put("SQL_TSI_HOUR", HOUR);
DATE_PART.put("HOUR", HOUR);
DATE_PART.put("HH", HOUR);
DATE_PART.put("SQL_TSI_MINUTE", MINUTE);
DATE_PART.put("MINUTE", MINUTE);
DATE_PART.put("MI", MINUTE);
DATE_PART.put("N", MINUTE);
DATE_PART.put("SQL_TSI_SECOND", SECOND);
DATE_PART.put("SECOND", SECOND);
DATE_PART.put("SS", SECOND);
DATE_PART.put("S", SECOND);
DATE_PART.put("MILLISECOND", MILLISECOND);
DATE_PART.put("MILLISECONDS", MILLISECOND);
DATE_PART.put("MS", MILLISECOND);
DATE_PART.put("EPOCH", EPOCH);
DATE_PART.put("MICROSECOND", MICROSECOND);
DATE_PART.put("MICROSECONDS", MICROSECOND);
DATE_PART.put("MCS", MICROSECOND);
DATE_PART.put("NANOSECOND", NANOSECOND);
DATE_PART.put("NS", NANOSECOND);
DATE_PART.put("TIMEZONE_HOUR", TIMEZONE_HOUR);
DATE_PART.put("TIMEZONE_MINUTE", TIMEZONE_MINUTE);
DATE_PART.put("DECADE", DECADE);
DATE_PART.put("CENTURY", CENTURY);
DATE_PART.put("MILLENNIUM", MILLENNIUM);
}
/**
* DATEADD function.
*
* @param part
* name of date-time part
* @param count
* count to add
* @param v
* value to add to
* @return result
*/
public static Value dateadd(String part, long count, Value v) {
int field = getDatePart(part);
if (field != MILLISECOND && field != MICROSECOND && field != NANOSECOND
&& (count > Integer.MAX_VALUE || count < Integer.MIN_VALUE)) {
throw DbException.getInvalidValueException("DATEADD count", count);
}
boolean withDate = !(v instanceof ValueTime);
boolean withTime = !(v instanceof ValueDate);
boolean forceTimestamp = false;
long[] a = DateTimeUtils.dateAndTimeFromValue(v);
long dateValue = a[0];
long timeNanos = a[1];
switch (field) {
case QUARTER:
count *= 3;
//$FALL-THROUGH$
case YEAR:
case MONTH: {
if (!withDate) {
throw DbException.getInvalidValueException("DATEADD time part", part);
}
long year = DateTimeUtils.yearFromDateValue(dateValue);
long month = DateTimeUtils.monthFromDateValue(dateValue);
int day = DateTimeUtils.dayFromDateValue(dateValue);
if (field == YEAR) {
year += count;
} else {
month += count;
}
dateValue = DateTimeUtils.dateValueFromDenormalizedDate(year, month, day);
return DateTimeUtils.dateTimeToValue(v, dateValue, timeNanos, forceTimestamp);
}
case WEEK:
case ISO_WEEK:
count *= 7;
//$FALL-THROUGH$
case DAY_OF_WEEK:
case ISO_DAY_OF_WEEK:
case DAY_OF_MONTH:
case DAY_OF_YEAR:
if (!withDate) {
throw DbException.getInvalidValueException("DATEADD time part", part);
}
dateValue = DateTimeUtils
.dateValueFromAbsoluteDay(DateTimeUtils.absoluteDayFromDateValue(dateValue) + count);
return DateTimeUtils.dateTimeToValue(v, dateValue, timeNanos, forceTimestamp);
case HOUR:
count *= 3_600_000_000_000L;
break;
case MINUTE:
count *= 60_000_000_000L;
break;
case SECOND:
case EPOCH:
count *= 1_000_000_000;
break;
case MILLISECOND:
count *= 1_000_000;
break;
case MICROSECOND:
count *= 1_000;
break;
case NANOSECOND:
break;
case TIMEZONE_HOUR:
count *= 60;
//$FALL-THROUGH$
case TIMEZONE_MINUTE: {
if (!(v instanceof ValueTimestampTimeZone)) {
throw DbException.getUnsupportedException("DATEADD " + part);
}
count += ((ValueTimestampTimeZone) v).getTimeZoneOffsetMins();
return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos, (short) count);
}
default:
throw DbException.getUnsupportedException("DATEADD " + part);
}
if (!withTime) {
// Treat date as timestamp at the start of this date
forceTimestamp = true;
}
timeNanos += count;
if (timeNanos >= DateTimeUtils.NANOS_PER_DAY || timeNanos < 0) {
long d;
if (timeNanos >= DateTimeUtils.NANOS_PER_DAY) {
d = timeNanos / DateTimeUtils.NANOS_PER_DAY;
} else {
d = (timeNanos - DateTimeUtils.NANOS_PER_DAY + 1) / DateTimeUtils.NANOS_PER_DAY;
}
timeNanos -= d * DateTimeUtils.NANOS_PER_DAY;
return DateTimeUtils.dateTimeToValue(v,
DateTimeUtils.dateValueFromAbsoluteDay(DateTimeUtils.absoluteDayFromDateValue(dateValue) + d),
timeNanos, forceTimestamp);
}
return DateTimeUtils.dateTimeToValue(v, dateValue, timeNanos, forceTimestamp);
}
/**
* Calculate the number of crossed unit boundaries between two timestamps. This
* method is supported for MS SQL Server compatibility.
*
* <pre>
* DATEDIFF(YEAR, '2004-12-31', '2005-01-01') = 1
* </pre>
*
* @param part
* the part
* @param v1
* the first date-time value
* @param v2
* the second date-time value
* @return the number of crossed boundaries
*/
public static long datediff(String part, Value v1, Value v2) {
int field = getDatePart(part);
long[] a1 = DateTimeUtils.dateAndTimeFromValue(v1);
long dateValue1 = a1[0];
long absolute1 = DateTimeUtils.absoluteDayFromDateValue(dateValue1);
long[] a2 = DateTimeUtils.dateAndTimeFromValue(v2);
long dateValue2 = a2[0];
long absolute2 = DateTimeUtils.absoluteDayFromDateValue(dateValue2);
switch (field) {
case NANOSECOND:
case MICROSECOND:
case MILLISECOND:
case SECOND:
case EPOCH:
case MINUTE:
case HOUR:
long timeNanos1 = a1[1];
long timeNanos2 = a2[1];
switch (field) {
case NANOSECOND:
return (absolute2 - absolute1) * DateTimeUtils.NANOS_PER_DAY + (timeNanos2 - timeNanos1);
case MICROSECOND:
return (absolute2 - absolute1) * (DateTimeUtils.MILLIS_PER_DAY * 1_000)
+ (timeNanos2 / 1_000 - timeNanos1 / 1_000);
case MILLISECOND:
return (absolute2 - absolute1) * DateTimeUtils.MILLIS_PER_DAY
+ (timeNanos2 / 1_000_000 - timeNanos1 / 1_000_000);
case SECOND:
case EPOCH:
return (absolute2 - absolute1) * 86_400 + (timeNanos2 / 1_000_000_000 - timeNanos1 / 1_000_000_000);
case MINUTE:
return (absolute2 - absolute1) * 1_440 + (timeNanos2 / 60_000_000_000L - timeNanos1 / 60_000_000_000L);
case HOUR:
return (absolute2 - absolute1) * 24
+ (timeNanos2 / 3_600_000_000_000L - timeNanos1 / 3_600_000_000_000L);
}
// Fake fall-through
// $FALL-THROUGH$
case DAY_OF_MONTH:
case DAY_OF_YEAR:
case DAY_OF_WEEK:
case ISO_DAY_OF_WEEK:
return absolute2 - absolute1;
case WEEK:
return weekdiff(absolute1, absolute2, 0);
case ISO_WEEK:
return weekdiff(absolute1, absolute2, 1);
case MONTH:
return (DateTimeUtils.yearFromDateValue(dateValue2) - DateTimeUtils.yearFromDateValue(dateValue1)) * 12
+ DateTimeUtils.monthFromDateValue(dateValue2) - DateTimeUtils.monthFromDateValue(dateValue1);
case QUARTER:
return (DateTimeUtils.yearFromDateValue(dateValue2) - DateTimeUtils.yearFromDateValue(dateValue1)) * 4
+ (DateTimeUtils.monthFromDateValue(dateValue2) - 1) / 3
- (DateTimeUtils.monthFromDateValue(dateValue1) - 1) / 3;
case YEAR:
return DateTimeUtils.yearFromDateValue(dateValue2) - DateTimeUtils.yearFromDateValue(dateValue1);
case TIMEZONE_HOUR:
case TIMEZONE_MINUTE: {
int offsetMinutes1;
if (v1 instanceof ValueTimestampTimeZone) {
offsetMinutes1 = ((ValueTimestampTimeZone) v1).getTimeZoneOffsetMins();
} else {
offsetMinutes1 = DateTimeUtils.getTimeZoneOffsetMillis(null, dateValue1, a1[1]);
}
int offsetMinutes2;
if (v2 instanceof ValueTimestampTimeZone) {
offsetMinutes2 = ((ValueTimestampTimeZone) v2).getTimeZoneOffsetMins();
} else {
offsetMinutes2 = DateTimeUtils.getTimeZoneOffsetMillis(null, dateValue2, a2[1]);
}
if (field == TIMEZONE_HOUR) {
return (offsetMinutes2 / 60) - (offsetMinutes1 / 60);
} else {
return offsetMinutes2 - offsetMinutes1;
}
}
default:
throw DbException.getUnsupportedException("DATEDIFF " + part);
}
}
/**
* Extracts specified field from the specified date-time value.
*
* @param part
* the date part
* @param value
* the date-time value
* @return extracted field
*/
public static Value extract(String part, Value value) {
Value result;
int field = getDatePart(part);
if (field != EPOCH) {
result = ValueInt.get(getIntDatePart(value, field));
} else {
// Case where we retrieve the EPOCH time.
// First we retrieve the dateValue and his time in nanoseconds.
long[] a = DateTimeUtils.dateAndTimeFromValue(value);
long dateValue = a[0];
long timeNanos = a[1];
// We compute the time in nanoseconds and the total number of days.
BigDecimal timeNanosBigDecimal = new BigDecimal(timeNanos);
BigDecimal numberOfDays = new BigDecimal(DateTimeUtils.absoluteDayFromDateValue(dateValue));
BigDecimal nanosSeconds = new BigDecimal(1_000_000_000);
BigDecimal secondsPerDay = new BigDecimal(DateTimeUtils.SECONDS_PER_DAY);
// Case where the value is of type time e.g. '10:00:00'
if (value instanceof ValueTime) {
// In order to retrieve the EPOCH time we only have to convert the time
// in nanoseconds (previously retrieved) in seconds.
result = ValueDecimal.get(timeNanosBigDecimal.divide(nanosSeconds));
} else if (value instanceof ValueDate) {
// Case where the value is of type date '2000:01:01', we have to retrieve the
// total number of days and multiply it by the number of seconds in a day.
result = ValueDecimal.get(numberOfDays.multiply(secondsPerDay));
} else if (value instanceof ValueTimestampTimeZone) {
// Case where the value is a of type ValueTimestampTimeZone
// ('2000:01:01 10:00:00+05').
// We retrieve the time zone offset in minutes
ValueTimestampTimeZone v = (ValueTimestampTimeZone) value;
BigDecimal timeZoneOffsetSeconds = new BigDecimal(v.getTimeZoneOffsetMins() * 60);
// Sum the time in nanoseconds and the total number of days in seconds
// and adding the timeZone offset in seconds.
result = ValueDecimal.get(timeNanosBigDecimal.divide(nanosSeconds)
.add(numberOfDays.multiply(secondsPerDay)).subtract(timeZoneOffsetSeconds));
} else {
// By default, we have the date and the time ('2000:01:01 10:00:00') if no type
// is given.
// We just have to sum the time in nanoseconds and the total number of days in
// seconds.
result = ValueDecimal
.get(timeNanosBigDecimal.divide(nanosSeconds).add(numberOfDays.multiply(secondsPerDay)));
}
}
return result;
}
/**
* Truncate the given date to the unit specified
*
* @param datePartStr the time unit (e.g. 'DAY', 'HOUR', etc.)
* @param valueDate the date
* @return date truncated to 'day'
*/
public static Value truncateDate(String datePartStr, Value valueDate) {
int timeUnit = getDatePart(datePartStr);
// Retrieve the dateValue and the time in nanoseconds of the date.
long[] fieldDateAndTime = DateTimeUtils.dateAndTimeFromValue(valueDate);
long dateValue = fieldDateAndTime[0];
long timeNanosRetrieved = fieldDateAndTime[1];
// Variable used to the time in nanoseconds of the date truncated.
long timeNanos;
// Compute the number of time unit in the date, for example, the
// number of time unit 'HOUR' in '15:14:13' is '15'. Then convert the
// result to nanoseconds.
switch (timeUnit) {
case MICROSECOND:
long nanoInMicroSecond = 1_000L;
long microseconds = timeNanosRetrieved / nanoInMicroSecond;
timeNanos = microseconds * nanoInMicroSecond;
break;
case MILLISECOND:
long nanoInMilliSecond = 1_000_000L;
long milliseconds = timeNanosRetrieved / nanoInMilliSecond;
timeNanos = milliseconds * nanoInMilliSecond;
break;
case SECOND:
long nanoInSecond = 1_000_000_000L;
long seconds = timeNanosRetrieved / nanoInSecond;
timeNanos = seconds * nanoInSecond;
break;
case MINUTE:
long nanoInMinute = 60_000_000_000L;
long minutes = timeNanosRetrieved / nanoInMinute;
timeNanos = minutes * nanoInMinute;
break;
case HOUR:
long nanoInHour = 3_600_000_000_000L;
long hours = timeNanosRetrieved / nanoInHour;
timeNanos = hours * nanoInHour;
break;
case DAY_OF_MONTH:
timeNanos = 0L;
break;
case WEEK:
long absoluteDay = DateTimeUtils.absoluteDayFromDateValue(dateValue);
int dayOfWeek = DateTimeUtils.getDayOfWeekFromAbsolute(absoluteDay, 1);
if (dayOfWeek != 1) {
dateValue = DateTimeUtils.dateValueFromAbsoluteDay(absoluteDay - dayOfWeek + 1);
}
timeNanos = 0L;
break;
case MONTH: {
long year = DateTimeUtils.yearFromDateValue(dateValue);
int month = DateTimeUtils.monthFromDateValue(dateValue);
dateValue = DateTimeUtils.dateValue(year, month, 1);
timeNanos = 0L;
break;
}
case QUARTER: {
long year = DateTimeUtils.yearFromDateValue(dateValue);
int month = DateTimeUtils.monthFromDateValue(dateValue);
month = ((month - 1) / 3) * 3 + 1;
dateValue = DateTimeUtils.dateValue(year, month, 1);
timeNanos = 0L;
break;
}
case YEAR: {
long year = DateTimeUtils.yearFromDateValue(dateValue);
dateValue = DateTimeUtils.dateValue(year, 1, 1);
timeNanos = 0L;
break;
}
case DECADE: {
long year = DateTimeUtils.yearFromDateValue(dateValue);
year = (year / 10) * 10;
dateValue = DateTimeUtils.dateValue(year, 1, 1);
timeNanos = 0L;
break;
}
case CENTURY: {
long year = DateTimeUtils.yearFromDateValue(dateValue);
year = ((year - 1) / 100) * 100 + 1;
dateValue = DateTimeUtils.dateValue(year, 1, 1);
timeNanos = 0L;
break;
}
case MILLENNIUM: {
long year = DateTimeUtils.yearFromDateValue(dateValue);
year = ((year - 1) / 1000) * 1000 + 1;
dateValue = DateTimeUtils.dateValue(year, 1, 1);
timeNanos = 0L;
break;
}
default:
// Return an exception in the timeUnit is not recognized
throw DbException.getUnsupportedException(datePartStr);
}
Value result;
if (valueDate instanceof ValueTimestampTimeZone) {
// Case we create a timestamp with timezone with the dateValue and
// timeNanos computed.
ValueTimestampTimeZone vTmp = (ValueTimestampTimeZone) valueDate;
result = ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos, vTmp.getTimeZoneOffsetMins());
} else {
// By default, we create a timestamp with the dateValue and
// timeNanos computed.
result = ValueTimestamp.fromDateValueAndNanos(dateValue, timeNanos);
}
return result;
}
/**
* Formats a date using a format string.
*
* @param date
* the date to format
* @param format
* the format string
* @param locale
* the locale
* @param timeZone
* the timezone
* @return the formatted date
*/
public static String formatDateTime(java.util.Date date, String format, String locale, String timeZone) {
SimpleDateFormat dateFormat = getDateFormat(format, locale, timeZone);
synchronized (dateFormat) {
return dateFormat.format(date);
}
}
private static SimpleDateFormat getDateFormat(String format, String locale, String timeZone) {
try {
// currently, a new instance is create for each call
// however, could cache the last few instances
SimpleDateFormat df;
if (locale == null) {
df = new SimpleDateFormat(format);
} else {
Locale l = new Locale(locale);
df = new SimpleDateFormat(format, l);
}
if (timeZone != null) {
df.setTimeZone(TimeZone.getTimeZone(timeZone));
}
return df;
} catch (Exception e) {
throw DbException.get(ErrorCode.PARSE_ERROR_1, e, format + "/" + locale + "/" + timeZone);
}
}
private static int getDatePart(String part) {
Integer p = DATE_PART.get(StringUtils.toUpperEnglish(part));
if (p == null) {
throw DbException.getInvalidValueException("date part", part);
}
return p.intValue();
}
/**
* Get the specified field of a date, however with years normalized to positive
* or negative, and month starting with 1.
*
* @param date
* the date value
* @param field
* the field type, see {@link Function} for constants
* @return the value
*/
public static int getIntDatePart(Value date, int field) {
long[] a = DateTimeUtils.dateAndTimeFromValue(date);
long dateValue = a[0];
long timeNanos = a[1];
switch (field) {
case YEAR:
return DateTimeUtils.yearFromDateValue(dateValue);
case MONTH:
return DateTimeUtils.monthFromDateValue(dateValue);
case DAY_OF_MONTH:
return DateTimeUtils.dayFromDateValue(dateValue);
case HOUR:
return (int) (timeNanos / 3_600_000_000_000L % 24);
case MINUTE:
return (int) (timeNanos / 60_000_000_000L % 60);
case SECOND:
return (int) (timeNanos / 1_000_000_000 % 60);
case MILLISECOND:
return (int) (timeNanos / 1_000_000 % 1_000);
case MICROSECOND:
return (int) (timeNanos / 1_000 % 1_000_000);
case NANOSECOND:
return (int) (timeNanos % 1_000_000_000);
case DAY_OF_YEAR:
return DateTimeUtils.getDayOfYear(dateValue);
case DAY_OF_WEEK:
return DateTimeUtils.getSundayDayOfWeek(dateValue);
case WEEK:
GregorianCalendar gc = DateTimeUtils.getCalendar();
return DateTimeUtils.getWeekOfYear(dateValue, gc.getFirstDayOfWeek() - 1, gc.getMinimalDaysInFirstWeek());
case QUARTER:
return (DateTimeUtils.monthFromDateValue(dateValue) - 1) / 3 + 1;
case ISO_YEAR:
return DateTimeUtils.getIsoWeekYear(dateValue);
case ISO_WEEK:
return DateTimeUtils.getIsoWeekOfYear(dateValue);
case ISO_DAY_OF_WEEK:
return DateTimeUtils.getIsoDayOfWeek(dateValue);
case TIMEZONE_HOUR:
case TIMEZONE_MINUTE: {
int offsetMinutes;
if (date instanceof ValueTimestampTimeZone) {
offsetMinutes = ((ValueTimestampTimeZone) date).getTimeZoneOffsetMins();
} else {
offsetMinutes = DateTimeUtils.getTimeZoneOffsetMillis(null, dateValue, timeNanos);
}
if (field == TIMEZONE_HOUR) {
return offsetMinutes / 60;
}
return offsetMinutes % 60;
}
}
throw DbException.getUnsupportedException("getDatePart(" + date + ", " + field + ')');
}
/**
* Return names of month or weeks.
*
* @param field
* 0 for months, 1 for weekdays
* @return names of month or weeks
*/
public static String[] getMonthsAndWeeks(int field) {
String[][] result = MONTHS_AND_WEEKS;
if (result == null) {
result = new String[2][];
DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ENGLISH);
result[0] = dfs.getMonths();
result[1] = dfs.getWeekdays();
MONTHS_AND_WEEKS = result;
}
return result[field];
}
/**
* Check if a given string is a valid date part string.
*
* @param part
* the string
* @return true if it is
*/
public static boolean isDatePart(String part) {
return DATE_PART.containsKey(StringUtils.toUpperEnglish(part));
}
/**
* Parses a date using a format string.
*
* @param date
* the date to parse
* @param format
* the parsing format
* @param locale
* the locale
* @param timeZone
* the timeZone
* @return the parsed date
*/
public static java.util.Date parseDateTime(String date, String format, String locale, String timeZone) {
SimpleDateFormat dateFormat = getDateFormat(format, locale, timeZone);
try {
synchronized (dateFormat) {
return dateFormat.parse(date);
}
} catch (Exception e) {
// ParseException
throw DbException.get(ErrorCode.PARSE_ERROR_1, e, date);
}
}
private static long weekdiff(long absolute1, long absolute2, int firstDayOfWeek) {
absolute1 += 4 - firstDayOfWeek;
long r1 = absolute1 / 7;
if (absolute1 < 0 && (r1 * 7 != absolute1)) {
r1--;
}
absolute2 += 4 - firstDayOfWeek;
long r2 = absolute2 / 7;
if (absolute2 < 0 && (r2 * 7 != absolute2)) {
r2--;
}
return r2 - r1;
}
private DateTimeFunctions() {
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/DateTimeUtils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, and the
* EPL 1.0 (http://h2database.com/html/license.html). Initial Developer: H2
* Group Iso8601: Initial Developer: Robert Rathsack (firstName dot lastName at
* gmx dot de)
*/
package org.h2.util;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.h2.engine.Mode;
import org.h2.message.DbException;
import org.h2.value.Value;
import org.h2.value.ValueDate;
import org.h2.value.ValueNull;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueTimestampTimeZone;
/**
* This utility class contains time conversion functions.
* <p>
* Date value: a bit field with bits for the year, month, and day. Absolute day:
* the day number (0 means 1970-01-01).
*/
public class DateTimeUtils {
/**
* The number of milliseconds per day.
*/
public static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
/**
* The number of seconds per day.
*/
public static final long SECONDS_PER_DAY = 24 * 60 * 60;
/**
* UTC time zone.
*/
public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
/**
* The number of nanoseconds per day.
*/
public static final long NANOS_PER_DAY = MILLIS_PER_DAY * 1_000_000;
private static final int SHIFT_YEAR = 9;
private static final int SHIFT_MONTH = 5;
/**
* Date value for 1970-01-01.
*/
public static final int EPOCH_DATE_VALUE = (1970 << SHIFT_YEAR) + (1 << SHIFT_MONTH) + 1;
private static final int[] NORMAL_DAYS_PER_MONTH = { 0, 31, 28, 31, 30, 31,
30, 31, 31, 30, 31, 30, 31 };
/**
* Offsets of month within a year, starting with March, April,...
*/
private static final int[] DAYS_OFFSET = { 0, 31, 61, 92, 122, 153, 184,
214, 245, 275, 306, 337, 366 };
/**
* Multipliers for {@link #convertScale(long, int)}.
*/
private static final int[] CONVERT_SCALE_TABLE = { 1_000_000_000, 100_000_000,
10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10 };
/**
* The thread local. Can not override initialValue because this would result
* in an inner class, which would not be garbage collected in a web
* container, and prevent the class loader of H2 from being garbage
* collected. Using a ThreadLocal on a system class like Calendar does not
* have that problem, and while it is still a small memory leak, it is not a
* class loader memory leak.
*/
private static final ThreadLocal<GregorianCalendar> CACHED_CALENDAR = new ThreadLocal<>();
/**
* A cached instance of Calendar used when a timezone is specified.
*/
private static final ThreadLocal<GregorianCalendar> CACHED_CALENDAR_NON_DEFAULT_TIMEZONE =
new ThreadLocal<>();
/**
* Cached local time zone.
*/
private static volatile TimeZone timeZone;
/**
* Observed JVM behaviour is that if the timezone of the host computer is
* changed while the JVM is running, the zone offset does not change but
* keeps the initial value. So it is correct to measure this once and use
* this value throughout the JVM's lifecycle. In any case, it is safer to
* use a fixed value throughout the duration of the JVM's life, rather than
* have this offset change, possibly midway through a long-running query.
*/
private static int zoneOffsetMillis = createGregorianCalendar().get(Calendar.ZONE_OFFSET);
private DateTimeUtils() {
// utility class
}
/**
* Returns local time zone.
*
* @return local time zone
*/
private static TimeZone getTimeZone() {
TimeZone tz = timeZone;
if (tz == null) {
timeZone = tz = TimeZone.getDefault();
}
return tz;
}
/**
* Reset the cached calendar for default timezone, for example after
* changing the default timezone.
*/
public static void resetCalendar() {
CACHED_CALENDAR.remove();
timeZone = null;
zoneOffsetMillis = createGregorianCalendar().get(Calendar.ZONE_OFFSET);
}
/**
* Get a calendar for the default timezone.
*
* @return a calendar instance. A cached instance is returned where possible
*/
public static GregorianCalendar getCalendar() {
GregorianCalendar c = CACHED_CALENDAR.get();
if (c == null) {
c = createGregorianCalendar();
CACHED_CALENDAR.set(c);
}
c.clear();
return c;
}
/**
* Get a calendar for the given timezone.
*
* @param tz timezone for the calendar, is never null
* @return a calendar instance. A cached instance is returned where possible
*/
private static GregorianCalendar getCalendar(TimeZone tz) {
GregorianCalendar c = CACHED_CALENDAR_NON_DEFAULT_TIMEZONE.get();
if (c == null || !c.getTimeZone().equals(tz)) {
c = createGregorianCalendar(tz);
CACHED_CALENDAR_NON_DEFAULT_TIMEZONE.set(c);
}
c.clear();
return c;
}
/**
* Creates a Gregorian calendar for the default timezone using the default
* locale. Dates in H2 are represented in a Gregorian calendar. So this
* method should be used instead of Calendar.getInstance() to ensure that
* the Gregorian calendar is used for all date processing instead of a
* default locale calendar that can be non-Gregorian in some locales.
*
* @return a new calendar instance.
*/
public static GregorianCalendar createGregorianCalendar() {
return new GregorianCalendar();
}
/**
* Creates a Gregorian calendar for the given timezone using the default
* locale. Dates in H2 are represented in a Gregorian calendar. So this
* method should be used instead of Calendar.getInstance() to ensure that
* the Gregorian calendar is used for all date processing instead of a
* default locale calendar that can be non-Gregorian in some locales.
*
* @param tz timezone for the calendar, is never null
* @return a new calendar instance.
*/
public static GregorianCalendar createGregorianCalendar(TimeZone tz) {
return new GregorianCalendar(tz);
}
/**
* Convert the date to the specified time zone.
*
* @param value the date (might be ValueNull)
* @param calendar the calendar
* @return the date using the correct time zone
*/
public static Date convertDate(Value value, Calendar calendar) {
if (value == ValueNull.INSTANCE) {
return null;
}
ValueDate d = (ValueDate) value.convertTo(Value.DATE);
Calendar cal = (Calendar) calendar.clone();
cal.clear();
cal.setLenient(true);
long dateValue = d.getDateValue();
long ms = convertToMillis(cal, yearFromDateValue(dateValue),
monthFromDateValue(dateValue), dayFromDateValue(dateValue), 0,
0, 0, 0);
return new Date(ms);
}
/**
* Convert the time to the specified time zone.
*
* @param value the time (might be ValueNull)
* @param calendar the calendar
* @return the time using the correct time zone
*/
public static Time convertTime(Value value, Calendar calendar) {
if (value == ValueNull.INSTANCE) {
return null;
}
ValueTime t = (ValueTime) value.convertTo(Value.TIME);
Calendar cal = (Calendar) calendar.clone();
cal.clear();
cal.setLenient(true);
long nanos = t.getNanos();
long millis = nanos / 1_000_000;
nanos -= millis * 1_000_000;
long s = millis / 1_000;
millis -= s * 1_000;
long m = s / 60;
s -= m * 60;
long h = m / 60;
m -= h * 60;
return new Time(convertToMillis(cal, 1970, 1, 1, (int) h, (int) m, (int) s, (int) millis));
}
/**
* Convert the timestamp to the specified time zone.
*
* @param value the timestamp (might be ValueNull)
* @param calendar the calendar
* @return the timestamp using the correct time zone
*/
public static Timestamp convertTimestamp(Value value, Calendar calendar) {
if (value == ValueNull.INSTANCE) {
return null;
}
ValueTimestamp ts = (ValueTimestamp) value.convertTo(Value.TIMESTAMP);
Calendar cal = (Calendar) calendar.clone();
cal.clear();
cal.setLenient(true);
long dateValue = ts.getDateValue();
long nanos = ts.getTimeNanos();
long millis = nanos / 1_000_000;
nanos -= millis * 1_000_000;
long s = millis / 1_000;
millis -= s * 1_000;
long m = s / 60;
s -= m * 60;
long h = m / 60;
m -= h * 60;
long ms = convertToMillis(cal, yearFromDateValue(dateValue),
monthFromDateValue(dateValue), dayFromDateValue(dateValue),
(int) h, (int) m, (int) s, (int) millis);
Timestamp x = new Timestamp(ms);
x.setNanos((int) (nanos + millis * 1_000_000));
return x;
}
/**
* Convert a java.util.Date using the specified calendar.
*
* @param x the date
* @param calendar the calendar
* @return the date
*/
public static ValueDate convertDate(Date x, Calendar calendar) {
if (calendar == null) {
throw DbException.getInvalidValueException("calendar", null);
}
Calendar cal = (Calendar) calendar.clone();
cal.setTimeInMillis(x.getTime());
long dateValue = dateValueFromCalendar(cal);
return ValueDate.fromDateValue(dateValue);
}
/**
* Convert the time using the specified calendar.
*
* @param x the time
* @param calendar the calendar
* @return the time
*/
public static ValueTime convertTime(Time x, Calendar calendar) {
if (calendar == null) {
throw DbException.getInvalidValueException("calendar", null);
}
Calendar cal = (Calendar) calendar.clone();
cal.setTimeInMillis(x.getTime());
long nanos = nanosFromCalendar(cal);
return ValueTime.fromNanos(nanos);
}
/**
* Convert the timestamp using the specified calendar.
*
* @param x the time
* @param calendar the calendar
* @return the timestamp
*/
public static ValueTimestamp convertTimestamp(Timestamp x,
Calendar calendar) {
if (calendar == null) {
throw DbException.getInvalidValueException("calendar", null);
}
Calendar cal = (Calendar) calendar.clone();
cal.setTimeInMillis(x.getTime());
long dateValue = dateValueFromCalendar(cal);
long nanos = nanosFromCalendar(cal);
nanos += x.getNanos() % 1_000_000;
return ValueTimestamp.fromDateValueAndNanos(dateValue, nanos);
}
/**
* Parse a date string. The format is: [+|-]year-month-day
*
* @param s the string to parse
* @param start the parse index start
* @param end the parse index end
* @return the date value
* @throws IllegalArgumentException if there is a problem
*/
public static long parseDateValue(String s, int start, int end) {
if (s.charAt(start) == '+') {
// +year
start++;
}
// start at position 1 to support "-year"
int s1 = s.indexOf('-', start + 1);
int s2 = s.indexOf('-', s1 + 1);
if (s1 <= 0 || s2 <= s1) {
throw new IllegalArgumentException(s);
}
int year = Integer.parseInt(s.substring(start, s1));
int month = Integer.parseInt(s.substring(s1 + 1, s2));
int day = Integer.parseInt(s.substring(s2 + 1, end));
if (!isValidDate(year, month, day)) {
throw new IllegalArgumentException(year + "-" + month + "-" + day);
}
return dateValue(year, month, day);
}
/**
* Parse a time string. The format is: [-]hour:minute:second[.nanos] or
* alternatively [-]hour.minute.second[.nanos].
*
* @param s the string to parse
* @param start the parse index start
* @param end the parse index end
* @param timeOfDay whether the result need to be within 0 (inclusive) and 1
* day (exclusive)
* @return the time in nanoseconds
* @throws IllegalArgumentException if there is a problem
*/
public static long parseTimeNanos(String s, int start, int end,
boolean timeOfDay) {
int hour = 0, minute = 0, second = 0;
long nanos = 0;
int s1 = s.indexOf(':', start);
int s2 = s.indexOf(':', s1 + 1);
int s3 = s.indexOf('.', s2 + 1);
if (s1 <= 0 || s2 <= s1) {
// if first try fails try to use IBM DB2 time format
// [-]hour.minute.second[.nanos]
s1 = s.indexOf('.', start);
s2 = s.indexOf('.', s1 + 1);
s3 = s.indexOf('.', s2 + 1);
if (s1 <= 0 || s2 <= s1) {
throw new IllegalArgumentException(s);
}
}
boolean negative;
hour = Integer.parseInt(s.substring(start, s1));
if (hour < 0 || hour == 0 && s.charAt(0) == '-') {
if (timeOfDay) {
/*
* This also forbids -00:00:00 and similar values.
*/
throw new IllegalArgumentException(s);
}
negative = true;
hour = -hour;
} else {
negative = false;
}
minute = Integer.parseInt(s.substring(s1 + 1, s2));
if (s3 < 0) {
second = Integer.parseInt(s.substring(s2 + 1, end));
} else {
second = Integer.parseInt(s.substring(s2 + 1, s3));
String n = (s.substring(s3 + 1, end) + "000000000").substring(0, 9);
nanos = Integer.parseInt(n);
}
if (hour >= 2_000_000 || minute < 0 || minute >= 60 || second < 0
|| second >= 60) {
throw new IllegalArgumentException(s);
}
if (timeOfDay && hour >= 24) {
throw new IllegalArgumentException(s);
}
nanos += ((((hour * 60L) + minute) * 60) + second) * 1_000_000_000;
return negative ? -nanos : nanos;
}
/**
* See:
* https://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string#answer-3976656
*/
private static int findNthIndexOf(String str, char chr, int n) {
int pos = str.indexOf(chr);
while (--n > 0 && pos != -1) {
pos = str.indexOf(chr, pos + 1);
}
return pos;
}
/**
* Parses timestamp value from the specified string.
*
* @param s
* string to parse
* @param mode
* database mode, or {@code null}
* @param withTimeZone
* if {@code true} return {@link ValueTimestampTimeZone} instead of
* {@link ValueTimestamp}
* @return parsed timestamp
*/
public static Value parseTimestamp(String s, Mode mode, boolean withTimeZone) {
int dateEnd = s.indexOf(' ');
if (dateEnd < 0) {
// ISO 8601 compatibility
dateEnd = s.indexOf('T');
if (dateEnd < 0 && mode != null && mode.allowDB2TimestampFormat) {
// DB2 also allows dash between date and time
dateEnd = findNthIndexOf(s, '-', 3);
}
}
int timeStart;
if (dateEnd < 0) {
dateEnd = s.length();
timeStart = -1;
} else {
timeStart = dateEnd + 1;
}
long dateValue = parseDateValue(s, 0, dateEnd);
long nanos;
short tzMinutes = 0;
if (timeStart < 0) {
nanos = 0;
} else {
int timeEnd = s.length();
TimeZone tz = null;
if (s.endsWith("Z")) {
tz = UTC;
timeEnd--;
} else {
int timeZoneStart = s.indexOf('+', dateEnd + 1);
if (timeZoneStart < 0) {
timeZoneStart = s.indexOf('-', dateEnd + 1);
}
if (timeZoneStart >= 0) {
// Allow [timeZoneName] part after time zone offset
int offsetEnd = s.indexOf('[', timeZoneStart + 1);
if (offsetEnd < 0) {
offsetEnd = s.length();
}
String tzName = "GMT" + s.substring(timeZoneStart, offsetEnd);
tz = TimeZone.getTimeZone(tzName);
if (!tz.getID().startsWith(tzName)) {
throw new IllegalArgumentException(
tzName + " (" + tz.getID() + "?)");
}
if (s.charAt(timeZoneStart - 1) == ' ') {
timeZoneStart--;
}
timeEnd = timeZoneStart;
} else {
timeZoneStart = s.indexOf(' ', dateEnd + 1);
if (timeZoneStart > 0) {
String tzName = s.substring(timeZoneStart + 1);
tz = TimeZone.getTimeZone(tzName);
if (!tz.getID().startsWith(tzName)) {
throw new IllegalArgumentException(tzName);
}
timeEnd = timeZoneStart;
}
}
}
nanos = parseTimeNanos(s, dateEnd + 1, timeEnd, true);
if (tz != null) {
if (withTimeZone) {
if (tz != UTC) {
long millis = convertDateTimeValueToMillis(tz, dateValue, nanos / 1_000_000);
tzMinutes = (short) (tz.getOffset(millis) / 1000 / 60);
}
} else {
long millis = convertDateTimeValueToMillis(tz, dateValue, nanos / 1_000_000);
dateValue = dateValueFromDate(millis);
nanos = nanos % 1_000_000 + nanosFromDate(millis);
}
}
}
if (withTimeZone) {
return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, nanos, tzMinutes);
}
return ValueTimestamp.fromDateValueAndNanos(dateValue, nanos);
}
/**
* Calculates the time zone offset in minutes for the specified time zone, date
* value, and nanoseconds since midnight.
*
* @param tz
* time zone, or {@code null} for default
* @param dateValue
* date value
* @param timeNanos
* nanoseconds since midnight
* @return time zone offset in milliseconds
*/
public static int getTimeZoneOffsetMillis(TimeZone tz, long dateValue, long timeNanos) {
long msec = timeNanos / 1_000_000;
long utc = convertDateTimeValueToMillis(tz, dateValue, msec);
long local = absoluteDayFromDateValue(dateValue) * MILLIS_PER_DAY + msec;
return (int) (local - utc);
}
/**
* Calculates the milliseconds since epoch for the specified date value,
* nanoseconds since midnight, and time zone offset.
* @param dateValue
* date value
* @param timeNanos
* nanoseconds since midnight
* @param offsetMins
* time zone offset in minutes
* @return milliseconds since epoch in UTC
*/
public static long getMillis(long dateValue, long timeNanos, short offsetMins) {
return absoluteDayFromDateValue(dateValue) * MILLIS_PER_DAY
+ timeNanos / 1_000_000 - offsetMins * 60_000;
}
/**
* Calculate the milliseconds since 1970-01-01 (UTC) for the given date and
* time (in the specified timezone).
*
* @param tz the timezone of the parameters, or null for the default
* timezone
* @param year the absolute year (positive or negative)
* @param month the month (1-12)
* @param day the day (1-31)
* @param hour the hour (0-23)
* @param minute the minutes (0-59)
* @param second the number of seconds (0-59)
* @param millis the number of milliseconds
* @return the number of milliseconds (UTC)
*/
public static long getMillis(TimeZone tz, int year, int month, int day,
int hour, int minute, int second, int millis) {
GregorianCalendar c;
if (tz == null) {
c = getCalendar();
} else {
c = getCalendar(tz);
}
c.setLenient(false);
try {
return convertToMillis(c, year, month, day, hour, minute, second, millis);
} catch (IllegalArgumentException e) {
// special case: if the time simply doesn't exist because of
// daylight saving time changes, use the lenient version
String message = e.toString();
if (message.indexOf("HOUR_OF_DAY") > 0) {
if (hour < 0 || hour > 23) {
throw e;
}
} else if (message.indexOf("DAY_OF_MONTH") > 0) {
int maxDay;
if (month == 2) {
maxDay = c.isLeapYear(year) ? 29 : 28;
} else {
maxDay = NORMAL_DAYS_PER_MONTH[month];
}
if (day < 1 || day > maxDay) {
throw e;
}
// DAY_OF_MONTH is thrown for years > 2037
// using the timezone Brasilia and others,
// for example for 2042-10-12 00:00:00.
hour += 6;
}
c.setLenient(true);
return convertToMillis(c, year, month, day, hour, minute, second, millis);
}
}
private static long convertToMillis(Calendar cal, int year, int month, int day,
int hour, int minute, int second, int millis) {
if (year <= 0) {
cal.set(Calendar.ERA, GregorianCalendar.BC);
cal.set(Calendar.YEAR, 1 - year);
} else {
cal.set(Calendar.ERA, GregorianCalendar.AD);
cal.set(Calendar.YEAR, year);
}
// january is 0
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
cal.set(Calendar.MILLISECOND, millis);
return cal.getTimeInMillis();
}
/**
* Extracts date value and nanos of day from the specified value.
*
* @param value
* value to extract fields from
* @return array with date value and nanos of day
*/
public static long[] dateAndTimeFromValue(Value value) {
long dateValue = EPOCH_DATE_VALUE;
long timeNanos = 0;
if (value instanceof ValueTimestamp) {
ValueTimestamp v = (ValueTimestamp) value;
dateValue = v.getDateValue();
timeNanos = v.getTimeNanos();
} else if (value instanceof ValueDate) {
dateValue = ((ValueDate) value).getDateValue();
} else if (value instanceof ValueTime) {
timeNanos = ((ValueTime) value).getNanos();
} else if (value instanceof ValueTimestampTimeZone) {
ValueTimestampTimeZone v = (ValueTimestampTimeZone) value;
dateValue = v.getDateValue();
timeNanos = v.getTimeNanos();
} else {
ValueTimestamp v = (ValueTimestamp) value.convertTo(Value.TIMESTAMP);
dateValue = v.getDateValue();
timeNanos = v.getTimeNanos();
}
return new long[] {dateValue, timeNanos};
}
/**
* Creates a new date-time value with the same type as original value. If
* original value is a ValueTimestampTimeZone, returned value will have the same
* time zone offset as original value.
*
* @param original
* original value
* @param dateValue
* date value for the returned value
* @param timeNanos
* nanos of day for the returned value
* @param forceTimestamp
* if {@code true} return ValueTimestamp if original argument is
* ValueDate or ValueTime
* @return new value with specified date value and nanos of day
*/
public static Value dateTimeToValue(Value original, long dateValue, long timeNanos, boolean forceTimestamp) {
if (!(original instanceof ValueTimestamp)) {
if (!forceTimestamp) {
if (original instanceof ValueDate) {
return ValueDate.fromDateValue(dateValue);
}
if (original instanceof ValueTime) {
return ValueTime.fromNanos(timeNanos);
}
}
if (original instanceof ValueTimestampTimeZone) {
return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos,
((ValueTimestampTimeZone) original).getTimeZoneOffsetMins());
}
}
return ValueTimestamp.fromDateValueAndNanos(dateValue, timeNanos);
}
/**
* Get the number of milliseconds since 1970-01-01 in the local timezone,
* but without daylight saving time into account.
*
* @param d the date
* @return the milliseconds
*/
public static long getTimeLocalWithoutDst(java.util.Date d) {
return d.getTime() + zoneOffsetMillis;
}
/**
* Convert the number of milliseconds since 1970-01-01 in the local timezone
* to UTC, but without daylight saving time into account.
*
* @param millis the number of milliseconds in the local timezone
* @return the number of milliseconds in UTC
*/
public static long getTimeUTCWithoutDst(long millis) {
return millis - zoneOffsetMillis;
}
/**
* Returns day of week.
*
* @param dateValue
* the date value
* @param firstDayOfWeek
* first day of week, Monday as 1, Sunday as 7 or 0
* @return day of week
* @see #getIsoDayOfWeek(long)
*/
public static int getDayOfWeek(long dateValue, int firstDayOfWeek) {
return getDayOfWeekFromAbsolute(absoluteDayFromDateValue(dateValue), firstDayOfWeek);
}
/**
* Get the day of the week from the absolute day value.
*
* @param absoluteValue the absolute day
* @param firstDayOfWeek the first day of the week
* @return the day of week
*/
public static int getDayOfWeekFromAbsolute(long absoluteValue, int firstDayOfWeek) {
return absoluteValue >= 0 ? (int) ((absoluteValue - firstDayOfWeek + 11) % 7) + 1
: (int) ((absoluteValue - firstDayOfWeek - 2) % 7) + 7;
}
/**
* Returns number of day in year.
*
* @param dateValue
* the date value
* @return number of day in year
*/
public static int getDayOfYear(long dateValue) {
return (int) (absoluteDayFromDateValue(dateValue) - absoluteDayFromYear(yearFromDateValue(dateValue))) + 1;
}
/**
* Returns ISO day of week.
*
* @param dateValue
* the date value
* @return ISO day of week, Monday as 1 to Sunday as 7
* @see #getSundayDayOfWeek(long)
*/
public static int getIsoDayOfWeek(long dateValue) {
return getDayOfWeek(dateValue, 1);
}
/**
* Returns ISO number of week in year.
*
* @param dateValue
* the date value
* @return number of week in year
* @see #getIsoWeekYear(long)
* @see #getWeekOfYear(long, int, int)
*/
public static int getIsoWeekOfYear(long dateValue) {
return getWeekOfYear(dateValue, 1, 4);
}
/**
* Returns ISO week year.
*
* @param dateValue
* the date value
* @return ISO week year
* @see #getIsoWeekOfYear(long)
* @see #getWeekYear(long, int, int)
*/
public static int getIsoWeekYear(long dateValue) {
return getWeekYear(dateValue, 1, 4);
}
/**
* Returns day of week with Sunday as 1.
*
* @param dateValue
* the date value
* @return day of week, Sunday as 1 to Monday as 7
* @see #getIsoDayOfWeek(long)
*/
public static int getSundayDayOfWeek(long dateValue) {
return getDayOfWeek(dateValue, 0);
}
/**
* Returns number of week in year.
*
* @param dateValue
* the date value
* @param firstDayOfWeek
* first day of week, Monday as 1, Sunday as 7 or 0
* @param minimalDaysInFirstWeek
* minimal days in first week of year
* @return number of week in year
* @see #getIsoWeekOfYear(long)
*/
public static int getWeekOfYear(long dateValue, int firstDayOfWeek, int minimalDaysInFirstWeek) {
long abs = absoluteDayFromDateValue(dateValue);
int year = yearFromDateValue(dateValue);
long base = getWeekOfYearBase(year, firstDayOfWeek, minimalDaysInFirstWeek);
if (abs - base < 0) {
base = getWeekOfYearBase(year - 1, firstDayOfWeek, minimalDaysInFirstWeek);
} else if (monthFromDateValue(dateValue) == 12 && 24 + minimalDaysInFirstWeek < dayFromDateValue(dateValue)) {
if (abs >= getWeekOfYearBase(year + 1, firstDayOfWeek, minimalDaysInFirstWeek)) {
return 1;
}
}
return (int) ((abs - base) / 7) + 1;
}
private static long getWeekOfYearBase(int year, int firstDayOfWeek, int minimalDaysInFirstWeek) {
long first = absoluteDayFromYear(year);
int daysInFirstWeek = 8 - getDayOfWeekFromAbsolute(first, firstDayOfWeek);
long base = first + daysInFirstWeek;
if (daysInFirstWeek >= minimalDaysInFirstWeek) {
base -= 7;
}
return base;
}
/**
* Returns week year.
*
* @param dateValue
* the date value
* @param firstDayOfWeek
* first day of week, Monday as 1, Sunday as 7 or 0
* @param minimalDaysInFirstWeek
* minimal days in first week of year
* @return week year
* @see #getIsoWeekYear(long)
*/
public static int getWeekYear(long dateValue, int firstDayOfWeek, int minimalDaysInFirstWeek) {
long abs = absoluteDayFromDateValue(dateValue);
int year = yearFromDateValue(dateValue);
long base = getWeekOfYearBase(year, firstDayOfWeek, minimalDaysInFirstWeek);
if (abs - base < 0) {
return year - 1;
} else if (monthFromDateValue(dateValue) == 12 && 24 + minimalDaysInFirstWeek < dayFromDateValue(dateValue)) {
if (abs >= getWeekOfYearBase(year + 1, firstDayOfWeek, minimalDaysInFirstWeek)) {
return year + 1;
}
}
return year;
}
/**
* Returns number of days in month.
*
* @param year the year
* @param month the month
* @return number of days in the specified month
*/
public static int getDaysInMonth(int year, int month) {
if (month != 2) {
return NORMAL_DAYS_PER_MONTH[month];
}
// All leap years divisible by 4
return (year & 3) == 0
// All such years before 1582 are Julian and leap
&& (year < 1582
// Otherwise check Gregorian conditions
|| year % 100 != 0 || year % 400 == 0)
? 29 : 28;
}
/**
* Verify if the specified date is valid.
*
* @param year the year
* @param month the month (January is 1)
* @param day the day (1 is the first of the month)
* @return true if it is valid
*/
public static boolean isValidDate(int year, int month, int day) {
if (month < 1 || month > 12 || day < 1) {
return false;
}
if (year == 1582 && month == 10) {
// special case: days 1582-10-05 .. 1582-10-14 don't exist
return day < 5 || (day > 14 && day <= 31);
}
return day <= getDaysInMonth(year, month);
}
/**
* Convert an encoded date value to a java.util.Date, using the default
* timezone.
*
* @param dateValue the date value
* @return the date
*/
public static Date convertDateValueToDate(long dateValue) {
long millis = getMillis(null, yearFromDateValue(dateValue),
monthFromDateValue(dateValue), dayFromDateValue(dateValue), 0,
0, 0, 0);
return new Date(millis);
}
/**
* Convert an encoded date-time value to millis, using the supplied timezone.
*
* @param tz the timezone
* @param dateValue the date value
* @param ms milliseconds of day
* @return the date
*/
public static long convertDateTimeValueToMillis(TimeZone tz, long dateValue, long ms) {
long second = ms / 1000;
ms -= second * 1000;
int minute = (int) (second / 60);
second -= minute * 60;
int hour = minute / 60;
minute -= hour * 60;
return getMillis(tz, yearFromDateValue(dateValue), monthFromDateValue(dateValue), dayFromDateValue(dateValue),
hour, minute, (int) second, (int) ms);
}
/**
* Convert an encoded date value / time value to a timestamp, using the
* default timezone.
*
* @param dateValue the date value
* @param timeNanos the nanoseconds since midnight
* @return the timestamp
*/
public static Timestamp convertDateValueToTimestamp(long dateValue,
long timeNanos) {
Timestamp ts = new Timestamp(convertDateTimeValueToMillis(null, dateValue, timeNanos / 1_000_000));
// This method expects the complete nanoseconds value including milliseconds
ts.setNanos((int) (timeNanos % 1_000_000_000));
return ts;
}
/**
* Convert an encoded date value / time value to a timestamp using the specified
* time zone offset.
*
* @param dateValue the date value
* @param timeNanos the nanoseconds since midnight
* @param offsetMins time zone offset in minutes
* @return the timestamp
*/
public static Timestamp convertTimestampTimeZoneToTimestamp(long dateValue, long timeNanos, short offsetMins) {
Timestamp ts = new Timestamp(getMillis(dateValue, timeNanos, offsetMins));
ts.setNanos((int) (timeNanos % 1_000_000_000));
return ts;
}
/**
* Convert a time value to a time, using the default timezone.
*
* @param nanosSinceMidnight the nanoseconds since midnight
* @return the time
*/
public static Time convertNanoToTime(long nanosSinceMidnight) {
long millis = nanosSinceMidnight / 1_000_000;
long s = millis / 1_000;
millis -= s * 1_000;
long m = s / 60;
s -= m * 60;
long h = m / 60;
m -= h * 60;
long ms = getMillis(null, 1970, 1, 1, (int) (h % 24), (int) m, (int) s,
(int) millis);
return new Time(ms);
}
/**
* Get the year from a date value.
*
* @param x the date value
* @return the year
*/
public static int yearFromDateValue(long x) {
return (int) (x >>> SHIFT_YEAR);
}
/**
* Get the month from a date value.
*
* @param x the date value
* @return the month (1..12)
*/
public static int monthFromDateValue(long x) {
return (int) (x >>> SHIFT_MONTH) & 15;
}
/**
* Get the day of month from a date value.
*
* @param x the date value
* @return the day (1..31)
*/
public static int dayFromDateValue(long x) {
return (int) (x & 31);
}
/**
* Get the date value from a given date.
*
* @param year the year
* @param month the month (1..12)
* @param day the day (1..31)
* @return the date value
*/
public static long dateValue(long year, int month, int day) {
return (year << SHIFT_YEAR) | (month << SHIFT_MONTH) | day;
}
/**
* Get the date value from a given denormalized date with possible out of range
* values of month and/or day. Used after addition or subtraction month or years
* to (from) it to get a valid date.
*
* @param year
* the year
* @param month
* the month, if out of range month and year will be normalized
* @param day
* the day of the month, if out of range it will be saturated
* @return the date value
*/
public static long dateValueFromDenormalizedDate(long year, long month, int day) {
long mm1 = month - 1;
long yd = mm1 / 12;
if (mm1 < 0 && yd * 12 != mm1) {
yd--;
}
int y = (int) (year + yd);
int m = (int) (month - yd * 12);
if (day < 1) {
day = 1;
} else {
int max = getDaysInMonth(y, m);
if (day > max) {
day = max;
}
}
return dateValue(y, m, day);
}
/**
* Convert a UTC datetime in millis to an encoded date in the default
* timezone.
*
* @param ms the milliseconds
* @return the date value
*/
public static long dateValueFromDate(long ms) {
ms += getTimeZone().getOffset(ms);
long absoluteDay = ms / MILLIS_PER_DAY;
// Round toward negative infinity
if (ms < 0 && (absoluteDay * MILLIS_PER_DAY != ms)) {
absoluteDay--;
}
return dateValueFromAbsoluteDay(absoluteDay);
}
/**
* Calculate the encoded date value from a given calendar.
*
* @param cal the calendar
* @return the date value
*/
private static long dateValueFromCalendar(Calendar cal) {
int year = cal.get(Calendar.YEAR);
if (cal.get(Calendar.ERA) == GregorianCalendar.BC) {
year = 1 - year;
}
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
return ((long) year << SHIFT_YEAR) | (month << SHIFT_MONTH) | day;
}
/**
* Convert a time in milliseconds in UTC to the nanoseconds since midnight
* (in the default timezone).
*
* @param ms the milliseconds
* @return the nanoseconds
*/
public static long nanosFromDate(long ms) {
ms += getTimeZone().getOffset(ms);
long absoluteDay = ms / MILLIS_PER_DAY;
// Round toward negative infinity
if (ms < 0 && (absoluteDay * MILLIS_PER_DAY != ms)) {
absoluteDay--;
}
return (ms - absoluteDay * MILLIS_PER_DAY) * 1_000_000;
}
/**
* Convert a java.util.Calendar to nanoseconds since midnight.
*
* @param cal the calendar
* @return the nanoseconds
*/
private static long nanosFromCalendar(Calendar cal) {
int h = cal.get(Calendar.HOUR_OF_DAY);
int m = cal.get(Calendar.MINUTE);
int s = cal.get(Calendar.SECOND);
int millis = cal.get(Calendar.MILLISECOND);
return ((((((h * 60L) + m) * 60) + s) * 1000) + millis) * 1000000;
}
/**
* Calculate the normalized timestamp.
*
* @param absoluteDay the absolute day
* @param nanos the nanoseconds (may be negative or larger than one day)
* @return the timestamp
*/
public static ValueTimestamp normalizeTimestamp(long absoluteDay,
long nanos) {
if (nanos > NANOS_PER_DAY || nanos < 0) {
long d;
if (nanos > NANOS_PER_DAY) {
d = nanos / NANOS_PER_DAY;
} else {
d = (nanos - NANOS_PER_DAY + 1) / NANOS_PER_DAY;
}
nanos -= d * NANOS_PER_DAY;
absoluteDay += d;
}
return ValueTimestamp.fromDateValueAndNanos(
dateValueFromAbsoluteDay(absoluteDay), nanos);
}
/**
* Converts local date value and nanoseconds to timestamp with time zone.
*
* @param dateValue
* date value
* @param timeNanos
* nanoseconds since midnight
* @return timestamp with time zone
*/
public static ValueTimestampTimeZone timestampTimeZoneFromLocalDateValueAndNanos(long dateValue, long timeNanos) {
int timeZoneOffset = getTimeZoneOffsetMillis(null, dateValue, timeNanos);
int offsetMins = timeZoneOffset / 60_000;
int correction = timeZoneOffset % 60_000;
if (correction != 0) {
timeNanos -= correction;
if (timeNanos < 0) {
timeNanos += NANOS_PER_DAY;
dateValue = decrementDateValue(dateValue);
} else if (timeNanos >= NANOS_PER_DAY) {
timeNanos -= NANOS_PER_DAY;
dateValue = incrementDateValue(dateValue);
}
}
return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos, (short) offsetMins);
}
/**
* Calculate the absolute day for a January, 1 of the specified year.
*
* @param year
* the year
* @return the absolute day
*/
public static long absoluteDayFromYear(long year) {
year--;
long a = ((year * 1461L) >> 2) - 719_177;
if (year < 1582) {
// Julian calendar
a += 13;
} else if (year < 1900 || year > 2099) {
// Gregorian calendar (slow mode)
a += (year / 400) - (year / 100) + 15;
}
return a;
}
/**
* Calculate the absolute day from an encoded date value.
*
* @param dateValue the date value
* @return the absolute day
*/
public static long absoluteDayFromDateValue(long dateValue) {
long y = yearFromDateValue(dateValue);
int m = monthFromDateValue(dateValue);
int d = dayFromDateValue(dateValue);
if (m <= 2) {
y--;
m += 12;
}
long a = ((y * 1461L) >> 2) + DAYS_OFFSET[m - 3] + d - 719_484;
if (y <= 1582 && ((y < 1582) || (m * 100 + d < 10_15))) {
// Julian calendar (cutover at 1582-10-04 / 1582-10-15)
a += 13;
} else if (y < 1900 || y > 2099) {
// Gregorian calendar (slow mode)
a += (y / 400) - (y / 100) + 15;
}
return a;
}
/**
* Calculate the absolute day from an encoded date value in proleptic Gregorian
* calendar.
*
* @param dateValue the date value
* @return the absolute day in proleptic Gregorian calendar
*/
public static long prolepticGregorianAbsoluteDayFromDateValue(long dateValue) {
long y = yearFromDateValue(dateValue);
int m = monthFromDateValue(dateValue);
int d = dayFromDateValue(dateValue);
if (m <= 2) {
y--;
m += 12;
}
long a = ((y * 1461L) >> 2) + DAYS_OFFSET[m - 3] + d - 719_484;
if (y < 1900 || y > 2099) {
// Slow mode
a += (y / 400) - (y / 100) + 15;
}
return a;
}
/**
* Calculate the encoded date value from an absolute day.
*
* @param absoluteDay the absolute day
* @return the date value
*/
public static long dateValueFromAbsoluteDay(long absoluteDay) {
long d = absoluteDay + 719_468;
long y100, offset;
if (d > 578_040) {
// Gregorian calendar
long y400 = d / 146_097;
d -= y400 * 146_097;
y100 = d / 36_524;
d -= y100 * 36_524;
offset = y400 * 400 + y100 * 100;
} else {
// Julian calendar
y100 = 0;
d += 292_200_000_002L;
offset = -800_000_000;
}
long y4 = d / 1461;
d -= y4 * 1461;
long y = d / 365;
d -= y * 365;
if (d == 0 && (y == 4 || y100 == 4)) {
y--;
d += 365;
}
y += offset + y4 * 4;
// month of a day
int m = ((int) d * 2 + 1) * 5 / 306;
d -= DAYS_OFFSET[m] - 1;
if (m >= 10) {
y++;
m -= 12;
}
return dateValue(y, m + 3, (int) d);
}
/**
* Return the next date value.
*
* @param dateValue
* the date value
* @return the next date value
*/
public static long incrementDateValue(long dateValue) {
int year = yearFromDateValue(dateValue);
if (year == 1582) {
// Use slow way instead of rarely needed large custom code.
return dateValueFromAbsoluteDay(absoluteDayFromDateValue(dateValue) + 1);
}
int day = dayFromDateValue(dateValue);
if (day < 28) {
return dateValue + 1;
}
int month = monthFromDateValue(dateValue);
if (day < getDaysInMonth(year, month)) {
return dateValue + 1;
}
if (month < 12) {
month++;
} else {
month = 1;
year++;
}
return dateValue(year, month, 1);
}
/**
* Return the previous date value.
*
* @param dateValue
* the date value
* @return the previous date value
*/
public static long decrementDateValue(long dateValue) {
int year = yearFromDateValue(dateValue);
if (year == 1582) {
// Use slow way instead of rarely needed large custom code.
return dateValueFromAbsoluteDay(absoluteDayFromDateValue(dateValue) - 1);
}
if (dayFromDateValue(dateValue) > 1) {
return dateValue - 1;
}
int month = monthFromDateValue(dateValue);
if (month > 1) {
month--;
} else {
month = 12;
year--;
}
return dateValue(year, month, getDaysInMonth(year, month));
}
/**
* Append a date to the string builder.
*
* @param buff the target string builder
* @param dateValue the date value
*/
public static void appendDate(StringBuilder buff, long dateValue) {
int y = yearFromDateValue(dateValue);
int m = monthFromDateValue(dateValue);
int d = dayFromDateValue(dateValue);
if (y > 0 && y < 10_000) {
StringUtils.appendZeroPadded(buff, 4, y);
} else {
buff.append(y);
}
buff.append('-');
StringUtils.appendZeroPadded(buff, 2, m);
buff.append('-');
StringUtils.appendZeroPadded(buff, 2, d);
}
/**
* Append a time to the string builder.
*
* @param buff the target string builder
* @param nanos the time in nanoseconds
*/
public static void appendTime(StringBuilder buff, long nanos) {
if (nanos < 0) {
buff.append('-');
nanos = -nanos;
}
/*
* nanos now either in range from 0 to Long.MAX_VALUE or equals to
* Long.MIN_VALUE. We need to divide nanos by 1000000 with unsigned division to
* get correct result. The simplest way to do this with such constraints is to
* divide -nanos by -1000000.
*/
long ms = -nanos / -1_000_000;
nanos -= ms * 1_000_000;
long s = ms / 1_000;
ms -= s * 1_000;
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 (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);
}
}
}
/**
* Append a time zone to the string builder.
*
* @param buff the target string builder
* @param tz the time zone in minutes
*/
public static void appendTimeZone(StringBuilder buff, short tz) {
if (tz < 0) {
buff.append('-');
tz = (short) -tz;
} else {
buff.append('+');
}
int hours = tz / 60;
tz -= hours * 60;
int mins = tz;
StringUtils.appendZeroPadded(buff, 2, hours);
if (mins != 0) {
buff.append(':');
StringUtils.appendZeroPadded(buff, 2, mins);
}
}
/**
* Formats timestamp with time zone as string.
*
* @param dateValue the year-month-day bit field
* @param timeNanos nanoseconds since midnight
* @param timeZoneOffsetMins the time zone offset in minutes
* @return formatted string
*/
public static String timestampTimeZoneToString(long dateValue, long timeNanos, short timeZoneOffsetMins) {
StringBuilder buff = new StringBuilder(ValueTimestampTimeZone.MAXIMUM_PRECISION);
appendDate(buff, dateValue);
buff.append(' ');
appendTime(buff, timeNanos);
appendTimeZone(buff, timeZoneOffsetMins);
return buff.toString();
}
/**
* Generates time zone name for the specified offset in minutes.
*
* @param offsetMins
* offset in minutes
* @return time zone name
*/
public static String timeZoneNameFromOffsetMins(int offsetMins) {
if (offsetMins == 0) {
return "UTC";
}
StringBuilder b = new StringBuilder(9);
b.append("GMT");
if (offsetMins < 0) {
b.append('-');
offsetMins = -offsetMins;
} else {
b.append('+');
}
StringUtils.appendZeroPadded(b, 2, offsetMins / 60);
b.append(':');
StringUtils.appendZeroPadded(b, 2, offsetMins % 60);
return b.toString();
}
/**
* Converts scale of nanoseconds.
*
* @param nanosOfDay nanoseconds of day
* @param scale fractional seconds precision
* @return scaled value
*/
public static long convertScale(long nanosOfDay, int scale) {
if (scale >= 9) {
return nanosOfDay;
}
int m = CONVERT_SCALE_TABLE[scale];
long mod = nanosOfDay % m;
if (mod >= m >>> 1) {
nanosOfDay += m;
}
return nanosOfDay - mod;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/DbDriverActivator.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/**
* The driver activator loads the H2 driver when starting the bundle. The driver
* is unloaded when stopping the bundle.
*/
public class DbDriverActivator implements BundleActivator {
private static final String DATASOURCE_FACTORY_CLASS =
"org.osgi.service.jdbc.DataSourceFactory";
/**
* Start the bundle. If the 'org.osgi.service.jdbc.DataSourceFactory' class
* is available in the class path, this will load the database driver and
* register the DataSourceFactory service.
*
* @param bundleContext the bundle context
*/
@Override
public void start(BundleContext bundleContext) {
org.h2.Driver driver = org.h2.Driver.load();
try {
JdbcUtils.loadUserClass(DATASOURCE_FACTORY_CLASS);
} catch (Exception e) {
// class not found - don't register
return;
}
// but don't ignore exceptions in this call
OsgiDataSourceFactory.registerService(bundleContext, driver);
}
/**
* Stop the bundle. This will unload the database driver. The
* DataSourceFactory service is implicitly un-registered by the OSGi
* framework.
*
* @param bundleContext the bundle context
*/
@Override
public void stop(BundleContext bundleContext) {
org.h2.Driver.unload();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/DebuggingThreadLocal.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* Similar to ThreadLocal, except that it allows its data to be read from other
* threads - useful for debugging info.
*
* @param <T> the type
*/
public class DebuggingThreadLocal<T> {
private final ConcurrentHashMap<Long, T> map = new ConcurrentHashMap<>();
public void set(T value) {
map.put(Thread.currentThread().getId(), value);
}
/**
* Remove the value for the current thread.
*/
public void remove() {
map.remove(Thread.currentThread().getId());
}
public T get() {
return map.get(Thread.currentThread().getId());
}
/**
* Get a snapshot of the data of all threads.
*
* @return a HashMap containing a mapping from thread-id to value
*/
public HashMap<Long, T> getSnapshotOfAllThreads() {
return new HashMap<>(map);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/DoneFuture.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Future which is already done.
*
* @param <T> Result value.
* @author Sergi Vladykin
*/
public class DoneFuture<T> implements Future<T> {
final T x;
public DoneFuture(T x) {
this.x = x;
}
@Override
public T get() throws InterruptedException, ExecutionException {
return x;
}
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return x;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public String toString() {
return "DoneFuture->" + x;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/HashBase.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
/**
* The base for other hash classes.
*/
public abstract class HashBase {
/**
* The maximum load, in percent.
* declared as long so we do long arithmetic so we don't overflow.
*/
private static final long MAX_LOAD = 90;
/**
* The bit mask to get the index from the hash code.
*/
protected int mask;
/**
* The number of slots in the table.
*/
protected int len;
/**
* The number of occupied slots, excluding the zero key (if any).
*/
protected int size;
/**
* The number of deleted slots.
*/
protected int deletedCount;
/**
* The level. The number of slots is 2 ^ level.
*/
protected int level;
/**
* Whether the zero key is used.
*/
protected boolean zeroKey;
private int maxSize, minSize, maxDeleted;
public HashBase() {
reset(2);
}
/**
* Increase the size of the underlying table and re-distribute the elements.
*
* @param newLevel the new level
*/
protected abstract void rehash(int newLevel);
/**
* Get the size of the map.
*
* @return the size
*/
public int size() {
return size + (zeroKey ? 1 : 0);
}
/**
* Check the size before adding an entry. This method resizes the map if
* required.
*/
void checkSizePut() {
if (deletedCount > size) {
rehash(level);
}
if (size + deletedCount >= maxSize) {
rehash(level + 1);
}
}
/**
* Check the size before removing an entry. This method resizes the map if
* required.
*/
protected void checkSizeRemove() {
if (size < minSize && level > 0) {
rehash(level - 1);
} else if (deletedCount > maxDeleted) {
rehash(level);
}
}
/**
* Clear the map and reset the level to the specified value.
*
* @param newLevel the new level
*/
protected void reset(int newLevel) {
// can't exceed 30 or we will generate a negative value
// for the "len" field
if (newLevel > 30) {
throw new IllegalStateException("exceeded max size of hash table");
}
size = 0;
level = newLevel;
len = 2 << level;
mask = len - 1;
minSize = (int) ((1 << level) * MAX_LOAD / 100);
maxSize = (int) (len * MAX_LOAD / 100);
deletedCount = 0;
maxDeleted = 20 + len / 2;
}
/**
* Calculate the index for this hash code.
*
* @param hash the hash code
* @return the index
*/
protected int getIndex(int hash) {
return hash & mask;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/IOUtils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
/**
* This utility class contains input/output functions.
*/
public class IOUtils {
private IOUtils() {
// utility class
}
/**
* Close a Closeable without throwing an exception.
*
* @param out the Closeable or null
*/
public static void closeSilently(Closeable out) {
if (out != null) {
try {
trace("closeSilently", null, out);
out.close();
} catch (Exception e) {
// ignore
}
}
}
/**
* Close an AutoCloseable without throwing an exception.
*
* @param out the AutoCloseable or null
*/
public static void closeSilently(AutoCloseable out) {
if (out != null) {
try {
trace("closeSilently", null, out);
out.close();
} catch (Exception e) {
// ignore
}
}
}
/**
* Skip a number of bytes in an input stream.
*
* @param in the input stream
* @param skip the number of bytes to skip
* @throws EOFException if the end of file has been reached before all bytes
* could be skipped
* @throws IOException if an IO exception occurred while skipping
*/
public static void skipFully(InputStream in, long skip) throws IOException {
try {
while (skip > 0) {
long skipped = in.skip(skip);
if (skipped <= 0) {
throw new EOFException();
}
skip -= skipped;
}
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
}
/**
* Skip a number of characters in a reader.
*
* @param reader the reader
* @param skip the number of characters to skip
* @throws EOFException if the end of file has been reached before all
* characters could be skipped
* @throws IOException if an IO exception occurred while skipping
*/
public static void skipFully(Reader reader, long skip) throws IOException {
try {
while (skip > 0) {
long skipped = reader.skip(skip);
if (skipped <= 0) {
throw new EOFException();
}
skip -= skipped;
}
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
}
/**
* Copy all data from the input stream to the output stream and close both
* streams. Exceptions while closing are ignored.
*
* @param in the input stream
* @param out the output stream
* @return the number of bytes copied
*/
public static long copyAndClose(InputStream in, OutputStream out)
throws IOException {
try {
long len = copyAndCloseInput(in, out);
out.close();
return len;
} catch (Exception e) {
throw DbException.convertToIOException(e);
} finally {
closeSilently(out);
}
}
/**
* Copy all data from the input stream to the output stream and close the
* input stream. Exceptions while closing are ignored.
*
* @param in the input stream
* @param out the output stream (null if writing is not required)
* @return the number of bytes copied
*/
public static long copyAndCloseInput(InputStream in, OutputStream out)
throws IOException {
try {
return copy(in, out);
} catch (Exception e) {
throw DbException.convertToIOException(e);
} finally {
closeSilently(in);
}
}
/**
* Copy all data from the input stream to the output stream. Both streams
* are kept open.
*
* @param in the input stream
* @param out the output stream (null if writing is not required)
* @return the number of bytes copied
*/
public static long copy(InputStream in, OutputStream out)
throws IOException {
return copy(in, out, Long.MAX_VALUE);
}
/**
* Copy all data from the input stream to the output stream. Both streams
* are kept open.
*
* @param in the input stream
* @param out the output stream (null if writing is not required)
* @param length the maximum number of bytes to copy
* @return the number of bytes copied
*/
public static long copy(InputStream in, OutputStream out, long length)
throws IOException {
try {
long copied = 0;
int len = (int) Math.min(length, Constants.IO_BUFFER_SIZE);
byte[] buffer = new byte[len];
while (length > 0) {
len = in.read(buffer, 0, len);
if (len < 0) {
break;
}
if (out != null) {
out.write(buffer, 0, len);
}
copied += len;
length -= len;
len = (int) Math.min(length, Constants.IO_BUFFER_SIZE);
}
return copied;
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
}
/**
* Copy all data from the reader to the writer and close the reader.
* Exceptions while closing are ignored.
*
* @param in the reader
* @param out the writer (null if writing is not required)
* @param length the maximum number of bytes to copy
* @return the number of characters copied
*/
public static long copyAndCloseInput(Reader in, Writer out, long length)
throws IOException {
try {
long copied = 0;
int len = (int) Math.min(length, Constants.IO_BUFFER_SIZE);
char[] buffer = new char[len];
while (length > 0) {
len = in.read(buffer, 0, len);
if (len < 0) {
break;
}
if (out != null) {
out.write(buffer, 0, len);
}
length -= len;
len = (int) Math.min(length, Constants.IO_BUFFER_SIZE);
copied += len;
}
return copied;
} catch (Exception e) {
throw DbException.convertToIOException(e);
} finally {
in.close();
}
}
/**
* Close an input stream without throwing an exception.
*
* @param in the input stream or null
*/
public static void closeSilently(InputStream in) {
if (in != null) {
try {
trace("closeSilently", null, in);
in.close();
} catch (Exception e) {
// ignore
}
}
}
/**
* Close a reader without throwing an exception.
*
* @param reader the reader or null
*/
public static void closeSilently(Reader reader) {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
// ignore
}
}
}
/**
* Close a writer without throwing an exception.
*
* @param writer the writer or null
*/
public static void closeSilently(Writer writer) {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
// ignore
}
}
}
/**
* Read a number of bytes from an input stream and close the stream.
*
* @param in the input stream
* @param length the maximum number of bytes to read, or -1 to read until
* the end of file
* @return the bytes read
*/
public static byte[] readBytesAndClose(InputStream in, int length)
throws IOException {
try {
if (length <= 0) {
length = Integer.MAX_VALUE;
}
int block = Math.min(Constants.IO_BUFFER_SIZE, length);
ByteArrayOutputStream out = new ByteArrayOutputStream(block);
copy(in, out, length);
return out.toByteArray();
} catch (Exception e) {
throw DbException.convertToIOException(e);
} finally {
in.close();
}
}
/**
* Read a number of characters from a reader and close it.
*
* @param in the reader
* @param length the maximum number of characters to read, or -1 to read
* until the end of file
* @return the string read
*/
public static String readStringAndClose(Reader in, int length)
throws IOException {
try {
if (length <= 0) {
length = Integer.MAX_VALUE;
}
int block = Math.min(Constants.IO_BUFFER_SIZE, length);
StringWriter out = new StringWriter(block);
copyAndCloseInput(in, out, length);
return out.toString();
} finally {
in.close();
}
}
/**
* Try to read the given number of bytes to the buffer. This method reads
* until the maximum number of bytes have been read or until the end of
* file.
*
* @param in the input stream
* @param buffer the output buffer
* @param max the number of bytes to read at most
* @return the number of bytes read, 0 meaning EOF
*/
public static int readFully(InputStream in, byte[] buffer, int max)
throws IOException {
try {
int result = 0, len = Math.min(max, buffer.length);
while (len > 0) {
int l = in.read(buffer, result, len);
if (l < 0) {
break;
}
result += l;
len -= l;
}
return result;
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
}
/**
* Try to read the given number of characters to the buffer. This method
* reads until the maximum number of characters have been read or until the
* end of file.
*
* @param in the reader
* @param buffer the output buffer
* @param max the number of characters to read at most
* @return the number of characters read, 0 meaning EOF
*/
public static int readFully(Reader in, char[] buffer, int max)
throws IOException {
try {
int result = 0, len = Math.min(max, buffer.length);
while (len > 0) {
int l = in.read(buffer, result, len);
if (l < 0) {
break;
}
result += l;
len -= l;
}
return result;
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
}
/**
* Create a buffered reader to read from an input stream using the UTF-8
* format. If the input stream is null, this method returns null. The
* InputStreamReader that is used here is not exact, that means it may read
* some additional bytes when buffering.
*
* @param in the input stream or null
* @return the reader
*/
public static Reader getBufferedReader(InputStream in) {
return in == null ? null : new BufferedReader(
new InputStreamReader(in, StandardCharsets.UTF_8));
}
/**
* Create a reader to read from an input stream using the UTF-8 format. If
* the input stream is null, this method returns null. The InputStreamReader
* that is used here is not exact, that means it may read some additional
* bytes when buffering.
*
* @param in the input stream or null
* @return the reader
*/
public static Reader getReader(InputStream in) {
// InputStreamReader may read some more bytes
return in == null ? null : new BufferedReader(
new InputStreamReader(in, StandardCharsets.UTF_8));
}
/**
* Create a buffered writer to write to an output stream using the UTF-8
* format. If the output stream is null, this method returns null.
*
* @param out the output stream or null
* @return the writer
*/
public static Writer getBufferedWriter(OutputStream out) {
return out == null ? null : new BufferedWriter(
new OutputStreamWriter(out, StandardCharsets.UTF_8));
}
/**
* Wrap an input stream in a reader. The bytes are converted to characters
* using the US-ASCII character set.
*
* @param in the input stream
* @return the reader
*/
public static Reader getAsciiReader(InputStream in) {
return in == null ? null : new InputStreamReader(in, StandardCharsets.US_ASCII);
}
/**
* Trace input or output operations if enabled.
*
* @param method the method from where this method was called
* @param fileName the file name
* @param o the object to append to the message
*/
public static void trace(String method, String fileName, Object o) {
if (SysProperties.TRACE_IO) {
System.out.println("IOUtils." + method + " " + fileName + " " + o);
}
}
/**
* Create an input stream to read from a string. The string is converted to
* a byte array using UTF-8 encoding.
* If the string is null, this method returns null.
*
* @param s the string
* @return the input stream
*/
public static InputStream getInputStreamFromString(String s) {
if (s == null) {
return null;
}
return new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
}
/**
* Copy a file from one directory to another, or to another file.
*
* @param original the original file name
* @param copy the file name of the copy
*/
public static void copyFiles(String original, String copy) throws IOException {
InputStream in = FileUtils.newInputStream(original);
OutputStream out = FileUtils.newOutputStream(copy, false);
copyAndClose(in, out);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/IntArray.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.Arrays;
import org.h2.engine.SysProperties;
/**
* An array with integer element.
*/
public class IntArray {
private int[] data;
private int size;
private int hash;
/**
* Create an int array with the default initial capacity.
*/
public IntArray() {
this(10);
}
/**
* Create an int array with specified initial capacity.
*
* @param capacity the initial capacity
*/
public IntArray(int capacity) {
data = new int[capacity];
}
/**
* Create an int array with the given values and size.
*
* @param data the int array
*/
public IntArray(int[] data) {
this.data = data;
size = data.length;
}
/**
* Append a value.
*
* @param value the value to append
*/
public void add(int value) {
if (size >= data.length) {
ensureCapacity(size + size);
}
data[size++] = value;
}
/**
* Get the value at the given index.
*
* @param index the index
* @return the value
*/
public int get(int index) {
if (SysProperties.CHECK) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException("i=" + index + " size=" + size);
}
}
return data[index];
}
/**
* Remove the value at the given index.
*
* @param index the index
*/
public void remove(int index) {
if (SysProperties.CHECK) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException("i=" + index + " size=" + size);
}
}
System.arraycopy(data, index + 1, data, index, size - index - 1);
size--;
}
/**
* Ensure the the underlying array is large enough for the given number of
* entries.
*
* @param minCapacity the minimum capacity
*/
public void ensureCapacity(int minCapacity) {
minCapacity = Math.max(4, minCapacity);
if (minCapacity >= data.length) {
data = Arrays.copyOf(data, minCapacity);
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof IntArray)) {
return false;
}
IntArray other = (IntArray) obj;
if (hashCode() != other.hashCode() || size != other.size) {
return false;
}
for (int i = 0; i < size; i++) {
if (data[i] != other.data[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
if (hash != 0) {
return hash;
}
int h = size + 1;
for (int i = 0; i < size; i++) {
h = h * 31 + data[i];
}
hash = h;
return h;
}
/**
* Get the size of the list.
*
* @return the size
*/
public int size() {
return size;
}
/**
* Convert this list to an array. The target array must be big enough.
*
* @param array the target array
*/
public void toArray(int[] array) {
System.arraycopy(data, 0, array, 0, size);
}
@Override
public String toString() {
StatementBuilder buff = new StatementBuilder("{");
for (int i = 0; i < size; i++) {
buff.appendExceptFirst(", ");
buff.append(data[i]);
}
return buff.append('}').toString();
}
/**
* Remove a number of elements.
*
* @param fromIndex the index of the first item to remove
* @param toIndex upper bound (exclusive)
*/
public void removeRange(int fromIndex, int toIndex) {
if (SysProperties.CHECK) {
if (fromIndex > toIndex || toIndex > size) {
throw new ArrayIndexOutOfBoundsException("from=" + fromIndex +
" to=" + toIndex + " size=" + size);
}
}
System.arraycopy(data, toIndex, data, fromIndex, size - toIndex);
size -= toIndex - fromIndex;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/IntIntHashMap.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import org.h2.message.DbException;
/**
* A hash map with int key and int values. There is a restriction: the
* value -1 (NOT_FOUND) cannot be stored in the map. 0 can be stored.
* An empty record has key=0 and value=0.
* A deleted record has key=0 and value=DELETED
*/
public class IntIntHashMap extends HashBase {
/**
* The value indicating that the entry has not been found.
*/
public static final int NOT_FOUND = -1;
private static final int DELETED = 1;
private int[] keys;
private int[] values;
private int zeroValue;
@Override
protected void reset(int newLevel) {
super.reset(newLevel);
keys = new int[len];
values = new int[len];
}
/**
* Store the given key-value pair. The value is overwritten or added.
*
* @param key the key
* @param value the value (-1 is not supported)
*/
public void put(int key, int value) {
if (key == 0) {
zeroKey = true;
zeroValue = value;
return;
}
checkSizePut();
internalPut(key, value);
}
private void internalPut(int key, int value) {
int index = getIndex(key);
int plus = 1;
int deleted = -1;
do {
int k = keys[index];
if (k == 0) {
if (values[index] != DELETED) {
// found an empty record
if (deleted >= 0) {
index = deleted;
deletedCount--;
}
size++;
keys[index] = key;
values[index] = value;
return;
}
// found a deleted record
if (deleted < 0) {
deleted = index;
}
} else if (k == key) {
// update existing
values[index] = value;
return;
}
index = (index + plus++) & mask;
} while (plus <= len);
// no space
DbException.throwInternalError("hashmap is full");
}
/**
* Remove the key-value pair with the given key.
*
* @param key the key
*/
public void remove(int key) {
if (key == 0) {
zeroKey = false;
return;
}
checkSizeRemove();
int index = getIndex(key);
int plus = 1;
do {
int k = keys[index];
if (k == key) {
// found the record
keys[index] = 0;
values[index] = DELETED;
deletedCount++;
size--;
return;
} else if (k == 0 && values[index] == 0) {
// found an empty record
return;
}
index = (index + plus++) & mask;
} while (plus <= len);
// not found
}
@Override
protected void rehash(int newLevel) {
int[] oldKeys = keys;
int[] oldValues = values;
reset(newLevel);
for (int i = 0; i < oldKeys.length; i++) {
int k = oldKeys[i];
if (k != 0) {
// skip the checkSizePut so we don't end up
// accidentally recursing
internalPut(k, oldValues[i]);
}
}
}
/**
* Get the value for the given key. This method returns NOT_FOUND if the
* entry has not been found.
*
* @param key the key
* @return the value or NOT_FOUND
*/
public int get(int key) {
if (key == 0) {
return zeroKey ? zeroValue : NOT_FOUND;
}
int index = getIndex(key);
int plus = 1;
do {
int k = keys[index];
if (k == 0 && values[index] == 0) {
// found an empty record
return NOT_FOUND;
} else if (k == key) {
// found it
return values[index];
}
index = (index + plus++) & mask;
} while (plus <= len);
return NOT_FOUND;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/JdbcUtils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Properties;
import javax.naming.Context;
import javax.sql.DataSource;
import org.h2.api.CustomDataTypesHandler;
import org.h2.api.ErrorCode;
import org.h2.api.JavaObjectSerializer;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.DataHandler;
import org.h2.util.Utils.ClassFactory;
/**
* This is a utility class with JDBC helper functions.
*/
public class JdbcUtils {
/**
* The serializer to use.
*/
public static JavaObjectSerializer serializer;
/**
* Custom data types handler to use.
*/
public static CustomDataTypesHandler customDataTypesHandler;
private static final String[] DRIVERS = {
"h2:", "org.h2.Driver",
"Cache:", "com.intersys.jdbc.CacheDriver",
"daffodilDB://", "in.co.daffodil.db.rmi.RmiDaffodilDBDriver",
"daffodil", "in.co.daffodil.db.jdbc.DaffodilDBDriver",
"db2:", "com.ibm.db2.jcc.DB2Driver",
"derby:net:", "org.apache.derby.jdbc.ClientDriver",
"derby://", "org.apache.derby.jdbc.ClientDriver",
"derby:", "org.apache.derby.jdbc.EmbeddedDriver",
"FrontBase:", "com.frontbase.jdbc.FBJDriver",
"firebirdsql:", "org.firebirdsql.jdbc.FBDriver",
"hsqldb:", "org.hsqldb.jdbcDriver",
"informix-sqli:", "com.informix.jdbc.IfxDriver",
"jtds:", "net.sourceforge.jtds.jdbc.Driver",
"microsoft:", "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"mimer:", "com.mimer.jdbc.Driver",
"mysql:", "com.mysql.jdbc.Driver",
"odbc:", "sun.jdbc.odbc.JdbcOdbcDriver",
"oracle:", "oracle.jdbc.driver.OracleDriver",
"pervasive:", "com.pervasive.jdbc.v2.Driver",
"pointbase:micro:", "com.pointbase.me.jdbc.jdbcDriver",
"pointbase:", "com.pointbase.jdbc.jdbcUniversalDriver",
"postgresql:", "org.postgresql.Driver",
"sybase:", "com.sybase.jdbc3.jdbc.SybDriver",
"sqlserver:", "com.microsoft.sqlserver.jdbc.SQLServerDriver",
"teradata:", "com.ncr.teradata.TeraDriver",
};
private static boolean allowAllClasses;
private static HashSet<String> allowedClassNames;
/**
* In order to manage more than one class loader
*/
private static ArrayList<ClassFactory> userClassFactories =
new ArrayList<>();
private static String[] allowedClassNamePrefixes;
private JdbcUtils() {
// utility class
}
/**
* Add a class factory in order to manage more than one class loader.
*
* @param classFactory An object that implements ClassFactory
*/
public static void addClassFactory(ClassFactory classFactory) {
getUserClassFactories().add(classFactory);
}
/**
* Remove a class factory
*
* @param classFactory Already inserted class factory instance
*/
public static void removeClassFactory(ClassFactory classFactory) {
getUserClassFactories().remove(classFactory);
}
private static ArrayList<ClassFactory> getUserClassFactories() {
if (userClassFactories == null) {
// initially, it is empty
// but Apache Tomcat may clear the fields as well
userClassFactories = new ArrayList<>();
}
return userClassFactories;
}
static {
String clazz = SysProperties.JAVA_OBJECT_SERIALIZER;
if (clazz != null) {
try {
serializer = (JavaObjectSerializer) loadUserClass(clazz).newInstance();
} catch (Exception e) {
throw DbException.convert(e);
}
}
String customTypeHandlerClass = SysProperties.CUSTOM_DATA_TYPES_HANDLER;
if (customTypeHandlerClass != null) {
try {
customDataTypesHandler = (CustomDataTypesHandler)
loadUserClass(customTypeHandlerClass).newInstance();
} catch (Exception e) {
throw DbException.convert(e);
}
}
}
/**
* Load a class, but check if it is allowed to load this class first. To
* perform access rights checking, the system property h2.allowedClasses
* needs to be set to a list of class file name prefixes.
*
* @param className the name of the class
* @return the class object
*/
@SuppressWarnings("unchecked")
public static <Z> Class<Z> loadUserClass(String className) {
if (allowedClassNames == null) {
// initialize the static fields
String s = SysProperties.ALLOWED_CLASSES;
ArrayList<String> prefixes = New.arrayList();
boolean allowAll = false;
HashSet<String> classNames = new HashSet<>();
for (String p : StringUtils.arraySplit(s, ',', true)) {
if (p.equals("*")) {
allowAll = true;
} else if (p.endsWith("*")) {
prefixes.add(p.substring(0, p.length() - 1));
} else {
classNames.add(p);
}
}
allowedClassNamePrefixes = prefixes.toArray(new String[0]);
allowAllClasses = allowAll;
allowedClassNames = classNames;
}
if (!allowAllClasses && !allowedClassNames.contains(className)) {
boolean allowed = false;
for (String s : allowedClassNamePrefixes) {
if (className.startsWith(s)) {
allowed = true;
}
}
if (!allowed) {
throw DbException.get(
ErrorCode.ACCESS_DENIED_TO_CLASS_1, className);
}
}
// Use provided class factory first.
for (ClassFactory classFactory : getUserClassFactories()) {
if (classFactory.match(className)) {
try {
Class<?> userClass = classFactory.loadClass(className);
if (!(userClass == null)) {
return (Class<Z>) userClass;
}
} catch (Exception e) {
throw DbException.get(
ErrorCode.CLASS_NOT_FOUND_1, e, className);
}
}
}
// Use local ClassLoader
try {
return (Class<Z>) Class.forName(className);
} catch (ClassNotFoundException e) {
try {
return (Class<Z>) Class.forName(
className, true,
Thread.currentThread().getContextClassLoader());
} catch (Exception e2) {
throw DbException.get(
ErrorCode.CLASS_NOT_FOUND_1, e, className);
}
} catch (NoClassDefFoundError e) {
throw DbException.get(
ErrorCode.CLASS_NOT_FOUND_1, e, className);
} catch (Error e) {
// UnsupportedClassVersionError
throw DbException.get(
ErrorCode.GENERAL_ERROR_1, e, className);
}
}
/**
* Close a statement without throwing an exception.
*
* @param stat the statement or null
*/
public static void closeSilently(Statement stat) {
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
// ignore
}
}
}
/**
* Close a connection without throwing an exception.
*
* @param conn the connection or null
*/
public static void closeSilently(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// ignore
}
}
}
/**
* Close a result set without throwing an exception.
*
* @param rs the result set or null
*/
public static void closeSilently(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// ignore
}
}
}
/**
* Open a new database connection with the given settings.
*
* @param driver the driver class name
* @param url the database URL
* @param user the user name
* @param password the password
* @return the database connection
*/
public static Connection getConnection(String driver, String url,
String user, String password) throws SQLException {
Properties prop = new Properties();
if (user != null) {
prop.setProperty("user", user);
}
if (password != null) {
prop.setProperty("password", password);
}
return getConnection(driver, url, prop);
}
/**
* Open a new database connection with the given settings.
*
* @param driver the driver class name
* @param url the database URL
* @param prop the properties containing at least the user name and password
* @return the database connection
*/
public static Connection getConnection(String driver, String url,
Properties prop) throws SQLException {
if (StringUtils.isNullOrEmpty(driver)) {
JdbcUtils.load(url);
} else {
Class<?> d = loadUserClass(driver);
if (java.sql.Driver.class.isAssignableFrom(d)) {
try {
Driver driverInstance = (Driver) d.newInstance();
return driverInstance.connect(url, prop); /*fix issue #695 with drivers with the same
jdbc subprotocol in classpath of jdbc drivers (as example redshift and postgresql drivers)*/
} catch (Exception e) {
throw DbException.toSQLException(e);
}
} else if (javax.naming.Context.class.isAssignableFrom(d)) {
// JNDI context
try {
Context context = (Context) d.newInstance();
DataSource ds = (DataSource) context.lookup(url);
String user = prop.getProperty("user");
String password = prop.getProperty("password");
if (StringUtils.isNullOrEmpty(user) && StringUtils.isNullOrEmpty(password)) {
return ds.getConnection();
}
return ds.getConnection(user, password);
} catch (Exception e) {
throw DbException.toSQLException(e);
}
} else {
// don't know, but maybe it loaded a JDBC Driver
return DriverManager.getConnection(url, prop);
}
}
return DriverManager.getConnection(url, prop);
}
/**
* Get the driver class name for the given URL, or null if the URL is
* unknown.
*
* @param url the database URL
* @return the driver class name
*/
public static String getDriver(String url) {
if (url.startsWith("jdbc:")) {
url = url.substring("jdbc:".length());
for (int i = 0; i < DRIVERS.length; i += 2) {
String prefix = DRIVERS[i];
if (url.startsWith(prefix)) {
return DRIVERS[i + 1];
}
}
}
return null;
}
/**
* Load the driver class for the given URL, if the database URL is known.
*
* @param url the database URL
*/
public static void load(String url) {
String driver = getDriver(url);
if (driver != null) {
loadUserClass(driver);
}
}
/**
* Serialize the object to a byte array, using the serializer specified by
* the connection info if set, or the default serializer.
*
* @param obj the object to serialize
* @param dataHandler provides the object serializer (may be null)
* @return the byte array
*/
public static byte[] serialize(Object obj, DataHandler dataHandler) {
try {
JavaObjectSerializer handlerSerializer = null;
if (dataHandler != null) {
handlerSerializer = dataHandler.getJavaObjectSerializer();
}
if (handlerSerializer != null) {
return handlerSerializer.serialize(obj);
}
if (serializer != null) {
return serializer.serialize(obj);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
} catch (Throwable e) {
throw DbException.get(ErrorCode.SERIALIZATION_FAILED_1, e, e.toString());
}
}
/**
* De-serialize the byte array to an object, eventually using the serializer
* specified by the connection info.
*
* @param data the byte array
* @param dataHandler provides the object serializer (may be null)
* @return the object
* @throws DbException if serialization fails
*/
public static Object deserialize(byte[] data, DataHandler dataHandler) {
try {
JavaObjectSerializer dbJavaObjectSerializer = null;
if (dataHandler != null) {
dbJavaObjectSerializer = dataHandler.getJavaObjectSerializer();
}
if (dbJavaObjectSerializer != null) {
return dbJavaObjectSerializer.deserialize(data);
}
if (serializer != null) {
return serializer.deserialize(data);
}
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is;
if (SysProperties.USE_THREAD_CONTEXT_CLASS_LOADER) {
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
is = new ObjectInputStream(in) {
@Override
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
try {
return Class.forName(desc.getName(), true, loader);
} catch (ClassNotFoundException e) {
return super.resolveClass(desc);
}
}
};
} else {
is = new ObjectInputStream(in);
}
return is.readObject();
} catch (Throwable e) {
throw DbException.get(ErrorCode.DESERIALIZATION_FAILED_1, e, e.toString());
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/LazyFuture.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.h2.message.DbException;
/**
* Single threaded lazy future.
*
* @author Sergi Vladykin
*
* @param <T> the result type
*/
public abstract class LazyFuture<T> implements Future<T> {
private static final int S_READY = 0;
private static final int S_DONE = 1;
private static final int S_ERROR = 2;
private static final int S_CANCELED = 3;
private int state = S_READY;
private T result;
private Exception error;
/**
* Reset this future to the initial state.
*
* @return {@code false} if it was already in initial state
*/
public boolean reset() {
if (state == S_READY) {
return false;
}
state = S_READY;
result = null;
error = null;
return true;
}
/**
* Run computation and produce the result.
*
* @return the result of computation
*/
protected abstract T run() throws Exception;
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (state != S_READY) {
return false;
}
state = S_CANCELED;
return true;
}
@Override
public T get() throws InterruptedException, ExecutionException {
switch (state) {
case S_READY:
try {
result = run();
state = S_DONE;
} catch (Exception e) {
error = e;
if (e instanceof InterruptedException) {
throw (InterruptedException) e;
}
throw new ExecutionException(e);
} finally {
if (state != S_DONE) {
state = S_ERROR;
}
}
return result;
case S_DONE:
return result;
case S_ERROR:
throw new ExecutionException(error);
case S_CANCELED:
throw new CancellationException();
default:
throw DbException.throwInternalError("" + state);
}
}
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException {
return get();
}
@Override
public boolean isCancelled() {
return state == S_CANCELED;
}
@Override
public boolean isDone() {
return state != S_READY;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/LocalDateTimeUtils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
* Iso8601: Initial Developer: Philippe Marschall (firstName dot lastName
* at gmail dot com)
*/
package org.h2.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.h2.message.DbException;
import org.h2.value.Value;
import org.h2.value.ValueDate;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueTimestampTimeZone;
/**
* This utility class contains time conversion functions for Java 8
* Date and Time API classes.
*
* <p>This class is implemented using reflection so that it compiles on
* Java 7 as well.</p>
*
* <p>Custom conversion methods between H2 internal values and JSR-310 classes
* are used in most cases without intermediate conversions to java.sql classes.
* Direct conversion is simpler, faster, and it does not inherit limitations
* and issues from java.sql classes and conversion methods provided by JDK.</p>
*
* <p>The only one exclusion is a conversion between {@link Timestamp} and
* Instant.</p>
*
* <p>Once the driver requires Java 8 and Android API 26 all the reflection
* can be removed.</p>
*/
public class LocalDateTimeUtils {
/**
* {@code Class<java.time.LocalDate>} or {@code null}.
*/
public static final Class<?> LOCAL_DATE;
/**
* {@code Class<java.time.LocalTime>} or {@code null}.
*/
public static final Class<?> LOCAL_TIME;
/**
* {@code Class<java.time.LocalDateTime>} or {@code null}.
*/
public static final Class<?> LOCAL_DATE_TIME;
/**
* {@code Class<java.time.Instant>} or {@code null}.
*/
public static final Class<?> INSTANT;
/**
* {@code Class<java.time.OffsetDateTime>} or {@code null}.
*/
public static final Class<?> OFFSET_DATE_TIME;
/**
* {@code Class<java.time.ZoneOffset>} or {@code null}.
*/
private static final Class<?> ZONE_OFFSET;
/**
* {@code java.time.LocalTime#ofNanoOfDay()} or {@code null}.
*/
private static final Method LOCAL_TIME_OF_NANO;
/**
* {@code java.time.LocalTime#toNanoOfDay()} or {@code null}.
*/
private static final Method LOCAL_TIME_TO_NANO;
/**
* {@code java.time.LocalDate#of(int, int, int)} or {@code null}.
*/
private static final Method LOCAL_DATE_OF_YEAR_MONTH_DAY;
/**
* {@code java.time.LocalDate#parse(CharSequence)} or {@code null}.
*/
private static final Method LOCAL_DATE_PARSE;
/**
* {@code java.time.LocalDate#getYear()} or {@code null}.
*/
private static final Method LOCAL_DATE_GET_YEAR;
/**
* {@code java.time.LocalDate#getMonthValue()} or {@code null}.
*/
private static final Method LOCAL_DATE_GET_MONTH_VALUE;
/**
* {@code java.time.LocalDate#getDayOfMonth()} or {@code null}.
*/
private static final Method LOCAL_DATE_GET_DAY_OF_MONTH;
/**
* {@code java.time.LocalDate#atStartOfDay()} or {@code null}.
*/
private static final Method LOCAL_DATE_AT_START_OF_DAY;
/**
* {@code java.time.Instant#getEpochSecond()} or {@code null}.
*/
private static final Method INSTANT_GET_EPOCH_SECOND;
/**
* {@code java.time.Instant#getNano()} or {@code null}.
*/
private static final Method INSTANT_GET_NANO;
/**
* {@code java.sql.Timestamp.toInstant()} or {@code null}.
*/
private static final Method TIMESTAMP_TO_INSTANT;
/**
* {@code java.time.LocalTime#parse(CharSequence)} or {@code null}.
*/
private static final Method LOCAL_TIME_PARSE;
/**
* {@code java.time.LocalDateTime#plusNanos(long)} or {@code null}.
*/
private static final Method LOCAL_DATE_TIME_PLUS_NANOS;
/**
* {@code java.time.LocalDateTime#toLocalDate()} or {@code null}.
*/
private static final Method LOCAL_DATE_TIME_TO_LOCAL_DATE;
/**
* {@code java.time.LocalDateTime#toLocalTime()} or {@code null}.
*/
private static final Method LOCAL_DATE_TIME_TO_LOCAL_TIME;
/**
* {@code java.time.LocalDateTime#parse(CharSequence)} or {@code null}.
*/
private static final Method LOCAL_DATE_TIME_PARSE;
/**
* {@code java.time.ZoneOffset#ofTotalSeconds(int)} or {@code null}.
*/
private static final Method ZONE_OFFSET_OF_TOTAL_SECONDS;
/**
* {@code java.time.OffsetDateTime#of(LocalDateTime, ZoneOffset)} or
* {@code null}.
*/
private static final Method OFFSET_DATE_TIME_OF_LOCAL_DATE_TIME_ZONE_OFFSET;
/**
* {@code java.time.OffsetDateTime#parse(CharSequence)} or {@code null}.
*/
private static final Method OFFSET_DATE_TIME_PARSE;
/**
* {@code java.time.OffsetDateTime#toLocalDateTime()} or {@code null}.
*/
private static final Method OFFSET_DATE_TIME_TO_LOCAL_DATE_TIME;
/**
* {@code java.time.OffsetDateTime#getOffset()} or {@code null}.
*/
private static final Method OFFSET_DATE_TIME_GET_OFFSET;
/**
* {@code java.time.ZoneOffset#getTotalSeconds()} or {@code null}.
*/
private static final Method ZONE_OFFSET_GET_TOTAL_SECONDS;
private static final boolean IS_JAVA8_DATE_API_PRESENT;
static {
LOCAL_DATE = tryGetClass("java.time.LocalDate");
LOCAL_TIME = tryGetClass("java.time.LocalTime");
LOCAL_DATE_TIME = tryGetClass("java.time.LocalDateTime");
INSTANT = tryGetClass("java.time.Instant");
OFFSET_DATE_TIME = tryGetClass("java.time.OffsetDateTime");
ZONE_OFFSET = tryGetClass("java.time.ZoneOffset");
IS_JAVA8_DATE_API_PRESENT = LOCAL_DATE != null && LOCAL_TIME != null &&
LOCAL_DATE_TIME != null && INSTANT != null &&
OFFSET_DATE_TIME != null && ZONE_OFFSET != null;
if (IS_JAVA8_DATE_API_PRESENT) {
LOCAL_TIME_OF_NANO = getMethod(LOCAL_TIME, "ofNanoOfDay", long.class);
LOCAL_TIME_TO_NANO = getMethod(LOCAL_TIME, "toNanoOfDay");
LOCAL_DATE_OF_YEAR_MONTH_DAY = getMethod(LOCAL_DATE, "of",
int.class, int.class, int.class);
LOCAL_DATE_PARSE = getMethod(LOCAL_DATE, "parse",
CharSequence.class);
LOCAL_DATE_GET_YEAR = getMethod(LOCAL_DATE, "getYear");
LOCAL_DATE_GET_MONTH_VALUE = getMethod(LOCAL_DATE, "getMonthValue");
LOCAL_DATE_GET_DAY_OF_MONTH = getMethod(LOCAL_DATE, "getDayOfMonth");
LOCAL_DATE_AT_START_OF_DAY = getMethod(LOCAL_DATE, "atStartOfDay");
INSTANT_GET_EPOCH_SECOND = getMethod(INSTANT, "getEpochSecond");
INSTANT_GET_NANO = getMethod(INSTANT, "getNano");
TIMESTAMP_TO_INSTANT = getMethod(Timestamp.class, "toInstant");
LOCAL_TIME_PARSE = getMethod(LOCAL_TIME, "parse", CharSequence.class);
LOCAL_DATE_TIME_PLUS_NANOS = getMethod(LOCAL_DATE_TIME, "plusNanos", long.class);
LOCAL_DATE_TIME_TO_LOCAL_DATE = getMethod(LOCAL_DATE_TIME, "toLocalDate");
LOCAL_DATE_TIME_TO_LOCAL_TIME = getMethod(LOCAL_DATE_TIME, "toLocalTime");
LOCAL_DATE_TIME_PARSE = getMethod(LOCAL_DATE_TIME, "parse", CharSequence.class);
ZONE_OFFSET_OF_TOTAL_SECONDS = getMethod(ZONE_OFFSET, "ofTotalSeconds", int.class);
OFFSET_DATE_TIME_TO_LOCAL_DATE_TIME = getMethod(OFFSET_DATE_TIME, "toLocalDateTime");
OFFSET_DATE_TIME_GET_OFFSET = getMethod(OFFSET_DATE_TIME, "getOffset");
OFFSET_DATE_TIME_OF_LOCAL_DATE_TIME_ZONE_OFFSET = getMethod(
OFFSET_DATE_TIME, "of", LOCAL_DATE_TIME, ZONE_OFFSET);
OFFSET_DATE_TIME_PARSE = getMethod(OFFSET_DATE_TIME, "parse", CharSequence.class);
ZONE_OFFSET_GET_TOTAL_SECONDS = getMethod(ZONE_OFFSET, "getTotalSeconds");
} else {
LOCAL_TIME_OF_NANO = null;
LOCAL_TIME_TO_NANO = null;
LOCAL_DATE_OF_YEAR_MONTH_DAY = null;
LOCAL_DATE_PARSE = null;
LOCAL_DATE_GET_YEAR = null;
LOCAL_DATE_GET_MONTH_VALUE = null;
LOCAL_DATE_GET_DAY_OF_MONTH = null;
LOCAL_DATE_AT_START_OF_DAY = null;
INSTANT_GET_EPOCH_SECOND = null;
INSTANT_GET_NANO = null;
TIMESTAMP_TO_INSTANT = null;
LOCAL_TIME_PARSE = null;
LOCAL_DATE_TIME_PLUS_NANOS = null;
LOCAL_DATE_TIME_TO_LOCAL_DATE = null;
LOCAL_DATE_TIME_TO_LOCAL_TIME = null;
LOCAL_DATE_TIME_PARSE = null;
ZONE_OFFSET_OF_TOTAL_SECONDS = null;
OFFSET_DATE_TIME_TO_LOCAL_DATE_TIME = null;
OFFSET_DATE_TIME_GET_OFFSET = null;
OFFSET_DATE_TIME_OF_LOCAL_DATE_TIME_ZONE_OFFSET = null;
OFFSET_DATE_TIME_PARSE = null;
ZONE_OFFSET_GET_TOTAL_SECONDS = null;
}
}
private LocalDateTimeUtils() {
// utility class
}
/**
* Checks if the Java 8 Date and Time API is present.
*
* <p>This is the case on Java 8 and later and not the case on
* Java 7. Versions older than Java 7 are not supported.</p>
*
* @return if the Java 8 Date and Time API is present
*/
public static boolean isJava8DateApiPresent() {
return IS_JAVA8_DATE_API_PRESENT;
}
/**
* Parses an ISO date string into a java.time.LocalDate.
*
* @param text the ISO date string
* @return the java.time.LocalDate instance
*/
public static Object parseLocalDate(CharSequence text) {
try {
return LOCAL_DATE_PARSE.invoke(null, text);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("error when parsing text '" + text + "'", e);
}
}
/**
* Parses an ISO time string into a java.time.LocalTime.
*
* @param text the ISO time string
* @return the java.time.LocalTime instance
*/
public static Object parseLocalTime(CharSequence text) {
try {
return LOCAL_TIME_PARSE.invoke(null, text);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("error when parsing text '" + text + "'", e);
}
}
/**
* Parses an ISO date string into a java.time.LocalDateTime.
*
* @param text the ISO date string
* @return the java.time.LocalDateTime instance
*/
public static Object parseLocalDateTime(CharSequence text) {
try {
return LOCAL_DATE_TIME_PARSE.invoke(null, text);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("error when parsing text '" + text + "'", e);
}
}
/**
* Parses an ISO date string into a java.time.OffsetDateTime.
*
* @param text the ISO date string
* @return the java.time.OffsetDateTime instance
*/
public static Object parseOffsetDateTime(CharSequence text) {
try {
return OFFSET_DATE_TIME_PARSE.invoke(null, text);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("error when parsing text '" + text + "'", e);
}
}
private static Class<?> tryGetClass(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
}
private static Method getMethod(Class<?> clazz, String methodName,
Class<?>... parameterTypes) {
try {
return clazz.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Java 8 or later but method " +
clazz.getName() + "#" + methodName + "(" +
Arrays.toString(parameterTypes) + ") is missing", e);
}
}
/**
* Converts a value to a LocalDate.
*
* <p>This method should only called from Java 8 or later.</p>
*
* @param value the value to convert
* @return the LocalDate
*/
public static Object valueToLocalDate(Value value) {
try {
return localDateFromDateValue(((ValueDate) value.convertTo(Value.DATE)).getDateValue());
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "date conversion failed");
}
}
/**
* Converts a value to a LocalTime.
*
* <p>This method should only called from Java 8 or later.</p>
*
* @param value the value to convert
* @return the LocalTime
*/
public static Object valueToLocalTime(Value value) {
try {
return LOCAL_TIME_OF_NANO.invoke(null,
((ValueTime) value.convertTo(Value.TIME)).getNanos());
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "time conversion failed");
}
}
/**
* Converts a value to a LocalDateTime.
*
* <p>This method should only called from Java 8 or later.</p>
*
* @param value the value to convert
* @return the LocalDateTime
*/
public static Object valueToLocalDateTime(Value value) {
ValueTimestamp valueTimestamp = (ValueTimestamp) value.convertTo(Value.TIMESTAMP);
long dateValue = valueTimestamp.getDateValue();
long timeNanos = valueTimestamp.getTimeNanos();
try {
return localDateTimeFromDateNanos(dateValue, timeNanos);
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "timestamp conversion failed");
}
}
/**
* Converts a value to a Instant.
*
* <p>This method should only called from Java 8 or later.</p>
*
* @param value the value to convert
* @return the Instant
*/
public static Object valueToInstant(Value value) {
try {
return TIMESTAMP_TO_INSTANT.invoke(value.getTimestamp());
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "timestamp conversion failed");
}
}
/**
* Converts a value to a OffsetDateTime.
*
* <p>This method should only called from Java 8 or later.</p>
*
* @param value the value to convert
* @return the OffsetDateTime
*/
public static Object valueToOffsetDateTime(Value value) {
ValueTimestampTimeZone valueTimestampTimeZone = (ValueTimestampTimeZone) value.convertTo(Value.TIMESTAMP_TZ);
long dateValue = valueTimestampTimeZone.getDateValue();
long timeNanos = valueTimestampTimeZone.getTimeNanos();
try {
Object localDateTime = localDateTimeFromDateNanos(dateValue, timeNanos);
short timeZoneOffsetMins = valueTimestampTimeZone.getTimeZoneOffsetMins();
int offsetSeconds = (int) TimeUnit.MINUTES.toSeconds(timeZoneOffsetMins);
Object offset = ZONE_OFFSET_OF_TOTAL_SECONDS.invoke(null, offsetSeconds);
return OFFSET_DATE_TIME_OF_LOCAL_DATE_TIME_ZONE_OFFSET.invoke(null,
localDateTime, offset);
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "timestamp with time zone conversion failed");
}
}
/**
* Converts a LocalDate to a Value.
*
* @param localDate the LocalDate to convert, not {@code null}
* @return the value
*/
public static Value localDateToDateValue(Object localDate) {
try {
return ValueDate.fromDateValue(dateValueFromLocalDate(localDate));
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "date conversion failed");
}
}
/**
* Converts a LocalTime to a Value.
*
* @param localTime the LocalTime to convert, not {@code null}
* @return the value
*/
public static Value localTimeToTimeValue(Object localTime) {
try {
return ValueTime.fromNanos((Long) LOCAL_TIME_TO_NANO.invoke(localTime));
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "time conversion failed");
}
}
/**
* Converts a LocalDateTime to a Value.
*
* @param localDateTime the LocalDateTime to convert, not {@code null}
* @return the value
*/
public static Value localDateTimeToValue(Object localDateTime) {
try {
Object localDate = LOCAL_DATE_TIME_TO_LOCAL_DATE.invoke(localDateTime);
long dateValue = dateValueFromLocalDate(localDate);
long timeNanos = timeNanosFromLocalDateTime(localDateTime);
return ValueTimestamp.fromDateValueAndNanos(dateValue, timeNanos);
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "local date time conversion failed");
}
}
/**
* Converts a Instant to a Value.
*
* @param instant the Instant to convert, not {@code null}
* @return the value
*/
public static Value instantToValue(Object instant) {
try {
long epochSecond = (long) INSTANT_GET_EPOCH_SECOND.invoke(instant);
int nano = (int) INSTANT_GET_NANO.invoke(instant);
long absoluteDay = epochSecond / 86_400;
// Round toward negative infinity
if (epochSecond < 0 && (absoluteDay * 86_400 != epochSecond)) {
absoluteDay--;
}
long timeNanos = (epochSecond - absoluteDay * 86_400) * 1_000_000_000 + nano;
return ValueTimestampTimeZone.fromDateValueAndNanos(
DateTimeUtils.dateValueFromAbsoluteDay(absoluteDay), timeNanos, (short) 0);
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "instant conversion failed");
}
}
/**
* Converts a OffsetDateTime to a Value.
*
* @param offsetDateTime the OffsetDateTime to convert, not {@code null}
* @return the value
*/
public static Value offsetDateTimeToValue(Object offsetDateTime) {
try {
Object localDateTime = OFFSET_DATE_TIME_TO_LOCAL_DATE_TIME.invoke(offsetDateTime);
Object localDate = LOCAL_DATE_TIME_TO_LOCAL_DATE.invoke(localDateTime);
Object zoneOffset = OFFSET_DATE_TIME_GET_OFFSET.invoke(offsetDateTime);
long dateValue = dateValueFromLocalDate(localDate);
long timeNanos = timeNanosFromLocalDateTime(localDateTime);
short timeZoneOffsetMins = zoneOffsetToOffsetMinute(zoneOffset);
return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue,
timeNanos, timeZoneOffsetMins);
} catch (IllegalAccessException e) {
throw DbException.convert(e);
} catch (InvocationTargetException e) {
throw DbException.convertInvocation(e, "time conversion failed");
}
}
private static long dateValueFromLocalDate(Object localDate)
throws IllegalAccessException, InvocationTargetException {
int year = (Integer) LOCAL_DATE_GET_YEAR.invoke(localDate);
int month = (Integer) LOCAL_DATE_GET_MONTH_VALUE.invoke(localDate);
int day = (Integer) LOCAL_DATE_GET_DAY_OF_MONTH.invoke(localDate);
return DateTimeUtils.dateValue(year, month, day);
}
private static long timeNanosFromLocalDateTime(Object localDateTime)
throws IllegalAccessException, InvocationTargetException {
Object localTime = LOCAL_DATE_TIME_TO_LOCAL_TIME.invoke(localDateTime);
return (Long) LOCAL_TIME_TO_NANO.invoke(localTime);
}
private static short zoneOffsetToOffsetMinute(Object zoneOffset)
throws IllegalAccessException, InvocationTargetException {
int totalSeconds = (Integer) ZONE_OFFSET_GET_TOTAL_SECONDS.invoke(zoneOffset);
return (short) TimeUnit.SECONDS.toMinutes(totalSeconds);
}
private static Object localDateFromDateValue(long dateValue)
throws IllegalAccessException, InvocationTargetException {
int year = DateTimeUtils.yearFromDateValue(dateValue);
int month = DateTimeUtils.monthFromDateValue(dateValue);
int day = DateTimeUtils.dayFromDateValue(dateValue);
try {
return LOCAL_DATE_OF_YEAR_MONTH_DAY.invoke(null, year, month, day);
} catch (InvocationTargetException e) {
if (year <= 1500 && (year & 3) == 0 && month == 2 && day == 29) {
// If proleptic Gregorian doesn't have such date use the next day
return LOCAL_DATE_OF_YEAR_MONTH_DAY.invoke(null, year, 3, 1);
}
throw e;
}
}
private static Object localDateTimeFromDateNanos(long dateValue, long timeNanos)
throws IllegalAccessException, InvocationTargetException {
Object localDate = localDateFromDateValue(dateValue);
Object localDateTime = LOCAL_DATE_AT_START_OF_DAY.invoke(localDate);
return LOCAL_DATE_TIME_PLUS_NANOS.invoke(localDateTime, timeNanos);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/MathUtils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.concurrent.ThreadLocalRandom;
/**
* This is a utility class with mathematical helper functions.
*/
public class MathUtils {
/**
* The secure random object.
*/
static SecureRandom cachedSecureRandom;
/**
* True if the secure random object is seeded.
*/
static volatile boolean seeded;
private MathUtils() {
// utility class
}
/**
* Round the value up to the next block size. The block size must be a power
* of two. As an example, using the block size of 8, the following rounding
* operations are done: 0 stays 0; values 1..8 results in 8, 9..16 results
* in 16, and so on.
*
* @param x the value to be rounded
* @param blockSizePowerOf2 the block size
* @return the rounded value
*/
public static int roundUpInt(int x, int blockSizePowerOf2) {
return (x + blockSizePowerOf2 - 1) & (-blockSizePowerOf2);
}
/**
* Round the value up to the next block size. The block size must be a power
* of two. As an example, using the block size of 8, the following rounding
* operations are done: 0 stays 0; values 1..8 results in 8, 9..16 results
* in 16, and so on.
*
* @param x the value to be rounded
* @param blockSizePowerOf2 the block size
* @return the rounded value
*/
public static long roundUpLong(long x, long blockSizePowerOf2) {
return (x + blockSizePowerOf2 - 1) & (-blockSizePowerOf2);
}
private static synchronized SecureRandom getSecureRandom() {
if (cachedSecureRandom != null) {
return cachedSecureRandom;
}
// Workaround for SecureRandom problem as described in
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6202721
// Can not do that in a static initializer block, because
// threads are not started until after the initializer block exits
try {
cachedSecureRandom = SecureRandom.getInstance("SHA1PRNG");
// On some systems, secureRandom.generateSeed() is very slow.
// In this case it is initialized using our own seed implementation
// and afterwards (in the thread) using the regular algorithm.
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] seed = sr.generateSeed(20);
synchronized (cachedSecureRandom) {
cachedSecureRandom.setSeed(seed);
seeded = true;
}
} catch (Exception e) {
// NoSuchAlgorithmException
warn("SecureRandom", e);
}
}
};
try {
Thread t = new Thread(runnable, "Generate Seed");
// let the process terminate even if generating the seed is
// really slow
t.setDaemon(true);
t.start();
Thread.yield();
try {
// normally, generateSeed takes less than 200 ms
t.join(400);
} catch (InterruptedException e) {
warn("InterruptedException", e);
}
if (!seeded) {
byte[] seed = generateAlternativeSeed();
// this never reduces randomness
synchronized (cachedSecureRandom) {
cachedSecureRandom.setSeed(seed);
}
}
} catch (SecurityException e) {
// workaround for the Google App Engine: don't use a thread
runnable.run();
generateAlternativeSeed();
}
} catch (Exception e) {
// NoSuchAlgorithmException
warn("SecureRandom", e);
cachedSecureRandom = new SecureRandom();
}
return cachedSecureRandom;
}
/**
* Generate a seed value, using as much unpredictable data as possible.
*
* @return the seed
*/
public static byte[] generateAlternativeSeed() {
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bout);
// milliseconds and nanoseconds
out.writeLong(System.currentTimeMillis());
out.writeLong(System.nanoTime());
// memory
out.writeInt(new Object().hashCode());
Runtime runtime = Runtime.getRuntime();
out.writeLong(runtime.freeMemory());
out.writeLong(runtime.maxMemory());
out.writeLong(runtime.totalMemory());
// environment
try {
String s = System.getProperties().toString();
// can't use writeUTF, as the string
// might be larger than 64 KB
out.writeInt(s.length());
out.write(s.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
warn("generateAlternativeSeed", e);
}
// host name and ip addresses (if any)
try {
// workaround for the Google App Engine: don't use InetAddress
Class<?> inetAddressClass = Class.forName(
"java.net.InetAddress");
Object localHost = inetAddressClass.getMethod(
"getLocalHost").invoke(null);
String hostName = inetAddressClass.getMethod(
"getHostName").invoke(localHost).toString();
out.writeUTF(hostName);
Object[] list = (Object[]) inetAddressClass.getMethod(
"getAllByName", String.class).invoke(null, hostName);
Method getAddress = inetAddressClass.getMethod(
"getAddress");
for (Object o : list) {
out.write((byte[]) getAddress.invoke(o));
}
} catch (Throwable e) {
// on some system, InetAddress is not supported
// on some system, InetAddress.getLocalHost() doesn't work
// for some reason (incorrect configuration)
}
// timing (a second thread is already running usually)
for (int j = 0; j < 16; j++) {
int i = 0;
long end = System.currentTimeMillis();
while (end == System.currentTimeMillis()) {
i++;
}
out.writeInt(i);
}
out.close();
return bout.toByteArray();
} catch (IOException e) {
warn("generateAlternativeSeed", e);
return new byte[1];
}
}
/**
* Print a message to system output if there was a problem initializing the
* random number generator.
*
* @param s the message to print
* @param t the stack trace
*/
static void warn(String s, Throwable t) {
// not a fatal problem, but maybe reduced security
System.out.println("Warning: " + s);
if (t != null) {
t.printStackTrace();
}
}
/**
* Get the value that is equal to or higher than this value, and that is a
* power of two.
*
* @param x the original value
* @return the next power of two value
* @throws IllegalArgumentException if x < 0 or x > 0x40000000
*/
public static int nextPowerOf2(int x) throws IllegalArgumentException {
if (x == 0) {
return 1;
} else if (x < 0 || x > 0x4000_0000 ) {
throw new IllegalArgumentException("Argument out of range"
+ " [0x0-0x40000000]. Argument was: " + x);
}
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return ++x;
}
/**
* Convert a long value to an int value. Values larger than the biggest int
* value is converted to the biggest int value, and values smaller than the
* smallest int value are converted to the smallest int value.
*
* @param l the value to convert
* @return the converted int value
*/
public static int convertLongToInt(long l) {
if (l <= Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
} else if (l >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else {
return (int) l;
}
}
/**
* Get a cryptographically secure pseudo random long value.
*
* @return the random long value
*/
public static long secureRandomLong() {
return getSecureRandom().nextLong();
}
/**
* Get a number of pseudo random bytes.
*
* @param bytes the target array
*/
public static void randomBytes(byte[] bytes) {
ThreadLocalRandom.current().nextBytes(bytes);
}
/**
* Get a number of cryptographically secure pseudo random bytes.
*
* @param len the number of bytes
* @return the random bytes
*/
public static byte[] secureRandomBytes(int len) {
if (len <= 0) {
len = 1;
}
byte[] buff = new byte[len];
getSecureRandom().nextBytes(buff);
return buff;
}
/**
* Get a pseudo random int value between 0 (including and the given value
* (excluding). The value is not cryptographically secure.
*
* @param lowerThan the value returned will be lower than this value
* @return the random long value
*/
public static int randomInt(int lowerThan) {
return ThreadLocalRandom.current().nextInt(lowerThan);
}
/**
* Get a cryptographically secure pseudo random int value between 0
* (including and the given value (excluding).
*
* @param lowerThan the value returned will be lower than this value
* @return the random long value
*/
public static int secureRandomInt(int lowerThan) {
return getSecureRandom().nextInt(lowerThan);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/MergedResultSet.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.h2.tools.SimpleResultSet;
/**
* Merged result set. Used to combine several result sets into one. Merged
* result set will contain rows from all appended result sets. Result sets are
* not required to have the same lists of columns, but required to have
* compatible column definitions, for example, if one result set has a
* {@link java.sql.Types#VARCHAR} column {@code NAME} then another results sets
* that have {@code NAME} column should also define it with the same type.
*/
public final class MergedResultSet {
/**
* Metadata of a column.
*/
private static final class ColumnInfo {
final String name;
final int type;
final int precision;
final int scale;
/**
* Creates metadata.
*
* @param name
* name of the column
* @param type
* type of the column, see {@link java.sql.Types}
* @param precision
* precision of the column
* @param scale
* scale of the column
*/
ColumnInfo(String name, int type, int precision, int scale) {
this.name = name;
this.type = type;
this.precision = precision;
this.scale = scale;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ColumnInfo other = (ColumnInfo) obj;
return name.equals(other.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
private final ArrayList<Map<ColumnInfo, Object>> data = New.arrayList();
private final ArrayList<ColumnInfo> columns = New.arrayList();
/**
* Appends a result set.
*
* @param rs
* result set to append
* @throws SQLException
* on SQL exception
*/
public void add(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
if (cols == 0) {
return;
}
ColumnInfo[] info = new ColumnInfo[cols];
for (int i = 1; i <= cols; i++) {
ColumnInfo ci = new ColumnInfo(meta.getColumnName(i), meta.getColumnType(i), meta.getPrecision(i),
meta.getScale(i));
info[i - 1] = ci;
if (!columns.contains(ci)) {
columns.add(ci);
}
}
while (rs.next()) {
if (cols == 1) {
data.add(Collections.singletonMap(info[0], rs.getObject(1)));
} else {
HashMap<ColumnInfo, Object> map = new HashMap<>();
for (int i = 1; i <= cols; i++) {
ColumnInfo ci = info[i - 1];
map.put(ci, rs.getObject(i));
}
data.add(map);
}
}
}
/**
* Returns merged results set.
*
* @return result set with rows from all appended result sets
*/
public SimpleResultSet getResult() {
SimpleResultSet rs = new SimpleResultSet();
for (ColumnInfo ci : columns) {
rs.addColumn(ci.name, ci.type, ci.precision, ci.scale);
}
for (Map<ColumnInfo, Object> map : data) {
Object[] row = new Object[columns.size()];
for (Map.Entry<ColumnInfo, Object> entry : map.entrySet()) {
row[columns.indexOf(entry.getKey())] = entry.getValue();
}
rs.addRow(row);
}
return rs;
}
@Override
public String toString() {
return columns + ": " + data.size();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/NetUtils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.IOException;
import java.net.BindException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import org.h2.api.ErrorCode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.security.CipherFactory;
/**
* This utility class contains socket helper functions.
*/
public class NetUtils {
private static final int CACHE_MILLIS = 1000;
private static InetAddress cachedBindAddress;
private static String cachedLocalAddress;
private static long cachedLocalAddressTime;
private NetUtils() {
// utility class
}
/**
* Create a loopback socket (a socket that is connected to localhost) on
* this port.
*
* @param port the port
* @param ssl if SSL should be used
* @return the socket
*/
public static Socket createLoopbackSocket(int port, boolean ssl)
throws IOException {
String local = getLocalAddress();
try {
return createSocket(local, port, ssl);
} catch (IOException e) {
try {
return createSocket("localhost", port, ssl);
} catch (IOException e2) {
// throw the original exception
throw e;
}
}
}
/**
* Create a client socket that is connected to the given address and port.
*
* @param server to connect to (including an optional port)
* @param defaultPort the default port (if not specified in the server
* address)
* @param ssl if SSL should be used
* @return the socket
*/
public static Socket createSocket(String server, int defaultPort,
boolean ssl) throws IOException {
int port = defaultPort;
// IPv6: RFC 2732 format is '[a:b:c:d:e:f:g:h]' or
// '[a:b:c:d:e:f:g:h]:port'
// RFC 2396 format is 'a.b.c.d' or 'a.b.c.d:port' or 'hostname' or
// 'hostname:port'
int startIndex = server.startsWith("[") ? server.indexOf(']') : 0;
int idx = server.indexOf(':', startIndex);
if (idx >= 0) {
port = Integer.decode(server.substring(idx + 1));
server = server.substring(0, idx);
}
InetAddress address = InetAddress.getByName(server);
return createSocket(address, port, ssl);
}
/**
* Create a client socket that is connected to the given address and port.
*
* @param address the address to connect to
* @param port the port
* @param ssl if SSL should be used
* @return the socket
*/
public static Socket createSocket(InetAddress address, int port, boolean ssl)
throws IOException {
long start = System.nanoTime();
for (int i = 0;; i++) {
try {
if (ssl) {
return CipherFactory.createSocket(address, port);
}
Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, port),
SysProperties.SOCKET_CONNECT_TIMEOUT);
return socket;
} catch (IOException e) {
if (System.nanoTime() - start >=
TimeUnit.MILLISECONDS.toNanos(SysProperties.SOCKET_CONNECT_TIMEOUT)) {
// either it was a connect timeout,
// or list of different exceptions
throw e;
}
if (i >= SysProperties.SOCKET_CONNECT_RETRY) {
throw e;
}
// wait a bit and retry
try {
// sleep at most 256 ms
long sleep = Math.min(256, i * i);
Thread.sleep(sleep);
} catch (InterruptedException e2) {
// ignore
}
}
}
}
/**
* Create a server socket. The system property h2.bindAddress is used if
* set. If SSL is used and h2.enableAnonymousTLS is true, an attempt is
* made to modify the security property jdk.tls.legacyAlgorithms
* (in newer JVMs) to allow anonymous TLS.
* <p>
* This system change is effectively permanent for the lifetime of the JVM.
* @see CipherFactory#removeAnonFromLegacyAlgorithms()
*
* @param port the port to listen on
* @param ssl if SSL should be used
* @return the server socket
*/
public static ServerSocket createServerSocket(int port, boolean ssl) {
try {
return createServerSocketTry(port, ssl);
} catch (Exception e) {
// try again
return createServerSocketTry(port, ssl);
}
}
/**
* Get the bind address if the system property h2.bindAddress is set, or
* null if not.
*
* @return the bind address
*/
private static InetAddress getBindAddress() throws UnknownHostException {
String host = SysProperties.BIND_ADDRESS;
if (host == null || host.length() == 0) {
return null;
}
synchronized (NetUtils.class) {
if (cachedBindAddress == null) {
cachedBindAddress = InetAddress.getByName(host);
}
}
return cachedBindAddress;
}
private static ServerSocket createServerSocketTry(int port, boolean ssl) {
try {
InetAddress bindAddress = getBindAddress();
if (ssl) {
return CipherFactory.createServerSocket(port, bindAddress);
}
if (bindAddress == null) {
return new ServerSocket(port);
}
return new ServerSocket(port, 0, bindAddress);
} catch (BindException be) {
throw DbException.get(ErrorCode.EXCEPTION_OPENING_PORT_2,
be, "" + port, be.toString());
} catch (IOException e) {
throw DbException.convertIOException(e, "port: " + port + " ssl: " + ssl);
}
}
/**
* Check if a socket is connected to a local address.
*
* @param socket the socket
* @return true if it is
*/
public static boolean isLocalAddress(Socket socket)
throws UnknownHostException {
InetAddress test = socket.getInetAddress();
if (test.isLoopbackAddress()) {
return true;
}
InetAddress localhost = InetAddress.getLocalHost();
// localhost.getCanonicalHostName() is very very slow
String host = localhost.getHostAddress();
for (InetAddress addr : InetAddress.getAllByName(host)) {
if (test.equals(addr)) {
return true;
}
}
return false;
}
/**
* Close a server socket and ignore any exceptions.
*
* @param socket the socket
* @return null
*/
public static ServerSocket closeSilently(ServerSocket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// ignore
}
}
return null;
}
/**
* Get the local host address as a string.
* For performance, the result is cached for one second.
*
* @return the local host address
*/
public static synchronized String getLocalAddress() {
long now = System.nanoTime();
if (cachedLocalAddress != null) {
if (cachedLocalAddressTime + TimeUnit.MILLISECONDS.toNanos(CACHE_MILLIS) > now) {
return cachedLocalAddress;
}
}
InetAddress bind = null;
boolean useLocalhost = false;
try {
bind = getBindAddress();
if (bind == null) {
useLocalhost = true;
}
} catch (UnknownHostException e) {
// ignore
}
if (useLocalhost) {
try {
bind = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
throw DbException.convert(e);
}
}
String address;
if (bind == null) {
address = "localhost";
} else {
address = bind.getHostAddress();
if (bind instanceof Inet6Address) {
if (address.indexOf('%') >= 0) {
address = "localhost";
} else if (address.indexOf(':') >= 0 && !address.startsWith("[")) {
// adds'[' and ']' if required for
// Inet6Address that contain a ':'.
address = "[" + address + "]";
}
}
}
if (address.equals("127.0.0.1")) {
address = "localhost";
}
cachedLocalAddress = address;
cachedLocalAddressTime = now;
return address;
}
/**
* Get the host name of a local address, if available.
*
* @param localAddress the local address
* @return the host name, or another text if not available
*/
public static String getHostName(String localAddress) {
try {
InetAddress addr = InetAddress.getByName(localAddress);
return addr.getHostName();
} catch (Exception e) {
return "unknown";
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/New.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.ArrayList;
/**
* This class contains static methods to construct commonly used generic objects
* such as ArrayList.
*/
public class New {
/**
* Create a new ArrayList.
*
* @param <T> the type
* @return the object
*/
public static <T> ArrayList<T> arrayList() {
return new ArrayList<>(4);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/OsgiDataSourceFactory.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import org.h2.engine.Constants;
import org.h2.jdbcx.JdbcDataSource;
import org.osgi.framework.BundleContext;
import org.osgi.service.jdbc.DataSourceFactory;
/**
* This class implements the OSGi DataSourceFactory interface for the H2 JDBC
* driver. The following standard configuration properties are supported:
* {@link #JDBC_USER}, {@link #JDBC_PASSWORD}, {@link #JDBC_DESCRIPTION},
* {@link #JDBC_DATASOURCE_NAME}, {@link #JDBC_NETWORK_PROTOCOL},
* {@link #JDBC_URL}, {@link #JDBC_SERVER_NAME}, {@link #JDBC_PORT_NUMBER}. The
* following standard configuration properties are not supported:
* {@link #JDBC_ROLE_NAME}, {@link #JDBC_DATABASE_NAME},
* {@link #JDBC_INITIAL_POOL_SIZE}, {@link #JDBC_MAX_POOL_SIZE},
* {@link #JDBC_MIN_POOL_SIZE}, {@link #JDBC_MAX_IDLE_TIME},
* {@link #JDBC_MAX_STATEMENTS}, {@link #JDBC_PROPERTY_CYCLE}. Any other
* property will be treated as a H2 specific option. If the {@link #JDBC_URL}
* property is passed to any of the DataSource factories, the following
* properties will be ignored: {@link #JDBC_DATASOURCE_NAME},
* {@link #JDBC_NETWORK_PROTOCOL}, {@link #JDBC_SERVER_NAME},
* {@link #JDBC_PORT_NUMBER}.
*
* @author Per Otterstrom
*/
public class OsgiDataSourceFactory implements DataSourceFactory {
private final org.h2.Driver driver;
public OsgiDataSourceFactory(org.h2.Driver driver) {
this.driver = driver;
}
/**
* Creates a basic data source.
*
* @param properties the properties for the data source.
* @throws SQLException if unsupported properties are supplied, or if data
* source can not be created.
* @return a new data source.
*/
@Override
public DataSource createDataSource(Properties properties)
throws SQLException {
// Make copy of properties
Properties propertiesCopy = new Properties();
if (properties != null) {
propertiesCopy.putAll(properties);
}
// Verify that no unsupported standard options are used
rejectUnsupportedOptions(propertiesCopy);
// Standard pool properties in OSGi not applicable here
rejectPoolingOptions(propertiesCopy);
JdbcDataSource dataSource = new JdbcDataSource();
setupH2DataSource(dataSource, propertiesCopy);
return dataSource;
}
/**
* Creates a pooled data source.
*
* @param properties the properties for the data source.
* @throws SQLException if unsupported properties are supplied, or if data
* source can not be created.
* @return a new data source.
*/
@Override
public ConnectionPoolDataSource createConnectionPoolDataSource(
Properties properties) throws SQLException {
// Make copy of properties
Properties propertiesCopy = new Properties();
if (properties != null) {
propertiesCopy.putAll(properties);
}
// Verify that no unsupported standard options are used
rejectUnsupportedOptions(propertiesCopy);
// The integrated connection pool is H2 is not configurable
rejectPoolingOptions(propertiesCopy);
JdbcDataSource dataSource = new JdbcDataSource();
setupH2DataSource(dataSource, propertiesCopy);
return dataSource;
}
/**
* Creates a pooled XA data source.
*
* @param properties the properties for the data source.
* @throws SQLException if unsupported properties are supplied, or if data
* source can not be created.
* @return a new data source.
*/
@Override
public XADataSource createXADataSource(Properties properties)
throws SQLException {
// Make copy of properties
Properties propertiesCopy = new Properties();
if (properties != null) {
propertiesCopy.putAll(properties);
}
// Verify that no unsupported standard options are used
rejectUnsupportedOptions(propertiesCopy);
// The integrated connection pool is H2 is not configurable
rejectPoolingOptions(propertiesCopy);
JdbcDataSource dataSource = new JdbcDataSource();
setupH2DataSource(dataSource, propertiesCopy);
return dataSource;
}
/**
* Returns a driver. The H2 driver does not support any properties.
*
* @param properties must be null or empty list.
* @throws SQLException if any property is supplied.
* @return a driver.
*/
@Override
public java.sql.Driver createDriver(Properties properties)
throws SQLException {
if (properties != null && !properties.isEmpty()) {
// No properties supported
throw new SQLException();
}
return driver;
}
/**
* Checker method that will throw if any unsupported standard OSGi options
* is present.
*
* @param p the properties to check
* @throws SQLFeatureNotSupportedException if unsupported properties are
* present
*/
private static void rejectUnsupportedOptions(Properties p)
throws SQLFeatureNotSupportedException {
// Unsupported standard properties in OSGi
if (p.containsKey(DataSourceFactory.JDBC_ROLE_NAME)) {
throw new SQLFeatureNotSupportedException("The " +
DataSourceFactory.JDBC_ROLE_NAME +
" property is not supported by H2");
}
if (p.containsKey(DataSourceFactory.JDBC_DATASOURCE_NAME)) {
throw new SQLFeatureNotSupportedException("The " +
DataSourceFactory.JDBC_DATASOURCE_NAME +
" property is not supported by H2");
}
}
/**
* Applies common OSGi properties to a H2 data source. Non standard
* properties will be applied as H2 options.
*
* @param dataSource the data source to configure
* @param p the properties to apply to the data source
*/
private static void setupH2DataSource(JdbcDataSource dataSource,
Properties p) {
// Setting user and password
if (p.containsKey(DataSourceFactory.JDBC_USER)) {
dataSource.setUser((String) p.remove(DataSourceFactory.JDBC_USER));
}
if (p.containsKey(DataSourceFactory.JDBC_PASSWORD)) {
dataSource.setPassword((String) p
.remove(DataSourceFactory.JDBC_PASSWORD));
}
// Setting description
if (p.containsKey(DataSourceFactory.JDBC_DESCRIPTION)) {
dataSource.setDescription((String) p
.remove(DataSourceFactory.JDBC_DESCRIPTION));
}
// Setting URL
StringBuilder connectionUrl = new StringBuilder();
if (p.containsKey(DataSourceFactory.JDBC_URL)) {
// Use URL if specified
connectionUrl.append(p.remove(DataSourceFactory.JDBC_URL));
// Remove individual properties
p.remove(DataSourceFactory.JDBC_NETWORK_PROTOCOL);
p.remove(DataSourceFactory.JDBC_SERVER_NAME);
p.remove(DataSourceFactory.JDBC_PORT_NUMBER);
p.remove(DataSourceFactory.JDBC_DATABASE_NAME);
} else {
// Creating URL from individual properties
connectionUrl.append(Constants.START_URL);
// Set network protocol (tcp/ssl) or DB type (mem/file)
String protocol = "";
if (p.containsKey(DataSourceFactory.JDBC_NETWORK_PROTOCOL)) {
protocol = (String) p.remove(DataSourceFactory.JDBC_NETWORK_PROTOCOL);
connectionUrl.append(protocol).append(":");
}
// Host name and/or port
if (p.containsKey(DataSourceFactory.JDBC_SERVER_NAME)) {
connectionUrl.append("//").append(
p.remove(DataSourceFactory.JDBC_SERVER_NAME));
if (p.containsKey(DataSourceFactory.JDBC_PORT_NUMBER)) {
connectionUrl.append(":").append(
p.remove(DataSourceFactory.JDBC_PORT_NUMBER));
}
connectionUrl.append("/");
} else if (p.containsKey(
DataSourceFactory.JDBC_PORT_NUMBER)) {
// Assume local host if only port was set
connectionUrl
.append("//localhost:")
.append(p.remove(DataSourceFactory.JDBC_PORT_NUMBER))
.append("/");
} else if (protocol.equals("tcp") || protocol.equals("ssl")) {
// Assume local host if network protocol is set, but no host or
// port is set
connectionUrl.append("//localhost/");
}
// DB path and name
if (p.containsKey(DataSourceFactory.JDBC_DATABASE_NAME)) {
connectionUrl.append(
p.remove(DataSourceFactory.JDBC_DATABASE_NAME));
}
}
// Add remaining properties as options
for (Object option : p.keySet()) {
connectionUrl.append(";").append(option).append("=")
.append(p.get(option));
}
if (connectionUrl.length() > Constants.START_URL.length()) {
dataSource.setURL(connectionUrl.toString());
}
}
/**
* Checker method that will throw if any pooling related standard OSGi
* options are present.
*
* @param p the properties to check
* @throws SQLFeatureNotSupportedException if unsupported properties are
* present
*/
private static void rejectPoolingOptions(Properties p)
throws SQLFeatureNotSupportedException {
if (p.containsKey(DataSourceFactory.JDBC_INITIAL_POOL_SIZE) ||
p.containsKey(DataSourceFactory.JDBC_MAX_IDLE_TIME) ||
p.containsKey(DataSourceFactory.JDBC_MAX_POOL_SIZE) ||
p.containsKey(DataSourceFactory.JDBC_MAX_STATEMENTS) ||
p.containsKey(DataSourceFactory.JDBC_MIN_POOL_SIZE) ||
p.containsKey(DataSourceFactory.JDBC_PROPERTY_CYCLE)) {
throw new SQLFeatureNotSupportedException(
"Pooling properties are not supported by H2");
}
}
/**
* Register the H2 JDBC driver service.
*
* @param bundleContext the bundle context
* @param driver the driver
*/
static void registerService(BundleContext bundleContext,
org.h2.Driver driver) {
Properties properties = new Properties();
properties.put(
DataSourceFactory.OSGI_JDBC_DRIVER_CLASS,
org.h2.Driver.class.getName());
properties.put(
DataSourceFactory.OSGI_JDBC_DRIVER_NAME,
"H2 JDBC Driver");
properties.put(
DataSourceFactory.OSGI_JDBC_DRIVER_VERSION,
Constants.getFullVersion());
bundleContext.registerService(
DataSourceFactory.class.getName(),
new OsgiDataSourceFactory(driver), properties);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ParserUtil.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
public class ParserUtil {
/**
* A keyword.
*/
public static final int KEYWORD = 1;
/**
* An identifier (table name, column name,...).
*/
public static final int IDENTIFIER = 2;
/**
* The token "null".
*/
public static final int NULL = 3;
/**
* The token "true".
*/
public static final int TRUE = 4;
/**
* The token "false".
*/
public static final int FALSE = 5;
/**
* The token "rownum".
*/
public static final int ROWNUM = 6;
private ParserUtil() {
// utility class
}
/**
* Checks if this string is a SQL keyword.
*
* @param s the token to check
* @return true if it is a keyword
*/
public static boolean isKeyword(String s) {
if (s == null || s.length() == 0) {
return false;
}
return getSaveTokenType(s, false) != IDENTIFIER;
}
/**
* Is this a simple identifier (in the JDBC specification sense).
*
* @param s identifier to check
* @param functionsAsKeywords treat system functions as keywords
* @return is specified identifier may be used without quotes
* @throws NullPointerException if s is {@code null}
*/
public static boolean isSimpleIdentifier(String s, boolean functionsAsKeywords) {
if (s.length() == 0) {
return false;
}
char c = s.charAt(0);
// lowercase a-z is quoted as well
if ((!Character.isLetter(c) && c != '_') || Character.isLowerCase(c)) {
return false;
}
for (int i = 1, length = s.length(); i < length; i++) {
c = s.charAt(i);
if ((!Character.isLetterOrDigit(c) && c != '_') ||
Character.isLowerCase(c)) {
return false;
}
}
return getSaveTokenType(s, functionsAsKeywords) == IDENTIFIER;
}
/**
* Get the token type.
*
* @param s the token
* @param functionsAsKeywords whether "current data / time" functions are keywords
* @return the token type
*/
public static int getSaveTokenType(String s, boolean functionsAsKeywords) {
switch (s.charAt(0)) {
case 'A':
return getKeywordOrIdentifier(s, "ALL", KEYWORD);
case 'C':
if ("CHECK".equals(s)) {
return KEYWORD;
} else if ("CONSTRAINT".equals(s)) {
return KEYWORD;
} else if ("CROSS".equals(s)) {
return KEYWORD;
}
if (functionsAsKeywords) {
if ("CURRENT_DATE".equals(s) || "CURRENT_TIME".equals(s) || "CURRENT_TIMESTAMP".equals(s)) {
return KEYWORD;
}
}
return IDENTIFIER;
case 'D':
return getKeywordOrIdentifier(s, "DISTINCT", KEYWORD);
case 'E':
if ("EXCEPT".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "EXISTS", KEYWORD);
case 'F':
if ("FETCH".equals(s)) {
return KEYWORD;
} else if ("FROM".equals(s)) {
return KEYWORD;
} else if ("FOR".equals(s)) {
return KEYWORD;
} else if ("FOREIGN".equals(s)) {
return KEYWORD;
} else if ("FULL".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "FALSE", FALSE);
case 'G':
return getKeywordOrIdentifier(s, "GROUP", KEYWORD);
case 'H':
return getKeywordOrIdentifier(s, "HAVING", KEYWORD);
case 'I':
if ("INNER".equals(s)) {
return KEYWORD;
} else if ("INTERSECT".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "IS", KEYWORD);
case 'J':
return getKeywordOrIdentifier(s, "JOIN", KEYWORD);
case 'L':
if ("LIMIT".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "LIKE", KEYWORD);
case 'M':
return getKeywordOrIdentifier(s, "MINUS", KEYWORD);
case 'N':
if ("NOT".equals(s)) {
return KEYWORD;
} else if ("NATURAL".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "NULL", NULL);
case 'O':
if ("OFFSET".equals(s)) {
return KEYWORD;
} else if ("ON".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "ORDER", KEYWORD);
case 'P':
return getKeywordOrIdentifier(s, "PRIMARY", KEYWORD);
case 'R':
return getKeywordOrIdentifier(s, "ROWNUM", ROWNUM);
case 'S':
if ("SELECT".equals(s)) {
return KEYWORD;
}
if (functionsAsKeywords) {
if ("SYSDATE".equals(s) || "SYSTIME".equals(s) || "SYSTIMESTAMP".equals(s)) {
return KEYWORD;
}
}
return IDENTIFIER;
case 'T':
if ("TRUE".equals(s)) {
return TRUE;
}
if (functionsAsKeywords) {
if ("TODAY".equals(s)) {
return KEYWORD;
}
}
return IDENTIFIER;
case 'U':
if ("UNIQUE".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "UNION", KEYWORD);
case 'W':
if ("WITH".equals(s)) {
return KEYWORD;
}
return getKeywordOrIdentifier(s, "WHERE", KEYWORD);
default:
return IDENTIFIER;
}
}
private static int getKeywordOrIdentifier(String s1, String s2,
int keywordType) {
if (s1.equals(s2)) {
return keywordType;
}
return IDENTIFIER;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/Permutations.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*
* According to a mail from Alan Tucker to Chris H Miller from IBM,
* the algorithm is in the public domain:
*
* Date: 2010-07-15 15:57
* Subject: Re: Applied Combinatorics Code
*
* Chris,
* The combinatorics algorithms in my textbook are all not under patent
* or copyright. They are as much in the public domain as the solution to any
* common question in an undergraduate mathematics course, e.g., in my
* combinatorics course, the solution to the problem of how many arrangements
* there are of the letters in the word MATHEMATICS. I appreciate your due
* diligence.
* -Alan
*/
package org.h2.util;
import org.h2.message.DbException;
/**
* A class to iterate over all permutations of an array.
* The algorithm is from Applied Combinatorics, by Alan Tucker as implemented in
* http://www.koders.com/java/fidD3445CD11B1DC687F6B8911075E7F01E23171553.aspx
*
* @param <T> the element type
*/
public class Permutations<T> {
private final T[] in;
private final T[] out;
private final int n, m;
private final int[] index;
private boolean hasNext = true;
private Permutations(T[] in, T[] out, int m) {
this.n = in.length;
this.m = m;
if (n < m || m < 0) {
DbException.throwInternalError("n < m or m < 0");
}
this.in = in;
this.out = out;
index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
// The elements from m to n are always kept ascending right to left.
// This keeps the dip in the interesting region.
reverseAfter(m - 1);
}
/**
* Create a new permutations object.
*
* @param <T> the type
* @param in the source array
* @param out the target array
* @return the generated permutations object
*/
public static <T> Permutations<T> create(T[] in, T[] out) {
return new Permutations<>(in, out, in.length);
}
/**
* Create a new permutations object.
*
* @param <T> the type
* @param in the source array
* @param out the target array
* @param m the number of output elements to generate
* @return the generated permutations object
*/
public static <T> Permutations<T> create(T[] in, T[] out, int m) {
return new Permutations<>(in, out, m);
}
/**
* Move the index forward a notch. The algorithm first finds the rightmost
* index that is less than its neighbor to the right. This is the dip point.
* The algorithm next finds the least element to the right of the dip that
* is greater than the dip. That element is switched with the dip. Finally,
* the list of elements to the right of the dip is reversed.
* For example, in a permutation of 5 items, the index may be {1, 2, 4, 3,
* 0}. The dip is 2 the rightmost element less than its neighbor on its
* right. The least element to the right of 2 that is greater than 2 is 3.
* These elements are swapped, yielding {1, 3, 4, 2, 0}, and the list right
* of the dip point is reversed, yielding {1, 3, 0, 2, 4}.
*/
private void moveIndex() {
// find the index of the first element that dips
int i = rightmostDip();
if (i < 0) {
hasNext = false;
return;
}
// find the least greater element to the right of the dip
int leastToRightIndex = i + 1;
for (int j = i + 2; j < n; j++) {
if (index[j] < index[leastToRightIndex] && index[j] > index[i]) {
leastToRightIndex = j;
}
}
// switch dip element with least greater element to its right
int t = index[i];
index[i] = index[leastToRightIndex];
index[leastToRightIndex] = t;
if (m - 1 > i) {
// reverse the elements to the right of the dip
reverseAfter(i);
// reverse the elements to the right of m - 1
reverseAfter(m - 1);
}
}
/**
* Get the index of the first element from the right that is less
* than its neighbor on the right.
*
* @return the index or -1 if non is found
*/
private int rightmostDip() {
for (int i = n - 2; i >= 0; i--) {
if (index[i] < index[i + 1]) {
return i;
}
}
return -1;
}
/**
* Reverse the elements to the right of the specified index.
*
* @param i the index
*/
private void reverseAfter(int i) {
int start = i + 1;
int end = n - 1;
while (start < end) {
int t = index[start];
index[start] = index[end];
index[end] = t;
start++;
end--;
}
}
/**
* Go to the next lineup, and if available, fill the target array.
*
* @return if a new lineup is available
*/
public boolean next() {
if (!hasNext) {
return false;
}
for (int i = 0; i < m; i++) {
out[i] = in[index[i]];
}
moveIndex();
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/Profiler.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.instrument.Instrumentation;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* A simple CPU profiling tool similar to java -Xrunhprof. It can be used
* in-process (to profile the current application) or as a standalone program
* (to profile a different process, or files containing full thread dumps).
*/
public class Profiler implements Runnable {
private static Instrumentation instrumentation;
private static final String LINE_SEPARATOR =
System.getProperty("line.separator", "\n");
private static final int MAX_ELEMENTS = 1000;
public int interval = 2;
public int depth = 48;
public boolean paused;
public boolean sumClasses;
public boolean sumMethods;
private int pid;
private final String[] ignoreLines = (
"java," +
"sun," +
"com.sun.," +
"com.google.common.," +
"com.mongodb.," +
"org.bson.,"
).split(",");
private final String[] ignorePackages = (
"java," +
"sun," +
"com.sun.," +
"com.google.common.," +
"com.mongodb.," +
"org.bson"
).split(",");
private final String[] ignoreThreads = (
"java.lang.Object.wait," +
"java.lang.Thread.dumpThreads," +
"java.lang.Thread.getThreads," +
"java.lang.Thread.sleep," +
"java.lang.UNIXProcess.waitForProcessExit," +
"java.net.PlainDatagramSocketImpl.receive0," +
"java.net.PlainSocketImpl.accept," +
"java.net.PlainSocketImpl.socketAccept," +
"java.net.SocketInputStream.socketRead," +
"java.net.SocketOutputStream.socketWrite," +
"org.eclipse.jetty.io.nio.SelectorManager$SelectSet.doSelect," +
"sun.awt.windows.WToolkit.eventLoop," +
"sun.misc.Unsafe.park," +
"sun.nio.ch.EPollArrayWrapper.epollWait," +
"sun.nio.ch.KQueueArrayWrapper.kevent0," +
"sun.nio.ch.ServerSocketChannelImpl.accept," +
"dalvik.system.VMStack.getThreadStackTrace," +
"dalvik.system.NativeStart.run"
).split(",");
private volatile boolean stop;
private final HashMap<String, Integer> counts =
new HashMap<>();
/**
* The summary (usually one entry per package, unless sumClasses is enabled,
* in which case it's one entry per class).
*/
private final HashMap<String, Integer> summary =
new HashMap<>();
private int minCount = 1;
private int total;
private Thread thread;
private long start;
private long time;
private int threadDumps;
/**
* This method is called when the agent is installed.
*
* @param agentArgs the agent arguments
* @param inst the instrumentation object
*/
public static void premain(@SuppressWarnings("unused") String agentArgs, Instrumentation inst) {
instrumentation = inst;
}
/**
* Get the instrumentation object if started as an agent.
*
* @return the instrumentation, or null
*/
public static Instrumentation getInstrumentation() {
return instrumentation;
}
/**
* Run the command line version of the profiler. The JDK (jps and jstack)
* need to be in the path.
*
* @param args the process id of the process - if not set the java processes
* are listed
*/
public static void main(String... args) {
new Profiler().run(args);
}
private void run(String... args) {
if (args.length == 0) {
System.out.println("Show profiling data");
System.out.println("Usage: java " + getClass().getName() +
" <pid> | <stackTraceFileNames>");
System.out.println("Processes:");
String processes = exec("jps", "-l");
System.out.println(processes);
return;
}
start = System.nanoTime();
if (args[0].matches("\\d+")) {
pid = Integer.parseInt(args[0]);
long last = 0;
while (true) {
tick();
long t = System.nanoTime();
if (t - last > TimeUnit.SECONDS.toNanos(5)) {
time = System.nanoTime() - start;
System.out.println(getTopTraces(3));
last = t;
}
}
}
try {
for (String arg : args) {
if (arg.startsWith("-")) {
if ("-classes".equals(arg)) {
sumClasses = true;
} else if ("-methods".equals(arg)) {
sumMethods = true;
} else if ("-packages".equals(arg)) {
sumClasses = false;
sumMethods = false;
} else {
throw new IllegalArgumentException(arg);
}
continue;
}
try (Reader reader = new InputStreamReader(new FileInputStream(arg), "CP1252")) {
LineNumberReader r = new LineNumberReader(reader);
while (true) {
String line = r.readLine();
if (line == null) {
break;
} else if (line.startsWith("Full thread dump")) {
threadDumps++;
}
}
}
try (Reader reader = new InputStreamReader(new FileInputStream(arg), "CP1252")) {
LineNumberReader r = new LineNumberReader(reader);
processList(readStackTrace(r));
}
}
System.out.println(getTopTraces(5));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static List<Object[]> getRunnableStackTraces() {
ArrayList<Object[]> list = new ArrayList<>();
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
Thread t = entry.getKey();
if (t.getState() != Thread.State.RUNNABLE) {
continue;
}
StackTraceElement[] dump = entry.getValue();
if (dump == null || dump.length == 0) {
continue;
}
list.add(dump);
}
return list;
}
private static List<Object[]> readRunnableStackTraces(int pid) {
try {
String jstack = exec("jstack", "" + pid);
LineNumberReader r = new LineNumberReader(
new StringReader(jstack));
return readStackTrace(r);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static List<Object[]> readStackTrace(LineNumberReader r)
throws IOException {
ArrayList<Object[]> list = new ArrayList<>();
while (true) {
String line = r.readLine();
if (line == null) {
break;
}
if (!line.startsWith("\"")) {
// not a thread
continue;
}
line = r.readLine();
if (line == null) {
break;
}
line = line.trim();
if (!line.startsWith("java.lang.Thread.State: RUNNABLE")) {
continue;
}
ArrayList<String> stack = new ArrayList<>();
while (true) {
line = r.readLine();
if (line == null) {
break;
}
line = line.trim();
if (line.startsWith("- ")) {
continue;
}
if (!line.startsWith("at ")) {
break;
}
line = line.substring(3).trim();
stack.add(line);
}
if (!stack.isEmpty()) {
String[] s = stack.toArray(new String[0]);
list.add(s);
}
}
return list;
}
private static String exec(String... args) {
ByteArrayOutputStream err = new ByteArrayOutputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
Process p = Runtime.getRuntime().exec(args);
copyInThread(p.getInputStream(), out);
copyInThread(p.getErrorStream(), err);
p.waitFor();
String e = new String(err.toByteArray(), StandardCharsets.UTF_8);
if (e.length() > 0) {
throw new RuntimeException(e);
}
return new String(out.toByteArray(), StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void copyInThread(final InputStream in,
final OutputStream out) {
new Thread("Profiler stream copy") {
@Override
public void run() {
byte[] buffer = new byte[4096];
try {
while (true) {
int len = in.read(buffer, 0, buffer.length);
if (len < 0) {
break;
}
out.write(buffer, 0, len);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
}
/**
* Start collecting profiling data.
*
* @return this
*/
public Profiler startCollecting() {
thread = new Thread(this, "Profiler");
thread.setDaemon(true);
thread.start();
return this;
}
/**
* Stop collecting.
*
* @return this
*/
public Profiler stopCollecting() {
stop = true;
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
thread = null;
}
return this;
}
@Override
public void run() {
start = System.nanoTime();
while (!stop) {
try {
tick();
} catch (Throwable t) {
break;
}
}
time = System.nanoTime() - start;
}
private void tick() {
if (interval > 0) {
if (paused) {
return;
}
try {
Thread.sleep(interval);
} catch (Exception e) {
// ignore
}
}
List<Object[]> list;
if (pid != 0) {
list = readRunnableStackTraces(pid);
} else {
list = getRunnableStackTraces();
}
threadDumps++;
processList(list);
}
private void processList(List<Object[]> list) {
for (Object[] dump : list) {
if (startsWithAny(dump[0].toString(), ignoreThreads)) {
continue;
}
StringBuilder buff = new StringBuilder();
// simple recursive calls are ignored
String last = null;
boolean packageCounts = false;
for (int j = 0, i = 0; i < dump.length && j < depth; i++) {
String el = dump[i].toString();
if (!el.equals(last) && !startsWithAny(el, ignoreLines)) {
last = el;
buff.append("at ").append(el).append(LINE_SEPARATOR);
if (!packageCounts && !startsWithAny(el, ignorePackages)) {
packageCounts = true;
int index = 0;
for (; index < el.length(); index++) {
char c = el.charAt(index);
if (c == '(' || Character.isUpperCase(c)) {
break;
}
}
if (index > 0 && el.charAt(index - 1) == '.') {
index--;
}
if (sumClasses) {
int m = el.indexOf('.', index + 1);
index = m >= 0 ? m : index;
}
if (sumMethods) {
int m = el.indexOf('(', index + 1);
index = m >= 0 ? m : index;
}
String groupName = el.substring(0, index);
increment(summary, groupName, 0);
}
j++;
}
}
if (buff.length() > 0) {
minCount = increment(counts, buff.toString().trim(), minCount);
total++;
}
}
}
private static boolean startsWithAny(String s, String[] prefixes) {
for (String p : prefixes) {
if (p.length() > 0 && s.startsWith(p)) {
return true;
}
}
return false;
}
private static int increment(HashMap<String, Integer> map, String trace,
int minCount) {
Integer oldCount = map.get(trace);
if (oldCount == null) {
map.put(trace, 1);
} else {
map.put(trace, oldCount + 1);
}
while (map.size() > MAX_ELEMENTS) {
for (Iterator<Map.Entry<String, Integer>> ei =
map.entrySet().iterator(); ei.hasNext();) {
Map.Entry<String, Integer> e = ei.next();
if (e.getValue() <= minCount) {
ei.remove();
}
}
if (map.size() > MAX_ELEMENTS) {
minCount++;
}
}
return minCount;
}
/**
* Get the top stack traces.
*
* @param count the maximum number of stack traces
* @return the stack traces.
*/
public String getTop(int count) {
stopCollecting();
return getTopTraces(count);
}
private String getTopTraces(int count) {
StringBuilder buff = new StringBuilder();
buff.append("Profiler: top ").append(count).append(" stack trace(s) of ");
if (time > 0) {
buff.append(" of ").append(TimeUnit.NANOSECONDS.toMillis(time)).append(" ms");
}
if (threadDumps > 0) {
buff.append(" of ").append(threadDumps).append(" thread dumps");
}
buff.append(":").append(LINE_SEPARATOR);
if (counts.size() == 0) {
buff.append("(none)").append(LINE_SEPARATOR);
}
HashMap<String, Integer> copy = new HashMap<>(counts);
appendTop(buff, copy, count, total, false);
buff.append("summary:").append(LINE_SEPARATOR);
copy = new HashMap<>(summary);
appendTop(buff, copy, count, total, true);
buff.append('.');
return buff.toString();
}
private static void appendTop(StringBuilder buff,
HashMap<String, Integer> map, int count, int total, boolean table) {
for (int x = 0, min = 0;;) {
int highest = 0;
Map.Entry<String, Integer> best = null;
for (Map.Entry<String, Integer> el : map.entrySet()) {
if (el.getValue() > highest) {
best = el;
highest = el.getValue();
}
}
if (best == null) {
break;
}
map.remove(best.getKey());
if (++x >= count) {
if (best.getValue() < min) {
break;
}
min = best.getValue();
}
int c = best.getValue();
int percent = 100 * c / Math.max(total, 1);
if (table) {
if (percent > 1) {
buff.append(percent).
append("%: ").append(best.getKey()).
append(LINE_SEPARATOR);
}
} else {
buff.append(c).append('/').append(total).append(" (").
append(percent).
append("%):").append(LINE_SEPARATOR).
append(best.getKey()).
append(LINE_SEPARATOR);
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ScriptReader.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import org.h2.engine.Constants;
import org.h2.message.DbException;
/**
* This class can split SQL scripts to single SQL statements.
* Each SQL statement ends with the character ';', however it is ignored
* in comments and quotes.
*/
public class ScriptReader implements Closeable {
private final Reader reader;
private char[] buffer;
/**
* The position in the buffer of the next char to be read
*/
private int bufferPos;
/**
* The position in the buffer of the statement start
*/
private int bufferStart = -1;
/**
* The position in the buffer of the last available char
*/
private int bufferEnd;
/**
* True if we have read past the end of file
*/
private boolean endOfFile;
/**
* True if we are inside a comment
*/
private boolean insideRemark;
/**
* Only valid if insideRemark is true. True if we are inside a block
* comment, false if we are inside a line comment
*/
private boolean blockRemark;
/**
* True if comments should be skipped completely by this reader.
*/
private boolean skipRemarks;
/**
* The position in buffer of start of comment
*/
private int remarkStart;
/**
* Create a new SQL script reader from the given reader
*
* @param reader the reader
*/
public ScriptReader(Reader reader) {
this.reader = reader;
buffer = new char[Constants.IO_BUFFER_SIZE * 2];
}
/**
* Close the underlying reader.
*/
@Override
public void close() {
try {
reader.close();
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
/**
* Read a statement from the reader. This method returns null if the end has
* been reached.
*
* @return the SQL statement or null
*/
public String readStatement() {
if (endOfFile) {
return null;
}
try {
return readStatementLoop();
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
private String readStatementLoop() throws IOException {
bufferStart = bufferPos;
int c = read();
while (true) {
if (c < 0) {
endOfFile = true;
if (bufferPos - 1 == bufferStart) {
return null;
}
break;
} else if (c == ';') {
break;
}
switch (c) {
case '$': {
c = read();
if (c == '$' && (bufferPos - bufferStart < 3 || buffer[bufferPos - 3] <= ' ')) {
// dollar quoted string
while (true) {
c = read();
if (c < 0) {
break;
}
if (c == '$') {
c = read();
if (c < 0) {
break;
}
if (c == '$') {
break;
}
}
}
c = read();
}
break;
}
case '\'':
while (true) {
c = read();
if (c < 0) {
break;
}
if (c == '\'') {
break;
}
}
c = read();
break;
case '"':
while (true) {
c = read();
if (c < 0) {
break;
}
if (c == '\"') {
break;
}
}
c = read();
break;
case '/': {
c = read();
if (c == '*') {
// block comment
startRemark(true);
while (true) {
c = read();
if (c < 0) {
break;
}
if (c == '*') {
c = read();
if (c < 0) {
clearRemark();
break;
}
if (c == '/') {
endRemark();
break;
}
}
}
c = read();
} else if (c == '/') {
// single line comment
startRemark(false);
while (true) {
c = read();
if (c < 0) {
clearRemark();
break;
}
if (c == '\r' || c == '\n') {
endRemark();
break;
}
}
c = read();
}
break;
}
case '-': {
c = read();
if (c == '-') {
// single line comment
startRemark(false);
while (true) {
c = read();
if (c < 0) {
clearRemark();
break;
}
if (c == '\r' || c == '\n') {
endRemark();
break;
}
}
c = read();
}
break;
}
default: {
c = read();
}
}
}
return new String(buffer, bufferStart, bufferPos - 1 - bufferStart);
}
private void startRemark(boolean block) {
blockRemark = block;
remarkStart = bufferPos - 2;
insideRemark = true;
}
private void endRemark() {
clearRemark();
insideRemark = false;
}
private void clearRemark() {
if (skipRemarks) {
Arrays.fill(buffer, remarkStart, bufferPos, ' ');
}
}
private int read() throws IOException {
if (bufferPos >= bufferEnd) {
return readBuffer();
}
return buffer[bufferPos++];
}
private int readBuffer() throws IOException {
if (endOfFile) {
return -1;
}
int keep = bufferPos - bufferStart;
if (keep > 0) {
char[] src = buffer;
if (keep + Constants.IO_BUFFER_SIZE > src.length) {
// protect against NegativeArraySizeException
if (src.length >= Integer.MAX_VALUE / 2) {
throw new IOException("Error in parsing script, " +
"statement size exceeds 1G, " +
"first 80 characters of statement looks like: " +
new String(buffer, bufferStart, 80));
}
buffer = new char[src.length * 2];
}
System.arraycopy(src, bufferStart, buffer, 0, keep);
}
remarkStart -= bufferStart;
bufferStart = 0;
bufferPos = keep;
int len = reader.read(buffer, keep, Constants.IO_BUFFER_SIZE);
if (len == -1) {
// ensure bufferPos > bufferEnd
bufferEnd = -1024;
endOfFile = true;
// ensure the right number of characters are read
// in case the input buffer is still used
bufferPos++;
return -1;
}
bufferEnd = keep + len;
return buffer[bufferPos++];
}
/**
* Check if this is the last statement, and if the single line or block
* comment is not finished yet.
*
* @return true if the current position is inside a remark
*/
public boolean isInsideRemark() {
return insideRemark;
}
/**
* If currently inside a remark, this method tells if it is a block comment
* (true) or single line comment (false)
*
* @return true if inside a block comment
*/
public boolean isBlockRemark() {
return blockRemark;
}
/**
* If comments should be skipped completely by this reader.
*
* @param skipRemarks true if comments should be skipped
*/
public void setSkipRemarks(boolean skipRemarks) {
this.skipRemarks = skipRemarks;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/SmallLRUCache.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* This class implements a small LRU object cache.
*
* @param <K> the key
* @param <V> the value
*/
public class SmallLRUCache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private int size;
private SmallLRUCache(int size) {
super(size, (float) 0.75, true);
this.size = size;
}
/**
* Create a new object with all elements of the given collection.
*
* @param <K> the key type
* @param <V> the value type
* @param size the number of elements
* @return the object
*/
public static <K, V> SmallLRUCache<K, V> newInstance(int size) {
return new SmallLRUCache<>(size);
}
public void setMaxSize(int size) {
this.size = size;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/SmallMap.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.HashMap;
import java.util.Iterator;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* A simple hash table with an optimization for the last recently used object.
*/
public class SmallMap {
private final HashMap<Integer, Object> map = new HashMap<>();
private Object cache;
private int cacheId;
private int lastId;
private final int maxElements;
/**
* Create a map with the given maximum number of entries.
*
* @param maxElements the maximum number of entries
*/
public SmallMap(int maxElements) {
this.maxElements = maxElements;
}
/**
* Add an object to the map. If the size of the map is larger than twice the
* maximum size, objects with a low id are removed.
*
* @param id the object id
* @param o the object
* @return the id
*/
public int addObject(int id, Object o) {
if (map.size() > maxElements * 2) {
Iterator<Integer> it = map.keySet().iterator();
while (it.hasNext()) {
Integer k = it.next();
if (k.intValue() + maxElements < lastId) {
it.remove();
}
}
}
if (id > lastId) {
lastId = id;
}
map.put(id, o);
cacheId = id;
cache = o;
return id;
}
/**
* Remove an object from the map.
*
* @param id the id of the object to remove
*/
public void freeObject(int id) {
if (cacheId == id) {
cacheId = -1;
cache = null;
}
map.remove(id);
}
/**
* Get an object from the map if it is stored.
*
* @param id the id of the object
* @param ifAvailable only return it if available, otherwise return null
* @return the object or null
* @throws DbException if isAvailable is false and the object has not been
* found
*/
public Object getObject(int id, boolean ifAvailable) {
if (id == cacheId) {
return cache;
}
Object obj = map.get(id);
if (obj == null && !ifAvailable) {
throw DbException.get(ErrorCode.OBJECT_CLOSED);
}
return obj;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/SoftHashMap.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Map which stores items using SoftReference. Items can be garbage collected
* and removed. It is not a general purpose cache, as it doesn't implement some
* methods, and others not according to the map definition, to improve speed.
*
* @param <K> the key type
* @param <V> the value type
*/
public class SoftHashMap<K, V> extends AbstractMap<K, V> {
private final Map<K, SoftValue<V>> map;
private final ReferenceQueue<V> queue = new ReferenceQueue<>();
public SoftHashMap() {
map = new HashMap<>();
}
@SuppressWarnings("unchecked")
private void processQueue() {
while (true) {
Reference<? extends V> o = queue.poll();
if (o == null) {
return;
}
SoftValue<V> k = (SoftValue<V>) o;
Object key = k.key;
map.remove(key);
}
}
@Override
public V get(Object key) {
processQueue();
SoftReference<V> o = map.get(key);
if (o == null) {
return null;
}
return o.get();
}
/**
* Store the object. The return value of this method is null or a
* SoftReference.
*
* @param key the key
* @param value the value
* @return null or the old object.
*/
@Override
public V put(K key, V value) {
processQueue();
SoftValue<V> old = map.put(key, new SoftValue<>(value, queue, key));
return old == null ? null : old.get();
}
/**
* Remove an object.
*
* @param key the key
* @return null or the old object
*/
@Override
public V remove(Object key) {
processQueue();
SoftReference<V> ref = map.remove(key);
return ref == null ? null : ref.get();
}
@Override
public void clear() {
processQueue();
map.clear();
}
@Override
public Set<Entry<K, V>> entrySet() {
throw new UnsupportedOperationException();
}
/**
* A soft reference that has a hard reference to the key.
*/
private static class SoftValue<T> extends SoftReference<T> {
final Object key;
public SoftValue(T ref, ReferenceQueue<T> q, Object key) {
super(ref, q);
this.key = key;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/SortedProperties.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
import java.util.Vector;
import org.h2.store.fs.FileUtils;
/**
* Sorted properties file.
* This implementation requires that store() internally calls keys().
*/
public class SortedProperties extends Properties {
private static final long serialVersionUID = 1L;
@Override
public synchronized Enumeration<Object> keys() {
Vector<String> v = new Vector<>();
for (Object o : keySet()) {
v.add(o.toString());
}
Collections.sort(v);
return new Vector<Object>(v).elements();
}
/**
* Get a boolean property value from a properties object.
*
* @param prop the properties object
* @param key the key
* @param def the default value
* @return the value if set, or the default value if not
*/
public static boolean getBooleanProperty(Properties prop, String key,
boolean def) {
try {
return Utils.parseBoolean(prop.getProperty(key, null), def, true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return def;
}
}
/**
* Get an int property value from a properties object.
*
* @param prop the properties object
* @param key the key
* @param def the default value
* @return the value if set, or the default value if not
*/
public static int getIntProperty(Properties prop, String key, int def) {
String value = prop.getProperty(key, "" + def);
try {
return Integer.decode(value);
} catch (Exception e) {
e.printStackTrace();
return def;
}
}
/**
* Load a properties object from a file.
*
* @param fileName the name of the properties file
* @return the properties object
*/
public static synchronized SortedProperties loadProperties(String fileName)
throws IOException {
SortedProperties prop = new SortedProperties();
if (FileUtils.exists(fileName)) {
try (InputStream in = FileUtils.newInputStream(fileName)) {
prop.load(in);
}
}
return prop;
}
/**
* Store a properties file. The header and the date is not written.
*
* @param fileName the target file name
*/
public synchronized void store(String fileName) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
store(out, null);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.ISO_8859_1);
LineNumberReader r = new LineNumberReader(reader);
Writer w;
try {
w = new OutputStreamWriter(FileUtils.newOutputStream(fileName, false));
} catch (Exception e) {
throw new IOException(e.toString(), e);
}
try (PrintWriter writer = new PrintWriter(new BufferedWriter(w))) {
while (true) {
String line = r.readLine();
if (line == null) {
break;
}
if (!line.startsWith("#")) {
writer.print(line + "\n");
}
}
}
}
/**
* Convert the map to a list of line in the form key=value.
*
* @return the lines
*/
public synchronized String toLines() {
StringBuilder buff = new StringBuilder();
for (Entry<Object, Object> e : new TreeMap<>(this).entrySet()) {
buff.append(e.getKey()).append('=').append(e.getValue()).append('\n');
}
return buff.toString();
}
/**
* 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;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/SourceCompiler.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.h2.api.ErrorCode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
/**
* This class allows to convert source code to a class. It uses one class loader
* per class.
*/
public class SourceCompiler {
/**
* The "com.sun.tools.javac.Main" (if available).
*/
static final JavaCompiler JAVA_COMPILER;
private static final Class<?> JAVAC_SUN;
private static final String COMPILE_DIR =
Utils.getProperty("java.io.tmpdir", ".");
/**
* The class name to source code map.
*/
final HashMap<String, String> sources = new HashMap<>();
/**
* The class name to byte code map.
*/
final HashMap<String, Class<?>> compiled = new HashMap<>();
/**
* The class name to compiled scripts map.
*/
final Map<String, CompiledScript> compiledScripts = new HashMap<>();
/**
* Whether to use the ToolProvider.getSystemJavaCompiler().
*/
boolean useJavaSystemCompiler = SysProperties.JAVA_SYSTEM_COMPILER;
static {
JavaCompiler c;
try {
c = ToolProvider.getSystemJavaCompiler();
} catch (Exception e) {
// ignore
c = null;
}
JAVA_COMPILER = c;
Class<?> clazz;
try {
clazz = Class.forName("com.sun.tools.javac.Main");
} catch (Exception e) {
clazz = null;
}
JAVAC_SUN = clazz;
}
/**
* Set the source code for the specified class.
* This will reset all compiled classes.
*
* @param className the class name
* @param source the source code
*/
public void setSource(String className, String source) {
sources.put(className, source);
compiled.clear();
}
/**
* Enable or disable the usage of the Java system compiler.
*
* @param enabled true to enable
*/
public void setJavaSystemCompiler(boolean enabled) {
this.useJavaSystemCompiler = enabled;
}
/**
* Get the class object for the given name.
*
* @param packageAndClassName the class name
* @return the class
*/
public Class<?> getClass(String packageAndClassName)
throws ClassNotFoundException {
Class<?> compiledClass = compiled.get(packageAndClassName);
if (compiledClass != null) {
return compiledClass;
}
String source = sources.get(packageAndClassName);
if (isGroovySource(source)) {
Class<?> clazz = GroovyCompiler.parseClass(source, packageAndClassName);
compiled.put(packageAndClassName, clazz);
return clazz;
}
ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) {
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> classInstance = compiled.get(name);
if (classInstance == null) {
String source = sources.get(name);
String packageName = null;
int idx = name.lastIndexOf('.');
String className;
if (idx >= 0) {
packageName = name.substring(0, idx);
className = name.substring(idx + 1);
} else {
className = name;
}
String s = getCompleteSourceCode(packageName, className, source);
if (JAVA_COMPILER != null && useJavaSystemCompiler) {
classInstance = javaxToolsJavac(packageName, className, s);
} else {
byte[] data = javacCompile(packageName, className, s);
if (data == null) {
classInstance = findSystemClass(name);
} else {
classInstance = defineClass(name, data, 0, data.length);
}
}
compiled.put(name, classInstance);
}
return classInstance;
}
};
return classLoader.loadClass(packageAndClassName);
}
private static boolean isGroovySource(String source) {
return source.startsWith("//groovy") || source.startsWith("@groovy");
}
private static boolean isJavascriptSource(String source) {
return source.startsWith("//javascript");
}
private static boolean isRubySource(String source) {
return source.startsWith("#ruby");
}
/**
* Whether the passed source can be compiled using {@link javax.script.ScriptEngineManager}.
*
* @param source the source to test.
* @return <code>true</code> if {@link #getCompiledScript(String)} can be called.
*/
public static boolean isJavaxScriptSource(String source) {
return isJavascriptSource(source) || isRubySource(source);
}
/**
* Get the compiled script.
*
* @param packageAndClassName the package and class name
* @return the compiled script
*/
public CompiledScript getCompiledScript(String packageAndClassName) throws ScriptException {
CompiledScript compiledScript = compiledScripts.get(packageAndClassName);
if (compiledScript == null) {
String source = sources.get(packageAndClassName);
final String lang;
if (isJavascriptSource(source)) {
lang = "javascript";
} else if (isRubySource(source)) {
lang = "ruby";
} else {
throw new IllegalStateException("Unknown language for " + source);
}
final Compilable jsEngine = (Compilable) new ScriptEngineManager().getEngineByName(lang);
compiledScript = jsEngine.compile(source);
compiledScripts.put(packageAndClassName, compiledScript);
}
return compiledScript;
}
/**
* Get the first public static method of the given class.
*
* @param className the class name
* @return the method name
*/
public Method getMethod(String className) throws ClassNotFoundException {
Class<?> clazz = getClass(className);
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
int modifiers = m.getModifiers();
if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
String name = m.getName();
if (!name.startsWith("_") && !m.getName().equals("main")) {
return m;
}
}
}
return null;
}
/**
* Compile the given class. This method tries to use the class
* "com.sun.tools.javac.Main" if available. If not, it tries to run "javac"
* in a separate process.
*
* @param packageName the package name
* @param className the class name
* @param source the source code
* @return the class file
*/
byte[] javacCompile(String packageName, String className, String source) {
File dir = new File(COMPILE_DIR);
if (packageName != null) {
dir = new File(dir, packageName.replace('.', '/'));
FileUtils.createDirectories(dir.getAbsolutePath());
}
File javaFile = new File(dir, className + ".java");
File classFile = new File(dir, className + ".class");
try {
OutputStream f = FileUtils.newOutputStream(javaFile.getAbsolutePath(), false);
Writer out = IOUtils.getBufferedWriter(f);
classFile.delete();
out.write(source);
out.close();
if (JAVAC_SUN != null) {
javacSun(javaFile);
} else {
javacProcess(javaFile);
}
byte[] data = new byte[(int) classFile.length()];
DataInputStream in = new DataInputStream(new FileInputStream(classFile));
in.readFully(data);
in.close();
return data;
} catch (Exception e) {
throw DbException.convert(e);
} finally {
javaFile.delete();
classFile.delete();
}
}
/**
* Get the complete source code (including package name, imports, and so
* on).
*
* @param packageName the package name
* @param className the class name
* @param source the (possibly shortened) source code
* @return the full source code
*/
static String getCompleteSourceCode(String packageName, String className,
String source) {
if (source.startsWith("package ")) {
return source;
}
StringBuilder buff = new StringBuilder();
if (packageName != null) {
buff.append("package ").append(packageName).append(";\n");
}
int endImport = source.indexOf("@CODE");
String importCode =
"import java.util.*;\n" +
"import java.math.*;\n" +
"import java.sql.*;\n";
if (endImport >= 0) {
importCode = source.substring(0, endImport);
source = source.substring("@CODE".length() + endImport);
}
buff.append(importCode);
buff.append("public class ").append(className).append(
" {\n" +
" public static ").append(source).append("\n" +
"}\n");
return buff.toString();
}
/**
* Compile using the standard java compiler.
*
* @param packageName the package name
* @param className the class name
* @param source the source code
* @return the class
*/
Class<?> javaxToolsJavac(String packageName, String className, String source) {
String fullClassName = packageName + "." + className;
StringWriter writer = new StringWriter();
try (JavaFileManager fileManager = new
ClassFileManager(JAVA_COMPILER
.getStandardFileManager(null, null, null))) {
ArrayList<JavaFileObject> compilationUnits = new ArrayList<>();
compilationUnits.add(new StringJavaFileObject(fullClassName, source));
// cannot concurrently compile
synchronized (JAVA_COMPILER) {
JAVA_COMPILER.getTask(writer, fileManager, null, null,
null, compilationUnits).call();
}
String output = writer.toString();
handleSyntaxError(output);
return fileManager.getClassLoader(null).loadClass(fullClassName);
} catch (ClassNotFoundException | IOException e) {
throw DbException.convert(e);
}
}
private static void javacProcess(File javaFile) {
exec("javac",
"-sourcepath", COMPILE_DIR,
"-d", COMPILE_DIR,
"-encoding", "UTF-8",
javaFile.getAbsolutePath());
}
private static int exec(String... args) {
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
ProcessBuilder builder = new ProcessBuilder();
// The javac executable allows some of it's flags
// to be smuggled in via environment variables.
// But if it sees those flags, it will write out a message
// to stderr, which messes up our parsing of the output.
builder.environment().remove("JAVA_TOOL_OPTIONS");
builder.command(args);
Process p = builder.start();
copyInThread(p.getInputStream(), buff);
copyInThread(p.getErrorStream(), buff);
p.waitFor();
String output = new String(buff.toByteArray(), StandardCharsets.UTF_8);
handleSyntaxError(output);
return p.exitValue();
} catch (Exception e) {
throw DbException.convert(e);
}
}
private static void copyInThread(final InputStream in, final OutputStream out) {
new Task() {
@Override
public void call() throws IOException {
IOUtils.copy(in, out);
}
}.execute();
}
private static synchronized void javacSun(File javaFile) {
PrintStream old = System.err;
ByteArrayOutputStream buff = new ByteArrayOutputStream();
PrintStream temp = new PrintStream(buff);
try {
System.setErr(temp);
Method compile;
compile = JAVAC_SUN.getMethod("compile", String[].class);
Object javac = JAVAC_SUN.newInstance();
compile.invoke(javac, (Object) new String[] {
"-sourcepath", COMPILE_DIR,
// "-Xlint:unchecked",
"-d", COMPILE_DIR,
"-encoding", "UTF-8",
javaFile.getAbsolutePath() });
String output = new String(buff.toByteArray(), StandardCharsets.UTF_8);
handleSyntaxError(output);
} catch (Exception e) {
throw DbException.convert(e);
} finally {
System.setErr(old);
}
}
private static void handleSyntaxError(String output) {
boolean syntaxError = false;
final BufferedReader reader = new BufferedReader(new StringReader(output));
try {
for (String line; (line = reader.readLine()) != null;) {
if (line.endsWith("warning")) {
// ignore summary line
} else if (line.startsWith("Note:")
|| line.startsWith("warning:")) {
// just a warning (e.g. unchecked or unsafe operations)
} else {
syntaxError = true;
break;
}
}
} catch (IOException ignored) {
// exception ignored
}
if (syntaxError) {
output = StringUtils.replaceAll(output, COMPILE_DIR, "");
throw DbException.get(ErrorCode.SYNTAX_ERROR_1, output);
}
}
/**
* Access the Groovy compiler using reflection, so that we do not gain a
* compile-time dependency unnecessarily.
*/
private static final class GroovyCompiler {
private static final Object LOADER;
private static final Throwable INIT_FAIL_EXCEPTION;
static {
Object loader = null;
Throwable initFailException = null;
try {
// Create an instance of ImportCustomizer
Class<?> importCustomizerClass = Class.forName(
"org.codehaus.groovy.control.customizers.ImportCustomizer");
Object importCustomizer = Utils.newInstance(
"org.codehaus.groovy.control.customizers.ImportCustomizer");
// Call the method ImportCustomizer.addImports(String[])
String[] importsArray = {
"java.sql.Connection",
"java.sql.Types",
"java.sql.ResultSet",
"groovy.sql.Sql",
"org.h2.tools.SimpleResultSet"
};
Utils.callMethod(importCustomizer, "addImports", new Object[] { importsArray });
// Call the method
// CompilerConfiguration.addCompilationCustomizers(
// ImportCustomizer...)
Object importCustomizerArray = Array.newInstance(importCustomizerClass, 1);
Array.set(importCustomizerArray, 0, importCustomizer);
Object configuration = Utils.newInstance(
"org.codehaus.groovy.control.CompilerConfiguration");
Utils.callMethod(configuration,
"addCompilationCustomizers", importCustomizerArray);
ClassLoader parent = GroovyCompiler.class.getClassLoader();
loader = Utils.newInstance(
"groovy.lang.GroovyClassLoader", parent, configuration);
} catch (Exception ex) {
initFailException = ex;
}
LOADER = loader;
INIT_FAIL_EXCEPTION = initFailException;
}
public static Class<?> parseClass(String source,
String packageAndClassName) {
if (LOADER == null) {
throw new RuntimeException(
"Compile fail: no Groovy jar in the classpath", INIT_FAIL_EXCEPTION);
}
try {
Object codeSource = Utils.newInstance("groovy.lang.GroovyCodeSource",
source, packageAndClassName + ".groovy", "UTF-8");
Utils.callMethod(codeSource, "setCachable", false);
return (Class<?>) Utils.callMethod(
LOADER, "parseClass", codeSource);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* An in-memory java source file object.
*/
static class StringJavaFileObject extends SimpleJavaFileObject {
private final String sourceCode;
public StringJavaFileObject(String className, String sourceCode) {
super(URI.create("string:///" + className.replace('.', '/')
+ Kind.SOURCE.extension), Kind.SOURCE);
this.sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return sourceCode;
}
}
/**
* An in-memory java class object.
*/
static class JavaClassObject extends SimpleJavaFileObject {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
public JavaClassObject(String name, Kind kind) {
super(URI.create("string:///" + name.replace('.', '/')
+ kind.extension), kind);
}
public byte[] getBytes() {
return out.toByteArray();
}
@Override
public OutputStream openOutputStream() throws IOException {
return out;
}
}
/**
* An in-memory class file manager.
*/
static class ClassFileManager extends
ForwardingJavaFileManager<StandardJavaFileManager> {
/**
* The class (only one class is kept).
*/
JavaClassObject classObject;
public ClassFileManager(StandardJavaFileManager standardManager) {
super(standardManager);
}
@Override
public ClassLoader getClassLoader(Location location) {
return new SecureClassLoader() {
@Override
protected Class<?> findClass(String name)
throws ClassNotFoundException {
byte[] bytes = classObject.getBytes();
return super.defineClass(name, bytes, 0,
bytes.length);
}
};
}
@Override
public JavaFileObject getJavaFileForOutput(Location location,
String className, Kind kind, FileObject sibling) throws IOException {
classObject = new JavaClassObject(className, kind);
return classObject;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/StatementBuilder.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
/**
* A utility class to build a statement. In addition to the methods supported by
* StringBuilder, it allows to add a text only in the second iteration. This
* simplified constructs such as:
* <pre>
* StringBuilder buff = new StringBuilder();
* for (int i = 0; i < args.length; i++) {
* if (i > 0) {
* buff.append(", ");
* }
* buff.append(args[i]);
* }
* </pre>
* to
* <pre>
* StatementBuilder buff = new StatementBuilder();
* for (String s : args) {
* buff.appendExceptFirst(", ");
* buff.append(a);
* }
*</pre>
*/
public class StatementBuilder {
private final StringBuilder builder = new StringBuilder();
private int index;
/**
* Create a new builder.
*/
public StatementBuilder() {
// nothing to do
}
/**
* Create a new builder.
*
* @param string the initial string
*/
public StatementBuilder(String string) {
builder.append(string);
}
/**
* Append a text.
*
* @param s the text to append
* @return itself
*/
public StatementBuilder append(String s) {
builder.append(s);
return this;
}
/**
* Append a character.
*
* @param c the character to append
* @return itself
*/
public StatementBuilder append(char c) {
builder.append(c);
return this;
}
/**
* Append a number.
*
* @param x the number to append
* @return itself
*/
public StatementBuilder append(long x) {
builder.append(x);
return this;
}
/**
* Reset the loop counter.
*
* @return itself
*/
public StatementBuilder resetCount() {
index = 0;
return this;
}
/**
* Append a text, but only if appendExceptFirst was never called.
*
* @param s the text to append
*/
public void appendOnlyFirst(String s) {
if (index == 0) {
builder.append(s);
}
}
/**
* Append a text, except when this method is called the first time.
*
* @param s the text to append
*/
public void appendExceptFirst(String s) {
if (index++ > 0) {
builder.append(s);
}
}
@Override
public String toString() {
return builder.toString();
}
/**
* Get the length.
*
* @return the length
*/
public int length() {
return builder.length();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/StringUtils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.lang.ref.SoftReference;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.h2.api.ErrorCode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
/**
* A few String utility functions.
*/
public class StringUtils {
private static SoftReference<String[]> softCache =
new SoftReference<>(null);
private static long softCacheCreatedNs;
private static final char[] HEX = "0123456789abcdef".toCharArray();
private static final int[] HEX_DECODE = new int['f' + 1];
// memory used by this cache:
// 4 * 1024 * 2 (strings per pair) * 64 * 2 (bytes per char) = 0.5 MB
private static final int TO_UPPER_CACHE_LENGTH = 2 * 1024;
private static final int TO_UPPER_CACHE_MAX_ENTRY_LENGTH = 64;
private static final String[][] TO_UPPER_CACHE = new String[TO_UPPER_CACHE_LENGTH][];
static {
for (int i = 0; i < HEX_DECODE.length; i++) {
HEX_DECODE[i] = -1;
}
for (int i = 0; i <= 9; i++) {
HEX_DECODE[i + '0'] = i;
}
for (int i = 0; i <= 5; i++) {
HEX_DECODE[i + 'a'] = HEX_DECODE[i + 'A'] = i + 10;
}
}
private StringUtils() {
// utility class
}
private static String[] getCache() {
String[] cache;
// softCache can be null due to a Tomcat problem
// a workaround is disable the system property org.apache.
// catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES
if (softCache != null) {
cache = softCache.get();
if (cache != null) {
return cache;
}
}
// create a new cache at most every 5 seconds
// so that out of memory exceptions are not delayed
long time = System.nanoTime();
if (softCacheCreatedNs != 0 && time - softCacheCreatedNs < TimeUnit.SECONDS.toNanos(5)) {
return null;
}
try {
cache = new String[SysProperties.OBJECT_CACHE_SIZE];
softCache = new SoftReference<>(cache);
return cache;
} finally {
softCacheCreatedNs = System.nanoTime();
}
}
/**
* Convert a string to uppercase using the English locale.
*
* @param s the test to convert
* @return the uppercase text
*/
public static String toUpperEnglish(String s) {
if (s.length() > TO_UPPER_CACHE_MAX_ENTRY_LENGTH) {
return s.toUpperCase(Locale.ENGLISH);
}
int index = s.hashCode() & (TO_UPPER_CACHE_LENGTH - 1);
String[] e = TO_UPPER_CACHE[index];
if (e != null) {
if (e[0].equals(s)) {
return e[1];
}
}
String s2 = s.toUpperCase(Locale.ENGLISH);
e = new String[] { s, s2 };
TO_UPPER_CACHE[index] = e;
return s2;
}
/**
* Convert a string to lowercase using the English locale.
*
* @param s the text to convert
* @return the lowercase text
*/
public static String toLowerEnglish(String s) {
return s.toLowerCase(Locale.ENGLISH);
}
/**
* Check is a string starts with another string, ignoring the case.
*
* @param s the string to check (must be longer than start)
* @param start the prefix of s
* @return true if start is a prefix of s
*/
public static boolean startsWithIgnoreCase(String s, String start) {
if (s.length() < start.length()) {
return false;
}
return s.substring(0, start.length()).equalsIgnoreCase(start);
}
/**
* Convert a string to a SQL literal. Null is converted to NULL. The text is
* enclosed in single quotes. If there are any special characters, the
* method STRINGDECODE is used.
*
* @param s the text to convert.
* @return the SQL literal
*/
public static String quoteStringSQL(String s) {
if (s == null) {
return "NULL";
}
int length = s.length();
StringBuilder buff = new StringBuilder(length + 2);
buff.append('\'');
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == '\'') {
buff.append(c);
} else if (c < ' ' || c > 127) {
// need to start from the beginning because maybe there was a \
// that was not quoted
return "STRINGDECODE(" + quoteStringSQL(javaEncode(s)) + ")";
}
buff.append(c);
}
buff.append('\'');
return buff.toString();
}
/**
* Convert a string to a Java literal using the correct escape sequences.
* The literal is not enclosed in double quotes. The result can be used in
* properties files or in Java source code.
*
* @param s the text to convert
* @return the Java representation
*/
public static String javaEncode(String s) {
int length = s.length();
StringBuilder buff = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
switch (c) {
// case '\b':
// // BS backspace
// // not supported in properties files
// buff.append("\\b");
// break;
case '\t':
// HT horizontal tab
buff.append("\\t");
break;
case '\n':
// LF linefeed
buff.append("\\n");
break;
case '\f':
// FF form feed
buff.append("\\f");
break;
case '\r':
// CR carriage return
buff.append("\\r");
break;
case '"':
// double quote
buff.append("\\\"");
break;
case '\\':
// backslash
buff.append("\\\\");
break;
default:
int ch = c & 0xffff;
if (ch >= ' ' && (ch < 0x80)) {
buff.append(c);
// not supported in properties files
// } else if (ch < 0xff) {
// buff.append("\\");
// // make sure it's three characters (0x200 is octal 1000)
// buff.append(Integer.toOctalString(0x200 | ch).substring(1));
} else {
buff.append("\\u");
String hex = Integer.toHexString(ch);
// make sure it's four characters
for (int len = hex.length(); len < 4; len++) {
buff.append('0');
}
buff.append(hex);
}
}
}
return buff.toString();
}
/**
* Add an asterisk ('[*]') at the given position. This format is used to
* show where parsing failed in a statement.
*
* @param s the text
* @param index the position
* @return the text with asterisk
*/
public static String addAsterisk(String s, int index) {
if (s != null) {
index = Math.min(index, s.length());
s = s.substring(0, index) + "[*]" + s.substring(index);
}
return s;
}
private static DbException getFormatException(String s, int i) {
return DbException.get(ErrorCode.STRING_FORMAT_ERROR_1, addAsterisk(s, i));
}
/**
* Decode a text that is encoded as a Java string literal. The Java
* properties file format and Java source code format is supported.
*
* @param s the encoded string
* @return the string
*/
public static String javaDecode(String s) {
int length = s.length();
StringBuilder buff = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == '\\') {
if (i + 1 >= s.length()) {
throw getFormatException(s, i);
}
c = s.charAt(++i);
switch (c) {
case 't':
buff.append('\t');
break;
case 'r':
buff.append('\r');
break;
case 'n':
buff.append('\n');
break;
case 'b':
buff.append('\b');
break;
case 'f':
buff.append('\f');
break;
case '#':
// for properties files
buff.append('#');
break;
case '=':
// for properties files
buff.append('=');
break;
case ':':
// for properties files
buff.append(':');
break;
case '"':
buff.append('"');
break;
case '\\':
buff.append('\\');
break;
case 'u': {
try {
c = (char) (Integer.parseInt(s.substring(i + 1, i + 5), 16));
} catch (NumberFormatException e) {
throw getFormatException(s, i);
}
i += 4;
buff.append(c);
break;
}
default:
if (c >= '0' && c <= '9') {
try {
c = (char) (Integer.parseInt(s.substring(i, i + 3), 8));
} catch (NumberFormatException e) {
throw getFormatException(s, i);
}
i += 2;
buff.append(c);
} else {
throw getFormatException(s, i);
}
}
} else {
buff.append(c);
}
}
return buff.toString();
}
/**
* Convert a string to the Java literal and enclose it with double quotes.
* Null will result in "null" (without double quotes).
*
* @param s the text to convert
* @return the Java representation
*/
public static String quoteJavaString(String s) {
if (s == null) {
return "null";
}
return "\"" + javaEncode(s) + "\"";
}
/**
* Convert a string array to the Java source code that represents this
* array. Null will be converted to 'null'.
*
* @param array the string array
* @return the Java source code (including new String[]{})
*/
public static String quoteJavaStringArray(String[] array) {
if (array == null) {
return "null";
}
StatementBuilder buff = new StatementBuilder("new String[]{");
for (String a : array) {
buff.appendExceptFirst(", ");
buff.append(quoteJavaString(a));
}
return buff.append('}').toString();
}
/**
* Convert an int array to the Java source code that represents this array.
* Null will be converted to 'null'.
*
* @param array the int array
* @return the Java source code (including new int[]{})
*/
public static String quoteJavaIntArray(int[] array) {
if (array == null) {
return "null";
}
StatementBuilder buff = new StatementBuilder("new int[]{");
for (int a : array) {
buff.appendExceptFirst(", ");
buff.append(a);
}
return buff.append('}').toString();
}
/**
* Enclose a string with '(' and ')' if this is not yet done.
*
* @param s the string
* @return the enclosed string
*/
public static String enclose(String s) {
if (s.startsWith("(")) {
return s;
}
return "(" + s + ")";
}
/**
* Remove enclosing '(' and ')' if this text is enclosed.
*
* @param s the potentially enclosed string
* @return the string
*/
public static String unEnclose(String s) {
if (s.startsWith("(") && s.endsWith(")")) {
return s.substring(1, s.length() - 1);
}
return s;
}
/**
* Encode the string as an URL.
*
* @param s the string to encode
* @return the encoded string
*/
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (Exception e) {
// UnsupportedEncodingException
throw DbException.convert(e);
}
}
/**
* Decode the URL to a string.
*
* @param encoded the encoded URL
* @return the decoded string
*/
public static String urlDecode(String encoded) {
int length = encoded.length();
byte[] buff = new byte[length];
int j = 0;
for (int i = 0; i < length; i++) {
char ch = encoded.charAt(i);
if (ch == '+') {
buff[j++] = ' ';
} else if (ch == '%') {
buff[j++] = (byte) Integer.parseInt(encoded.substring(i + 1, i + 3), 16);
i += 2;
} else {
if (SysProperties.CHECK) {
if (ch > 127 || ch < ' ') {
throw new IllegalArgumentException(
"Unexpected char " + (int) ch + " decoding " + encoded);
}
}
buff[j++] = (byte) ch;
}
}
return new String(buff, 0, j, StandardCharsets.UTF_8);
}
/**
* Split a string into an array of strings using the given separator. A null
* string will result in a null array, and an empty string in a zero element
* array.
*
* @param s the string to split
* @param separatorChar the separator character
* @param trim whether each element should be trimmed
* @return the array list
*/
public static String[] arraySplit(String s, char separatorChar, boolean trim) {
if (s == null) {
return null;
}
int length = s.length();
if (length == 0) {
return new String[0];
}
ArrayList<String> list = New.arrayList();
StringBuilder buff = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == separatorChar) {
String e = buff.toString();
list.add(trim ? e.trim() : e);
buff.setLength(0);
} else if (c == '\\' && i < length - 1) {
buff.append(s.charAt(++i));
} else {
buff.append(c);
}
}
String e = buff.toString();
list.add(trim ? e.trim() : e);
return list.toArray(new String[0]);
}
/**
* Combine an array of strings to one array using the given separator
* character. A backslash and the separator character and escaped using a
* backslash.
*
* @param list the string array
* @param separatorChar the separator character
* @return the combined string
*/
public static String arrayCombine(String[] list, char separatorChar) {
StatementBuilder buff = new StatementBuilder();
for (String s : list) {
buff.appendExceptFirst(String.valueOf(separatorChar));
if (s == null) {
s = "";
}
for (int j = 0, length = s.length(); j < length; j++) {
char c = s.charAt(j);
if (c == '\\' || c == separatorChar) {
buff.append('\\');
}
buff.append(c);
}
}
return buff.toString();
}
/**
* Creates an XML attribute of the form name="value".
* A single space is prepended to the name,
* so that multiple attributes can be concatenated.
* @param name the attribute name
* @param value the attribute value
* @return the attribute
*/
public static String xmlAttr(String name, String value) {
return " " + name + "=\"" + xmlText(value) + "\"";
}
/**
* Create an XML node with optional attributes and content.
* The data is indented with 4 spaces if it contains a newline character.
*
* @param name the element name
* @param attributes the attributes (may be null)
* @param content the content (may be null)
* @return the node
*/
public static String xmlNode(String name, String attributes, String content) {
return xmlNode(name, attributes, content, true);
}
/**
* Create an XML node with optional attributes and content. The data is
* indented with 4 spaces if it contains a newline character and the indent
* parameter is set to true.
*
* @param name the element name
* @param attributes the attributes (may be null)
* @param content the content (may be null)
* @param indent whether to indent the content if it contains a newline
* @return the node
*/
public static String xmlNode(String name, String attributes,
String content, boolean indent) {
String start = attributes == null ? name : name + attributes;
if (content == null) {
return "<" + start + "/>\n";
}
if (indent && content.indexOf('\n') >= 0) {
content = "\n" + indent(content);
}
return "<" + start + ">" + content + "</" + name + ">\n";
}
/**
* Indents a string with 4 spaces.
*
* @param s the string
* @return the indented string
*/
public static String indent(String s) {
return indent(s, 4, true);
}
/**
* Indents a string with spaces.
*
* @param s the string
* @param spaces the number of spaces
* @param newline append a newline if there is none
* @return the indented string
*/
public static String indent(String s, int spaces, boolean newline) {
StringBuilder buff = new StringBuilder(s.length() + spaces);
for (int i = 0; i < s.length();) {
for (int j = 0; j < spaces; j++) {
buff.append(' ');
}
int n = s.indexOf('\n', i);
n = n < 0 ? s.length() : n + 1;
buff.append(s, i, n);
i = n;
}
if (newline && !s.endsWith("\n")) {
buff.append('\n');
}
return buff.toString();
}
/**
* Escapes a comment.
* If the data contains '--', it is converted to '- -'.
* The data is indented with 4 spaces if it contains a newline character.
*
* @param data the comment text
* @return <!-- data -->
*/
public static String xmlComment(String data) {
int idx = 0;
while (true) {
idx = data.indexOf("--", idx);
if (idx < 0) {
break;
}
data = data.substring(0, idx + 1) + " " + data.substring(idx + 1);
}
// must have a space at the beginning and at the end,
// otherwise the data must not contain '-' as the first/last character
if (data.indexOf('\n') >= 0) {
return "<!--\n" + indent(data) + "-->\n";
}
return "<!-- " + data + " -->\n";
}
/**
* Converts the data to a CDATA element.
* If the data contains ']]>', it is escaped as a text element.
*
* @param data the text data
* @return <![CDATA[data]]>
*/
public static String xmlCData(String data) {
if (data.contains("]]>")) {
return xmlText(data);
}
boolean newline = data.endsWith("\n");
data = "<![CDATA[" + data + "]]>";
return newline ? data + "\n" : data;
}
/**
* Returns <?xml version="1.0"?>
* @return <?xml version="1.0"?>
*/
public static String xmlStartDoc() {
return "<?xml version=\"1.0\"?>\n";
}
/**
* Escapes an XML text element.
*
* @param text the text data
* @return the escaped text
*/
public static String xmlText(String text) {
return xmlText(text, false);
}
/**
* Escapes an XML text element.
*
* @param text the text data
* @param escapeNewline whether to escape newlines
* @return the escaped text
*/
public static String xmlText(String text, boolean escapeNewline) {
int length = text.length();
StringBuilder buff = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char ch = text.charAt(i);
switch (ch) {
case '<':
buff.append("<");
break;
case '>':
buff.append(">");
break;
case '&':
buff.append("&");
break;
case '\'':
// ' is not valid in HTML
buff.append("'");
break;
case '\"':
buff.append(""");
break;
case '\r':
case '\n':
if (escapeNewline) {
buff.append("&#x").
append(Integer.toHexString(ch)).
append(';');
} else {
buff.append(ch);
}
break;
case '\t':
buff.append(ch);
break;
default:
if (ch < ' ' || ch > 127) {
buff.append("&#x").
append(Integer.toHexString(ch)).
append(';');
} else {
buff.append(ch);
}
}
}
return buff.toString();
}
/**
* Replace all occurrences of the before string with the after string. Unlike
* {@link String#replaceAll(String, String)} this method reads {@code before}
* and {@code after} arguments as plain strings and if {@code before} argument
* is an empty string this method returns original string {@code s}.
*
* @param s the string
* @param before the old text
* @param after the new text
* @return the string with the before string replaced
*/
public static String replaceAll(String s, String before, String after) {
int next = s.indexOf(before);
if (next < 0 || before.isEmpty()) {
return s;
}
StringBuilder buff = new StringBuilder(
s.length() - before.length() + after.length());
int index = 0;
while (true) {
buff.append(s, index, next).append(after);
index = next + before.length();
next = s.indexOf(before, index);
if (next < 0) {
buff.append(s, index, s.length());
break;
}
}
return buff.toString();
}
/**
* Enclose a string with double quotes. A double quote inside the string is
* escaped using a double quote.
*
* @param s the text
* @return the double quoted text
*/
public static String quoteIdentifier(String s) {
int length = s.length();
StringBuilder buff = new StringBuilder(length + 2);
buff.append('\"');
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == '"') {
buff.append(c);
}
buff.append(c);
}
return buff.append('\"').toString();
}
/**
* Check if a String is null or empty (the length is null).
*
* @param s the string to check
* @return true if it is null or empty
*/
public static boolean isNullOrEmpty(String s) {
return s == null || s.length() == 0;
}
/**
* In a string, replace block comment marks with /++ .. ++/.
*
* @param sql the string
* @return the resulting string
*/
public static String quoteRemarkSQL(String sql) {
sql = replaceAll(sql, "*/", "++/");
return replaceAll(sql, "/*", "/++");
}
/**
* Pad a string. This method is used for the SQL function RPAD and LPAD.
*
* @param string the original string
* @param n the target length
* @param padding the padding string
* @param right true if the padding should be appended at the end
* @return the padded string
*/
public static String pad(String string, int n, String padding, boolean right) {
if (n < 0) {
n = 0;
}
if (n < string.length()) {
return string.substring(0, n);
} else if (n == string.length()) {
return string;
}
char paddingChar;
if (padding == null || padding.length() == 0) {
paddingChar = ' ';
} else {
paddingChar = padding.charAt(0);
}
StringBuilder buff = new StringBuilder(n);
n -= string.length();
if (right) {
buff.append(string);
}
for (int i = 0; i < n; i++) {
buff.append(paddingChar);
}
if (!right) {
buff.append(string);
}
return buff.toString();
}
/**
* Create a new char array and copy all the data. If the size of the byte
* array is zero, the same array is returned.
*
* @param chars the char array (may be null)
* @return a new char array
*/
public static char[] cloneCharArray(char[] chars) {
if (chars == null) {
return null;
}
int len = chars.length;
if (len == 0) {
return chars;
}
return Arrays.copyOf(chars, len);
}
/**
* Trim a character from a string.
*
* @param s the string
* @param leading if leading characters should be removed
* @param trailing if trailing characters should be removed
* @param sp what to remove (only the first character is used)
* or null for a space
* @return the trimmed string
*/
public static String trim(String s, boolean leading, boolean trailing,
String sp) {
char space = sp == null || sp.isEmpty() ? ' ' : sp.charAt(0);
int begin = 0, end = s.length();
if (leading) {
while (begin < end && s.charAt(begin) == space) {
begin++;
}
}
if (trailing) {
while (end > begin && s.charAt(end - 1) == space) {
end--;
}
}
// substring() returns self if start == 0 && end == length()
return s.substring(begin, end);
}
/**
* Get the string from the cache if possible. If the string has not been
* found, it is added to the cache. If there is such a string in the cache,
* that one is returned.
*
* @param s the original string
* @return a string with the same content, if possible from the cache
*/
public static String cache(String s) {
if (!SysProperties.OBJECT_CACHE) {
return s;
}
if (s == null) {
return s;
} else if (s.length() == 0) {
return "";
}
int hash = s.hashCode();
String[] cache = getCache();
if (cache != null) {
int index = hash & (SysProperties.OBJECT_CACHE_SIZE - 1);
String cached = cache[index];
if (cached != null) {
if (s.equals(cached)) {
return cached;
}
}
cache[index] = s;
}
return s;
}
/**
* Clear the cache. This method is used for testing.
*/
public static void clearCache() {
softCache = new SoftReference<>(null);
}
/**
* Convert a hex encoded string to a byte array.
*
* @param s the hex encoded string
* @return the byte array
*/
public static byte[] convertHexToBytes(String s) {
int len = s.length();
if (len % 2 != 0) {
throw DbException.get(ErrorCode.HEX_STRING_ODD_1, s);
}
len /= 2;
byte[] buff = new byte[len];
int mask = 0;
int[] hex = HEX_DECODE;
try {
for (int i = 0; i < len; i++) {
int d = hex[s.charAt(i + i)] << 4 | hex[s.charAt(i + i + 1)];
mask |= d;
buff[i] = (byte) d;
}
} catch (ArrayIndexOutOfBoundsException e) {
throw DbException.get(ErrorCode.HEX_STRING_WRONG_1, s);
}
if ((mask & ~255) != 0) {
throw DbException.get(ErrorCode.HEX_STRING_WRONG_1, s);
}
return buff;
}
/**
* Convert a byte array to a hex encoded string.
*
* @param value the byte array
* @return the hex encoded string
*/
public static String convertBytesToHex(byte[] value) {
return convertBytesToHex(value, value.length);
}
/**
* Convert a byte array to a hex encoded string.
*
* @param value the byte array
* @param len the number of bytes to encode
* @return the hex encoded string
*/
public static String convertBytesToHex(byte[] value, int len) {
char[] buff = new char[len + len];
char[] hex = HEX;
for (int i = 0; i < len; i++) {
int c = value[i] & 0xff;
buff[i + i] = hex[c >> 4];
buff[i + i + 1] = hex[c & 0xf];
}
return new String(buff);
}
/**
* Check if this string is a decimal number.
*
* @param s the string
* @return true if it is
*/
public static boolean isNumber(String s) {
if (s.length() == 0) {
return false;
}
for (char c : s.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
/**
* Append a zero-padded number to a string builder.
*
* @param buff the string builder
* @param length the number of characters to append
* @param positiveValue the number to append
*/
public static void appendZeroPadded(StringBuilder buff, int length,
long positiveValue) {
if (length == 2) {
if (positiveValue < 10) {
buff.append('0');
}
buff.append(positiveValue);
} else {
String s = Long.toString(positiveValue);
length -= s.length();
while (length > 0) {
buff.append('0');
length--;
}
buff.append(s);
}
}
/**
* Escape table or schema patterns used for DatabaseMetaData functions.
*
* @param pattern the pattern
* @return the escaped pattern
*/
public static String escapeMetaDataPattern(String pattern) {
if (pattern == null || pattern.length() == 0) {
return pattern;
}
return replaceAll(pattern, "\\", "\\\\");
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/SynchronizedVerifier.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A utility class that allows to verify access to a resource is synchronized.
*/
public class SynchronizedVerifier {
private static volatile boolean enabled;
private static final Map<Class<?>, AtomicBoolean> DETECT =
Collections.synchronizedMap(new HashMap<Class<?>, AtomicBoolean>());
private static final Map<Object, Object> CURRENT =
Collections.synchronizedMap(new IdentityHashMap<>());
/**
* Enable or disable detection for a given class.
*
* @param clazz the class
* @param value the new value (true means detection is enabled)
*/
public static void setDetect(Class<?> clazz, boolean value) {
if (value) {
DETECT.put(clazz, new AtomicBoolean());
} else {
AtomicBoolean b = DETECT.remove(clazz);
if (b == null) {
throw new AssertionError("Detection was not enabled");
} else if (!b.get()) {
throw new AssertionError("No object of this class was tested");
}
}
enabled = DETECT.size() > 0;
}
/**
* Verify the object is not accessed concurrently.
*
* @param o the object
*/
public static void check(Object o) {
if (enabled) {
detectConcurrentAccess(o);
}
}
private static void detectConcurrentAccess(Object o) {
AtomicBoolean value = DETECT.get(o.getClass());
if (value != null) {
value.set(true);
if (CURRENT.remove(o) != null) {
throw new AssertionError("Concurrent access");
}
CURRENT.put(o, o);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// ignore
}
Object old = CURRENT.remove(o);
if (old == null) {
throw new AssertionError("Concurrent access");
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/Task.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A method call that is executed in a separate thread. If the method throws an
* exception, it is wrapped in a RuntimeException.
*/
public abstract class Task implements Runnable {
private static final AtomicInteger counter = new AtomicInteger();
/**
* A flag indicating the get() method has been called.
*/
public volatile boolean stop;
/**
* The result, if any.
*/
private volatile Object result;
private volatile boolean finished;
private Thread thread;
private volatile Exception ex;
/**
* The method to be implemented.
*
* @throws Exception any exception is wrapped in a RuntimeException
*/
public abstract void call() throws Exception;
@Override
public void run() {
try {
call();
} catch (Exception e) {
this.ex = e;
}
finished = true;
}
/**
* Start the thread.
*
* @return this
*/
public Task execute() {
return execute(getClass().getName() + ":" + counter.getAndIncrement());
}
/**
* Start the thread.
*
* @param threadName the name of the thread
* @return this
*/
public Task execute(String threadName) {
thread = new Thread(this, threadName);
thread.setDaemon(true);
thread.start();
return this;
}
/**
* Calling this method will set the stop flag and wait until the thread is
* stopped.
*
* @return the result, or null
* @throws RuntimeException if an exception in the method call occurs
*/
public Object get() {
Exception e = getException();
if (e != null) {
throw new RuntimeException(e);
}
return result;
}
/**
* Whether the call method has returned (with or without exception).
*
* @return true if yes
*/
public boolean isFinished() {
return finished;
}
/**
* Get the exception that was thrown in the call (if any).
*
* @return the exception or null
*/
public Exception getException() {
join();
if (ex != null) {
return ex;
}
return null;
}
/**
* Stop the thread and wait until it is no longer running. Exceptions are
* ignored.
*/
public void join() {
stop = true;
if (thread == null) {
throw new IllegalStateException("Thread not started");
}
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/TempFileDeleter.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.HashMap;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
/**
* This class deletes temporary files when they are not used any longer.
*/
public class TempFileDeleter {
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
private final HashMap<PhantomReference<?>, String> refMap = new HashMap<>();
private TempFileDeleter() {
// utility class
}
public static TempFileDeleter getInstance() {
return new TempFileDeleter();
}
/**
* Add a file to the list of temp files to delete. The file is deleted once
* the file object is garbage collected.
*
* @param fileName the file name
* @param file the object to monitor
* @return the reference that can be used to stop deleting the file
*/
public synchronized Reference<?> addFile(String fileName, Object file) {
IOUtils.trace("TempFileDeleter.addFile", fileName, file);
PhantomReference<?> ref = new PhantomReference<>(file, queue);
refMap.put(ref, fileName);
deleteUnused();
return ref;
}
/**
* Delete the given file now. This will remove the reference from the list.
*
* @param ref the reference as returned by addFile
* @param fileName the file name
*/
public synchronized void deleteFile(Reference<?> ref, String fileName) {
if (ref != null) {
String f2 = refMap.remove(ref);
if (f2 != null) {
if (SysProperties.CHECK) {
if (fileName != null && !f2.equals(fileName)) {
DbException.throwInternalError("f2:" + f2 + " f:" + fileName);
}
}
fileName = f2;
}
}
if (fileName != null && FileUtils.exists(fileName)) {
try {
IOUtils.trace("TempFileDeleter.deleteFile", fileName, null);
FileUtils.tryDelete(fileName);
} catch (Exception e) {
// TODO log such errors?
}
}
}
/**
* Delete all registered temp files.
*/
public void deleteAll() {
for (String tempFile : new ArrayList<>(refMap.values())) {
deleteFile(null, tempFile);
}
deleteUnused();
}
/**
* Delete all unused files now.
*/
public void deleteUnused() {
while (queue != null) {
Reference<?> ref = queue.poll();
if (ref == null) {
break;
}
deleteFile(ref, null);
}
}
/**
* This method is called if a file should no longer be deleted if the object
* is garbage collected.
*
* @param ref the reference as returned by addFile
* @param fileName the file name
*/
public void stopAutoDelete(Reference<?> ref, String fileName) {
IOUtils.trace("TempFileDeleter.stopAutoDelete", fileName, ref);
if (ref != null) {
String f2 = refMap.remove(ref);
if (SysProperties.CHECK) {
if (f2 == null || !f2.equals(fileName)) {
DbException.throwInternalError("f2:" + f2 +
" " + (f2 == null ? "" : f2) + " f:" + fileName);
}
}
}
deleteUnused();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ThreadDeadlockDetector.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import org.h2.engine.SysProperties;
import org.h2.mvstore.db.MVTable;
/**
* Detects deadlocks between threads. Prints out data in the same format as the
* CTRL-BREAK handler, but includes information about table locks.
*/
public class ThreadDeadlockDetector {
private static final String INDENT = " ";
private static ThreadDeadlockDetector detector;
private final ThreadMXBean threadBean;
// a daemon thread
private final Timer threadCheck = new Timer("ThreadDeadlockDetector", true);
private ThreadDeadlockDetector() {
this.threadBean = ManagementFactory.getThreadMXBean();
// delay: 10 ms
// period: 10000 ms (100 seconds)
threadCheck.schedule(new TimerTask() {
@Override
public void run() {
checkForDeadlocks();
}
}, 10, 10_000);
}
/**
* Initialize the detector.
*/
public static synchronized void init() {
if (detector == null) {
detector = new ThreadDeadlockDetector();
}
}
/**
* Checks if any threads are deadlocked. If any, print the thread dump
* information.
*/
void checkForDeadlocks() {
long[] deadlockedThreadIds = threadBean.findDeadlockedThreads();
if (deadlockedThreadIds == null) {
return;
}
dumpThreadsAndLocks("ThreadDeadlockDetector - deadlock found :",
threadBean, deadlockedThreadIds, System.out);
}
/**
* Dump all deadlocks (if any).
*
* @param msg the message
*/
public static void dumpAllThreadsAndLocks(String msg) {
dumpAllThreadsAndLocks(msg, System.out);
}
/**
* Dump all deadlocks (if any).
*
* @param msg the message
* @param out the output
*/
public static void dumpAllThreadsAndLocks(String msg, PrintStream out) {
final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
final long[] allThreadIds = threadBean.getAllThreadIds();
dumpThreadsAndLocks(msg, threadBean, allThreadIds, out);
}
private static void dumpThreadsAndLocks(String msg, ThreadMXBean threadBean,
long[] threadIds, PrintStream out) {
final StringWriter stringWriter = new StringWriter();
final PrintWriter print = new PrintWriter(stringWriter);
print.println(msg);
final HashMap<Long, String> tableWaitingForLockMap;
final HashMap<Long, ArrayList<String>> tableExclusiveLocksMap;
final HashMap<Long, ArrayList<String>> tableSharedLocksMap;
if (SysProperties.THREAD_DEADLOCK_DETECTOR) {
tableWaitingForLockMap = MVTable.WAITING_FOR_LOCK
.getSnapshotOfAllThreads();
tableExclusiveLocksMap = MVTable.EXCLUSIVE_LOCKS
.getSnapshotOfAllThreads();
tableSharedLocksMap = MVTable.SHARED_LOCKS
.getSnapshotOfAllThreads();
} else {
tableWaitingForLockMap = new HashMap<>();
tableExclusiveLocksMap = new HashMap<>();
tableSharedLocksMap = new HashMap<>();
}
final ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true,
true);
for (ThreadInfo ti : infos) {
printThreadInfo(print, ti);
printLockInfo(print, ti.getLockedSynchronizers(),
tableWaitingForLockMap.get(ti.getThreadId()),
tableExclusiveLocksMap.get(ti.getThreadId()),
tableSharedLocksMap.get(ti.getThreadId()));
}
print.flush();
// Dump it to system.out in one block, so it doesn't get mixed up with
// other stuff when we're using a logging subsystem.
out.println(stringWriter.getBuffer());
out.flush();
}
private static void printThreadInfo(PrintWriter print, ThreadInfo ti) {
// print thread information
printThread(print, ti);
// print stack trace with locks
StackTraceElement[] stackTrace = ti.getStackTrace();
MonitorInfo[] monitors = ti.getLockedMonitors();
for (int i = 0; i < stackTrace.length; i++) {
StackTraceElement e = stackTrace[i];
print.println(INDENT + "at " + e.toString());
for (MonitorInfo mi : monitors) {
if (mi.getLockedStackDepth() == i) {
print.println(INDENT + " - locked " + mi);
}
}
}
print.println();
}
private static void printThread(PrintWriter print, ThreadInfo ti) {
print.print("\"" + ti.getThreadName() + "\"" + " Id="
+ ti.getThreadId() + " in " + ti.getThreadState());
if (ti.getLockName() != null) {
print.append(" on lock=").append(ti.getLockName());
}
if (ti.isSuspended()) {
print.append(" (suspended)");
}
if (ti.isInNative()) {
print.append(" (running in native)");
}
print.println();
if (ti.getLockOwnerName() != null) {
print.println(INDENT + " owned by " + ti.getLockOwnerName() + " Id="
+ ti.getLockOwnerId());
}
}
private static void printLockInfo(PrintWriter print, LockInfo[] locks,
String tableWaitingForLock,
ArrayList<String> tableExclusiveLocks,
ArrayList<String> tableSharedLocksMap) {
print.println(INDENT + "Locked synchronizers: count = " + locks.length);
for (LockInfo li : locks) {
print.println(INDENT + " - " + li);
}
if (tableWaitingForLock != null) {
print.println(INDENT + "Waiting for table: " + tableWaitingForLock);
}
if (tableExclusiveLocks != null) {
print.println(INDENT + "Exclusive table locks: count = " + tableExclusiveLocks.size());
for (String name : tableExclusiveLocks) {
print.println(INDENT + " - " + name);
}
}
if (tableSharedLocksMap != null) {
print.println(INDENT + "Shared table locks: count = " + tableSharedLocksMap.size());
for (String name : tableSharedLocksMap) {
print.println(INDENT + " - " + name);
}
}
print.println();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ToChar.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: Daniel Gredler
*/
package org.h2.util;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Currency;
import java.util.Locale;
import java.util.TimeZone;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.value.Value;
import org.h2.value.ValueTimestampTimeZone;
/**
* Emulates Oracle's TO_CHAR function.
*/
public class ToChar {
/**
* The beginning of the Julian calendar.
*/
static final int JULIAN_EPOCH = -2_440_588;
private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,
5, 4, 1 };
private static final String[] ROMAN_NUMERALS = { "M", "CM", "D", "CD", "C", "XC",
"L", "XL", "X", "IX", "V", "IV", "I" };
/**
* The month field.
*/
static final int MONTHS = 0;
/**
* The month field (short form).
*/
static final int SHORT_MONTHS = 1;
/**
* The weekday field.
*/
static final int WEEKDAYS = 2;
/**
* The weekday field (short form).
*/
static final int SHORT_WEEKDAYS = 3;
/**
* The AM / PM field.
*/
static final int AM_PM = 4;
private static volatile String[][] NAMES;
private ToChar() {
// utility class
}
/**
* Emulates Oracle's TO_CHAR(number) function.
*
* <p><table border="1">
* <th><td>Input</td>
* <td>Output</td>
* <td>Closest {@link DecimalFormat} Equivalent</td></th>
* <tr><td>,</td>
* <td>Grouping separator.</td>
* <td>,</td></tr>
* <tr><td>.</td>
* <td>Decimal separator.</td>
* <td>.</td></tr>
* <tr><td>$</td>
* <td>Leading dollar sign.</td>
* <td>$</td></tr>
* <tr><td>0</td>
* <td>Leading or trailing zeroes.</td>
* <td>0</td></tr>
* <tr><td>9</td>
* <td>Digit.</td>
* <td>#</td></tr>
* <tr><td>B</td>
* <td>Blanks integer part of a fixed point number less than 1.</td>
* <td>#</td></tr>
* <tr><td>C</td>
* <td>ISO currency symbol.</td>
* <td>\u00A4</td></tr>
* <tr><td>D</td>
* <td>Local decimal separator.</td>
* <td>.</td></tr>
* <tr><td>EEEE</td>
* <td>Returns a value in scientific notation.</td>
* <td>E</td></tr>
* <tr><td>FM</td>
* <td>Returns values with no leading or trailing spaces.</td>
* <td>None.</td></tr>
* <tr><td>G</td>
* <td>Local grouping separator.</td>
* <td>,</td></tr>
* <tr><td>L</td>
* <td>Local currency symbol.</td>
* <td>\u00A4</td></tr>
* <tr><td>MI</td>
* <td>Negative values get trailing minus sign,
* positive get trailing space.</td>
* <td>-</td></tr>
* <tr><td>PR</td>
* <td>Negative values get enclosing angle brackets,
* positive get spaces.</td>
* <td>None.</td></tr>
* <tr><td>RN</td>
* <td>Returns values in Roman numerals.</td>
* <td>None.</td></tr>
* <tr><td>S</td>
* <td>Returns values with leading/trailing +/- signs.</td>
* <td>None.</td></tr>
* <tr><td>TM</td>
* <td>Returns smallest number of characters possible.</td>
* <td>None.</td></tr>
* <tr><td>U</td>
* <td>Returns the dual currency symbol.</td>
* <td>None.</td></tr>
* <tr><td>V</td>
* <td>Returns a value multiplied by 10^n.</td>
* <td>None.</td></tr>
* <tr><td>X</td>
* <td>Hex value.</td>
* <td>None.</td></tr>
* </table>
* See also TO_CHAR(number) and number format models
* in the Oracle documentation.
*
* @param number the number to format
* @param format the format pattern to use (if any)
* @param nlsParam the NLS parameter (if any)
* @return the formatted number
*/
public static String toChar(BigDecimal number, String format,
@SuppressWarnings("unused") String nlsParam) {
// short-circuit logic for formats that don't follow common logic below
String formatUp = format != null ? StringUtils.toUpperEnglish(format) : null;
if (formatUp == null || formatUp.equals("TM") || formatUp.equals("TM9")) {
String s = number.toPlainString();
return s.startsWith("0.") ? s.substring(1) : s;
} else if (formatUp.equals("TME")) {
int pow = number.precision() - number.scale() - 1;
number = number.movePointLeft(pow);
return number.toPlainString() + "E" +
(pow < 0 ? '-' : '+') + (Math.abs(pow) < 10 ? "0" : "") + Math.abs(pow);
} else if (formatUp.equals("RN")) {
boolean lowercase = format.startsWith("r");
String rn = StringUtils.pad(toRomanNumeral(number.intValue()), 15, " ", false);
return lowercase ? rn.toLowerCase() : rn;
} else if (formatUp.equals("FMRN")) {
boolean lowercase = format.charAt(2) == 'r';
String rn = toRomanNumeral(number.intValue());
return lowercase ? rn.toLowerCase() : rn;
} else if (formatUp.endsWith("X")) {
return toHex(number, format);
}
String originalFormat = format;
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
char localGrouping = symbols.getGroupingSeparator();
char localDecimal = symbols.getDecimalSeparator();
boolean leadingSign = formatUp.startsWith("S");
if (leadingSign) {
format = format.substring(1);
}
boolean trailingSign = formatUp.endsWith("S");
if (trailingSign) {
format = format.substring(0, format.length() - 1);
}
boolean trailingMinus = formatUp.endsWith("MI");
if (trailingMinus) {
format = format.substring(0, format.length() - 2);
}
boolean angleBrackets = formatUp.endsWith("PR");
if (angleBrackets) {
format = format.substring(0, format.length() - 2);
}
int v = formatUp.indexOf('V');
if (v >= 0) {
int digits = 0;
for (int i = v + 1; i < format.length(); i++) {
char c = format.charAt(i);
if (c == '0' || c == '9') {
digits++;
}
}
number = number.movePointRight(digits);
format = format.substring(0, v) + format.substring(v + 1);
}
Integer power;
if (format.endsWith("EEEE")) {
power = number.precision() - number.scale() - 1;
number = number.movePointLeft(power);
format = format.substring(0, format.length() - 4);
} else {
power = null;
}
int maxLength = 1;
boolean fillMode = !formatUp.startsWith("FM");
if (!fillMode) {
format = format.substring(2);
}
// blanks flag doesn't seem to actually do anything
format = format.replaceAll("[Bb]", "");
// if we need to round the number to fit into the format specified,
// go ahead and do that first
int separator = findDecimalSeparator(format);
int formatScale = calculateScale(format, separator);
if (formatScale < number.scale()) {
number = number.setScale(formatScale, BigDecimal.ROUND_HALF_UP);
}
// any 9s to the left of the decimal separator but to the right of a
// 0 behave the same as a 0, e.g. "09999.99" -> "00000.99"
for (int i = format.indexOf('0'); i >= 0 && i < separator; i++) {
if (format.charAt(i) == '9') {
format = format.substring(0, i) + "0" + format.substring(i + 1);
}
}
StringBuilder output = new StringBuilder();
String unscaled = (number.abs().compareTo(BigDecimal.ONE) < 0 ?
zeroesAfterDecimalSeparator(number) : "") +
number.unscaledValue().abs().toString();
// start at the decimal point and fill in the numbers to the left,
// working our way from right to left
int i = separator - 1;
int j = unscaled.length() - number.scale() - 1;
for (; i >= 0; i--) {
char c = format.charAt(i);
maxLength++;
if (c == '9' || c == '0') {
if (j >= 0) {
char digit = unscaled.charAt(j);
output.insert(0, digit);
j--;
} else if (c == '0' && power == null) {
output.insert(0, '0');
}
} else if (c == ',') {
// only add the grouping separator if we have more numbers
if (j >= 0 || (i > 0 && format.charAt(i - 1) == '0')) {
output.insert(0, c);
}
} else if (c == 'G' || c == 'g') {
// only add the grouping separator if we have more numbers
if (j >= 0 || (i > 0 && format.charAt(i - 1) == '0')) {
output.insert(0, localGrouping);
}
} else if (c == 'C' || c == 'c') {
Currency currency = Currency.getInstance(Locale.getDefault());
output.insert(0, currency.getCurrencyCode());
maxLength += 6;
} else if (c == 'L' || c == 'l' || c == 'U' || c == 'u') {
Currency currency = Currency.getInstance(Locale.getDefault());
output.insert(0, currency.getSymbol());
maxLength += 9;
} else if (c == '$') {
Currency currency = Currency.getInstance(Locale.getDefault());
String cs = currency.getSymbol();
output.insert(0, cs);
} else {
throw DbException.get(
ErrorCode.INVALID_TO_CHAR_FORMAT, originalFormat);
}
}
// if the format (to the left of the decimal point) was too small
// to hold the number, return a big "######" string
if (j >= 0) {
return StringUtils.pad("", format.length() + 1, "#", true);
}
if (separator < format.length()) {
// add the decimal point
maxLength++;
char pt = format.charAt(separator);
if (pt == 'd' || pt == 'D') {
output.append(localDecimal);
} else {
output.append(pt);
}
// start at the decimal point and fill in the numbers to the right,
// working our way from left to right
i = separator + 1;
j = unscaled.length() - number.scale();
for (; i < format.length(); i++) {
char c = format.charAt(i);
maxLength++;
if (c == '9' || c == '0') {
if (j < unscaled.length()) {
char digit = unscaled.charAt(j);
output.append(digit);
j++;
} else {
if (c == '0' || fillMode) {
output.append('0');
}
}
} else {
throw DbException.get(
ErrorCode.INVALID_TO_CHAR_FORMAT, originalFormat);
}
}
}
addSign(output, number.signum(), leadingSign, trailingSign,
trailingMinus, angleBrackets, fillMode);
if (power != null) {
output.append('E');
output.append(power < 0 ? '-' : '+');
output.append(Math.abs(power) < 10 ? "0" : "");
output.append(Math.abs(power));
}
if (fillMode) {
if (power != null) {
output.insert(0, ' ');
} else {
while (output.length() < maxLength) {
output.insert(0, ' ');
}
}
}
return output.toString();
}
private static String zeroesAfterDecimalSeparator(BigDecimal number) {
final String numberStr = number.toPlainString();
final int idx = numberStr.indexOf('.');
if (idx < 0) {
return "";
}
int i = idx + 1;
boolean allZeroes = true;
for (; i < numberStr.length(); i++) {
if (numberStr.charAt(i) != '0') {
allZeroes = false;
break;
}
}
final char[] zeroes = new char[allZeroes ? numberStr.length() - idx - 1: i - 1 - idx];
Arrays.fill(zeroes, '0');
return String.valueOf(zeroes);
}
private static void addSign(StringBuilder output, int signum,
boolean leadingSign, boolean trailingSign, boolean trailingMinus,
boolean angleBrackets, boolean fillMode) {
if (angleBrackets) {
if (signum < 0) {
output.insert(0, '<');
output.append('>');
} else if (fillMode) {
output.insert(0, ' ');
output.append(' ');
}
} else {
String sign;
if (signum == 0) {
sign = "";
} else if (signum < 0) {
sign = "-";
} else {
if (leadingSign || trailingSign) {
sign = "+";
} else if (fillMode) {
sign = " ";
} else {
sign = "";
}
}
if (trailingMinus || trailingSign) {
output.append(sign);
} else {
output.insert(0, sign);
}
}
}
private static int findDecimalSeparator(String format) {
int index = format.indexOf('.');
if (index == -1) {
index = format.indexOf('D');
if (index == -1) {
index = format.indexOf('d');
if (index == -1) {
index = format.length();
}
}
}
return index;
}
private static int calculateScale(String format, int separator) {
int scale = 0;
for (int i = separator; i < format.length(); i++) {
char c = format.charAt(i);
if (c == '0' || c == '9') {
scale++;
}
}
return scale;
}
private static String toRomanNumeral(int number) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < ROMAN_VALUES.length; i++) {
int value = ROMAN_VALUES[i];
String numeral = ROMAN_NUMERALS[i];
while (number >= value) {
result.append(numeral);
number -= value;
}
}
return result.toString();
}
private static String toHex(BigDecimal number, String format) {
boolean fillMode = !StringUtils.toUpperEnglish(format).startsWith("FM");
boolean uppercase = !format.contains("x");
boolean zeroPadded = format.startsWith("0");
int digits = 0;
for (int i = 0; i < format.length(); i++) {
char c = format.charAt(i);
if (c == '0' || c == 'X' || c == 'x') {
digits++;
}
}
int i = number.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
String hex = Integer.toHexString(i);
if (digits < hex.length()) {
hex = StringUtils.pad("", digits + 1, "#", true);
} else {
if (uppercase) {
hex = StringUtils.toUpperEnglish(hex);
}
if (zeroPadded) {
hex = StringUtils.pad(hex, digits, "0", false);
}
if (fillMode) {
hex = StringUtils.pad(hex, format.length() + 1, " ", false);
}
}
return hex;
}
/**
* Get the date (month / weekday / ...) names.
*
* @param names the field
* @return the names
*/
static String[] getDateNames(int names) {
String[][] result = NAMES;
if (result == null) {
result = new String[5][];
DateFormatSymbols dfs = DateFormatSymbols.getInstance();
result[MONTHS] = dfs.getMonths();
String[] months = dfs.getShortMonths();
for (int i = 0; i < 12; i++) {
String month = months[i];
if (month.endsWith(".")) {
months[i] = month.substring(0, month.length() - 1);
}
}
result[SHORT_MONTHS] = months;
result[WEEKDAYS] = dfs.getWeekdays();
result[SHORT_WEEKDAYS] = dfs.getShortWeekdays();
result[AM_PM] = dfs.getAmPmStrings();
NAMES = result;
}
return result[names];
}
/**
* Returns time zone display name or ID for the specified date-time value.
*
* @param value
* value
* @param tzd
* if {@code true} return TZD (time zone region with Daylight Saving
* Time information included), if {@code false} return TZR (time zone
* region)
* @return time zone display name or ID
*/
private static String getTimeZone(Value value, boolean tzd) {
if (!(value instanceof ValueTimestampTimeZone)) {
TimeZone tz = TimeZone.getDefault();
if (tzd) {
boolean daylight = tz.inDaylightTime(value.getTimestamp());
return tz.getDisplayName(daylight, TimeZone.SHORT);
}
return tz.getID();
}
return DateTimeUtils.timeZoneNameFromOffsetMins(((ValueTimestampTimeZone) value).getTimeZoneOffsetMins());
}
/**
* Emulates Oracle's TO_CHAR(datetime) function.
*
* <p><table border="1">
* <th><td>Input</td>
* <td>Output</td>
* <td>Closest {@link SimpleDateFormat} Equivalent</td></th>
* <tr><td>- / , . ; : "text"</td>
* <td>Reproduced verbatim.</td>
* <td>'text'</td></tr>
* <tr><td>A.D. AD B.C. BC</td>
* <td>Era designator, with or without periods.</td>
* <td>G</td></tr>
* <tr><td>A.M. AM P.M. PM</td>
* <td>AM/PM marker.</td>
* <td>a</td></tr>
* <tr><td>CC SCC</td>
* <td>Century.</td>
* <td>None.</td></tr>
* <tr><td>D</td>
* <td>Day of week.</td>
* <td>u</td></tr>
* <tr><td>DAY</td>
* <td>Name of day.</td>
* <td>EEEE</td></tr>
* <tr><td>DY</td>
* <td>Abbreviated day name.</td>
* <td>EEE</td></tr>
* <tr><td>DD</td>
* <td>Day of month.</td>
* <td>d</td></tr>
* <tr><td>DDD</td>
* <td>Day of year.</td>
* <td>D</td></tr>
* <tr><td>DL</td>
* <td>Long date format.</td>
* <td>EEEE, MMMM d, yyyy</td></tr>
* <tr><td>DS</td>
* <td>Short date format.</td>
* <td>MM/dd/yyyy</td></tr>
* <tr><td>E</td>
* <td>Abbreviated era name (Japanese, Chinese, Thai)</td>
* <td>None.</td></tr>
* <tr><td>EE</td>
* <td>Full era name (Japanese, Chinese, Thai)</td>
* <td>None.</td></tr>
* <tr><td>FF[1-9]</td>
* <td>Fractional seconds.</td>
* <td>S</td></tr>
* <tr><td>FM</td>
* <td>Returns values with no leading or trailing spaces.</td>
* <td>None.</td></tr>
* <tr><td>FX</td>
* <td>Requires exact matches between character data and format model.</td>
* <td>None.</td></tr>
* <tr><td>HH HH12</td>
* <td>Hour in AM/PM (1-12).</td>
* <td>hh</td></tr>
* <tr><td>HH24</td>
* <td>Hour in day (0-23).</td>
* <td>HH</td></tr>
* <tr><td>IW</td>
* <td>Week in year.</td>
* <td>w</td></tr>
* <tr><td>WW</td>
* <td>Week in year.</td>
* <td>w</td></tr>
* <tr><td>W</td>
* <td>Week in month.</td>
* <td>W</td></tr>
* <tr><td>IYYY IYY IY I</td>
* <td>Last 4/3/2/1 digit(s) of ISO year.</td>
* <td>yyyy yyy yy y</td></tr>
* <tr><td>RRRR RR</td>
* <td>Last 4/2 digits of year.</td>
* <td>yyyy yy</td></tr>
* <tr><td>Y,YYY</td>
* <td>Year with comma.</td>
* <td>None.</td></tr>
* <tr><td>YEAR SYEAR</td>
* <td>Year spelled out (S prefixes BC years with minus sign).</td>
* <td>None.</td></tr>
* <tr><td>YYYY SYYYY</td>
* <td>4-digit year (S prefixes BC years with minus sign).</td>
* <td>yyyy</td></tr>
* <tr><td>YYY YY Y</td>
* <td>Last 3/2/1 digit(s) of year.</td>
* <td>yyy yy y</td></tr>
* <tr><td>J</td>
* <td>Julian day (number of days since January 1, 4712 BC).</td>
* <td>None.</td></tr>
* <tr><td>MI</td>
* <td>Minute in hour.</td>
* <td>mm</td></tr>
* <tr><td>MM</td>
* <td>Month in year.</td>
* <td>MM</td></tr>
* <tr><td>MON</td>
* <td>Abbreviated name of month.</td>
* <td>MMM</td></tr>
* <tr><td>MONTH</td>
* <td>Name of month, padded with spaces.</td>
* <td>MMMM</td></tr>
* <tr><td>RM</td>
* <td>Roman numeral month.</td>
* <td>None.</td></tr>
* <tr><td>Q</td>
* <td>Quarter of year.</td>
* <td>None.</td></tr>
* <tr><td>SS</td>
* <td>Seconds in minute.</td>
* <td>ss</td></tr>
* <tr><td>SSSSS</td>
* <td>Seconds in day.</td>
* <td>None.</td></tr>
* <tr><td>TS</td>
* <td>Short time format.</td>
* <td>h:mm:ss aa</td></tr>
* <tr><td>TZD</td>
* <td>Daylight savings time zone abbreviation.</td>
* <td>z</td></tr>
* <tr><td>TZR</td>
* <td>Time zone region information.</td>
* <td>zzzz</td></tr>
* <tr><td>X</td>
* <td>Local radix character.</td>
* <td>None.</td></tr>
* </table>
* <p>
* See also TO_CHAR(datetime) and datetime format models
* in the Oracle documentation.
*
* @param value the date-time value to format
* @param format the format pattern to use (if any)
* @param nlsParam the NLS parameter (if any)
* @return the formatted timestamp
*/
public static String toCharDateTime(Value value, String format, @SuppressWarnings("unused") String nlsParam) {
long[] a = DateTimeUtils.dateAndTimeFromValue(value);
long dateValue = a[0];
long timeNanos = a[1];
int year = DateTimeUtils.yearFromDateValue(dateValue);
int monthOfYear = DateTimeUtils.monthFromDateValue(dateValue);
int dayOfMonth = DateTimeUtils.dayFromDateValue(dateValue);
int posYear = Math.abs(year);
long second = timeNanos / 1_000_000_000;
int nanos = (int) (timeNanos - second * 1_000_000_000);
int minute = (int) (second / 60);
second -= minute * 60;
int hour = minute / 60;
minute -= hour * 60;
int h12 = (hour + 11) % 12 + 1;
boolean isAM = hour < 12;
if (format == null) {
format = "DD-MON-YY HH.MI.SS.FF PM";
}
StringBuilder output = new StringBuilder();
boolean fillMode = true;
for (int i = 0; i < format.length();) {
Capitalization cap;
// AD / BC
if ((cap = containsAt(format, i, "A.D.", "B.C.")) != null) {
String era = year > 0 ? "A.D." : "B.C.";
output.append(cap.apply(era));
i += 4;
} else if ((cap = containsAt(format, i, "AD", "BC")) != null) {
String era = year > 0 ? "AD" : "BC";
output.append(cap.apply(era));
i += 2;
// AM / PM
} else if ((cap = containsAt(format, i, "A.M.", "P.M.")) != null) {
String am = isAM ? "A.M." : "P.M.";
output.append(cap.apply(am));
i += 4;
} else if ((cap = containsAt(format, i, "AM", "PM")) != null) {
String am = isAM ? "AM" : "PM";
output.append(cap.apply(am));
i += 2;
// Long/short date/time format
} else if (containsAt(format, i, "DL") != null) {
String day = getDateNames(WEEKDAYS)[DateTimeUtils.getSundayDayOfWeek(dateValue)];
String month = getDateNames(MONTHS)[monthOfYear - 1];
output.append(day).append(", ").append(month).append(' ').append(dayOfMonth).append(", ");
StringUtils.appendZeroPadded(output, 4, posYear);
i += 2;
} else if (containsAt(format, i, "DS") != null) {
StringUtils.appendZeroPadded(output, 2, monthOfYear);
output.append('/');
StringUtils.appendZeroPadded(output, 2, dayOfMonth);
output.append('/');
StringUtils.appendZeroPadded(output, 4, posYear);
i += 2;
} else if (containsAt(format, i, "TS") != null) {
output.append(h12).append(':');
StringUtils.appendZeroPadded(output, 2, minute);
output.append(':');
StringUtils.appendZeroPadded(output, 2, second);
output.append(' ');
output.append(getDateNames(AM_PM)[isAM ? 0 : 1]);
i += 2;
// Day
} else if (containsAt(format, i, "DDD") != null) {
output.append(DateTimeUtils.getDayOfYear(dateValue));
i += 3;
} else if (containsAt(format, i, "DD") != null) {
StringUtils.appendZeroPadded(output, 2, dayOfMonth);
i += 2;
} else if ((cap = containsAt(format, i, "DY")) != null) {
String day = getDateNames(SHORT_WEEKDAYS)[DateTimeUtils.getSundayDayOfWeek(dateValue)];
output.append(cap.apply(day));
i += 2;
} else if ((cap = containsAt(format, i, "DAY")) != null) {
String day = getDateNames(WEEKDAYS)[DateTimeUtils.getSundayDayOfWeek(dateValue)];
if (fillMode) {
day = StringUtils.pad(day, "Wednesday".length(), " ", true);
}
output.append(cap.apply(day));
i += 3;
} else if (containsAt(format, i, "D") != null) {
output.append(DateTimeUtils.getSundayDayOfWeek(dateValue));
i += 1;
} else if (containsAt(format, i, "J") != null) {
output.append(DateTimeUtils.absoluteDayFromDateValue(dateValue) - JULIAN_EPOCH);
i += 1;
// Hours
} else if (containsAt(format, i, "HH24") != null) {
StringUtils.appendZeroPadded(output, 2, hour);
i += 4;
} else if (containsAt(format, i, "HH12") != null) {
StringUtils.appendZeroPadded(output, 2, h12);
i += 4;
} else if (containsAt(format, i, "HH") != null) {
StringUtils.appendZeroPadded(output, 2, h12);
i += 2;
// Minutes
} else if (containsAt(format, i, "MI") != null) {
StringUtils.appendZeroPadded(output, 2, minute);
i += 2;
// Seconds
} else if (containsAt(format, i, "SSSSS") != null) {
int seconds = (int) (timeNanos / 1_000_000_000);
output.append(seconds);
i += 5;
} else if (containsAt(format, i, "SS") != null) {
StringUtils.appendZeroPadded(output, 2, second);
i += 2;
// Fractional seconds
} else if (containsAt(format, i, "FF1", "FF2",
"FF3", "FF4", "FF5", "FF6", "FF7", "FF8", "FF9") != null) {
int x = format.charAt(i + 2) - '0';
int ff = (int) (nanos * Math.pow(10, x - 9));
StringUtils.appendZeroPadded(output, x, ff);
i += 3;
} else if (containsAt(format, i, "FF") != null) {
StringUtils.appendZeroPadded(output, 9, nanos);
i += 2;
// Time zone
} else if (containsAt(format, i, "TZR") != null) {
output.append(getTimeZone(value, false));
i += 3;
} else if (containsAt(format, i, "TZD") != null) {
output.append(getTimeZone(value, true));
i += 3;
// Week
} else if (containsAt(format, i, "IW", "WW") != null) {
output.append(DateTimeUtils.getWeekOfYear(dateValue, 0, 1));
i += 2;
} else if (containsAt(format, i, "W") != null) {
int w = 1 + dayOfMonth / 7;
output.append(w);
i += 1;
// Year
} else if (containsAt(format, i, "Y,YYY") != null) {
output.append(new DecimalFormat("#,###").format(posYear));
i += 5;
} else if (containsAt(format, i, "SYYYY") != null) {
// Should be <= 0, but Oracle prints negative years with off-by-one difference
if (year < 0) {
output.append('-');
}
StringUtils.appendZeroPadded(output, 4, posYear);
i += 5;
} else if (containsAt(format, i, "YYYY", "RRRR") != null) {
StringUtils.appendZeroPadded(output, 4, posYear);
i += 4;
} else if (containsAt(format, i, "IYYY") != null) {
StringUtils.appendZeroPadded(output, 4, Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)));
i += 4;
} else if (containsAt(format, i, "YYY") != null) {
StringUtils.appendZeroPadded(output, 3, posYear % 1000);
i += 3;
} else if (containsAt(format, i, "IYY") != null) {
StringUtils.appendZeroPadded(output, 3, Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)) % 1000);
i += 3;
} else if (containsAt(format, i, "YY", "RR") != null) {
StringUtils.appendZeroPadded(output, 2, posYear % 100);
i += 2;
} else if (containsAt(format, i, "IY") != null) {
StringUtils.appendZeroPadded(output, 2, Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)) % 100);
i += 2;
} else if (containsAt(format, i, "Y") != null) {
output.append(posYear % 10);
i += 1;
} else if (containsAt(format, i, "I") != null) {
output.append(Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)) % 10);
i += 1;
// Month / quarter
} else if ((cap = containsAt(format, i, "MONTH")) != null) {
String month = getDateNames(MONTHS)[monthOfYear - 1];
if (fillMode) {
month = StringUtils.pad(month, "September".length(), " ", true);
}
output.append(cap.apply(month));
i += 5;
} else if ((cap = containsAt(format, i, "MON")) != null) {
String month = getDateNames(SHORT_MONTHS)[monthOfYear - 1];
output.append(cap.apply(month));
i += 3;
} else if (containsAt(format, i, "MM") != null) {
StringUtils.appendZeroPadded(output, 2, monthOfYear);
i += 2;
} else if ((cap = containsAt(format, i, "RM")) != null) {
output.append(cap.apply(toRomanNumeral(monthOfYear)));
i += 2;
} else if (containsAt(format, i, "Q") != null) {
int q = 1 + ((monthOfYear - 1) / 3);
output.append(q);
i += 1;
// Local radix character
} else if (containsAt(format, i, "X") != null) {
char c = DecimalFormatSymbols.getInstance().getDecimalSeparator();
output.append(c);
i += 1;
// Format modifiers
} else if (containsAt(format, i, "FM") != null) {
fillMode = !fillMode;
i += 2;
} else if (containsAt(format, i, "FX") != null) {
i += 2;
// Literal text
} else if (containsAt(format, i, "\"") != null) {
for (i = i + 1; i < format.length(); i++) {
char c = format.charAt(i);
if (c != '"') {
output.append(c);
} else {
i++;
break;
}
}
} else if (format.charAt(i) == '-'
|| format.charAt(i) == '/'
|| format.charAt(i) == ','
|| format.charAt(i) == '.'
|| format.charAt(i) == ';'
|| format.charAt(i) == ':'
|| format.charAt(i) == ' ') {
output.append(format.charAt(i));
i += 1;
// Anything else
} else {
throw DbException.get(ErrorCode.INVALID_TO_CHAR_FORMAT, format);
}
}
return output.toString();
}
/**
* Returns a capitalization strategy if the specified string contains any of
* the specified substrings at the specified index. The capitalization
* strategy indicates the casing of the substring that was found. If none of
* the specified substrings are found, this method returns <code>null</code>
* .
*
* @param s the string to check
* @param index the index to check at
* @param substrings the substrings to check for within the string
* @return a capitalization strategy if the specified string contains any of
* the specified substrings at the specified index,
* <code>null</code> otherwise
*/
private static Capitalization containsAt(String s, int index,
String... substrings) {
for (String substring : substrings) {
if (index + substring.length() <= s.length()) {
boolean found = true;
Boolean up1 = null;
Boolean up2 = null;
for (int i = 0; i < substring.length(); i++) {
char c1 = s.charAt(index + i);
char c2 = substring.charAt(i);
if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) {
found = false;
break;
} else if (Character.isLetter(c1)) {
if (up1 == null) {
up1 = Character.isUpperCase(c1);
} else if (up2 == null) {
up2 = Character.isUpperCase(c1);
}
}
}
if (found) {
return Capitalization.toCapitalization(up1, up2);
}
}
}
return null;
}
/** Represents a capitalization / casing strategy. */
public enum Capitalization {
/**
* All letters are uppercased.
*/
UPPERCASE,
/**
* All letters are lowercased.
*/
LOWERCASE,
/**
* The string is capitalized (first letter uppercased, subsequent
* letters lowercased).
*/
CAPITALIZE;
/**
* Returns the capitalization / casing strategy which should be used
* when the first and second letters have the specified casing.
*
* @param up1 whether or not the first letter is uppercased
* @param up2 whether or not the second letter is uppercased
* @return the capitalization / casing strategy which should be used
* when the first and second letters have the specified casing
*/
static Capitalization toCapitalization(Boolean up1, Boolean up2) {
if (up1 == null) {
return Capitalization.CAPITALIZE;
} else if (up2 == null) {
return up1 ? Capitalization.UPPERCASE : Capitalization.LOWERCASE;
} else if (up1) {
return up2 ? Capitalization.UPPERCASE : Capitalization.CAPITALIZE;
} else {
return Capitalization.LOWERCASE;
}
}
/**
* Applies this capitalization strategy to the specified string.
*
* @param s the string to apply this strategy to
* @return the resultant string
*/
public String apply(String s) {
if (s == null || s.isEmpty()) {
return s;
}
switch (this) {
case UPPERCASE:
return StringUtils.toUpperEnglish(s);
case LOWERCASE:
return StringUtils.toLowerEnglish(s);
case CAPITALIZE:
return Character.toUpperCase(s.charAt(0)) +
(s.length() > 1 ? StringUtils.toLowerEnglish(s).substring(1) : "");
default:
throw new IllegalArgumentException(
"Unknown capitalization strategy: " + this);
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ToDateParser.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: Daniel Gredler
*/
package org.h2.util;
import static java.lang.String.format;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueTimestampTimeZone;
/**
* Emulates Oracle's TO_DATE function.<br>
* This class holds and handles the input data form the TO_DATE-method
*/
public class ToDateParser {
private final String unmodifiedInputStr;
private final String unmodifiedFormatStr;
private final ConfigParam functionName;
private String inputStr;
private String formatStr;
private boolean doyValid = false, absoluteDayValid = false,
hour12Valid = false,
timeZoneHMValid = false;
private boolean bc;
private long absoluteDay;
private int year, month, day = 1;
private int dayOfYear;
private int hour, minute, second, nanos;
private int hour12;
private boolean isAM = true;
private TimeZone timeZone;
private int timeZoneHour, timeZoneMinute;
private int currentYear, currentMonth;
/**
* @param input the input date with the date-time info
* @param format the format of date-time info
* @param functionName one of [TO_DATE, TO_TIMESTAMP] (both share the same
* code)
*/
private ToDateParser(ConfigParam functionName, String input, String format) {
this.functionName = functionName;
inputStr = input.trim();
// Keep a copy
unmodifiedInputStr = inputStr;
if (format == null || format.isEmpty()) {
// default Oracle format.
formatStr = functionName.getDefaultFormatStr();
} else {
formatStr = format.trim();
}
// Keep a copy
unmodifiedFormatStr = formatStr;
}
private static ToDateParser getTimestampParser(ConfigParam param, String input, String format) {
ToDateParser result = new ToDateParser(param, input, format);
parse(result);
return result;
}
private ValueTimestamp getResultingValue() {
long dateValue;
if (absoluteDayValid) {
dateValue = DateTimeUtils.dateValueFromAbsoluteDay(absoluteDay);
} else {
int year = this.year;
if (year == 0) {
year = getCurrentYear();
}
if (bc) {
year = 1 - year;
}
if (doyValid) {
dateValue = DateTimeUtils.dateValueFromAbsoluteDay(
DateTimeUtils.absoluteDayFromYear(year) + dayOfYear - 1);
} else {
int month = this.month;
if (month == 0) {
// Oracle uses current month as default
month = getCurrentMonth();
}
dateValue = DateTimeUtils.dateValue(year, month, day);
}
}
int hour;
if (hour12Valid) {
hour = hour12 % 12;
if (!isAM) {
hour += 12;
}
} else {
hour = this.hour;
}
long timeNanos = ((((hour * 60) + minute) * 60) + second) * 1_000_000_000L + nanos;
return ValueTimestamp.fromDateValueAndNanos(dateValue, timeNanos);
}
private ValueTimestampTimeZone getResultingValueWithTimeZone() {
ValueTimestamp ts = getResultingValue();
long dateValue = ts.getDateValue();
short offset;
if (timeZoneHMValid) {
offset = (short) (timeZoneHour * 60 + ((timeZoneHour >= 0) ? timeZoneMinute : -timeZoneMinute));
} else {
TimeZone timeZone = this.timeZone;
if (timeZone == null) {
timeZone = TimeZone.getDefault();
}
long millis = DateTimeUtils.convertDateTimeValueToMillis(timeZone, dateValue, nanos / 1_000_000);
offset = (short) (timeZone.getOffset(millis) / 60_000);
}
return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, ts.getTimeNanos(), offset);
}
String getInputStr() {
return inputStr;
}
String getFormatStr() {
return formatStr;
}
String getFunctionName() {
return functionName.name();
}
private void queryCurrentYearAndMonth() {
GregorianCalendar gc = DateTimeUtils.getCalendar();
gc.setTimeInMillis(System.currentTimeMillis());
currentYear = gc.get(Calendar.YEAR);
currentMonth = gc.get(Calendar.MONTH) + 1;
}
int getCurrentYear() {
if (currentYear == 0) {
queryCurrentYearAndMonth();
}
return currentYear;
}
int getCurrentMonth() {
if (currentMonth == 0) {
queryCurrentYearAndMonth();
}
return currentMonth;
}
void setAbsoluteDay(int absoluteDay) {
doyValid = false;
absoluteDayValid = true;
this.absoluteDay = absoluteDay;
}
void setBC(boolean bc) {
doyValid = false;
absoluteDayValid = false;
this.bc = bc;
}
void setYear(int year) {
doyValid = false;
absoluteDayValid = false;
this.year = year;
}
void setMonth(int month) {
doyValid = false;
absoluteDayValid = false;
this.month = month;
if (year == 0) {
year = 1970;
}
}
void setDay(int day) {
doyValid = false;
absoluteDayValid = false;
this.day = day;
if (year == 0) {
year = 1970;
}
}
void setDayOfYear(int dayOfYear) {
doyValid = true;
absoluteDayValid = false;
this.dayOfYear = dayOfYear;
}
void setHour(int hour) {
hour12Valid = false;
this.hour = hour;
}
void setMinute(int minute) {
this.minute = minute;
}
void setSecond(int second) {
this.second = second;
}
void setNanos(int nanos) {
this.nanos = nanos;
}
void setAmPm(boolean isAM) {
hour12Valid = true;
this.isAM = isAM;
}
void setHour12(int hour12) {
hour12Valid = true;
this.hour12 = hour12;
}
void setTimeZone(TimeZone timeZone) {
timeZoneHMValid = false;
this.timeZone = timeZone;
}
void setTimeZoneHour(int timeZoneHour) {
timeZoneHMValid = true;
this.timeZoneHour = timeZoneHour;
}
void setTimeZoneMinute(int timeZoneMinute) {
timeZoneHMValid = true;
this.timeZoneMinute = timeZoneMinute;
}
private boolean hasToParseData() {
return formatStr.length() > 0;
}
private void removeFirstChar() {
if (!formatStr.isEmpty()) {
formatStr = formatStr.substring(1);
}
if (!inputStr.isEmpty()) {
inputStr = inputStr.substring(1);
}
}
private static ToDateParser parse(ToDateParser p) {
while (p.hasToParseData()) {
List<ToDateTokenizer.FormatTokenEnum> tokenList =
ToDateTokenizer.FormatTokenEnum.getTokensInQuestion(p.getFormatStr());
if (tokenList.isEmpty()) {
p.removeFirstChar();
continue;
}
boolean foundAnToken = false;
for (ToDateTokenizer.FormatTokenEnum token : tokenList) {
if (token.parseFormatStrWithToken(p)) {
foundAnToken = true;
break;
}
}
if (!foundAnToken) {
p.removeFirstChar();
}
}
return p;
}
/**
* Remove a token from a string.
*
* @param inputFragmentStr the input fragment
* @param formatFragment the format fragment
*/
void remove(String inputFragmentStr, String formatFragment) {
if (inputFragmentStr != null && inputStr.length() >= inputFragmentStr.length()) {
inputStr = inputStr.substring(inputFragmentStr.length());
}
if (formatFragment != null && formatStr.length() >= formatFragment.length()) {
formatStr = formatStr.substring(formatFragment.length());
}
}
@Override
public String toString() {
int inputStrLen = inputStr.length();
int orgInputLen = unmodifiedInputStr.length();
int currentInputPos = orgInputLen - inputStrLen;
int restInputLen = inputStrLen <= 0 ? inputStrLen : inputStrLen - 1;
int orgFormatLen = unmodifiedFormatStr.length();
int currentFormatPos = orgFormatLen - formatStr.length();
return format("\n %s('%s', '%s')", functionName, unmodifiedInputStr, unmodifiedFormatStr)
+ format("\n %s^%s , %s^ <-- Parsing failed at this point",
format("%" + (functionName.name().length() + currentInputPos) + "s", ""),
restInputLen <= 0 ? "" : format("%" + restInputLen + "s", ""),
currentFormatPos <= 0 ? "" : format("%" + currentFormatPos + "s", ""));
}
/**
* Parse a string as a timestamp with the given format.
*
* @param input the input
* @param format the format
* @return the timestamp
*/
public static ValueTimestamp toTimestamp(String input, String format) {
ToDateParser parser = getTimestampParser(ConfigParam.TO_TIMESTAMP, input, format);
return parser.getResultingValue();
}
/**
* Parse a string as a timestamp with the given format.
*
* @param input the input
* @param format the format
* @return the timestamp
*/
public static ValueTimestampTimeZone toTimestampTz(String input, String format) {
ToDateParser parser = getTimestampParser(ConfigParam.TO_TIMESTAMP_TZ, input, format);
return parser.getResultingValueWithTimeZone();
}
/**
* Parse a string as a date with the given format.
*
* @param input the input
* @param format the format
* @return the date as a timestamp
*/
public static ValueTimestamp toDate(String input, String format) {
ToDateParser parser = getTimestampParser(ConfigParam.TO_DATE, input, format);
return parser.getResultingValue();
}
/**
* The configuration of the date parser.
*/
private enum ConfigParam {
TO_DATE("DD MON YYYY"),
TO_TIMESTAMP("DD MON YYYY HH:MI:SS"),
TO_TIMESTAMP_TZ("DD MON YYYY HH:MI:SS TZR");
private final String defaultFormatStr;
ConfigParam(String defaultFormatStr) {
this.defaultFormatStr = defaultFormatStr;
}
String getDefaultFormatStr() {
return defaultFormatStr;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ToDateTokenizer.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: Daniel Gredler
*/
package org.h2.util;
import static java.lang.String.format;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Emulates Oracle's TO_DATE function. This class knows all about the
* TO_DATE-format conventions and how to parse the corresponding data.
*/
class ToDateTokenizer {
/**
* The pattern for a number.
*/
static final Pattern PATTERN_INLINE = Pattern.compile("(\"[^\"]*\")");
/**
* The pattern for a number.
*/
static final Pattern PATTERN_NUMBER = Pattern.compile("^([+-]?[0-9]+)");
/**
* The pattern for four digits (typically a year).
*/
static final Pattern PATTERN_FOUR_DIGITS = Pattern
.compile("^([+-]?[0-9]{4})");
/**
* The pattern 2-4 digits (e.g. for RRRR).
*/
static final Pattern PATTERN_TWO_TO_FOUR_DIGITS = Pattern
.compile("^([+-]?[0-9]{2,4})");
/**
* The pattern for three digits.
*/
static final Pattern PATTERN_THREE_DIGITS = Pattern
.compile("^([+-]?[0-9]{3})");
/**
* The pattern for two digits.
*/
static final Pattern PATTERN_TWO_DIGITS = Pattern
.compile("^([+-]?[0-9]{2})");
/**
* The pattern for one or two digits.
*/
static final Pattern PATTERN_TWO_DIGITS_OR_LESS = Pattern
.compile("^([+-]?[0-9][0-9]?)");
/**
* The pattern for one digit.
*/
static final Pattern PATTERN_ONE_DIGIT = Pattern.compile("^([+-]?[0-9])");
/**
* The pattern for a fraction (of a second for example).
*/
static final Pattern PATTERN_FF = Pattern.compile("^(FF[0-9]?)",
Pattern.CASE_INSENSITIVE);
/**
* The pattern for "am" or "pm".
*/
static final Pattern PATTERN_AM_PM = Pattern
.compile("^(AM|A\\.M\\.|PM|P\\.M\\.)", Pattern.CASE_INSENSITIVE);
/**
* The pattern for "bc" or "ad".
*/
static final Pattern PATTERN_BC_AD = Pattern
.compile("^(BC|B\\.C\\.|AD|A\\.D\\.)", Pattern.CASE_INSENSITIVE);
/**
* The parslet for a year.
*/
static final YearParslet PARSLET_YEAR = new YearParslet();
/**
* The parslet for a month.
*/
static final MonthParslet PARSLET_MONTH = new MonthParslet();
/**
* The parslet for a day.
*/
static final DayParslet PARSLET_DAY = new DayParslet();
/**
* The parslet for time.
*/
static final TimeParslet PARSLET_TIME = new TimeParslet();
/**
* The inline parslet. E.g. 'YYYY-MM-DD"T"HH24:MI:SS"Z"' where "T" and "Z"
* are inlined
*/
static final InlineParslet PARSLET_INLINE = new InlineParslet();
/**
* Interface of the classes that can parse a specialized small bit of the
* TO_DATE format-string.
*/
interface ToDateParslet {
/**
* Parse a date part.
*
* @param params the parameters that contains the string
* @param formatTokenEnum the format
* @param formatTokenStr the format string
*/
void parse(ToDateParser params, FormatTokenEnum formatTokenEnum,
String formatTokenStr);
}
/**
* Parslet responsible for parsing year parameter
*/
static class YearParslet implements ToDateParslet {
@Override
public void parse(ToDateParser params, FormatTokenEnum formatTokenEnum,
String formatTokenStr) {
String inputFragmentStr = null;
int dateNr = 0;
switch (formatTokenEnum) {
case SYYYY:
case YYYY:
inputFragmentStr = matchStringOrThrow(PATTERN_FOUR_DIGITS,
params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
// Gregorian calendar does not have a year 0.
// 0 = 0001 BC, -1 = 0002 BC, ... so we adjust
if (dateNr == 0) {
throwException(params, "Year may not be zero");
}
params.setYear(dateNr >= 0 ? dateNr : dateNr + 1);
break;
case YYY:
inputFragmentStr = matchStringOrThrow(PATTERN_THREE_DIGITS,
params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
if (dateNr > 999) {
throwException(params, "Year may have only three digits with specified format");
}
dateNr += (params.getCurrentYear() / 1_000) * 1_000;
// Gregorian calendar does not have a year 0.
// 0 = 0001 BC, -1 = 0002 BC, ... so we adjust
params.setYear(dateNr >= 0 ? dateNr : dateNr + 1);
break;
case RRRR:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_TO_FOUR_DIGITS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
if (inputFragmentStr.length() < 4) {
if (dateNr < 50) {
dateNr += 2000;
} else if (dateNr < 100) {
dateNr += 1900;
}
}
if (dateNr == 0) {
throwException(params, "Year may not be zero");
}
params.setYear(dateNr);
break;
case RR:
int cc = params.getCurrentYear() / 100;
inputFragmentStr = matchStringOrThrow(PATTERN_TWO_DIGITS,
params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr) + cc * 100;
params.setYear(dateNr);
break;
case EE /* NOT supported yet */:
throwException(params, format("token '%s' not supported yet.",
formatTokenEnum.name()));
break;
case E /* NOT supported yet */:
throwException(params, format("token '%s' not supported yet.",
formatTokenEnum.name()));
break;
case YY:
inputFragmentStr = matchStringOrThrow(PATTERN_TWO_DIGITS,
params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
if (dateNr > 99) {
throwException(params, "Year may have only two digits with specified format");
}
dateNr += (params.getCurrentYear() / 100) * 100;
// Gregorian calendar does not have a year 0.
// 0 = 0001 BC, -1 = 0002 BC, ... so we adjust
params.setYear(dateNr >= 0 ? dateNr : dateNr + 1);
break;
case SCC:
case CC:
inputFragmentStr = matchStringOrThrow(PATTERN_TWO_DIGITS,
params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr) * 100;
params.setYear(dateNr);
break;
case Y:
inputFragmentStr = matchStringOrThrow(PATTERN_ONE_DIGIT, params,
formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
if (dateNr > 9) {
throwException(params, "Year may have only two digits with specified format");
}
dateNr += (params.getCurrentYear() / 10) * 10;
// Gregorian calendar does not have a year 0.
// 0 = 0001 BC, -1 = 0002 BC, ... so we adjust
params.setYear(dateNr >= 0 ? dateNr : dateNr + 1);
break;
case BC_AD:
inputFragmentStr = matchStringOrThrow(PATTERN_BC_AD, params,
formatTokenEnum);
params.setBC(inputFragmentStr.toUpperCase().startsWith("B"));
break;
default:
throw new IllegalArgumentException(format(
"%s: Internal Error. Unhandled case: %s",
this.getClass().getSimpleName(), formatTokenEnum));
}
params.remove(inputFragmentStr, formatTokenStr);
}
}
/**
* Parslet responsible for parsing month parameter
*/
static class MonthParslet implements ToDateParslet {
private static final String[] ROMAN_MONTH = { "I", "II", "III", "IV",
"V", "VI", "VII", "VIII", "IX", "X", "XI", "XII" };
@Override
public void parse(ToDateParser params, FormatTokenEnum formatTokenEnum,
String formatTokenStr) {
String s = params.getInputStr();
String inputFragmentStr = null;
int dateNr = 0;
switch (formatTokenEnum) {
case MONTH:
inputFragmentStr = setByName(params, ToChar.MONTHS);
break;
case Q /* NOT supported yet */:
throwException(params, format("token '%s' not supported yet.",
formatTokenEnum.name()));
break;
case MON:
inputFragmentStr = setByName(params, ToChar.SHORT_MONTHS);
break;
case MM:
// Note: In Calendar Month go from 0 - 11
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setMonth(dateNr);
break;
case RM:
dateNr = 0;
for (String monthName : ROMAN_MONTH) {
dateNr++;
int len = monthName.length();
if (s.length() >= len && monthName
.equalsIgnoreCase(s.substring(0, len))) {
params.setMonth(dateNr + 1);
inputFragmentStr = monthName;
break;
}
}
if (inputFragmentStr == null || inputFragmentStr.isEmpty()) {
throwException(params,
format("Issue happened when parsing token '%s'. "
+ "Expected one of: %s",
formatTokenEnum.name(),
Arrays.toString(ROMAN_MONTH)));
}
break;
default:
throw new IllegalArgumentException(format(
"%s: Internal Error. Unhandled case: %s",
this.getClass().getSimpleName(), formatTokenEnum));
}
params.remove(inputFragmentStr, formatTokenStr);
}
}
/**
* Parslet responsible for parsing day parameter
*/
static class DayParslet implements ToDateParslet {
@Override
public void parse(ToDateParser params, FormatTokenEnum formatTokenEnum,
String formatTokenStr) {
String inputFragmentStr = null;
int dateNr = 0;
switch (formatTokenEnum) {
case DDD:
inputFragmentStr = matchStringOrThrow(PATTERN_NUMBER, params,
formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setDayOfYear(dateNr);
break;
case DD:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setDay(dateNr);
break;
case D:
inputFragmentStr = matchStringOrThrow(PATTERN_ONE_DIGIT, params,
formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setDay(dateNr);
break;
case DAY:
inputFragmentStr = setByName(params, ToChar.WEEKDAYS);
break;
case DY:
inputFragmentStr = setByName(params, ToChar.SHORT_WEEKDAYS);
break;
case J:
inputFragmentStr = matchStringOrThrow(PATTERN_NUMBER, params,
formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setAbsoluteDay(dateNr + ToChar.JULIAN_EPOCH);
break;
default:
throw new IllegalArgumentException(format(
"%s: Internal Error. Unhandled case: %s",
this.getClass().getSimpleName(), formatTokenEnum));
}
params.remove(inputFragmentStr, formatTokenStr);
}
}
/**
* Parslet responsible for parsing time parameter
*/
static class TimeParslet implements ToDateParslet {
@Override
public void parse(ToDateParser params, FormatTokenEnum formatTokenEnum,
String formatTokenStr) {
String inputFragmentStr = null;
int dateNr = 0;
switch (formatTokenEnum) {
case HH24:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setHour(dateNr);
break;
case HH12:
case HH:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setHour12(dateNr);
break;
case MI:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setMinute(dateNr);
break;
case SS:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setSecond(dateNr);
break;
case SSSSS: {
inputFragmentStr = matchStringOrThrow(PATTERN_NUMBER, params,
formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
int second = dateNr % 60;
dateNr /= 60;
int minute = dateNr % 60;
dateNr /= 60;
int hour = dateNr % 24;
params.setHour(hour);
params.setMinute(minute);
params.setSecond(second);
break;
}
case FF:
inputFragmentStr = matchStringOrThrow(PATTERN_NUMBER, params,
formatTokenEnum);
String paddedRightNrStr = format("%-9s", inputFragmentStr)
.replace(' ', '0');
paddedRightNrStr = paddedRightNrStr.substring(0, 9);
double nineDigits = Double.parseDouble(paddedRightNrStr);
params.setNanos((int) nineDigits);
break;
case AM_PM:
inputFragmentStr = matchStringOrThrow(PATTERN_AM_PM, params,
formatTokenEnum);
if (inputFragmentStr.toUpperCase().startsWith("A")) {
params.setAmPm(true);
} else {
params.setAmPm(false);
}
break;
case TZH:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setTimeZoneHour(dateNr);
break;
case TZM:
inputFragmentStr = matchStringOrThrow(
PATTERN_TWO_DIGITS_OR_LESS, params, formatTokenEnum);
dateNr = Integer.parseInt(inputFragmentStr);
params.setTimeZoneMinute(dateNr);
break;
case TZR:
case TZD:
String tzName = params.getInputStr();
params.setTimeZone(TimeZone.getTimeZone(tzName));
inputFragmentStr = tzName;
break;
default:
throw new IllegalArgumentException(format(
"%s: Internal Error. Unhandled case: %s",
this.getClass().getSimpleName(), formatTokenEnum));
}
params.remove(inputFragmentStr, formatTokenStr);
}
}
/**
* Parslet responsible for parsing year parameter
*/
static class InlineParslet implements ToDateParslet {
@Override
public void parse(ToDateParser params, FormatTokenEnum formatTokenEnum,
String formatTokenStr) {
String inputFragmentStr = null;
switch (formatTokenEnum) {
case INLINE:
inputFragmentStr = formatTokenStr.replace("\"", "");
break;
default:
throw new IllegalArgumentException(format(
"%s: Internal Error. Unhandled case: %s",
this.getClass().getSimpleName(), formatTokenEnum));
}
params.remove(inputFragmentStr, formatTokenStr);
}
}
/**
* Match the pattern, or if not possible throw an exception.
*
* @param p the pattern
* @param params the parameters with the input string
* @param aEnum the pattern name
* @return the matched value
*/
static String matchStringOrThrow(Pattern p, ToDateParser params,
Enum<?> aEnum) {
String s = params.getInputStr();
Matcher matcher = p.matcher(s);
if (!matcher.find()) {
throwException(params, format(
"Issue happened when parsing token '%s'", aEnum.name()));
}
return matcher.group(1);
}
/**
* Set the given field in the calendar.
*
* @param params the parameters with the input string
* @param field the field to set
* @return the matched value
*/
static String setByName(ToDateParser params, int field) {
String inputFragmentStr = null;
String s = params.getInputStr();
String[] values = ToChar.getDateNames(field);
for (int i = 0; i < values.length; i++) {
String dayName = values[i];
if (dayName == null) {
continue;
}
int len = dayName.length();
if (dayName.equalsIgnoreCase(s.substring(0, len))) {
switch (field) {
case ToChar.MONTHS:
case ToChar.SHORT_MONTHS:
params.setMonth(i + 1);
break;
case ToChar.WEEKDAYS:
case ToChar.SHORT_WEEKDAYS:
// TODO
break;
default:
throw new IllegalArgumentException();
}
inputFragmentStr = dayName;
break;
}
}
if (inputFragmentStr == null || inputFragmentStr.isEmpty()) {
throwException(params, format(
"Tried to parse one of '%s' but failed (may be an internal error?)",
Arrays.toString(values)));
}
return inputFragmentStr;
}
/**
* Throw a parse exception.
*
* @param params the parameters with the input string
* @param errorStr the error string
*/
static void throwException(ToDateParser params, String errorStr) {
throw DbException.get(ErrorCode.INVALID_TO_DATE_FORMAT,
params.getFunctionName(),
format(" %s. Details: %s", errorStr, params));
}
/**
* The format tokens.
*/
public enum FormatTokenEnum {
// 4-digit year
YYYY(PARSLET_YEAR),
// 4-digit year with sign (- = B.C.)
SYYYY(PARSLET_YEAR),
// 3-digit year
YYY(PARSLET_YEAR),
// 2-digit year
YY(PARSLET_YEAR),
// Two-digit century with with sign (- = B.C.)
SCC(PARSLET_YEAR),
// Two-digit century.
CC(PARSLET_YEAR),
// 2-digit -> 4-digit year 0-49 -> 20xx , 50-99 -> 19xx
RRRR(PARSLET_YEAR),
// last 2-digit of the year using "current" century value.
RR(PARSLET_YEAR),
// Meridian indicator
BC_AD(PARSLET_YEAR, PATTERN_BC_AD),
// Full Name of month
MONTH(PARSLET_MONTH),
// Abbreviated name of month.
MON(PARSLET_MONTH),
// Month (01-12; JAN = 01).
MM(PARSLET_MONTH),
// Roman numeral month (I-XII; JAN = I).
RM(PARSLET_MONTH),
// Day of year (1-366).
DDD(PARSLET_DAY),
// Name of day.
DAY(PARSLET_DAY),
// Day of month (1-31).
DD(PARSLET_DAY),
// Abbreviated name of day.
DY(PARSLET_DAY), HH24(PARSLET_TIME), HH12(PARSLET_TIME),
// Hour of day (1-12).
HH(PARSLET_TIME),
// Min
MI(PARSLET_TIME),
// Seconds past midnight (0-86399)
SSSSS(PARSLET_TIME), SS(PARSLET_TIME),
// Fractional seconds
FF(PARSLET_TIME, PATTERN_FF),
// Time zone hour.
TZH(PARSLET_TIME),
// Time zone minute.
TZM(PARSLET_TIME),
// Time zone region ID
TZR(PARSLET_TIME),
// Daylight savings information. Example:
// PST (for US/Pacific standard time);
TZD(PARSLET_TIME),
// Meridian indicator
AM_PM(PARSLET_TIME, PATTERN_AM_PM),
// NOT supported yet -
// Full era name (Japanese Imperial, ROC Official,
// and Thai Buddha calendars).
EE(PARSLET_YEAR),
// NOT supported yet -
// Abbreviated era name (Japanese Imperial,
// ROC Official, and Thai Buddha calendars).
E(PARSLET_YEAR), Y(PARSLET_YEAR),
// Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
Q(PARSLET_MONTH),
// Day of week (1-7).
D(PARSLET_DAY),
// NOT supported yet -
// Julian day; the number of days since Jan 1, 4712 BC.
J(PARSLET_DAY),
// Inline text e.g. to_date('2017-04-21T00:00:00Z',
// 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
// where "T" and "Z" are inlined
INLINE(PARSLET_INLINE, PATTERN_INLINE);
private static final List<FormatTokenEnum> EMPTY_LIST = Collections
.emptyList();
private static final Map<Character, List<FormatTokenEnum>> CACHE = new HashMap<>(
FormatTokenEnum.values().length);
private final ToDateParslet toDateParslet;
private final Pattern patternToUse;
/**
* Construct a format token.
*
* @param toDateParslet the date parslet
* @param patternToUse the pattern
*/
FormatTokenEnum(ToDateParslet toDateParslet, Pattern patternToUse) {
this.toDateParslet = toDateParslet;
this.patternToUse = patternToUse;
}
/**
* Construct a format token.
*
* @param toDateParslet the date parslet
*/
FormatTokenEnum(ToDateParslet toDateParslet) {
this.toDateParslet = toDateParslet;
patternToUse = Pattern.compile(format("^(%s)", name()),
Pattern.CASE_INSENSITIVE);
}
/**
* Optimization: Only return a list of {@link FormatTokenEnum} that
* share the same 1st char using the 1st char of the 'to parse'
* formatStr. Or return empty list if no match.
*
* @param formatStr the format string
* @return the list of tokens
*/
static List<FormatTokenEnum> getTokensInQuestion(String formatStr) {
List<FormatTokenEnum> result = EMPTY_LIST;
if (CACHE.size() <= 0) {
initCache();
}
if (formatStr != null && formatStr.length() > 0) {
Character key = Character.toUpperCase(formatStr.charAt(0));
switch (key) {
case '"':
result = new ArrayList<>();
result.add(INLINE);
break;
default:
result = CACHE.get(key);
}
}
if (result == null) {
result = EMPTY_LIST;
}
return result;
}
private static synchronized void initCache() {
if (CACHE.size() <= 0) {
for (FormatTokenEnum token : FormatTokenEnum.values()) {
List<Character> tokenKeys = new ArrayList<>();
if (token.name().contains("_")) {
String[] tokens = token.name().split("_");
for (String tokenLets : tokens) {
tokenKeys.add(tokenLets.toUpperCase().charAt(0));
}
} else {
tokenKeys.add(token.name().toUpperCase().charAt(0));
}
for (Character tokenKey : tokenKeys) {
List<FormatTokenEnum> l = CACHE.get(tokenKey);
if (l == null) {
l = new ArrayList<>(1);
CACHE.put(tokenKey, l);
}
l.add(token);
}
}
}
}
/**
* Parse the format-string with passed token of {@link FormatTokenEnum}.
* If token matches return true, otherwise false.
*
* @param params the parameters
* @return true if it matches
*/
boolean parseFormatStrWithToken(ToDateParser params) {
Matcher matcher = patternToUse.matcher(params.getFormatStr());
boolean foundToken = matcher.find();
if (foundToken) {
String formatTokenStr = matcher.group(1);
toDateParslet.parse(params, this, formatTokenStr);
}
return foundToken;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/Tool.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.SQLException;
import java.util.Properties;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.store.FileLister;
import org.h2.store.fs.FileUtils;
/**
* Command line tools implement the tool interface so that they can be used in
* the H2 Console.
*/
public abstract class Tool {
/**
* The output stream where this tool writes to.
*/
protected PrintStream out = System.out;
private Properties resources;
/**
* Sets the standard output stream.
*
* @param out the new standard output stream
*/
public void setOut(PrintStream out) {
this.out = out;
}
/**
* Run the tool with the given output stream and arguments.
*
* @param args the argument list
*/
public abstract void runTool(String... args) throws SQLException;
/**
* Throw a SQLException saying this command line option is not supported.
*
* @param option the unsupported option
* @return this method never returns normally
*/
protected SQLException showUsageAndThrowUnsupportedOption(String option)
throws SQLException {
showUsage();
throw throwUnsupportedOption(option);
}
/**
* Throw a SQLException saying this command line option is not supported.
*
* @param option the unsupported option
* @return this method never returns normally
*/
protected SQLException throwUnsupportedOption(String option)
throws SQLException {
throw DbException.get(
ErrorCode.FEATURE_NOT_SUPPORTED_1, option).getSQLException();
}
/**
* Print to the output stream that no database files have been found.
*
* @param dir the directory or null
* @param db the database name or null
*/
protected void printNoDatabaseFilesFound(String dir, String db) {
StringBuilder buff;
dir = FileLister.getDir(dir);
if (!FileUtils.isDirectory(dir)) {
buff = new StringBuilder("Directory not found: ");
buff.append(dir);
} else {
buff = new StringBuilder("No database files have been found");
buff.append(" in directory ").append(dir);
if (db != null) {
buff.append(" for the database ").append(db);
}
}
out.println(buff.toString());
}
/**
* Print the usage of the tool. This method reads the description from the
* resource file.
*/
protected void showUsage() {
if (resources == null) {
resources = new Properties();
String resourceName = "/org/h2/res/javadoc.properties";
try {
byte[] buff = Utils.getResource(resourceName);
if (buff != null) {
resources.load(new ByteArrayInputStream(buff));
}
} catch (IOException e) {
out.println("Cannot load " + resourceName);
}
}
String className = getClass().getName();
out.println(resources.get(className));
out.println("Usage: java "+getClass().getName() + " <options>");
out.println(resources.get(className + ".main"));
out.println("See also http://h2database.com/javadoc/" +
className.replace('.', '/') + ".html");
}
/**
* Check if the argument matches the option.
* If the argument starts with this option, but doesn't match,
* then an exception is thrown.
*
* @param arg the argument
* @param option the command line option
* @return true if it matches
*/
public static boolean isOption(String arg, String option) {
if (arg.equals(option)) {
return true;
} else if (arg.startsWith(option)) {
throw DbException.getUnsupportedException(
"expected: " + option + " got: " + arg);
}
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/Utils.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* This utility class contains miscellaneous functions.
*/
public class Utils {
/**
* An 0-size byte array.
*/
public static final byte[] EMPTY_BYTES = {};
/**
* An 0-size int array.
*/
public static final int[] EMPTY_INT_ARRAY = {};
/**
* An 0-size long array.
*/
private static final long[] EMPTY_LONG_ARRAY = {};
private static final int GC_DELAY = 50;
private static final int MAX_GC = 8;
private static long lastGC;
private static final HashMap<String, byte[]> RESOURCES = new HashMap<>();
private Utils() {
// utility class
}
/**
* Calculate the index of the first occurrence of the pattern in the byte
* array, starting with the given index. This methods returns -1 if the
* pattern has not been found, and the start position if the pattern is
* empty.
*
* @param bytes the byte array
* @param pattern the pattern
* @param start the start index from where to search
* @return the index
*/
public static int indexOf(byte[] bytes, byte[] pattern, int start) {
if (pattern.length == 0) {
return start;
}
if (start > bytes.length) {
return -1;
}
int last = bytes.length - pattern.length + 1;
int patternLen = pattern.length;
next:
for (; start < last; start++) {
for (int i = 0; i < patternLen; i++) {
if (bytes[start + i] != pattern[i]) {
continue next;
}
}
return start;
}
return -1;
}
/**
* Calculate the hash code of the given byte array.
*
* @param value the byte array
* @return the hash code
*/
public static int getByteArrayHash(byte[] value) {
int len = value.length;
int h = len;
if (len < 50) {
for (int i = 0; i < len; i++) {
h = 31 * h + value[i];
}
} else {
int step = len / 16;
for (int i = 0; i < 4; i++) {
h = 31 * h + value[i];
h = 31 * h + value[--len];
}
for (int i = 4 + step; i < len; i += step) {
h = 31 * h + value[i];
}
}
return h;
}
/**
* Compare two byte arrays. This method will always loop over all bytes and
* doesn't use conditional operations in the loop to make sure an attacker
* can not use a timing attack when trying out passwords.
*
* @param test the first array
* @param good the second array
* @return true if both byte arrays contain the same bytes
*/
public static boolean compareSecure(byte[] test, byte[] good) {
if ((test == null) || (good == null)) {
return (test == null) && (good == null);
}
int len = test.length;
if (len != good.length) {
return false;
}
if (len == 0) {
return true;
}
// don't use conditional operations inside the loop
int bits = 0;
for (int i = 0; i < len; i++) {
// this will never reset any bits
bits |= test[i] ^ good[i];
}
return bits == 0;
}
/**
* Copy the contents of the source array to the target array. If the size if
* the target array is too small, a larger array is created.
*
* @param source the source array
* @param target the target array
* @return the target array or a new one if the target array was too small
*/
public static byte[] copy(byte[] source, byte[] target) {
int len = source.length;
if (len > target.length) {
target = new byte[len];
}
System.arraycopy(source, 0, target, 0, len);
return target;
}
/**
* Create an array of bytes with the given size. If this is not possible
* because not enough memory is available, an OutOfMemoryError with the
* requested size in the message is thrown.
* <p>
* This method should be used if the size of the array is user defined, or
* stored in a file, so wrong size data can be distinguished from regular
* out-of-memory.
* </p>
*
* @param len the number of bytes requested
* @return the byte array
* @throws OutOfMemoryError if the allocation was too large
*/
public static byte[] newBytes(int len) {
if (len == 0) {
return EMPTY_BYTES;
}
try {
return new byte[len];
} catch (OutOfMemoryError e) {
Error e2 = new OutOfMemoryError("Requested memory: " + len);
e2.initCause(e);
throw e2;
}
}
/**
* Creates a copy of array of bytes with the new size. If this is not possible
* because not enough memory is available, an OutOfMemoryError with the
* requested size in the message is thrown.
* <p>
* This method should be used if the size of the array is user defined, or
* stored in a file, so wrong size data can be distinguished from regular
* out-of-memory.
* </p>
*
* @param bytes source array
* @param len the number of bytes in the new array
* @return the byte array
* @throws OutOfMemoryError if the allocation was too large
* @see Arrays#copyOf(byte[], int)
*/
public static byte[] copyBytes(byte[] bytes, int len) {
if (len == 0) {
return EMPTY_BYTES;
}
try {
return Arrays.copyOf(bytes, len);
} catch (OutOfMemoryError e) {
Error e2 = new OutOfMemoryError("Requested memory: " + len);
e2.initCause(e);
throw e2;
}
}
/**
* Create a new byte array and copy all the data. If the size of the byte
* array is zero, the same array is returned.
*
* @param b the byte array (may not be null)
* @return a new byte array
*/
public static byte[] cloneByteArray(byte[] b) {
if (b == null) {
return null;
}
int len = b.length;
if (len == 0) {
return EMPTY_BYTES;
}
return Arrays.copyOf(b, len);
}
/**
* Get the used memory in KB.
* This method possibly calls System.gc().
*
* @return the used memory
*/
public static int getMemoryUsed() {
collectGarbage();
Runtime rt = Runtime.getRuntime();
long mem = rt.totalMemory() - rt.freeMemory();
return (int) (mem >> 10);
}
/**
* Get the free memory in KB.
* This method possibly calls System.gc().
*
* @return the free memory
*/
public static int getMemoryFree() {
collectGarbage();
Runtime rt = Runtime.getRuntime();
long mem = rt.freeMemory();
return (int) (mem >> 10);
}
/**
* Get the maximum memory in KB.
*
* @return the maximum memory
*/
public static long getMemoryMax() {
long max = Runtime.getRuntime().maxMemory();
return max / 1024;
}
public static long getGarbageCollectionTime() {
long totalGCTime = 0;
for (GarbageCollectorMXBean gcMXBean : ManagementFactory.getGarbageCollectorMXBeans()) {
long collectionTime = gcMXBean.getCollectionTime();
if(collectionTime > 0) {
totalGCTime += collectionTime;
}
}
return totalGCTime;
}
private static synchronized void collectGarbage() {
Runtime runtime = Runtime.getRuntime();
long total = runtime.totalMemory();
long time = System.nanoTime();
if (lastGC + TimeUnit.MILLISECONDS.toNanos(GC_DELAY) < time) {
for (int i = 0; i < MAX_GC; i++) {
runtime.gc();
long now = runtime.totalMemory();
if (now == total) {
lastGC = System.nanoTime();
break;
}
total = now;
}
}
}
/**
* Create an int array with the given size.
*
* @param len the number of bytes requested
* @return the int array
*/
public static int[] newIntArray(int len) {
if (len == 0) {
return EMPTY_INT_ARRAY;
}
return new int[len];
}
/**
* Create a long array with the given size.
*
* @param len the number of bytes requested
* @return the int array
*/
public static long[] newLongArray(int len) {
if (len == 0) {
return EMPTY_LONG_ARRAY;
}
return new long[len];
}
/**
* Find the top limit values using given comparator and place them as in a
* full array sort, in descending order.
*
* @param array the array.
* @param offset the offset.
* @param limit the limit.
* @param comp the comparator.
*/
public static <X> void sortTopN(X[] array, int offset, int limit,
Comparator<? super X> comp) {
partitionTopN(array, offset, limit, comp);
Arrays.sort(array, offset,
(int) Math.min((long) offset + limit, array.length), comp);
}
/**
* Find the top limit values using given comparator and place them as in a
* full array sort. This method does not sort the top elements themselves.
*
* @param array the array
* @param offset the offset
* @param limit the limit
* @param comp the comparator
*/
private static <X> void partitionTopN(X[] array, int offset, int limit,
Comparator<? super X> comp) {
partialQuickSort(array, 0, array.length - 1, comp, offset, offset +
limit - 1);
}
private static <X> void partialQuickSort(X[] array, int low, int high,
Comparator<? super X> comp, int start, int end) {
if (low > end || high < start || (low > start && high < end)) {
return;
}
if (low == high) {
return;
}
int i = low, j = high;
// use a random pivot to protect against
// the worst case order
int p = low + MathUtils.randomInt(high - low);
X pivot = array[p];
int m = (low + high) >>> 1;
X temp = array[m];
array[m] = pivot;
array[p] = temp;
while (i <= j) {
while (comp.compare(array[i], pivot) < 0) {
i++;
}
while (comp.compare(array[j], pivot) > 0) {
j--;
}
if (i <= j) {
temp = array[i];
array[i++] = array[j];
array[j--] = temp;
}
}
if (low < j) {
partialQuickSort(array, low, j, comp, start, end);
}
if (i < high) {
partialQuickSort(array, i, high, comp, start, end);
}
}
/**
* Checks if given classes have a common Comparable superclass.
*
* @param c1 the first class
* @param c2 the second class
* @return true if they have
*/
public static boolean haveCommonComparableSuperclass(
Class<?> c1, Class<?> c2) {
if (c1 == c2 || c1.isAssignableFrom(c2) || c2.isAssignableFrom(c1)) {
return true;
}
Class<?> top1;
do {
top1 = c1;
c1 = c1.getSuperclass();
} while (Comparable.class.isAssignableFrom(c1));
Class<?> top2;
do {
top2 = c2;
c2 = c2.getSuperclass();
} while (Comparable.class.isAssignableFrom(c2));
return top1 == top2;
}
/**
* Get a resource from the resource map.
*
* @param name the name of the resource
* @return the resource data
*/
public static byte[] getResource(String name) throws IOException {
byte[] data = RESOURCES.get(name);
if (data == null) {
data = loadResource(name);
if (data != null) {
RESOURCES.put(name, data);
}
}
return data;
}
private static byte[] loadResource(String name) throws IOException {
InputStream in = Utils.class.getResourceAsStream("data.zip");
if (in == null) {
in = Utils.class.getResourceAsStream(name);
if (in == null) {
return null;
}
return IOUtils.readBytesAndClose(in, 0);
}
try (ZipInputStream zipIn = new ZipInputStream(in)) {
while (true) {
ZipEntry entry = zipIn.getNextEntry();
if (entry == null) {
break;
}
String entryName = entry.getName();
if (!entryName.startsWith("/")) {
entryName = "/" + entryName;
}
if (entryName.equals(name)) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(zipIn, out);
zipIn.closeEntry();
return out.toByteArray();
}
zipIn.closeEntry();
}
} catch (IOException e) {
// if this happens we have a real problem
e.printStackTrace();
}
return null;
}
/**
* Calls a static method via reflection. This will try to use the method
* where the most parameter classes match exactly (this algorithm is simpler
* than the one in the Java specification, but works well for most cases).
*
* @param classAndMethod a string with the entire class and method name, eg.
* "java.lang.System.gc"
* @param params the method parameters
* @return the return value from this call
*/
public static Object callStaticMethod(String classAndMethod,
Object... params) throws Exception {
int lastDot = classAndMethod.lastIndexOf('.');
String className = classAndMethod.substring(0, lastDot);
String methodName = classAndMethod.substring(lastDot + 1);
return callMethod(null, Class.forName(className), methodName, params);
}
/**
* Calls an instance method via reflection. This will try to use the method
* where the most parameter classes match exactly (this algorithm is simpler
* than the one in the Java specification, but works well for most cases).
*
* @param instance the instance on which the call is done
* @param methodName a string with the method name
* @param params the method parameters
* @return the return value from this call
*/
public static Object callMethod(
Object instance,
String methodName,
Object... params) throws Exception {
return callMethod(instance, instance.getClass(), methodName, params);
}
private static Object callMethod(
Object instance, Class<?> clazz,
String methodName,
Object... params) throws Exception {
Method best = null;
int bestMatch = 0;
boolean isStatic = instance == null;
for (Method m : clazz.getMethods()) {
if (Modifier.isStatic(m.getModifiers()) == isStatic &&
m.getName().equals(methodName)) {
int p = match(m.getParameterTypes(), params);
if (p > bestMatch) {
bestMatch = p;
best = m;
}
}
}
if (best == null) {
throw new NoSuchMethodException(methodName);
}
return best.invoke(instance, params);
}
/**
* Creates a new instance. This will try to use the constructor where the
* most parameter classes match exactly (this algorithm is simpler than the
* one in the Java specification, but works well for most cases).
*
* @param className a string with the entire class, eg. "java.lang.Integer"
* @param params the constructor parameters
* @return the newly created object
*/
public static Object newInstance(String className, Object... params)
throws Exception {
Constructor<?> best = null;
int bestMatch = 0;
for (Constructor<?> c : Class.forName(className).getConstructors()) {
int p = match(c.getParameterTypes(), params);
if (p > bestMatch) {
bestMatch = p;
best = c;
}
}
if (best == null) {
throw new NoSuchMethodException(className);
}
return best.newInstance(params);
}
private static int match(Class<?>[] params, Object[] values) {
int len = params.length;
if (len == values.length) {
int points = 1;
for (int i = 0; i < len; i++) {
Class<?> pc = getNonPrimitiveClass(params[i]);
Object v = values[i];
Class<?> vc = v == null ? null : v.getClass();
if (pc == vc) {
points++;
} else if (vc == null) {
// can't verify
} else if (!pc.isAssignableFrom(vc)) {
return 0;
}
}
return points;
}
return 0;
}
/**
* Returns a static field.
*
* @param classAndField a string with the entire class and field name
* @return the field value
*/
public static Object getStaticField(String classAndField) throws Exception {
int lastDot = classAndField.lastIndexOf('.');
String className = classAndField.substring(0, lastDot);
String fieldName = classAndField.substring(lastDot + 1);
return Class.forName(className).getField(fieldName).get(null);
}
/**
* Returns a static field.
*
* @param instance the instance on which the call is done
* @param fieldName the field name
* @return the field value
*/
public static Object getField(Object instance, String fieldName)
throws Exception {
return instance.getClass().getField(fieldName).get(instance);
}
/**
* Returns true if the class is present in the current class loader.
*
* @param fullyQualifiedClassName a string with the entire class name, eg.
* "java.lang.System"
* @return true if the class is present
*/
public static boolean isClassPresent(String fullyQualifiedClassName) {
try {
Class.forName(fullyQualifiedClassName);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
/**
* Convert primitive class names to java.lang.* class names.
*
* @param clazz the class (for example: int)
* @return the non-primitive class (for example: java.lang.Integer)
*/
public static Class<?> getNonPrimitiveClass(Class<?> clazz) {
if (!clazz.isPrimitive()) {
return clazz;
} else if (clazz == boolean.class) {
return Boolean.class;
} else if (clazz == byte.class) {
return Byte.class;
} else if (clazz == char.class) {
return Character.class;
} else if (clazz == double.class) {
return Double.class;
} else if (clazz == float.class) {
return Float.class;
} else if (clazz == int.class) {
return Integer.class;
} else if (clazz == long.class) {
return Long.class;
} else if (clazz == short.class) {
return Short.class;
} else if (clazz == void.class) {
return Void.class;
}
return clazz;
}
/**
* Parses the specified string to boolean value.
*
* @param value
* string to parse
* @param defaultValue
* value to return if value is null or on parsing error
* @param throwException
* throw exception on parsing error or return default value instead
* @return parsed or default value
* @throws IllegalArgumentException
* on parsing error if {@code throwException} is true
*/
public static boolean parseBoolean(String value, boolean defaultValue, boolean throwException) {
if (value == null) {
return defaultValue;
}
switch (value.length()) {
case 1:
if (value.equals("1") || value.equalsIgnoreCase("t") || value.equalsIgnoreCase("y")) {
return true;
}
if (value.equals("0") || value.equalsIgnoreCase("f") || value.equalsIgnoreCase("n")) {
return false;
}
break;
case 2:
if (value.equalsIgnoreCase("no")) {
return false;
}
break;
case 3:
if (value.equalsIgnoreCase("yes")) {
return true;
}
break;
case 4:
if (value.equalsIgnoreCase("true")) {
return true;
}
break;
case 5:
if (value.equalsIgnoreCase("false")) {
return false;
}
}
if (throwException) {
throw new IllegalArgumentException(value);
}
return defaultValue;
}
/**
* Get the system property. If the system property is not set, or if a
* security exception occurs, the default value is returned.
*
* @param key the key
* @param defaultValue the default value
* @return the value
*/
public static String getProperty(String key, String defaultValue) {
try {
return System.getProperty(key, defaultValue);
} catch (SecurityException se) {
return defaultValue;
}
}
/**
* Get the system property. If the system property is not set, or if a
* security exception occurs, the default value is returned.
*
* @param key the key
* @param defaultValue the default value
* @return the value
*/
public static int getProperty(String key, int defaultValue) {
String s = getProperty(key, null);
if (s != null) {
try {
return Integer.decode(s);
} catch (NumberFormatException e) {
// ignore
}
}
return defaultValue;
}
/**
* Get the system property. If the system property is not set, or if a
* security exception occurs, the default value is returned.
*
* @param key the key
* @param defaultValue the default value
* @return the value
*/
public static boolean getProperty(String key, boolean defaultValue) {
return parseBoolean(getProperty(key, null), defaultValue, false);
}
/**
* Scale the value with the available memory. If 1 GB of RAM is available,
* the value is returned, if 2 GB are available, then twice the value, and
* so on.
*
* @param value the value to scale
* @return the scaled value
*/
public static int scaleForAvailableMemory(int value) {
long maxMemory = Runtime.getRuntime().maxMemory();
if (maxMemory != Long.MAX_VALUE) {
// we are limited by an -XmX parameter
return (int) (value * maxMemory / (1024 * 1024 * 1024));
}
try {
OperatingSystemMXBean mxBean = ManagementFactory
.getOperatingSystemMXBean();
// this method is only available on the class
// com.sun.management.OperatingSystemMXBean, which mxBean
// is an instance of under the Oracle JDK, but it is not present on
// Android and other JDK's
Method method = Class.forName(
"com.sun.management.OperatingSystemMXBean").
getMethod("getTotalPhysicalMemorySize");
long physicalMemorySize = ((Number) method.invoke(mxBean)).longValue();
return (int) (value * physicalMemorySize / (1024 * 1024 * 1024));
} catch (Exception e) {
// ignore
}
return value;
}
/**
* The utility methods will try to use the provided class factories to
* convert binary name of class to Class object. Used by H2 OSGi Activator
* in order to provide a class from another bundle ClassLoader.
*/
public interface ClassFactory {
/**
* Check whether the factory can return the named class.
*
* @param name the binary name of the class
* @return true if this factory can return a valid class for the
* provided class name
*/
boolean match(String name);
/**
* Load the class.
*
* @param name the binary name of the class
* @return the class object
* @throws ClassNotFoundException If the class is not handle by this
* factory
*/
Class<?> loadClass(String name)
throws ClassNotFoundException;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/util/ValueHashMap.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
import java.util.ArrayList;
import org.h2.message.DbException;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* This hash map supports keys of type Value.
*
* @param <V> the value type
*/
public class ValueHashMap<V> extends HashBase {
private Value[] keys;
private V[] values;
/**
* Create a new value hash map.
*
* @return the object
*/
public static <T> ValueHashMap<T> newInstance() {
return new ValueHashMap<>();
}
@Override
@SuppressWarnings("unchecked")
protected void reset(int newLevel) {
super.reset(newLevel);
keys = new Value[len];
values = (V[]) new Object[len];
}
@Override
protected void rehash(int newLevel) {
Value[] oldKeys = keys;
V[] oldValues = values;
reset(newLevel);
int len = oldKeys.length;
for (int i = 0; i < len; i++) {
Value k = oldKeys[i];
if (k != null && k != ValueNull.DELETED) {
// skip the checkSizePut so we don't end up
// accidentally recursing
internalPut(k, oldValues[i]);
}
}
}
private int getIndex(Value key) {
return key.hashCode() & mask;
}
/**
* Add or update a key value pair.
*
* @param key the key
* @param value the new value
*/
public void put(Value key, V value) {
checkSizePut();
internalPut(key, value);
}
private void internalPut(Value key, V value) {
int index = getIndex(key);
int plus = 1;
int deleted = -1;
do {
Value k = keys[index];
if (k == null) {
// found an empty record
if (deleted >= 0) {
index = deleted;
deletedCount--;
}
size++;
keys[index] = key;
values[index] = value;
return;
} else if (k == ValueNull.DELETED) {
// found a deleted record
if (deleted < 0) {
deleted = index;
}
} else if (k.equals(key)) {
// update existing
values[index] = value;
return;
}
index = (index + plus++) & mask;
} while (plus <= len);
// no space
DbException.throwInternalError("hashmap is full");
}
/**
* Remove a key value pair.
*
* @param key the key
*/
public void remove(Value key) {
checkSizeRemove();
int index = getIndex(key);
int plus = 1;
do {
Value k = keys[index];
if (k == null) {
// found an empty record
return;
} else if (k == ValueNull.DELETED) {
// found a deleted record
} else if (k.equals(key)) {
// found the record
keys[index] = ValueNull.DELETED;
values[index] = null;
deletedCount++;
size--;
return;
}
index = (index + plus++) & mask;
} while (plus <= len);
// not found
}
/**
* Get the value for this key. This method returns null if the key was not
* found.
*
* @param key the key
* @return the value for the given key
*/
public V get(Value key) {
int index = getIndex(key);
int plus = 1;
do {
Value k = keys[index];
if (k == null) {
// found an empty record
return null;
} else if (k == ValueNull.DELETED) {
// found a deleted record
} else if (k.equals(key)) {
// found it
return values[index];
}
index = (index + plus++) & mask;
} while (plus <= len);
return null;
}
/**
* Get the list of keys.
*
* @return all keys
*/
public ArrayList<Value> keys() {
ArrayList<Value> list = new ArrayList<>(size);
for (Value k : keys) {
if (k != null && k != ValueNull.DELETED) {
list.add(k);
}
}
return list;
}
/**
* Get the list of values.
*
* @return all values
*/
public ArrayList<V> values() {
ArrayList<V> list = new ArrayList<>(size);
int len = keys.length;
for (int i = 0; i < len; i++) {
Value k = keys[i];
if (k != null && k != ValueNull.DELETED) {
list.add(values[i]);
}
}
return list;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/CaseInsensitiveConcurrentMap.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.util.concurrent.ConcurrentHashMap;
import org.h2.util.StringUtils;
/**
* A concurrent hash map with a case-insensitive string key, that also allows
* NULL as a key.
*
* @param <V> the value type
*/
public class CaseInsensitiveConcurrentMap<V> extends ConcurrentHashMap<String, V> {
private static final long serialVersionUID = 1L;
private static final String NULL = new String(new byte[0]);
@Override
public V get(Object key) {
return super.get(toUpper(key));
}
@Override
public V put(String key, V value) {
return super.put(toUpper(key), value);
}
@Override
public boolean containsKey(Object key) {
return super.containsKey(toUpper(key));
}
@Override
public V remove(Object key) {
return super.remove(toUpper(key));
}
private static String toUpper(Object key) {
return key == null ? NULL : StringUtils.toUpperEnglish(key.toString());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/CaseInsensitiveMap.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.util.HashMap;
import org.h2.util.StringUtils;
/**
* A hash map with a case-insensitive string key.
*
* @param <V> the value type
*/
public class CaseInsensitiveMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = 1L;
@Override
public V get(Object key) {
return super.get(toUpper(key));
}
@Override
public V put(String key, V value) {
return super.put(toUpper(key), value);
}
@Override
public boolean containsKey(Object key) {
return super.containsKey(toUpper(key));
}
@Override
public V remove(Object key) {
return super.remove(toUpper(key));
}
private static String toUpper(Object key) {
return key == null ? null : StringUtils.toUpperEnglish(key.toString());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/CharsetCollator.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.nio.charset.Charset;
import java.text.CollationKey;
import java.text.Collator;
import java.util.Comparator;
/**
* The charset collator sorts strings according to the order in the given charset.
*/
public class CharsetCollator extends Collator {
/**
* The comparator used to compare byte arrays.
*/
static final Comparator<byte[]> COMPARATOR = new Comparator<byte[]>() {
@Override
public int compare(byte[] b1, byte[] b2) {
int minLength = Math.min(b1.length, b2.length);
for (int index = 0; index < minLength; index++) {
int result = b1[index] - b2[index];
if (result != 0) {
return result;
}
}
return b1.length - b2.length;
}
};
private final Charset charset;
public CharsetCollator(Charset charset) {
this.charset = charset;
}
public Charset getCharset() {
return charset;
}
@Override
public int compare(String source, String target) {
return COMPARATOR.compare(toBytes(source), toBytes(target));
}
/**
* Convert the source to bytes, using the character set.
*
* @param source the source
* @return the bytes
*/
byte[] toBytes(String source) {
return source.getBytes(charset);
}
@Override
public CollationKey getCollationKey(final String source) {
return new CharsetCollationKey(source);
}
@Override
public int hashCode() {
return 255;
}
private class CharsetCollationKey extends CollationKey {
CharsetCollationKey(String source) {
super(source);
}
@Override
public int compareTo(CollationKey target) {
return COMPARATOR.compare(toByteArray(), toBytes(target.getSourceString()));
}
@Override
public byte[] toByteArray() {
return toBytes(getSourceString());
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/CompareMode.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.nio.charset.Charset;
import java.text.Collator;
import java.util.Locale;
import java.util.Objects;
import org.h2.engine.SysProperties;
import org.h2.util.StringUtils;
/**
* Instances of this class can compare strings. Case sensitive and case
* insensitive comparison is supported, and comparison using a collator.
*/
public class CompareMode {
/**
* This constant means there is no collator set, and the default string
* comparison is to be used.
*/
public static final String OFF = "OFF";
/**
* This constant means the default collator should be used, even if ICU4J is
* in the classpath.
*/
public static final String DEFAULT = "DEFAULT_";
/**
* This constant means ICU4J should be used (this will fail if it is not in
* the classpath).
*/
public static final String ICU4J = "ICU4J_";
/**
* This constant means the charset specified should be used.
* This will fail if the specified charset does not exist.
*/
public static final String CHARSET = "CHARSET_";
/**
* This constant means that the BINARY columns are sorted as if the bytes
* were signed.
*/
public static final String SIGNED = "SIGNED";
/**
* This constant means that the BINARY columns are sorted as if the bytes
* were unsigned.
*/
public static final String UNSIGNED = "UNSIGNED";
private static volatile CompareMode lastUsed;
private static final boolean CAN_USE_ICU4J;
static {
boolean b = false;
try {
Class.forName("com.ibm.icu.text.Collator");
b = true;
} catch (Exception e) {
// ignore
}
CAN_USE_ICU4J = b;
}
private final String name;
private final int strength;
/**
* If true, sort BINARY columns as if they contain unsigned bytes.
*/
private final boolean binaryUnsigned;
protected CompareMode(String name, int strength, boolean binaryUnsigned) {
this.name = name;
this.strength = strength;
this.binaryUnsigned = binaryUnsigned;
}
/**
* Create a new compare mode with the given collator and strength. If
* required, a new CompareMode is created, or if possible the last one is
* returned. A cache is used to speed up comparison when using a collator;
* CollationKey objects are cached.
*
* @param name the collation name or null
* @param strength the collation strength
* @return the compare mode
*/
public static CompareMode getInstance(String name, int strength) {
return getInstance(name, strength, SysProperties.SORT_BINARY_UNSIGNED);
}
/**
* Create a new compare mode with the given collator and strength. If
* required, a new CompareMode is created, or if possible the last one is
* returned. A cache is used to speed up comparison when using a collator;
* CollationKey objects are cached.
*
* @param name the collation name or null
* @param strength the collation strength
* @param binaryUnsigned whether to compare binaries as unsigned
* @return the compare mode
*/
public static CompareMode getInstance(String name, int strength, boolean binaryUnsigned) {
CompareMode last = lastUsed;
if (last != null) {
if (Objects.equals(last.name, name) &&
last.strength == strength &&
last.binaryUnsigned == binaryUnsigned) {
return last;
}
}
if (name == null || name.equals(OFF)) {
last = new CompareMode(name, strength, binaryUnsigned);
} else {
boolean useICU4J;
if (name.startsWith(ICU4J)) {
useICU4J = true;
name = name.substring(ICU4J.length());
} else if (name.startsWith(DEFAULT)) {
useICU4J = false;
name = name.substring(DEFAULT.length());
} else {
useICU4J = CAN_USE_ICU4J;
}
if (useICU4J) {
last = new CompareModeIcu4J(name, strength, binaryUnsigned);
} else {
last = new CompareModeDefault(name, strength, binaryUnsigned);
}
}
lastUsed = last;
return last;
}
/**
* Compare two characters in a string.
*
* @param a the first string
* @param ai the character index in the first string
* @param b the second string
* @param bi the character index in the second string
* @param ignoreCase true if a case-insensitive comparison should be made
* @return true if the characters are equals
*/
public boolean equalsChars(String a, int ai, String b, int bi,
boolean ignoreCase) {
char ca = a.charAt(ai);
char cb = b.charAt(bi);
if (ignoreCase) {
ca = Character.toUpperCase(ca);
cb = Character.toUpperCase(cb);
}
return ca == cb;
}
/**
* Compare two strings.
*
* @param a the first string
* @param b the second string
* @param ignoreCase true if a case-insensitive comparison should be made
* @return -1 if the first string is 'smaller', 1 if the second string is
* smaller, and 0 if they are equal
*/
public int compareString(String a, String b, boolean ignoreCase) {
if (ignoreCase) {
return a.compareToIgnoreCase(b);
}
return a.compareTo(b);
}
/**
* Get the collation name.
*
* @param l the locale
* @return the name of the collation
*/
public static String getName(Locale l) {
Locale english = Locale.ENGLISH;
String name = l.getDisplayLanguage(english) + ' ' +
l.getDisplayCountry(english) + ' ' + l.getVariant();
name = StringUtils.toUpperEnglish(name.trim().replace(' ', '_'));
return name;
}
/**
* Compare name name of the locale with the given name. The case of the name
* is ignored.
*
* @param locale the locale
* @param name the name
* @return true if they match
*/
static boolean compareLocaleNames(Locale locale, String name) {
return name.equalsIgnoreCase(locale.toString()) ||
name.equalsIgnoreCase(getName(locale));
}
/**
* Get the collator object for the given language name or language / country
* combination.
*
* @param name the language name
* @return the collator
*/
public static Collator getCollator(String name) {
Collator result = null;
if (name.startsWith(ICU4J)) {
name = name.substring(ICU4J.length());
} else if (name.startsWith(DEFAULT)) {
name = name.substring(DEFAULT.length());
} else if (name.startsWith(CHARSET)) {
return new CharsetCollator(Charset.forName(name.substring(CHARSET.length())));
}
if (name.length() == 2) {
Locale locale = new Locale(StringUtils.toLowerEnglish(name), "");
if (compareLocaleNames(locale, name)) {
result = Collator.getInstance(locale);
}
} else if (name.length() == 5) {
// LL_CC (language_country)
int idx = name.indexOf('_');
if (idx >= 0) {
String language = StringUtils.toLowerEnglish(name.substring(0, idx));
String country = name.substring(idx + 1);
Locale locale = new Locale(language, country);
if (compareLocaleNames(locale, name)) {
result = Collator.getInstance(locale);
}
}
}
if (result == null) {
for (Locale locale : Collator.getAvailableLocales()) {
if (compareLocaleNames(locale, name)) {
result = Collator.getInstance(locale);
break;
}
}
}
return result;
}
public String getName() {
return name == null ? OFF : name;
}
public int getStrength() {
return strength;
}
public boolean isBinaryUnsigned() {
return binaryUnsigned;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof CompareMode)) {
return false;
}
CompareMode o = (CompareMode) obj;
if (!getName().equals(o.getName())) {
return false;
}
if (strength != o.strength) {
return false;
}
if (binaryUnsigned != o.binaryUnsigned) {
return false;
}
return true;
}
@Override
public int hashCode() {
return getName().hashCode() ^ strength ^ (binaryUnsigned ? -1 : 0);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/CompareModeDefault.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.text.CollationKey;
import java.text.Collator;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.util.SmallLRUCache;
/**
* The default implementation of CompareMode. It uses java.text.Collator.
*/
public class CompareModeDefault extends CompareMode {
private final Collator collator;
private final SmallLRUCache<String, CollationKey> collationKeys;
protected CompareModeDefault(String name, int strength,
boolean binaryUnsigned) {
super(name, strength, binaryUnsigned);
collator = CompareMode.getCollator(name);
if (collator == null) {
throw DbException.throwInternalError(name);
}
collator.setStrength(strength);
int cacheSize = SysProperties.COLLATOR_CACHE_SIZE;
if (cacheSize != 0) {
collationKeys = SmallLRUCache.newInstance(cacheSize);
} else {
collationKeys = null;
}
}
@Override
public int compareString(String a, String b, boolean ignoreCase) {
if (ignoreCase) {
// this is locale sensitive
a = a.toUpperCase();
b = b.toUpperCase();
}
int comp;
if (collationKeys != null) {
CollationKey aKey = getKey(a);
CollationKey bKey = getKey(b);
comp = aKey.compareTo(bKey);
} else {
comp = collator.compare(a, b);
}
return comp;
}
@Override
public boolean equalsChars(String a, int ai, String b, int bi,
boolean ignoreCase) {
return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1),
ignoreCase) == 0;
}
private CollationKey getKey(String a) {
synchronized (collationKeys) {
CollationKey key = collationKeys.get(a);
if (key == null) {
key = collator.getCollationKey(a);
collationKeys.put(a, key);
}
return key;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/CompareModeIcu4J.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.Locale;
import org.h2.message.DbException;
import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils;
/**
* An implementation of CompareMode that uses the ICU4J Collator.
*/
public class CompareModeIcu4J extends CompareMode {
private final Comparator<String> collator;
protected CompareModeIcu4J(String name, int strength, boolean binaryUnsigned) {
super(name, strength, binaryUnsigned);
collator = getIcu4jCollator(name, strength);
}
@Override
public int compareString(String a, String b, boolean ignoreCase) {
if (ignoreCase) {
a = a.toUpperCase();
b = b.toUpperCase();
}
return collator.compare(a, b);
}
@Override
public boolean equalsChars(String a, int ai, String b, int bi,
boolean ignoreCase) {
return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1),
ignoreCase) == 0;
}
@SuppressWarnings("unchecked")
private static Comparator<String> getIcu4jCollator(String name, int strength) {
try {
Comparator<String> result = null;
Class<?> collatorClass = JdbcUtils.loadUserClass(
"com.ibm.icu.text.Collator");
Method getInstanceMethod = collatorClass.getMethod(
"getInstance", Locale.class);
if (name.length() == 2) {
Locale locale = new Locale(StringUtils.toLowerEnglish(name), "");
if (compareLocaleNames(locale, name)) {
result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
}
} else if (name.length() == 5) {
// LL_CC (language_country)
int idx = name.indexOf('_');
if (idx >= 0) {
String language = StringUtils.toLowerEnglish(name.substring(0, idx));
String country = name.substring(idx + 1);
Locale locale = new Locale(language, country);
if (compareLocaleNames(locale, name)) {
result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
}
}
}
if (result == null) {
for (Locale locale : (Locale[]) collatorClass.getMethod(
"getAvailableLocales").invoke(null)) {
if (compareLocaleNames(locale, name)) {
result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
break;
}
}
}
if (result == null) {
throw DbException.getInvalidValueException("collator", name);
}
collatorClass.getMethod("setStrength", int.class).invoke(result, strength);
return result;
} catch (Exception e) {
throw DbException.convert(e);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/DataType.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.h2.api.ErrorCode;
import org.h2.api.TimestampWithTimeZone;
import org.h2.engine.Mode;
import org.h2.engine.SessionInterface;
import org.h2.engine.SysProperties;
import org.h2.jdbc.JdbcArray;
import org.h2.jdbc.JdbcBlob;
import org.h2.jdbc.JdbcClob;
import org.h2.jdbc.JdbcConnection;
import org.h2.message.DbException;
import org.h2.tools.SimpleResultSet;
import org.h2.util.JdbcUtils;
import org.h2.util.LocalDateTimeUtils;
import org.h2.util.Utils;
/**
* This class contains meta data information about data types,
* and can convert between Java objects and Values.
*/
public class DataType {
/**
* This constant is used to represent the type of a ResultSet. There is no
* equivalent java.sql.Types value, but Oracle uses it to represent a
* ResultSet (OracleTypes.CURSOR = -10).
*/
public static final int TYPE_RESULT_SET = -10;
/**
* The Geometry class. This object is null if the jts jar file is not in the
* classpath.
*/
public static final Class<?> GEOMETRY_CLASS;
private static final String GEOMETRY_CLASS_NAME =
"org.locationtech.jts.geom.Geometry";
/**
* The list of types. An ArrayList so that Tomcat doesn't set it to null
* when clearing references.
*/
private static final ArrayList<DataType> TYPES = new ArrayList<>(96);
private static final HashMap<String, DataType> TYPES_BY_NAME = new HashMap<>(96);
private static final HashMap<Integer, DataType> TYPES_BY_VALUE_TYPE = new HashMap<>(48);
/**
* The value type of this data type.
*/
public int type;
/**
* The data type name.
*/
public String name;
/**
* The SQL type.
*/
public int sqlType;
/**
* How closely the data type maps to the corresponding JDBC SQL type (low is
* best).
*/
public int sqlTypePos;
/**
* The maximum supported precision.
*/
public long maxPrecision;
/**
* The lowest possible scale.
*/
public int minScale;
/**
* The highest possible scale.
*/
public int maxScale;
/**
* If this is a numeric type.
*/
public boolean decimal;
/**
* The prefix required for the SQL literal representation.
*/
public String prefix;
/**
* The suffix required for the SQL literal representation.
*/
public String suffix;
/**
* The list of parameters used in the column definition.
*/
public String params;
/**
* If this is an autoincrement type.
*/
public boolean autoIncrement;
/**
* If this data type is an autoincrement type.
*/
public boolean caseSensitive;
/**
* If the precision parameter is supported.
*/
public boolean supportsPrecision;
/**
* If the scale parameter is supported.
*/
public boolean supportsScale;
/**
* The default precision.
*/
public long defaultPrecision;
/**
* The default scale.
*/
public int defaultScale;
/**
* The default display size.
*/
public int defaultDisplaySize;
/**
* If this data type should not be listed in the database meta data.
*/
public boolean hidden;
/**
* The number of bytes required for an object.
*/
public int memory;
static {
Class<?> g;
try {
g = JdbcUtils.loadUserClass(GEOMETRY_CLASS_NAME);
} catch (Exception e) {
// class is not in the classpath - ignore
g = null;
}
GEOMETRY_CLASS = g;
}
static {
add(Value.NULL, Types.NULL,
new DataType(),
new String[]{"NULL"},
// the value is always in the cache
0
);
add(Value.STRING, Types.VARCHAR,
createString(true),
new String[]{"VARCHAR", "VARCHAR2", "NVARCHAR", "NVARCHAR2",
"VARCHAR_CASESENSITIVE", "CHARACTER VARYING", "TID"},
// 24 for ValueString, 24 for String
48
);
add(Value.STRING, Types.LONGVARCHAR,
createString(true),
new String[]{"LONGVARCHAR", "LONGNVARCHAR"},
48
);
add(Value.STRING_FIXED, Types.CHAR,
createString(true),
new String[]{"CHAR", "CHARACTER", "NCHAR"},
48
);
add(Value.STRING_IGNORECASE, Types.VARCHAR,
createString(false),
new String[]{"VARCHAR_IGNORECASE"},
48
);
add(Value.BOOLEAN, Types.BOOLEAN,
createDecimal(ValueBoolean.PRECISION, ValueBoolean.PRECISION,
0, ValueBoolean.DISPLAY_SIZE, false, false),
new String[]{"BOOLEAN", "BIT", "BOOL"},
// the value is always in the cache
0
);
add(Value.BYTE, Types.TINYINT,
createDecimal(ValueByte.PRECISION, ValueByte.PRECISION, 0,
ValueByte.DISPLAY_SIZE, false, false),
new String[]{"TINYINT"},
// the value is almost always in the cache
1
);
add(Value.SHORT, Types.SMALLINT,
createDecimal(ValueShort.PRECISION, ValueShort.PRECISION, 0,
ValueShort.DISPLAY_SIZE, false, false),
new String[]{"SMALLINT", "YEAR", "INT2"},
// in many cases the value is in the cache
20
);
add(Value.INT, Types.INTEGER,
createDecimal(ValueInt.PRECISION, ValueInt.PRECISION, 0,
ValueInt.DISPLAY_SIZE, false, false),
new String[]{"INTEGER", "INT", "MEDIUMINT", "INT4", "SIGNED"},
// in many cases the value is in the cache
20
);
add(Value.INT, Types.INTEGER,
createDecimal(ValueInt.PRECISION, ValueInt.PRECISION, 0,
ValueInt.DISPLAY_SIZE, false, true),
new String[]{"SERIAL"},
20
);
add(Value.LONG, Types.BIGINT,
createDecimal(ValueLong.PRECISION, ValueLong.PRECISION, 0,
ValueLong.DISPLAY_SIZE, false, false),
new String[]{"BIGINT", "INT8", "LONG"},
24
);
add(Value.LONG, Types.BIGINT,
createDecimal(ValueLong.PRECISION, ValueLong.PRECISION, 0,
ValueLong.DISPLAY_SIZE, false, true),
new String[]{"IDENTITY", "BIGSERIAL"},
24
);
if (SysProperties.BIG_DECIMAL_IS_DECIMAL) {
addDecimal();
addNumeric();
} else {
addNumeric();
addDecimal();
}
add(Value.FLOAT, Types.REAL,
createDecimal(ValueFloat.PRECISION, ValueFloat.PRECISION,
0, ValueFloat.DISPLAY_SIZE, false, false),
new String[] {"REAL", "FLOAT4"},
24
);
add(Value.DOUBLE, Types.DOUBLE,
createDecimal(ValueDouble.PRECISION, ValueDouble.PRECISION,
0, ValueDouble.DISPLAY_SIZE, false, false),
new String[] { "DOUBLE", "DOUBLE PRECISION" },
24
);
add(Value.DOUBLE, Types.FLOAT,
createDecimal(ValueDouble.PRECISION, ValueDouble.PRECISION,
0, ValueDouble.DISPLAY_SIZE, false, false),
new String[] {"FLOAT", "FLOAT8" },
24
);
add(Value.TIME, Types.TIME,
createDate(ValueTime.MAXIMUM_PRECISION, ValueTime.DEFAULT_PRECISION,
"TIME", true, ValueTime.DEFAULT_SCALE, ValueTime.MAXIMUM_SCALE),
new String[]{"TIME", "TIME WITHOUT TIME ZONE"},
// 24 for ValueTime, 32 for java.sql.Time
56
);
add(Value.DATE, Types.DATE,
createDate(ValueDate.PRECISION, ValueDate.PRECISION,
"DATE", false, 0, 0),
new String[]{"DATE"},
// 24 for ValueDate, 32 for java.sql.Data
56
);
add(Value.TIMESTAMP, Types.TIMESTAMP,
createDate(ValueTimestamp.MAXIMUM_PRECISION, ValueTimestamp.DEFAULT_PRECISION,
"TIMESTAMP", true, ValueTimestamp.DEFAULT_SCALE, ValueTimestamp.MAXIMUM_SCALE),
new String[]{"TIMESTAMP", "TIMESTAMP WITHOUT TIME ZONE",
"DATETIME", "DATETIME2", "SMALLDATETIME"},
// 24 for ValueTimestamp, 32 for java.sql.Timestamp
56
);
// 2014 is the value of Types.TIMESTAMP_WITH_TIMEZONE
// use the value instead of the reference because the code has to
// compile (on Java 1.7). Can be replaced with
// Types.TIMESTAMP_WITH_TIMEZONE once Java 1.8 is required.
add(Value.TIMESTAMP_TZ, 2014,
createDate(ValueTimestampTimeZone.MAXIMUM_PRECISION, ValueTimestampTimeZone.DEFAULT_PRECISION,
"TIMESTAMP_TZ", true, ValueTimestampTimeZone.DEFAULT_SCALE,
ValueTimestampTimeZone.MAXIMUM_SCALE),
new String[]{"TIMESTAMP WITH TIME ZONE"},
// 26 for ValueTimestampUtc, 32 for java.sql.Timestamp
58
);
add(Value.BYTES, Types.VARBINARY,
createString(false),
new String[]{"VARBINARY"},
32
);
add(Value.BYTES, Types.BINARY,
createString(false),
new String[]{"BINARY", "RAW", "BYTEA", "LONG RAW"},
32
);
add(Value.BYTES, Types.LONGVARBINARY,
createString(false),
new String[]{"LONGVARBINARY"},
32
);
add(Value.UUID, Types.BINARY,
createString(false),
// UNIQUEIDENTIFIER is the MSSQL mode equivalent
new String[]{"UUID", "UNIQUEIDENTIFIER"},
32
);
add(Value.JAVA_OBJECT, Types.OTHER,
createString(false),
new String[]{"OTHER", "OBJECT", "JAVA_OBJECT"},
24
);
add(Value.BLOB, Types.BLOB,
createLob(),
new String[]{"BLOB", "TINYBLOB", "MEDIUMBLOB",
"LONGBLOB", "IMAGE", "OID"},
// 80 for ValueLob, 24 for String
104
);
add(Value.CLOB, Types.CLOB,
createLob(),
new String[]{"CLOB", "TINYTEXT", "TEXT", "MEDIUMTEXT",
"LONGTEXT", "NTEXT", "NCLOB"},
// 80 for ValueLob, 24 for String
104
);
add(Value.GEOMETRY, Types.OTHER,
createString(false),
new String[]{"GEOMETRY"},
32
);
DataType dataType = new DataType();
dataType.prefix = "(";
dataType.suffix = "')";
add(Value.ARRAY, Types.ARRAY,
dataType,
new String[]{"ARRAY"},
32
);
dataType = new DataType();
add(Value.RESULT_SET, DataType.TYPE_RESULT_SET,
dataType,
new String[]{"RESULT_SET"},
400
);
dataType = createString(false);
dataType.supportsPrecision = false;
dataType.supportsScale = false;
add(Value.ENUM, Types.OTHER,
dataType,
new String[]{"ENUM"},
48
);
for (Integer i : TYPES_BY_VALUE_TYPE.keySet()) {
Value.getOrder(i);
}
}
private static void addDecimal() {
add(Value.DECIMAL, Types.DECIMAL,
createDecimal(Integer.MAX_VALUE,
ValueDecimal.DEFAULT_PRECISION,
ValueDecimal.DEFAULT_SCALE,
ValueDecimal.DEFAULT_DISPLAY_SIZE, true, false),
new String[]{"DECIMAL", "DEC"},
// 40 for ValueDecimal,
64
);
}
private static void addNumeric() {
add(Value.DECIMAL, Types.NUMERIC,
createDecimal(Integer.MAX_VALUE,
ValueDecimal.DEFAULT_PRECISION,
ValueDecimal.DEFAULT_SCALE,
ValueDecimal.DEFAULT_DISPLAY_SIZE, true, false),
new String[]{"NUMERIC", "NUMBER"},
64
);
}
private static void add(int type, int sqlType,
DataType dataType, String[] names, int memory) {
for (int i = 0; i < names.length; i++) {
DataType dt = new DataType();
dt.type = type;
dt.sqlType = sqlType;
dt.name = names[i];
dt.autoIncrement = dataType.autoIncrement;
dt.decimal = dataType.decimal;
dt.maxPrecision = dataType.maxPrecision;
dt.maxScale = dataType.maxScale;
dt.minScale = dataType.minScale;
dt.params = dataType.params;
dt.prefix = dataType.prefix;
dt.suffix = dataType.suffix;
dt.supportsPrecision = dataType.supportsPrecision;
dt.supportsScale = dataType.supportsScale;
dt.defaultPrecision = dataType.defaultPrecision;
dt.defaultScale = dataType.defaultScale;
dt.defaultDisplaySize = dataType.defaultDisplaySize;
dt.caseSensitive = dataType.caseSensitive;
dt.hidden = i > 0;
dt.memory = memory;
for (DataType t2 : TYPES) {
if (t2.sqlType == dt.sqlType) {
dt.sqlTypePos++;
}
}
TYPES_BY_NAME.put(dt.name, dt);
if (TYPES_BY_VALUE_TYPE.get(type) == null) {
TYPES_BY_VALUE_TYPE.put(type, dt);
}
TYPES.add(dt);
}
}
private static DataType createDecimal(int maxPrecision,
int defaultPrecision, int defaultScale, int defaultDisplaySize,
boolean needsPrecisionAndScale, boolean autoInc) {
DataType dataType = new DataType();
dataType.maxPrecision = maxPrecision;
dataType.defaultPrecision = defaultPrecision;
dataType.defaultScale = defaultScale;
dataType.defaultDisplaySize = defaultDisplaySize;
if (needsPrecisionAndScale) {
dataType.params = "PRECISION,SCALE";
dataType.supportsPrecision = true;
dataType.supportsScale = true;
}
dataType.decimal = true;
dataType.autoIncrement = autoInc;
return dataType;
}
private static DataType createDate(int maxPrecision, int precision, String prefix,
boolean supportsScale, int scale, int maxScale) {
DataType dataType = new DataType();
dataType.prefix = prefix + " '";
dataType.suffix = "'";
dataType.maxPrecision = maxPrecision;
dataType.supportsScale = supportsScale;
dataType.maxScale = maxScale;
dataType.defaultPrecision = precision;
dataType.defaultScale = scale;
dataType.defaultDisplaySize = precision;
return dataType;
}
private static DataType createString(boolean caseSensitive) {
DataType dataType = new DataType();
dataType.prefix = "'";
dataType.suffix = "'";
dataType.params = "LENGTH";
dataType.caseSensitive = caseSensitive;
dataType.supportsPrecision = true;
dataType.maxPrecision = Integer.MAX_VALUE;
dataType.defaultPrecision = Integer.MAX_VALUE;
dataType.defaultDisplaySize = Integer.MAX_VALUE;
return dataType;
}
private static DataType createLob() {
DataType t = createString(true);
t.maxPrecision = Long.MAX_VALUE;
t.defaultPrecision = Long.MAX_VALUE;
return t;
}
/**
* Get the list of data types.
*
* @return the list
*/
public static ArrayList<DataType> getTypes() {
return TYPES;
}
/**
* Read a value from the given result set.
*
* @param session the session
* @param rs the result set
* @param columnIndex the column index (1 based)
* @param type the data type
* @return the value
*/
public static Value readValue(SessionInterface session, ResultSet rs,
int columnIndex, int type) {
try {
Value v;
switch (type) {
case Value.NULL: {
return ValueNull.INSTANCE;
}
case Value.BYTES: {
/*
* Both BINARY and UUID may be mapped to Value.BYTES. getObject() returns byte[]
* for SQL BINARY, UUID for SQL UUID and null for SQL NULL.
*/
Object o = rs.getObject(columnIndex);
if (o instanceof byte[]) {
v = ValueBytes.getNoCopy((byte[]) o);
} else if (o != null) {
v = ValueUuid.get((UUID) o);
} else {
v = ValueNull.INSTANCE;
}
break;
}
case Value.UUID: {
Object o = rs.getObject(columnIndex);
if (o instanceof UUID) {
v = ValueUuid.get((UUID) o);
} else if (o != null) {
v = ValueUuid.get((byte[]) o);
} else {
v = ValueNull.INSTANCE;
}
break;
}
case Value.BOOLEAN: {
boolean value = rs.getBoolean(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueBoolean.get(value);
break;
}
case Value.BYTE: {
byte value = rs.getByte(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueByte.get(value);
break;
}
case Value.DATE: {
Date value = rs.getDate(columnIndex);
v = value == null ? (Value) ValueNull.INSTANCE :
ValueDate.get(value);
break;
}
case Value.TIME: {
Time value = rs.getTime(columnIndex);
v = value == null ? (Value) ValueNull.INSTANCE :
ValueTime.get(value);
break;
}
case Value.TIMESTAMP: {
Timestamp value = rs.getTimestamp(columnIndex);
v = value == null ? (Value) ValueNull.INSTANCE :
ValueTimestamp.get(value);
break;
}
case Value.TIMESTAMP_TZ: {
TimestampWithTimeZone value = (TimestampWithTimeZone) rs.getObject(columnIndex);
v = value == null ? (Value) ValueNull.INSTANCE :
ValueTimestampTimeZone.get(value);
break;
}
case Value.DECIMAL: {
BigDecimal value = rs.getBigDecimal(columnIndex);
v = value == null ? (Value) ValueNull.INSTANCE :
ValueDecimal.get(value);
break;
}
case Value.DOUBLE: {
double value = rs.getDouble(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueDouble.get(value);
break;
}
case Value.FLOAT: {
float value = rs.getFloat(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueFloat.get(value);
break;
}
case Value.INT: {
int value = rs.getInt(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueInt.get(value);
break;
}
case Value.LONG: {
long value = rs.getLong(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueLong.get(value);
break;
}
case Value.SHORT: {
short value = rs.getShort(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueShort.get(value);
break;
}
case Value.STRING_IGNORECASE: {
String s = rs.getString(columnIndex);
v = (s == null) ? (Value) ValueNull.INSTANCE :
ValueStringIgnoreCase.get(s);
break;
}
case Value.STRING_FIXED: {
String s = rs.getString(columnIndex);
v = (s == null) ? (Value) ValueNull.INSTANCE :
ValueStringFixed.get(s);
break;
}
case Value.STRING: {
String s = rs.getString(columnIndex);
v = (s == null) ? (Value) ValueNull.INSTANCE :
ValueString.get(s);
break;
}
case Value.CLOB: {
if (session == null) {
String s = rs.getString(columnIndex);
v = s == null ? ValueNull.INSTANCE :
ValueLobDb.createSmallLob(Value.CLOB, s.getBytes(StandardCharsets.UTF_8));
} else {
Reader in = rs.getCharacterStream(columnIndex);
if (in == null) {
v = ValueNull.INSTANCE;
} else {
v = session.getDataHandler().getLobStorage().
createClob(new BufferedReader(in), -1);
}
}
if (session != null) {
session.addTemporaryLob(v);
}
break;
}
case Value.BLOB: {
if (session == null) {
byte[] buff = rs.getBytes(columnIndex);
return buff == null ? ValueNull.INSTANCE :
ValueLobDb.createSmallLob(Value.BLOB, buff);
}
InputStream in = rs.getBinaryStream(columnIndex);
v = (in == null) ? (Value) ValueNull.INSTANCE :
session.getDataHandler().getLobStorage().createBlob(in, -1);
session.addTemporaryLob(v);
break;
}
case Value.JAVA_OBJECT: {
if (SysProperties.serializeJavaObject) {
byte[] buff = rs.getBytes(columnIndex);
v = buff == null ? ValueNull.INSTANCE :
ValueJavaObject.getNoCopy(null, buff, session.getDataHandler());
} else {
Object o = rs.getObject(columnIndex);
v = o == null ? ValueNull.INSTANCE :
ValueJavaObject.getNoCopy(o, null, session.getDataHandler());
}
break;
}
case Value.ARRAY: {
Array array = rs.getArray(columnIndex);
if (array == null) {
return ValueNull.INSTANCE;
}
Object[] list = (Object[]) array.getArray();
if (list == null) {
return ValueNull.INSTANCE;
}
int len = list.length;
Value[] values = new Value[len];
for (int i = 0; i < len; i++) {
values[i] = DataType.convertToValue(session, list[i], Value.NULL);
}
v = ValueArray.get(values);
break;
}
case Value.ENUM: {
int value = rs.getInt(columnIndex);
v = rs.wasNull() ? (Value) ValueNull.INSTANCE :
ValueInt.get(value);
break;
}
case Value.RESULT_SET: {
ResultSet x = (ResultSet) rs.getObject(columnIndex);
if (x == null) {
return ValueNull.INSTANCE;
}
return ValueResultSet.get(x);
}
case Value.GEOMETRY: {
Object x = rs.getObject(columnIndex);
if (x == null) {
return ValueNull.INSTANCE;
}
return ValueGeometry.getFromGeometry(x);
}
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.getValue(type,
rs.getObject(columnIndex),
session.getDataHandler());
}
throw DbException.throwInternalError("type="+type);
}
return v;
} catch (SQLException e) {
throw DbException.convert(e);
}
}
/**
* Get the name of the Java class for the given value type.
*
* @param type the value type
* @return the class name
*/
public static String getTypeClassName(int type) {
switch (type) {
case Value.BOOLEAN:
// "java.lang.Boolean";
return Boolean.class.getName();
case Value.BYTE:
// "java.lang.Byte";
return Byte.class.getName();
case Value.SHORT:
// "java.lang.Short";
return Short.class.getName();
case Value.INT:
case Value.ENUM:
// "java.lang.Integer";
return Integer.class.getName();
case Value.LONG:
// "java.lang.Long";
return Long.class.getName();
case Value.DECIMAL:
// "java.math.BigDecimal";
return BigDecimal.class.getName();
case Value.TIME:
// "java.sql.Time";
return Time.class.getName();
case Value.DATE:
// "java.sql.Date";
return Date.class.getName();
case Value.TIMESTAMP:
// "java.sql.Timestamp";
return Timestamp.class.getName();
case Value.TIMESTAMP_TZ:
// "org.h2.api.TimestampWithTimeZone";
return TimestampWithTimeZone.class.getName();
case Value.BYTES:
case Value.UUID:
// "[B", not "byte[]";
return byte[].class.getName();
case Value.STRING:
case Value.STRING_IGNORECASE:
case Value.STRING_FIXED:
// "java.lang.String";
return String.class.getName();
case Value.BLOB:
// "java.sql.Blob";
return java.sql.Blob.class.getName();
case Value.CLOB:
// "java.sql.Clob";
return java.sql.Clob.class.getName();
case Value.DOUBLE:
// "java.lang.Double";
return Double.class.getName();
case Value.FLOAT:
// "java.lang.Float";
return Float.class.getName();
case Value.NULL:
return null;
case Value.JAVA_OBJECT:
// "java.lang.Object";
return Object.class.getName();
case Value.UNKNOWN:
// anything
return Object.class.getName();
case Value.ARRAY:
return Array.class.getName();
case Value.RESULT_SET:
return ResultSet.class.getName();
case Value.GEOMETRY:
return GEOMETRY_CLASS_NAME;
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.getDataTypeClassName(type);
}
throw DbException.throwInternalError("type="+type);
}
}
/**
* Get the data type object for the given value type.
*
* @param type the value type
* @return the data type object
*/
public static DataType getDataType(int type) {
if (type == Value.UNKNOWN) {
throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1, "?");
}
DataType dt = TYPES_BY_VALUE_TYPE.get(type);
if (dt == null && JdbcUtils.customDataTypesHandler != null) {
dt = JdbcUtils.customDataTypesHandler.getDataTypeById(type);
}
if (dt == null) {
dt = TYPES_BY_VALUE_TYPE.get(Value.NULL);
}
return dt;
}
/**
* Convert a value type to a SQL type.
*
* @param type the value type
* @return the SQL type
*/
public static int convertTypeToSQLType(int type) {
return getDataType(type).sqlType;
}
/**
* Convert a SQL type to a value type using SQL type name, in order to
* manage SQL type extension mechanism.
*
* @param sqlType the SQL type
* @param sqlTypeName the SQL type name
* @return the value type
*/
public static int convertSQLTypeToValueType(int sqlType, String sqlTypeName) {
switch (sqlType) {
case Types.OTHER:
case Types.JAVA_OBJECT:
if (sqlTypeName.equalsIgnoreCase("geometry")) {
return Value.GEOMETRY;
}
}
return convertSQLTypeToValueType(sqlType);
}
/**
* Get the SQL type from the result set meta data for the given column. This
* method uses the SQL type and type name.
*
* @param meta the meta data
* @param columnIndex the column index (1, 2,...)
* @return the value type
*/
public static int getValueTypeFromResultSet(ResultSetMetaData meta,
int columnIndex) throws SQLException {
return convertSQLTypeToValueType(
meta.getColumnType(columnIndex),
meta.getColumnTypeName(columnIndex));
}
/**
* Convert a SQL type to a value type.
*
* @param sqlType the SQL type
* @return the value type
*/
public static int convertSQLTypeToValueType(int sqlType) {
switch (sqlType) {
case Types.CHAR:
case Types.NCHAR:
return Value.STRING_FIXED;
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.NVARCHAR:
case Types.LONGNVARCHAR:
return Value.STRING;
case Types.NUMERIC:
case Types.DECIMAL:
return Value.DECIMAL;
case Types.BIT:
case Types.BOOLEAN:
return Value.BOOLEAN;
case Types.INTEGER:
return Value.INT;
case Types.SMALLINT:
return Value.SHORT;
case Types.TINYINT:
return Value.BYTE;
case Types.BIGINT:
return Value.LONG;
case Types.REAL:
return Value.FLOAT;
case Types.DOUBLE:
case Types.FLOAT:
return Value.DOUBLE;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return Value.BYTES;
case Types.OTHER:
case Types.JAVA_OBJECT:
return Value.JAVA_OBJECT;
case Types.DATE:
return Value.DATE;
case Types.TIME:
return Value.TIME;
case Types.TIMESTAMP:
return Value.TIMESTAMP;
case 2014: // Types.TIMESTAMP_WITH_TIMEZONE
return Value.TIMESTAMP_TZ;
case Types.BLOB:
return Value.BLOB;
case Types.CLOB:
case Types.NCLOB:
return Value.CLOB;
case Types.NULL:
return Value.NULL;
case Types.ARRAY:
return Value.ARRAY;
case DataType.TYPE_RESULT_SET:
return Value.RESULT_SET;
default:
throw DbException.get(
ErrorCode.UNKNOWN_DATA_TYPE_1, "" + sqlType);
}
}
/**
* Get the value type for the given Java class.
*
* @param x the Java class
* @return the value type
*/
public static int getTypeFromClass(Class <?> x) {
// TODO refactor: too many if/else in functions, can reduce!
if (x == null || Void.TYPE == x) {
return Value.NULL;
}
if (x.isPrimitive()) {
x = Utils.getNonPrimitiveClass(x);
}
if (String.class == x) {
return Value.STRING;
} else if (Integer.class == x) {
return Value.INT;
} else if (Long.class == x) {
return Value.LONG;
} else if (Boolean.class == x) {
return Value.BOOLEAN;
} else if (Double.class == x) {
return Value.DOUBLE;
} else if (Byte.class == x) {
return Value.BYTE;
} else if (Short.class == x) {
return Value.SHORT;
} else if (Character.class == x) {
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, "char (not supported)");
} else if (Float.class == x) {
return Value.FLOAT;
} else if (byte[].class == x) {
return Value.BYTES;
} else if (UUID.class == x) {
return Value.UUID;
} else if (Void.class == x) {
return Value.NULL;
} else if (BigDecimal.class.isAssignableFrom(x)) {
return Value.DECIMAL;
} else if (ResultSet.class.isAssignableFrom(x)) {
return Value.RESULT_SET;
} else if (Value.ValueBlob.class.isAssignableFrom(x)) {
return Value.BLOB;
} else if (Value.ValueClob.class.isAssignableFrom(x)) {
return Value.CLOB;
} else if (Date.class.isAssignableFrom(x)) {
return Value.DATE;
} else if (Time.class.isAssignableFrom(x)) {
return Value.TIME;
} else if (Timestamp.class.isAssignableFrom(x)) {
return Value.TIMESTAMP;
} else if (java.util.Date.class.isAssignableFrom(x)) {
return Value.TIMESTAMP;
} else if (java.io.Reader.class.isAssignableFrom(x)) {
return Value.CLOB;
} else if (java.sql.Clob.class.isAssignableFrom(x)) {
return Value.CLOB;
} else if (java.io.InputStream.class.isAssignableFrom(x)) {
return Value.BLOB;
} else if (java.sql.Blob.class.isAssignableFrom(x)) {
return Value.BLOB;
} else if (Object[].class.isAssignableFrom(x)) {
// this includes String[] and so on
return Value.ARRAY;
} else if (isGeometryClass(x)) {
return Value.GEOMETRY;
} else if (LocalDateTimeUtils.LOCAL_DATE == x) {
return Value.DATE;
} else if (LocalDateTimeUtils.LOCAL_TIME == x) {
return Value.TIME;
} else if (LocalDateTimeUtils.LOCAL_DATE_TIME == x) {
return Value.TIMESTAMP;
} else if (LocalDateTimeUtils.OFFSET_DATE_TIME == x || LocalDateTimeUtils.INSTANT == x) {
return Value.TIMESTAMP_TZ;
} else {
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.getTypeIdFromClass(x);
}
return Value.JAVA_OBJECT;
}
}
/**
* Convert a Java object to a value.
*
* @param session the session
* @param x the value
* @param type the value type
* @return the value
*/
public static Value convertToValue(SessionInterface session, Object x,
int type) {
Value v = convertToValue1(session, x, type);
if (session != null) {
session.addTemporaryLob(v);
}
return v;
}
private static Value convertToValue1(SessionInterface session, Object x,
int type) {
if (x == null) {
return ValueNull.INSTANCE;
}
if (type == Value.JAVA_OBJECT) {
return ValueJavaObject.getNoCopy(x, null, session.getDataHandler());
}
if (x instanceof String) {
return ValueString.get((String) x);
} else if (x instanceof Value) {
return (Value) x;
} else if (x instanceof Long) {
return ValueLong.get(((Long) x).longValue());
} else if (x instanceof Integer) {
return ValueInt.get(((Integer) x).intValue());
} else if (x instanceof BigInteger) {
return ValueDecimal.get(new BigDecimal((BigInteger) x));
} else if (x instanceof BigDecimal) {
return ValueDecimal.get((BigDecimal) x);
} else if (x instanceof Boolean) {
return ValueBoolean.get(((Boolean) x).booleanValue());
} else if (x instanceof Byte) {
return ValueByte.get(((Byte) x).byteValue());
} else if (x instanceof Short) {
return ValueShort.get(((Short) x).shortValue());
} else if (x instanceof Float) {
return ValueFloat.get(((Float) x).floatValue());
} else if (x instanceof Double) {
return ValueDouble.get(((Double) x).doubleValue());
} else if (x instanceof byte[]) {
return ValueBytes.get((byte[]) x);
} else if (x instanceof Date) {
return ValueDate.get((Date) x);
} else if (x instanceof Time) {
return ValueTime.get((Time) x);
} else if (x instanceof Timestamp) {
return ValueTimestamp.get((Timestamp) x);
} else if (x instanceof java.util.Date) {
return ValueTimestamp.fromMillis(((java.util.Date) x).getTime());
} else if (x instanceof java.io.Reader) {
Reader r = new BufferedReader((java.io.Reader) x);
return session.getDataHandler().getLobStorage().
createClob(r, -1);
} else if (x instanceof java.sql.Clob) {
try {
java.sql.Clob clob = (java.sql.Clob) x;
Reader r = new BufferedReader(clob.getCharacterStream());
return session.getDataHandler().getLobStorage().
createClob(r, clob.length());
} catch (SQLException e) {
throw DbException.convert(e);
}
} else if (x instanceof java.io.InputStream) {
return session.getDataHandler().getLobStorage().
createBlob((java.io.InputStream) x, -1);
} else if (x instanceof java.sql.Blob) {
try {
java.sql.Blob blob = (java.sql.Blob) x;
return session.getDataHandler().getLobStorage().
createBlob(blob.getBinaryStream(), blob.length());
} catch (SQLException e) {
throw DbException.convert(e);
}
} else if (x instanceof java.sql.Array) {
java.sql.Array array = (java.sql.Array) x;
try {
return convertToValue(session, array.getArray(), Value.ARRAY);
} catch (SQLException e) {
throw DbException.convert(e);
}
} else if (x instanceof ResultSet) {
if (x instanceof SimpleResultSet) {
return ValueResultSet.get((ResultSet) x);
}
return ValueResultSet.getCopy((ResultSet) x, Integer.MAX_VALUE);
} else if (x instanceof UUID) {
return ValueUuid.get((UUID) x);
}
Class<?> clazz = x.getClass();
if (x instanceof Object[]) {
// (a.getClass().isArray());
// (a.getClass().getComponentType().isPrimitive());
Object[] o = (Object[]) x;
int len = o.length;
Value[] v = new Value[len];
for (int i = 0; i < len; i++) {
v[i] = convertToValue(session, o[i], type);
}
return ValueArray.get(clazz.getComponentType(), v);
} else if (x instanceof Character) {
return ValueStringFixed.get(((Character) x).toString());
} else if (isGeometry(x)) {
return ValueGeometry.getFromGeometry(x);
} else if (clazz == LocalDateTimeUtils.LOCAL_DATE) {
return LocalDateTimeUtils.localDateToDateValue(x);
} else if (clazz == LocalDateTimeUtils.LOCAL_TIME) {
return LocalDateTimeUtils.localTimeToTimeValue(x);
} else if (clazz == LocalDateTimeUtils.LOCAL_DATE_TIME) {
return LocalDateTimeUtils.localDateTimeToValue(x);
} else if (clazz == LocalDateTimeUtils.INSTANT) {
return LocalDateTimeUtils.instantToValue(x);
} else if (clazz == LocalDateTimeUtils.OFFSET_DATE_TIME) {
return LocalDateTimeUtils.offsetDateTimeToValue(x);
} else if (x instanceof TimestampWithTimeZone) {
return ValueTimestampTimeZone.get((TimestampWithTimeZone) x);
} else {
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.getValue(type, x,
session.getDataHandler());
}
return ValueJavaObject.getNoCopy(x, null, session.getDataHandler());
}
}
/**
* Check whether a given class matches the Geometry class.
*
* @param x the class
* @return true if it is a Geometry class
*/
public static boolean isGeometryClass(Class<?> x) {
if (x == null || GEOMETRY_CLASS == null) {
return false;
}
return GEOMETRY_CLASS.isAssignableFrom(x);
}
/**
* Check whether a given object is a Geometry object.
*
* @param x the the object
* @return true if it is a Geometry object
*/
public static boolean isGeometry(Object x) {
if (x == null) {
return false;
}
return isGeometryClass(x.getClass());
}
/**
* Get a data type object from a type name.
*
* @param s the type name
* @param mode database mode
* @return the data type object
*/
public static DataType getTypeByName(String s, Mode mode) {
DataType result = mode.typeByNameMap.get(s);
if (result == null) {
result = TYPES_BY_NAME.get(s);
if (result == null && JdbcUtils.customDataTypesHandler != null) {
result = JdbcUtils.customDataTypesHandler.getDataTypeByName(s);
}
}
return result;
}
/**
* Check if the given value type is a large object (BLOB or CLOB).
*
* @param type the value type
* @return true if the value type is a lob type
*/
public static boolean isLargeObject(int type) {
return type == Value.BLOB || type == Value.CLOB;
}
/**
* Check if the given value type is a String (VARCHAR,...).
*
* @param type the value type
* @return true if the value type is a String type
*/
public static boolean isStringType(int type) {
return type == Value.STRING || type == Value.STRING_FIXED || type == Value.STRING_IGNORECASE;
}
/**
* Check if the given value type supports the add operation.
*
* @param type the value type
* @return true if add is supported
*/
public static boolean supportsAdd(int type) {
switch (type) {
case Value.BYTE:
case Value.DECIMAL:
case Value.DOUBLE:
case Value.FLOAT:
case Value.INT:
case Value.LONG:
case Value.SHORT:
return true;
case Value.BOOLEAN:
case Value.TIME:
case Value.DATE:
case Value.TIMESTAMP:
case Value.TIMESTAMP_TZ:
case Value.BYTES:
case Value.UUID:
case Value.STRING:
case Value.STRING_IGNORECASE:
case Value.STRING_FIXED:
case Value.BLOB:
case Value.CLOB:
case Value.NULL:
case Value.JAVA_OBJECT:
case Value.UNKNOWN:
case Value.ARRAY:
case Value.RESULT_SET:
case Value.GEOMETRY:
return false;
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.supportsAdd(type);
}
return false;
}
}
/**
* Get the data type that will not overflow when calling 'add' 2 billion
* times.
*
* @param type the value type
* @return the data type that supports adding
*/
public static int getAddProofType(int type) {
switch (type) {
case Value.BYTE:
return Value.LONG;
case Value.FLOAT:
return Value.DOUBLE;
case Value.INT:
return Value.LONG;
case Value.LONG:
return Value.DECIMAL;
case Value.SHORT:
return Value.LONG;
case Value.BOOLEAN:
case Value.DECIMAL:
case Value.TIME:
case Value.DATE:
case Value.TIMESTAMP:
case Value.TIMESTAMP_TZ:
case Value.BYTES:
case Value.UUID:
case Value.STRING:
case Value.STRING_IGNORECASE:
case Value.STRING_FIXED:
case Value.BLOB:
case Value.CLOB:
case Value.DOUBLE:
case Value.NULL:
case Value.JAVA_OBJECT:
case Value.UNKNOWN:
case Value.ARRAY:
case Value.RESULT_SET:
case Value.GEOMETRY:
return type;
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.getAddProofType(type);
}
return type;
}
}
/**
* Get the default value in the form of a Java object for the given Java
* class.
*
* @param clazz the Java class
* @return the default object
*/
public static Object getDefaultForPrimitiveType(Class<?> clazz) {
if (clazz == Boolean.TYPE) {
return Boolean.FALSE;
} else if (clazz == Byte.TYPE) {
return (byte) 0;
} else if (clazz == Character.TYPE) {
return (char) 0;
} else if (clazz == Short.TYPE) {
return (short) 0;
} else if (clazz == Integer.TYPE) {
return 0;
} else if (clazz == Long.TYPE) {
return 0L;
} else if (clazz == Float.TYPE) {
return (float) 0;
} else if (clazz == Double.TYPE) {
return (double) 0;
}
throw DbException.throwInternalError(
"primitive=" + clazz.toString());
}
/**
* Convert a value to the specified class.
*
* @param conn the database connection
* @param v the value
* @param paramClass the target class
* @return the converted object
*/
public static Object convertTo(JdbcConnection conn, Value v,
Class<?> paramClass) {
if (paramClass == Blob.class) {
return new JdbcBlob(conn, v, 0);
} else if (paramClass == Clob.class) {
return new JdbcClob(conn, v, 0);
} else if (paramClass == Array.class) {
return new JdbcArray(conn, v, 0);
}
switch (v.getType()) {
case Value.JAVA_OBJECT: {
Object o = SysProperties.serializeJavaObject ? JdbcUtils.deserialize(v.getBytes(),
conn.getSession().getDataHandler()) : v.getObject();
if (paramClass.isAssignableFrom(o.getClass())) {
return o;
}
break;
}
case Value.BOOLEAN:
case Value.BYTE:
case Value.SHORT:
case Value.INT:
case Value.LONG:
case Value.DECIMAL:
case Value.TIME:
case Value.DATE:
case Value.TIMESTAMP:
case Value.TIMESTAMP_TZ:
case Value.BYTES:
case Value.UUID:
case Value.STRING:
case Value.STRING_IGNORECASE:
case Value.STRING_FIXED:
case Value.BLOB:
case Value.CLOB:
case Value.DOUBLE:
case Value.FLOAT:
case Value.NULL:
case Value.UNKNOWN:
case Value.ARRAY:
case Value.RESULT_SET:
case Value.GEOMETRY:
break;
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.getObject(v, paramClass);
}
}
throw DbException.getUnsupportedException("converting to class " + paramClass.getName());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/NullableKeyConcurrentMap.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.util.concurrent.ConcurrentHashMap;
/**
* A concurrent hash map that allows null keys
*
* @param <V> the value type
*/
public class NullableKeyConcurrentMap<V> extends ConcurrentHashMap<String, V> {
private static final long serialVersionUID = 1L;
private static final String NULL = new String(new byte[0]);
@Override
public V get(Object key) {
return super.get(toUpper(key));
}
@Override
public V put(String key, V value) {
return super.put(toUpper(key), value);
}
@Override
public boolean containsKey(Object key) {
return super.containsKey(toUpper(key));
}
@Override
public V remove(Object key) {
return super.remove(toUpper(key));
}
private static String toUpper(Object key) {
return key == null ? NULL : key.toString();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/Transfer.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.h2.api.ErrorCode;
import org.h2.engine.Constants;
import org.h2.engine.SessionInterface;
import org.h2.message.DbException;
import org.h2.security.SHA256;
import org.h2.store.Data;
import org.h2.store.DataReader;
import org.h2.tools.SimpleResultSet;
import org.h2.util.Bits;
import org.h2.util.DateTimeUtils;
import org.h2.util.IOUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.NetUtils;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* The transfer class is used to send and receive Value objects.
* It is used on both the client side, and on the server side.
*/
public class Transfer {
private static final int BUFFER_SIZE = 64 * 1024;
private static final int LOB_MAGIC = 0x1234;
private static final int LOB_MAC_SALT_LENGTH = 16;
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
private SessionInterface session;
private boolean ssl;
private int version;
private byte[] lobMacSalt;
/**
* Create a new transfer object for the specified session.
*
* @param session the session
* @param s the socket
*/
public Transfer(SessionInterface session, Socket s) {
this.session = session;
this.socket = s;
}
/**
* Initialize the transfer object. This method will try to open an input and
* output stream.
*/
public synchronized void init() throws IOException {
if (socket != null) {
in = new DataInputStream(
new BufferedInputStream(
socket.getInputStream(), Transfer.BUFFER_SIZE));
out = new DataOutputStream(
new BufferedOutputStream(
socket.getOutputStream(), Transfer.BUFFER_SIZE));
}
}
/**
* Write pending changes.
*/
public void flush() throws IOException {
out.flush();
}
/**
* Write a boolean.
*
* @param x the value
* @return itself
*/
public Transfer writeBoolean(boolean x) throws IOException {
out.writeByte((byte) (x ? 1 : 0));
return this;
}
/**
* Read a boolean.
*
* @return the value
*/
public boolean readBoolean() throws IOException {
return in.readByte() == 1;
}
/**
* Write a byte.
*
* @param x the value
* @return itself
*/
private Transfer writeByte(byte x) throws IOException {
out.writeByte(x);
return this;
}
/**
* Read a byte.
*
* @return the value
*/
private byte readByte() throws IOException {
return in.readByte();
}
/**
* Write an int.
*
* @param x the value
* @return itself
*/
public Transfer writeInt(int x) throws IOException {
out.writeInt(x);
return this;
}
/**
* Read an int.
*
* @return the value
*/
public int readInt() throws IOException {
return in.readInt();
}
/**
* Write a long.
*
* @param x the value
* @return itself
*/
public Transfer writeLong(long x) throws IOException {
out.writeLong(x);
return this;
}
/**
* Read a long.
*
* @return the value
*/
public long readLong() throws IOException {
return in.readLong();
}
/**
* Write a double.
*
* @param i the value
* @return itself
*/
private Transfer writeDouble(double i) throws IOException {
out.writeDouble(i);
return this;
}
/**
* Write a float.
*
* @param i the value
* @return itself
*/
private Transfer writeFloat(float i) throws IOException {
out.writeFloat(i);
return this;
}
/**
* Read a double.
*
* @return the value
*/
private double readDouble() throws IOException {
return in.readDouble();
}
/**
* Read a float.
*
* @return the value
*/
private float readFloat() throws IOException {
return in.readFloat();
}
/**
* Write a string. The maximum string length is Integer.MAX_VALUE.
*
* @param s the value
* @return itself
*/
public Transfer writeString(String s) throws IOException {
if (s == null) {
out.writeInt(-1);
} else {
int len = s.length();
out.writeInt(len);
for (int i = 0; i < len; i++) {
out.writeChar(s.charAt(i));
}
}
return this;
}
/**
* Read a string.
*
* @return the value
*/
public String readString() throws IOException {
int len = in.readInt();
if (len == -1) {
return null;
}
StringBuilder buff = new StringBuilder(len);
for (int i = 0; i < len; i++) {
buff.append(in.readChar());
}
String s = buff.toString();
s = StringUtils.cache(s);
return s;
}
/**
* Write a byte array.
*
* @param data the value
* @return itself
*/
public Transfer writeBytes(byte[] data) throws IOException {
if (data == null) {
writeInt(-1);
} else {
writeInt(data.length);
out.write(data);
}
return this;
}
/**
* Write a number of bytes.
*
* @param buff the value
* @param off the offset
* @param len the length
* @return itself
*/
public Transfer writeBytes(byte[] buff, int off, int len) throws IOException {
out.write(buff, off, len);
return this;
}
/**
* Read a byte array.
*
* @return the value
*/
public byte[] readBytes() throws IOException {
int len = readInt();
if (len == -1) {
return null;
}
byte[] b = Utils.newBytes(len);
in.readFully(b);
return b;
}
/**
* Read a number of bytes.
*
* @param buff the target buffer
* @param off the offset
* @param len the number of bytes to read
*/
public void readBytes(byte[] buff, int off, int len) throws IOException {
in.readFully(buff, off, len);
}
/**
* Close the transfer object and the socket.
*/
public synchronized void close() {
if (socket != null) {
try {
if (out != null) {
out.flush();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
DbException.traceThrowable(e);
} finally {
socket = null;
}
}
}
/**
* Write a value.
*
* @param v the value
*/
public void writeValue(Value v) throws IOException {
int type = v.getType();
writeInt(type);
switch (type) {
case Value.NULL:
break;
case Value.BYTES:
case Value.JAVA_OBJECT:
writeBytes(v.getBytesNoCopy());
break;
case Value.UUID: {
ValueUuid uuid = (ValueUuid) v;
writeLong(uuid.getHigh());
writeLong(uuid.getLow());
break;
}
case Value.BOOLEAN:
writeBoolean(v.getBoolean());
break;
case Value.BYTE:
writeByte(v.getByte());
break;
case Value.TIME:
if (version >= Constants.TCP_PROTOCOL_VERSION_9) {
writeLong(((ValueTime) v).getNanos());
} else {
writeLong(DateTimeUtils.getTimeLocalWithoutDst(v.getTime()));
}
break;
case Value.DATE:
if (version >= Constants.TCP_PROTOCOL_VERSION_9) {
writeLong(((ValueDate) v).getDateValue());
} else {
writeLong(DateTimeUtils.getTimeLocalWithoutDst(v.getDate()));
}
break;
case Value.TIMESTAMP: {
if (version >= Constants.TCP_PROTOCOL_VERSION_9) {
ValueTimestamp ts = (ValueTimestamp) v;
writeLong(ts.getDateValue());
writeLong(ts.getTimeNanos());
} else {
Timestamp ts = v.getTimestamp();
writeLong(DateTimeUtils.getTimeLocalWithoutDst(ts));
writeInt(ts.getNanos() % 1_000_000);
}
break;
}
case Value.TIMESTAMP_TZ: {
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) v;
writeLong(ts.getDateValue());
writeLong(ts.getTimeNanos());
writeInt(ts.getTimeZoneOffsetMins());
break;
}
case Value.DECIMAL:
writeString(v.getString());
break;
case Value.DOUBLE:
writeDouble(v.getDouble());
break;
case Value.FLOAT:
writeFloat(v.getFloat());
break;
case Value.INT:
writeInt(v.getInt());
break;
case Value.LONG:
writeLong(v.getLong());
break;
case Value.SHORT:
writeInt(v.getShort());
break;
case Value.STRING:
case Value.STRING_IGNORECASE:
case Value.STRING_FIXED:
writeString(v.getString());
break;
case Value.BLOB: {
if (version >= Constants.TCP_PROTOCOL_VERSION_11) {
if (v instanceof ValueLobDb) {
ValueLobDb lob = (ValueLobDb) v;
if (lob.isStored()) {
writeLong(-1);
writeInt(lob.getTableId());
writeLong(lob.getLobId());
if (version >= Constants.TCP_PROTOCOL_VERSION_12) {
writeBytes(calculateLobMac(lob.getLobId()));
}
writeLong(lob.getPrecision());
break;
}
}
}
long length = v.getPrecision();
if (length < 0) {
throw DbException.get(
ErrorCode.CONNECTION_BROKEN_1, "length=" + length);
}
writeLong(length);
long written = IOUtils.copyAndCloseInput(v.getInputStream(), out);
if (written != length) {
throw DbException.get(
ErrorCode.CONNECTION_BROKEN_1, "length:" + length + " written:" + written);
}
writeInt(LOB_MAGIC);
break;
}
case Value.CLOB: {
if (version >= Constants.TCP_PROTOCOL_VERSION_11) {
if (v instanceof ValueLobDb) {
ValueLobDb lob = (ValueLobDb) v;
if (lob.isStored()) {
writeLong(-1);
writeInt(lob.getTableId());
writeLong(lob.getLobId());
if (version >= Constants.TCP_PROTOCOL_VERSION_12) {
writeBytes(calculateLobMac(lob.getLobId()));
}
writeLong(lob.getPrecision());
break;
}
}
}
long length = v.getPrecision();
if (length < 0) {
throw DbException.get(
ErrorCode.CONNECTION_BROKEN_1, "length=" + length);
}
writeLong(length);
Reader reader = v.getReader();
Data.copyString(reader, out);
writeInt(LOB_MAGIC);
break;
}
case Value.ARRAY: {
ValueArray va = (ValueArray) v;
Value[] list = va.getList();
int len = list.length;
Class<?> componentType = va.getComponentType();
if (componentType == Object.class) {
writeInt(len);
} else {
writeInt(-(len + 1));
writeString(componentType.getName());
}
for (Value value : list) {
writeValue(value);
}
break;
}
case Value.ENUM: {
writeInt(v.getInt());
writeString(v.getString());
break;
}
case Value.RESULT_SET: {
try {
ResultSet rs = ((ValueResultSet) v).getResultSet();
rs.beforeFirst();
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
writeInt(columnCount);
for (int i = 0; i < columnCount; i++) {
writeString(meta.getColumnName(i + 1));
writeInt(meta.getColumnType(i + 1));
writeInt(meta.getPrecision(i + 1));
writeInt(meta.getScale(i + 1));
}
while (rs.next()) {
writeBoolean(true);
for (int i = 0; i < columnCount; i++) {
int t = DataType.getValueTypeFromResultSet(meta, i + 1);
Value val = DataType.readValue(session, rs, i + 1, t);
writeValue(val);
}
}
writeBoolean(false);
rs.beforeFirst();
} catch (SQLException e) {
throw DbException.convertToIOException(e);
}
break;
}
case Value.GEOMETRY:
if (version >= Constants.TCP_PROTOCOL_VERSION_14) {
writeBytes(v.getBytesNoCopy());
} else {
writeString(v.getString());
}
break;
default:
if (JdbcUtils.customDataTypesHandler != null) {
writeBytes(v.getBytesNoCopy());
break;
}
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "type=" + type);
}
}
/**
* Read a value.
*
* @return the value
*/
public Value readValue() throws IOException {
int type = readInt();
switch (type) {
case Value.NULL:
return ValueNull.INSTANCE;
case Value.BYTES:
return ValueBytes.getNoCopy(readBytes());
case Value.UUID:
return ValueUuid.get(readLong(), readLong());
case Value.JAVA_OBJECT:
return ValueJavaObject.getNoCopy(null, readBytes(), session.getDataHandler());
case Value.BOOLEAN:
return ValueBoolean.get(readBoolean());
case Value.BYTE:
return ValueByte.get(readByte());
case Value.DATE:
if (version >= Constants.TCP_PROTOCOL_VERSION_9) {
return ValueDate.fromDateValue(readLong());
} else {
return ValueDate.fromMillis(DateTimeUtils.getTimeUTCWithoutDst(readLong()));
}
case Value.TIME:
if (version >= Constants.TCP_PROTOCOL_VERSION_9) {
return ValueTime.fromNanos(readLong());
} else {
return ValueTime.fromMillis(DateTimeUtils.getTimeUTCWithoutDst(readLong()));
}
case Value.TIMESTAMP: {
if (version >= Constants.TCP_PROTOCOL_VERSION_9) {
return ValueTimestamp.fromDateValueAndNanos(
readLong(), readLong());
} else {
return ValueTimestamp.fromMillisNanos(
DateTimeUtils.getTimeUTCWithoutDst(readLong()),
readInt() % 1_000_000);
}
}
case Value.TIMESTAMP_TZ: {
return ValueTimestampTimeZone.fromDateValueAndNanos(readLong(),
readLong(), (short) readInt());
}
case Value.DECIMAL:
return ValueDecimal.get(new BigDecimal(readString()));
case Value.DOUBLE:
return ValueDouble.get(readDouble());
case Value.FLOAT:
return ValueFloat.get(readFloat());
case Value.ENUM: {
final int ordinal = readInt();
final String label = readString();
return ValueEnumBase.get(label, ordinal);
}
case Value.INT:
return ValueInt.get(readInt());
case Value.LONG:
return ValueLong.get(readLong());
case Value.SHORT:
return ValueShort.get((short) readInt());
case Value.STRING:
return ValueString.get(readString());
case Value.STRING_IGNORECASE:
return ValueStringIgnoreCase.get(readString());
case Value.STRING_FIXED:
return ValueStringFixed.get(readString(), ValueStringFixed.PRECISION_DO_NOT_TRIM, null);
case Value.BLOB: {
long length = readLong();
if (version >= Constants.TCP_PROTOCOL_VERSION_11) {
if (length == -1) {
int tableId = readInt();
long id = readLong();
byte[] hmac;
if (version >= Constants.TCP_PROTOCOL_VERSION_12) {
hmac = readBytes();
} else {
hmac = null;
}
long precision = readLong();
return ValueLobDb.create(
Value.BLOB, session.getDataHandler(), tableId, id, hmac, precision);
}
}
Value v = session.getDataHandler().getLobStorage().createBlob(in, length);
int magic = readInt();
if (magic != LOB_MAGIC) {
throw DbException.get(
ErrorCode.CONNECTION_BROKEN_1, "magic=" + magic);
}
return v;
}
case Value.CLOB: {
long length = readLong();
if (version >= Constants.TCP_PROTOCOL_VERSION_11) {
if (length == -1) {
int tableId = readInt();
long id = readLong();
byte[] hmac;
if (version >= Constants.TCP_PROTOCOL_VERSION_12) {
hmac = readBytes();
} else {
hmac = null;
}
long precision = readLong();
return ValueLobDb.create(
Value.CLOB, session.getDataHandler(), tableId, id, hmac, precision);
}
if (length < 0) {
throw DbException.get(
ErrorCode.CONNECTION_BROKEN_1, "length="+ length);
}
}
Value v = session.getDataHandler().getLobStorage().
createClob(new DataReader(in), length);
int magic = readInt();
if (magic != LOB_MAGIC) {
throw DbException.get(
ErrorCode.CONNECTION_BROKEN_1, "magic=" + magic);
}
return v;
}
case Value.ARRAY: {
int len = readInt();
Class<?> componentType = Object.class;
if (len < 0) {
len = -(len + 1);
componentType = JdbcUtils.loadUserClass(readString());
}
Value[] list = new Value[len];
for (int i = 0; i < len; i++) {
list[i] = readValue();
}
return ValueArray.get(componentType, list);
}
case Value.RESULT_SET: {
SimpleResultSet rs = new SimpleResultSet();
rs.setAutoClose(false);
int columns = readInt();
for (int i = 0; i < columns; i++) {
rs.addColumn(readString(), readInt(), readInt(), readInt());
}
while (readBoolean()) {
Object[] o = new Object[columns];
for (int i = 0; i < columns; i++) {
o[i] = readValue().getObject();
}
rs.addRow(o);
}
return ValueResultSet.get(rs);
}
case Value.GEOMETRY:
if (version >= Constants.TCP_PROTOCOL_VERSION_14) {
return ValueGeometry.get(readBytes());
}
return ValueGeometry.get(readString());
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.convert(
ValueBytes.getNoCopy(readBytes()), type);
}
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "type=" + type);
}
}
/**
* Get the socket.
*
* @return the socket
*/
public Socket getSocket() {
return socket;
}
/**
* Set the session.
*
* @param session the session
*/
public void setSession(SessionInterface session) {
this.session = session;
}
/**
* Enable or disable SSL.
*
* @param ssl the new value
*/
public void setSSL(boolean ssl) {
this.ssl = ssl;
}
/**
* Open a new new connection to the same address and port as this one.
*
* @return the new transfer object
*/
public Transfer openNewConnection() throws IOException {
InetAddress address = socket.getInetAddress();
int port = socket.getPort();
Socket s2 = NetUtils.createSocket(address, port, ssl);
Transfer trans = new Transfer(null, s2);
trans.setSSL(ssl);
return trans;
}
public void setVersion(int version) {
this.version = version;
}
public synchronized boolean isClosed() {
return socket == null || socket.isClosed();
}
/**
* Verify the HMAC.
*
* @param hmac the message authentication code
* @param lobId the lobId
* @throws DbException if the HMAC does not match
*/
public void verifyLobMac(byte[] hmac, long lobId) {
byte[] result = calculateLobMac(lobId);
if (!Utils.compareSecure(hmac, result)) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1,
"Invalid lob hmac; possibly the connection was re-opened internally");
}
}
private byte[] calculateLobMac(long lobId) {
if (lobMacSalt == null) {
lobMacSalt = MathUtils.secureRandomBytes(LOB_MAC_SALT_LENGTH);
}
byte[] data = new byte[8];
Bits.writeLong(data, 0, lobId);
return SHA256.getHashWithSalt(data, lobMacSalt);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/Value.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.ref.SoftReference;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import org.h2.api.ErrorCode;
import org.h2.engine.Mode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.DataHandler;
import org.h2.tools.SimpleResultSet;
import org.h2.util.Bits;
import org.h2.util.DateTimeUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.StringUtils;
/**
* This is the base class for all value classes.
* It provides conversion and comparison methods.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public abstract class Value {
/**
* The data type is unknown at this time.
*/
public static final int UNKNOWN = -1;
/**
* The value type for NULL.
*/
public static final int NULL = 0;
/**
* The value type for BOOLEAN values.
*/
public static final int BOOLEAN = 1;
/**
* The value type for BYTE values.
*/
public static final int BYTE = 2;
/**
* The value type for SHORT values.
*/
public static final int SHORT = 3;
/**
* The value type for INT values.
*/
public static final int INT = 4;
/**
* The value type for LONG values.
*/
public static final int LONG = 5;
/**
* The value type for DECIMAL values.
*/
public static final int DECIMAL = 6;
/**
* The value type for DOUBLE values.
*/
public static final int DOUBLE = 7;
/**
* The value type for FLOAT values.
*/
public static final int FLOAT = 8;
/**
* The value type for TIME values.
*/
public static final int TIME = 9;
/**
* The value type for DATE values.
*/
public static final int DATE = 10;
/**
* The value type for TIMESTAMP values.
*/
public static final int TIMESTAMP = 11;
/**
* The value type for BYTES values.
*/
public static final int BYTES = 12;
/**
* The value type for STRING values.
*/
public static final int STRING = 13;
/**
* The value type for case insensitive STRING values.
*/
public static final int STRING_IGNORECASE = 14;
/**
* The value type for BLOB values.
*/
public static final int BLOB = 15;
/**
* The value type for CLOB values.
*/
public static final int CLOB = 16;
/**
* The value type for ARRAY values.
*/
public static final int ARRAY = 17;
/**
* The value type for RESULT_SET values.
*/
public static final int RESULT_SET = 18;
/**
* The value type for JAVA_OBJECT values.
*/
public static final int JAVA_OBJECT = 19;
/**
* The value type for UUID values.
*/
public static final int UUID = 20;
/**
* The value type for string values with a fixed size.
*/
public static final int STRING_FIXED = 21;
/**
* The value type for string values with a fixed size.
*/
public static final int GEOMETRY = 22;
/**
* 23 was a short-lived experiment "TIMESTAMP UTC" which has been removed.
*/
/**
* The value type for TIMESTAMP WITH TIME ZONE values.
*/
public static final int TIMESTAMP_TZ = 24;
/**
* The value type for ENUM values.
*/
public static final int ENUM = 25;
/**
* The number of value types.
*/
public static final int TYPE_COUNT = ENUM;
private static SoftReference<Value[]> softCache =
new SoftReference<>(null);
private static final BigDecimal MAX_LONG_DECIMAL =
BigDecimal.valueOf(Long.MAX_VALUE);
private static final BigDecimal MIN_LONG_DECIMAL =
BigDecimal.valueOf(Long.MIN_VALUE);
/**
* Check the range of the parameters.
*
* @param zeroBasedOffset the offset (0 meaning no offset)
* @param length the length of the target
* @param dataSize the length of the source
*/
static void rangeCheck(long zeroBasedOffset, long length, long dataSize) {
if ((zeroBasedOffset | length) < 0 || length > dataSize - zeroBasedOffset) {
if (zeroBasedOffset < 0 || zeroBasedOffset > dataSize) {
throw DbException.getInvalidValueException("offset", zeroBasedOffset + 1);
}
throw DbException.getInvalidValueException("length", length);
}
}
/**
* Get the SQL expression for this value.
*
* @return the SQL expression
*/
public abstract String getSQL();
/**
* Get the value type.
*
* @return the type
*/
public abstract int getType();
/**
* Get the precision.
*
* @return the precision
*/
public abstract long getPrecision();
/**
* Get the display size in characters.
*
* @return the display size
*/
public abstract int getDisplaySize();
/**
* Get the memory used by this object.
*
* @return the memory used in bytes
*/
public int getMemory() {
return DataType.getDataType(getType()).memory;
}
/**
* Get the value as a string.
*
* @return the string
*/
public abstract String getString();
/**
* Get the value as an object.
*
* @return the object
*/
public abstract Object getObject();
/**
* Set the value as a parameter in a prepared statement.
*
* @param prep the prepared statement
* @param parameterIndex the parameter index
*/
public abstract void set(PreparedStatement prep, int parameterIndex)
throws SQLException;
/**
* Compare the value with another value of the same type.
*
* @param v the other value
* @param mode the compare mode
* @return 0 if both values are equal, -1 if the other value is smaller, and
* 1 otherwise
*/
protected abstract int compareSecure(Value v, CompareMode mode);
@Override
public abstract int hashCode();
/**
* Check if the two values have the same hash code. No data conversion is
* made; this method returns false if the other object is not of the same
* class. For some values, compareTo may return 0 even if equals return
* false. Example: ValueDecimal 0.0 and 0.00.
*
* @param other the other value
* @return true if they are equal
*/
@Override
public abstract boolean equals(Object other);
/**
* Get the order of this value type.
*
* @param type the value type
* @return the order number
*/
static int getOrder(int type) {
switch (type) {
case UNKNOWN:
return 1_000;
case NULL:
return 2_000;
case STRING:
return 10_000;
case CLOB:
return 11_000;
case STRING_FIXED:
return 12_000;
case STRING_IGNORECASE:
return 13_000;
case BOOLEAN:
return 20_000;
case BYTE:
return 21_000;
case SHORT:
return 22_000;
case INT:
return 23_000;
case LONG:
return 24_000;
case DECIMAL:
return 25_000;
case FLOAT:
return 26_000;
case DOUBLE:
return 27_000;
case TIME:
return 30_000;
case DATE:
return 31_000;
case TIMESTAMP:
return 32_000;
case TIMESTAMP_TZ:
return 34_000;
case BYTES:
return 40_000;
case BLOB:
return 41_000;
case JAVA_OBJECT:
return 42_000;
case UUID:
return 43_000;
case GEOMETRY:
return 44_000;
case ARRAY:
return 50_000;
case RESULT_SET:
return 51_000;
case ENUM:
return 52_000;
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.getDataTypeOrder(type);
}
throw DbException.throwInternalError("type:"+type);
}
}
/**
* Get the higher value order type of two value types. If values need to be
* converted to match the other operands value type, the value with the
* lower order is converted to the value with the higher order.
*
* @param t1 the first value type
* @param t2 the second value type
* @return the higher value type of the two
*/
public static int getHigherOrder(int t1, int t2) {
if (t1 == Value.UNKNOWN || t2 == Value.UNKNOWN) {
if (t1 == t2) {
throw DbException.get(
ErrorCode.UNKNOWN_DATA_TYPE_1, "?, ?");
} else if (t1 == Value.NULL) {
throw DbException.get(
ErrorCode.UNKNOWN_DATA_TYPE_1, "NULL, ?");
} else if (t2 == Value.NULL) {
throw DbException.get(
ErrorCode.UNKNOWN_DATA_TYPE_1, "?, NULL");
}
}
if (t1 == t2) {
return t1;
}
int o1 = getOrder(t1);
int o2 = getOrder(t2);
return o1 > o2 ? t1 : t2;
}
/**
* Check if a value is in the cache that is equal to this value. If yes,
* this value should be used to save memory. If the value is not in the
* cache yet, it is added.
*
* @param v the value to look for
* @return the value in the cache or the value passed
*/
static Value cache(Value v) {
if (SysProperties.OBJECT_CACHE) {
int hash = v.hashCode();
if (softCache == null) {
softCache = new SoftReference<>(null);
}
Value[] cache = softCache.get();
if (cache == null) {
cache = new Value[SysProperties.OBJECT_CACHE_SIZE];
softCache = new SoftReference<>(cache);
}
int index = hash & (SysProperties.OBJECT_CACHE_SIZE - 1);
Value cached = cache[index];
if (cached != null) {
if (cached.getType() == v.getType() && v.equals(cached)) {
// cacheHit++;
return cached;
}
}
// cacheMiss++;
// cache[cacheCleaner] = null;
// cacheCleaner = (cacheCleaner + 1) &
// (Constants.OBJECT_CACHE_SIZE - 1);
cache[index] = v;
}
return v;
}
/**
* Clear the value cache. Used for testing.
*/
public static void clearCache() {
softCache = null;
}
public boolean getBoolean() {
return ((ValueBoolean) convertTo(Value.BOOLEAN)).getBoolean();
}
public Date getDate() {
return ((ValueDate) convertTo(Value.DATE)).getDate();
}
public Time getTime() {
return ((ValueTime) convertTo(Value.TIME)).getTime();
}
public Timestamp getTimestamp() {
return ((ValueTimestamp) convertTo(Value.TIMESTAMP)).getTimestamp();
}
public byte[] getBytes() {
return ((ValueBytes) convertTo(Value.BYTES)).getBytes();
}
public byte[] getBytesNoCopy() {
return ((ValueBytes) convertTo(Value.BYTES)).getBytesNoCopy();
}
public byte getByte() {
return ((ValueByte) convertTo(Value.BYTE)).getByte();
}
public short getShort() {
return ((ValueShort) convertTo(Value.SHORT)).getShort();
}
public BigDecimal getBigDecimal() {
return ((ValueDecimal) convertTo(Value.DECIMAL)).getBigDecimal();
}
public double getDouble() {
return ((ValueDouble) convertTo(Value.DOUBLE)).getDouble();
}
public float getFloat() {
return ((ValueFloat) convertTo(Value.FLOAT)).getFloat();
}
public int getInt() {
return ((ValueInt) convertTo(Value.INT)).getInt();
}
public long getLong() {
return ((ValueLong) convertTo(Value.LONG)).getLong();
}
public InputStream getInputStream() {
return new ByteArrayInputStream(getBytesNoCopy());
}
/**
* Get the input stream
*
* @param oneBasedOffset the offset (1 means no offset)
* @param length the requested length
* @return the new input stream
*/
public InputStream getInputStream(long oneBasedOffset, long length) {
byte[] bytes = getBytesNoCopy();
long zeroBasedOffset = oneBasedOffset - 1;
rangeCheck(zeroBasedOffset, length, bytes.length);
return new ByteArrayInputStream(bytes, (int) zeroBasedOffset, (int) length);
}
public Reader getReader() {
return new StringReader(getString());
}
/**
* Get the reader
*
* @param oneBasedOffset the offset (1 means no offset)
* @param length the requested length
* @return the new reader
*/
public Reader getReader(long oneBasedOffset, long length) {
String string = getString();
long zeroBasedOffset = oneBasedOffset - 1;
rangeCheck(zeroBasedOffset, length, string.length());
int offset = (int) zeroBasedOffset;
return new StringReader(string.substring(offset, offset + (int) length));
}
/**
* Add a value and return the result.
*
* @param v the value to add
* @return the result
*/
public Value add(@SuppressWarnings("unused") Value v) {
throw throwUnsupportedExceptionForType("+");
}
public int getSignum() {
throw throwUnsupportedExceptionForType("SIGNUM");
}
/**
* Return -value if this value support arithmetic operations.
*
* @return the negative
*/
public Value negate() {
throw throwUnsupportedExceptionForType("NEG");
}
/**
* Subtract a value and return the result.
*
* @param v the value to subtract
* @return the result
*/
public Value subtract(@SuppressWarnings("unused") Value v) {
throw throwUnsupportedExceptionForType("-");
}
/**
* Divide by a value and return the result.
*
* @param v the value to divide by
* @return the result
*/
public Value divide(@SuppressWarnings("unused") Value v) {
throw throwUnsupportedExceptionForType("/");
}
/**
* Multiply with a value and return the result.
*
* @param v the value to multiply with
* @return the result
*/
public Value multiply(@SuppressWarnings("unused") Value v) {
throw throwUnsupportedExceptionForType("*");
}
/**
* Take the modulus with a value and return the result.
*
* @param v the value to take the modulus with
* @return the result
*/
public Value modulus(@SuppressWarnings("unused") Value v) {
throw throwUnsupportedExceptionForType("%");
}
/**
* Compare a value to the specified type.
*
* @param targetType the type of the returned value
* @return the converted value
*/
public Value convertTo(int targetType) {
// Use -1 to indicate "default behaviour" where value conversion should not
// depend on any datatype precision.
return convertTo(targetType, -1, null);
}
/**
* Convert value to ENUM value
* @param enumerators allowed values for the ENUM to which the value is converted
* @return value represented as ENUM
*/
public Value convertToEnum(String[] enumerators) {
// Use -1 to indicate "default behaviour" where value conversion should not
// depend on any datatype precision.
return convertTo(ENUM, -1, null, null, enumerators);
}
/**
* Compare a value to the specified type.
*
* @param targetType the type of the returned value
* @param precision the precision of the column to convert this value to.
* The special constant <code>-1</code> is used to indicate that
* the precision plays no role when converting the value
* @param mode the mode
* @return the converted value
*/
public final Value convertTo(int targetType, int precision, Mode mode) {
return convertTo(targetType, precision, mode, null, null);
}
/**
* Compare a value to the specified type.
*
* @param targetType the type of the returned value
* @param precision the precision of the column to convert this value to.
* The special constant <code>-1</code> is used to indicate that
* the precision plays no role when converting the value
* @param mode the conversion mode
* @param column the column (if any), used for to improve the error message if conversion fails
* @param enumerators the ENUM datatype enumerators (if any),
* for dealing with ENUM conversions
* @return the converted value
*/
public Value convertTo(int targetType, int precision, Mode mode, Object column, String[] enumerators) {
// converting NULL is done in ValueNull
// converting BLOB to CLOB and vice versa is done in ValueLob
if (getType() == targetType) {
return this;
}
try {
// decimal conversion
switch (targetType) {
case BOOLEAN: {
switch (getType()) {
case BYTE:
case SHORT:
case INT:
case LONG:
case DECIMAL:
case DOUBLE:
case FLOAT:
return ValueBoolean.get(getSignum() != 0);
case TIME:
case DATE:
case TIMESTAMP:
case TIMESTAMP_TZ:
case BYTES:
case JAVA_OBJECT:
case UUID:
case ENUM:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case BYTE: {
switch (getType()) {
case BOOLEAN:
return ValueByte.get(getBoolean() ? (byte) 1 : (byte) 0);
case SHORT:
case ENUM:
case INT:
return ValueByte.get(convertToByte(getInt(), column));
case LONG:
return ValueByte.get(convertToByte(getLong(), column));
case DECIMAL:
return ValueByte.get(convertToByte(convertToLong(getBigDecimal(), column), column));
case DOUBLE:
return ValueByte.get(convertToByte(convertToLong(getDouble(), column), column));
case FLOAT:
return ValueByte.get(convertToByte(convertToLong(getFloat(), column), column));
case BYTES:
return ValueByte.get((byte) Integer.parseInt(getString(), 16));
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case SHORT: {
switch (getType()) {
case BOOLEAN:
return ValueShort.get(getBoolean() ? (short) 1 : (short) 0);
case BYTE:
return ValueShort.get(getByte());
case ENUM:
case INT:
return ValueShort.get(convertToShort(getInt(), column));
case LONG:
return ValueShort.get(convertToShort(getLong(), column));
case DECIMAL:
return ValueShort.get(convertToShort(convertToLong(getBigDecimal(), column), column));
case DOUBLE:
return ValueShort.get(convertToShort(convertToLong(getDouble(), column), column));
case FLOAT:
return ValueShort.get(convertToShort(convertToLong(getFloat(), column), column));
case BYTES:
return ValueShort.get((short) Integer.parseInt(getString(), 16));
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case INT: {
switch (getType()) {
case BOOLEAN:
return ValueInt.get(getBoolean() ? 1 : 0);
case BYTE:
case ENUM:
case SHORT:
return ValueInt.get(getInt());
case LONG:
return ValueInt.get(convertToInt(getLong(), column));
case DECIMAL:
return ValueInt.get(convertToInt(convertToLong(getBigDecimal(), column), column));
case DOUBLE:
return ValueInt.get(convertToInt(convertToLong(getDouble(), column), column));
case FLOAT:
return ValueInt.get(convertToInt(convertToLong(getFloat(), column), column));
case BYTES:
return ValueInt.get((int) Long.parseLong(getString(), 16));
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case LONG: {
switch (getType()) {
case BOOLEAN:
return ValueLong.get(getBoolean() ? 1 : 0);
case BYTE:
case SHORT:
case ENUM:
case INT:
return ValueLong.get(getInt());
case DECIMAL:
return ValueLong.get(convertToLong(getBigDecimal(), column));
case DOUBLE:
return ValueLong.get(convertToLong(getDouble(), column));
case FLOAT:
return ValueLong.get(convertToLong(getFloat(), column));
case BYTES: {
// parseLong doesn't work for ffffffffffffffff
byte[] d = getBytes();
if (d.length == 8) {
return ValueLong.get(Bits.readLong(d, 0));
}
return ValueLong.get(Long.parseLong(getString(), 16));
}
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case DECIMAL: {
switch (getType()) {
case BOOLEAN:
return ValueDecimal.get(BigDecimal.valueOf(getBoolean() ? 1 : 0));
case BYTE:
case SHORT:
case ENUM:
case INT:
return ValueDecimal.get(BigDecimal.valueOf(getInt()));
case LONG:
return ValueDecimal.get(BigDecimal.valueOf(getLong()));
case DOUBLE: {
double d = getDouble();
if (Double.isInfinite(d) || Double.isNaN(d)) {
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, "" + d);
}
return ValueDecimal.get(BigDecimal.valueOf(d));
}
case FLOAT: {
float f = getFloat();
if (Float.isInfinite(f) || Float.isNaN(f)) {
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, "" + f);
}
// better rounding behavior than BigDecimal.valueOf(f)
return ValueDecimal.get(new BigDecimal(Float.toString(f)));
}
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case DOUBLE: {
switch (getType()) {
case BOOLEAN:
return ValueDouble.get(getBoolean() ? 1 : 0);
case BYTE:
case SHORT:
case INT:
return ValueDouble.get(getInt());
case LONG:
return ValueDouble.get(getLong());
case DECIMAL:
return ValueDouble.get(getBigDecimal().doubleValue());
case FLOAT:
return ValueDouble.get(getFloat());
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case FLOAT: {
switch (getType()) {
case BOOLEAN:
return ValueFloat.get(getBoolean() ? 1 : 0);
case BYTE:
case SHORT:
case INT:
return ValueFloat.get(getInt());
case LONG:
return ValueFloat.get(getLong());
case DECIMAL:
return ValueFloat.get(getBigDecimal().floatValue());
case DOUBLE:
return ValueFloat.get((float) getDouble());
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case DATE: {
switch (getType()) {
case TIME:
// because the time has set the date to 1970-01-01,
// this will be the result
return ValueDate.fromDateValue(DateTimeUtils.EPOCH_DATE_VALUE);
case TIMESTAMP:
return ValueDate.fromDateValue(
((ValueTimestamp) this).getDateValue());
case TIMESTAMP_TZ: {
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
long dateValue = ts.getDateValue(), timeNanos = ts.getTimeNanos();
long millis = DateTimeUtils.getMillis(dateValue, timeNanos, ts.getTimeZoneOffsetMins());
return ValueDate.fromMillis(millis);
}
case ENUM:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case TIME: {
switch (getType()) {
case DATE:
// need to normalize the year, month and day because a date
// has the time set to 0, the result will be 0
return ValueTime.fromNanos(0);
case TIMESTAMP:
return ValueTime.fromNanos(
((ValueTimestamp) this).getTimeNanos());
case TIMESTAMP_TZ: {
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
long dateValue = ts.getDateValue(), timeNanos = ts.getTimeNanos();
long millis = DateTimeUtils.getMillis(dateValue, timeNanos, ts.getTimeZoneOffsetMins());
return ValueTime.fromNanos(DateTimeUtils.nanosFromDate(millis) + timeNanos % 1_000_000);
}
case ENUM:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case TIMESTAMP: {
switch (getType()) {
case TIME:
return DateTimeUtils.normalizeTimestamp(
0, ((ValueTime) this).getNanos());
case DATE:
return ValueTimestamp.fromDateValueAndNanos(
((ValueDate) this).getDateValue(), 0);
case TIMESTAMP_TZ: {
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
long dateValue = ts.getDateValue(), timeNanos = ts.getTimeNanos();
long millis = DateTimeUtils.getMillis(dateValue, timeNanos, ts.getTimeZoneOffsetMins());
return ValueTimestamp.fromMillisNanos(millis, (int) (timeNanos % 1_000_000));
}
case ENUM:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case TIMESTAMP_TZ: {
switch (getType()) {
case TIME: {
ValueTimestamp ts = DateTimeUtils.normalizeTimestamp(0, ((ValueTime) this).getNanos());
return DateTimeUtils.timestampTimeZoneFromLocalDateValueAndNanos(
ts.getDateValue(), ts.getTimeNanos());
}
case DATE:
return DateTimeUtils.timestampTimeZoneFromLocalDateValueAndNanos(
((ValueDate) this).getDateValue(), 0);
case TIMESTAMP: {
ValueTimestamp ts = (ValueTimestamp) this;
return DateTimeUtils.timestampTimeZoneFromLocalDateValueAndNanos(
ts.getDateValue(), ts.getTimeNanos());
}
case ENUM:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case BYTES: {
switch (getType()) {
case JAVA_OBJECT:
case BLOB:
return ValueBytes.getNoCopy(getBytesNoCopy());
case UUID:
case GEOMETRY:
return ValueBytes.getNoCopy(getBytes());
case BYTE:
return ValueBytes.getNoCopy(new byte[]{getByte()});
case SHORT: {
int x = getShort();
return ValueBytes.getNoCopy(new byte[]{
(byte) (x >> 8),
(byte) x
});
}
case INT: {
byte[] b = new byte[4];
Bits.writeInt(b, 0, getInt());
return ValueBytes.getNoCopy(b);
}
case LONG: {
byte[] b = new byte[8];
Bits.writeLong(b, 0, getLong());
return ValueBytes.getNoCopy(b);
}
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case JAVA_OBJECT: {
switch (getType()) {
case BYTES:
case BLOB:
return ValueJavaObject.getNoCopy(
null, getBytesNoCopy(), getDataHandler());
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case ENUM: {
switch (getType()) {
case BYTE:
case SHORT:
case INT:
case LONG:
case DECIMAL:
return ValueEnum.get(enumerators, getInt());
case STRING:
case STRING_IGNORECASE:
case STRING_FIXED:
return ValueEnum.get(enumerators, getString());
default:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
}
case BLOB: {
switch (getType()) {
case BYTES:
return ValueLobDb.createSmallLob(
Value.BLOB, getBytesNoCopy());
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case UUID: {
switch (getType()) {
case BYTES:
return ValueUuid.get(getBytesNoCopy());
case JAVA_OBJECT:
Object object = JdbcUtils.deserialize(getBytesNoCopy(),
getDataHandler());
if (object instanceof java.util.UUID) {
return ValueUuid.get((java.util.UUID) object);
}
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case GEOMETRY: {
switch (getType()) {
case BYTES:
return ValueGeometry.get(getBytesNoCopy());
case JAVA_OBJECT:
Object object = JdbcUtils.deserialize(getBytesNoCopy(), getDataHandler());
if (DataType.isGeometry(object)) {
return ValueGeometry.getFromGeometry(object);
}
//$FALL-THROUGH$
case TIMESTAMP_TZ:
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
}
// conversion by parsing the string value
String s = getString();
switch (targetType) {
case NULL:
return ValueNull.INSTANCE;
case BOOLEAN: {
if (s.equalsIgnoreCase("true") ||
s.equalsIgnoreCase("t") ||
s.equalsIgnoreCase("yes") ||
s.equalsIgnoreCase("y")) {
return ValueBoolean.TRUE;
} else if (s.equalsIgnoreCase("false") ||
s.equalsIgnoreCase("f") ||
s.equalsIgnoreCase("no") ||
s.equalsIgnoreCase("n")) {
return ValueBoolean.FALSE;
} else {
// convert to a number, and if it is not 0 then it is true
return ValueBoolean.get(new BigDecimal(s).signum() != 0);
}
}
case BYTE:
return ValueByte.get(Byte.parseByte(s.trim()));
case SHORT:
return ValueShort.get(Short.parseShort(s.trim()));
case INT:
return ValueInt.get(Integer.parseInt(s.trim()));
case LONG:
return ValueLong.get(Long.parseLong(s.trim()));
case DECIMAL:
return ValueDecimal.get(new BigDecimal(s.trim()));
case TIME:
return ValueTime.parse(s.trim());
case DATE:
return ValueDate.parse(s.trim());
case TIMESTAMP:
return ValueTimestamp.parse(s.trim(), mode);
case TIMESTAMP_TZ:
return ValueTimestampTimeZone.parse(s.trim());
case BYTES:
return ValueBytes.getNoCopy(
StringUtils.convertHexToBytes(s.trim()));
case JAVA_OBJECT:
return ValueJavaObject.getNoCopy(null,
StringUtils.convertHexToBytes(s.trim()), getDataHandler());
case STRING:
return ValueString.get(s);
case STRING_IGNORECASE:
return ValueStringIgnoreCase.get(s);
case STRING_FIXED:
return ValueStringFixed.get(s, precision, mode);
case DOUBLE:
return ValueDouble.get(Double.parseDouble(s.trim()));
case FLOAT:
return ValueFloat.get(Float.parseFloat(s.trim()));
case CLOB:
return ValueLobDb.createSmallLob(
CLOB, s.getBytes(StandardCharsets.UTF_8));
case BLOB:
return ValueLobDb.createSmallLob(
BLOB, StringUtils.convertHexToBytes(s.trim()));
case ARRAY:
return ValueArray.get(new Value[]{ValueString.get(s)});
case RESULT_SET: {
SimpleResultSet rs = new SimpleResultSet();
rs.setAutoClose(false);
rs.addColumn("X", Types.VARCHAR, s.length(), 0);
rs.addRow(s);
return ValueResultSet.get(rs);
}
case UUID:
return ValueUuid.get(s);
case GEOMETRY:
return ValueGeometry.get(s);
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.convert(this, targetType);
}
throw DbException.throwInternalError("type=" + targetType);
}
} catch (NumberFormatException e) {
throw DbException.get(
ErrorCode.DATA_CONVERSION_ERROR_1, e, getString());
}
}
/**
* Compare this value against another value given that the values are of the
* same data type.
*
* @param v the other value
* @param mode the compare mode
* @return 0 if both values are equal, -1 if the other value is smaller, and
* 1 otherwise
*/
public final int compareTypeSafe(Value v, CompareMode mode) {
if (this == v) {
return 0;
} else if (this == ValueNull.INSTANCE) {
return -1;
} else if (v == ValueNull.INSTANCE) {
return 1;
}
return compareSecure(v, mode);
}
/**
* Compare this value against another value using the specified compare
* mode.
*
* @param v the other value
* @param mode the compare mode
* @return 0 if both values are equal, -1 if the other value is smaller, and
* 1 otherwise
*/
public final int compareTo(Value v, CompareMode mode) {
if (this == v) {
return 0;
}
if (this == ValueNull.INSTANCE) {
return v == ValueNull.INSTANCE ? 0 : -1;
} else if (v == ValueNull.INSTANCE) {
return 1;
}
if (getType() == v.getType()) {
return compareSecure(v, mode);
}
int t2 = Value.getHigherOrder(getType(), v.getType());
return convertTo(t2).compareSecure(v.convertTo(t2), mode);
}
public int getScale() {
return 0;
}
/**
* Convert the scale.
*
* @param onlyToSmallerScale if the scale should not reduced
* @param targetScale the requested scale
* @return the value
*/
@SuppressWarnings("unused")
public Value convertScale(boolean onlyToSmallerScale, int targetScale) {
return this;
}
/**
* Convert the precision to the requested value. The precision of the
* returned value may be somewhat larger than requested, because values with
* a fixed precision are not truncated.
*
* @param precision the new precision
* @param force true if losing numeric precision is allowed
* @return the new value
*/
@SuppressWarnings("unused")
public Value convertPrecision(long precision, boolean force) {
return this;
}
private static byte convertToByte(long x, Object column) {
if (x > Byte.MAX_VALUE || x < Byte.MIN_VALUE) {
throw DbException.get(
ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Long.toString(x), getColumnName(column));
}
return (byte) x;
}
private static short convertToShort(long x, Object column) {
if (x > Short.MAX_VALUE || x < Short.MIN_VALUE) {
throw DbException.get(
ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Long.toString(x), getColumnName(column));
}
return (short) x;
}
private static int convertToInt(long x, Object column) {
if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
throw DbException.get(
ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Long.toString(x), getColumnName(column));
}
return (int) x;
}
private static long convertToLong(double x, Object column) {
if (x > Long.MAX_VALUE || x < Long.MIN_VALUE) {
// TODO document that +Infinity, -Infinity throw an exception and
// NaN returns 0
throw DbException.get(
ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Double.toString(x), getColumnName(column));
}
return Math.round(x);
}
private static long convertToLong(BigDecimal x, Object column) {
if (x.compareTo(MAX_LONG_DECIMAL) > 0 ||
x.compareTo(Value.MIN_LONG_DECIMAL) < 0) {
throw DbException.get(
ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, x.toString(), getColumnName(column));
}
return x.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
}
private static String getColumnName(Object column) {
return column == null ? "" : column.toString();
}
/**
* Copy a large value, to be used in the given table. For values that are
* kept fully in memory this method has no effect.
*
* @param handler the data handler
* @param tableId the table where this object is used
* @return the new value or itself
*/
@SuppressWarnings("unused")
public Value copy(DataHandler handler, int tableId) {
return this;
}
/**
* Check if this value is linked to a specific table. For values that are
* kept fully in memory, this method returns false.
*
* @return true if it is
*/
public boolean isLinkedToTable() {
return false;
}
/**
* Remove the underlying resource, if any. For values that are kept fully in
* memory this method has no effect.
*/
public void remove() {
// nothing to do
}
/**
* Check if the precision is smaller or equal than the given precision.
*
* @param precision the maximum precision
* @return true if the precision of this value is smaller or equal to the
* given precision
*/
public boolean checkPrecision(long precision) {
return getPrecision() <= precision;
}
/**
* Get a medium size SQL expression for debugging or tracing. If the
* precision is too large, only a subset of the value is returned.
*
* @return the SQL expression
*/
public String getTraceSQL() {
return getSQL();
}
@Override
public String toString() {
return getTraceSQL();
}
/**
* Throw the exception that the feature is not support for the given data
* type.
*
* @param op the operation
* @return never returns normally
* @throws DbException the exception
*/
protected DbException throwUnsupportedExceptionForType(String op) {
throw DbException.getUnsupportedException(
DataType.getDataType(getType()).name + " " + op);
}
/**
* Get the table (only for LOB object).
*
* @return the table id
*/
public int getTableId() {
return 0;
}
/**
* Get the byte array.
*
* @return the byte array
*/
public byte[] getSmall() {
return null;
}
/**
* Copy this value to a temporary file if necessary.
*
* @return the new value
*/
public Value copyToTemp() {
return this;
}
/**
* Create an independent copy of this value if needed, that will be bound to
* a result. If the original row is removed, this copy is still readable.
*
* @return the value (this for small objects)
*/
public Value copyToResult() {
return this;
}
public ResultSet getResultSet() {
SimpleResultSet rs = new SimpleResultSet();
rs.setAutoClose(false);
rs.addColumn("X", DataType.convertTypeToSQLType(getType()),
MathUtils.convertLongToInt(getPrecision()), getScale());
rs.addRow(getObject());
return rs;
}
/**
* Return the data handler for the values that support it
* (actually only Java objects).
* @return the data handler
*/
protected DataHandler getDataHandler() {
return null;
}
/**
* A "binary large object".
*/
public interface ValueClob {
// this is a marker interface
}
/**
* A "character large object".
*/
public interface ValueBlob {
// this is a marker interface
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueArray.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.lang.reflect.Array;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
/**
* Implementation of the ARRAY data type.
*/
public class ValueArray extends Value {
private final Class<?> componentType;
private final Value[] values;
private int hash;
private ValueArray(Class<?> componentType, Value[] list) {
this.componentType = componentType;
this.values = list;
}
private ValueArray(Value[] list) {
this(Object.class, list);
}
/**
* Get or create a array value for the given value array.
* Do not clone the data.
*
* @param list the value array
* @return the value
*/
public static ValueArray get(Value[] list) {
return new ValueArray(list);
}
/**
* Get or create a array value for the given value array.
* Do not clone the data.
*
* @param componentType the array class (null for Object[])
* @param list the value array
* @return the value
*/
public static ValueArray get(Class<?> componentType, Value[] list) {
return new ValueArray(componentType, list);
}
@Override
public int hashCode() {
if (hash != 0) {
return hash;
}
int h = 1;
for (Value v : values) {
h = h * 31 + v.hashCode();
}
hash = h;
return h;
}
public Value[] getList() {
return values;
}
@Override
public int getType() {
return Value.ARRAY;
}
public Class<?> getComponentType() {
return componentType;
}
@Override
public long getPrecision() {
long p = 0;
for (Value v : values) {
p += v.getPrecision();
}
return p;
}
@Override
public String getString() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getString());
}
return buff.append(')').toString();
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueArray v = (ValueArray) o;
if (values == v.values) {
return 0;
}
int l = values.length;
int ol = v.values.length;
int len = Math.min(l, ol);
for (int i = 0; i < len; i++) {
Value v1 = values[i];
Value v2 = v.values[i];
int comp = v1.compareTo(v2, mode);
if (comp != 0) {
return comp;
}
}
return Integer.compare(l, ol);
}
@Override
public Object getObject() {
int len = values.length;
Object[] list = (Object[]) Array.newInstance(componentType, len);
for (int i = 0; i < len; i++) {
final Value value = values[i];
if (!SysProperties.OLD_RESULT_SET_GET_OBJECT) {
final int type = value.getType();
if (type == Value.BYTE || type == Value.SHORT) {
list[i] = value.getInt();
continue;
}
}
list[i] = value.getObject();
}
return list;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) {
throw throwUnsupportedExceptionForType("PreparedStatement.set");
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v.getSQL());
}
if (values.length == 1) {
buff.append(',');
}
return buff.append(')').toString();
}
@Override
public String getTraceSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Value v : values) {
buff.appendExceptFirst(", ");
buff.append(v == null ? "null" : v.getTraceSQL());
}
return buff.append(')').toString();
}
@Override
public int getDisplaySize() {
long size = 0;
for (Value v : values) {
size += v.getDisplaySize();
}
return MathUtils.convertLongToInt(size);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueArray)) {
return false;
}
ValueArray v = (ValueArray) other;
if (values == v.values) {
return true;
}
int len = values.length;
if (len != v.values.length) {
return false;
}
for (int i = 0; i < len; i++) {
if (!values[i].equals(v.values[i])) {
return false;
}
}
return true;
}
@Override
public int getMemory() {
int memory = 32;
for (Value v : values) {
memory += v.getMemory() + Constants.MEMORY_POINTER;
}
return memory;
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (!force) {
return this;
}
ArrayList<Value> list = New.arrayList();
for (Value v : values) {
v = v.convertPrecision(precision, true);
// empty byte arrays or strings have precision 0
// they count as precision 1 here
precision -= Math.max(1, v.getPrecision());
if (precision < 0) {
break;
}
list.add(v);
}
return get(list.toArray(new Value[0]));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueBoolean.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Implementation of the BOOLEAN data type.
*/
public class ValueBoolean extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 1;
/**
* The maximum display size of a boolean.
* Example: FALSE
*/
public static final int DISPLAY_SIZE = 5;
/**
* TRUE value.
*/
public static final ValueBoolean TRUE = new ValueBoolean(true);
/**
* FALSE value.
*/
public static final ValueBoolean FALSE = new ValueBoolean(false);
private final boolean value;
private ValueBoolean(boolean value) {
this.value = value;
}
@Override
public int getType() {
return Value.BOOLEAN;
}
@Override
public String getSQL() {
return getString();
}
@Override
public String getString() {
return value ? "TRUE" : "FALSE";
}
@Override
public Value negate() {
return value ? FALSE : TRUE;
}
@Override
public boolean getBoolean() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueBoolean v = (ValueBoolean) o;
return Boolean.compare(value, v.value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value ? 1 : 0;
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setBoolean(parameterIndex, value);
}
/**
* Get the boolean value for the given boolean.
*
* @param b the boolean
* @return the value
*/
public static ValueBoolean get(boolean b) {
return b ? TRUE : FALSE;
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
// there are only ever two instances, so the instance must match
return this == other;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueByte.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Implementation of the BYTE data type.
*/
public class ValueByte extends Value {
/**
* The precision in digits.
*/
static final int PRECISION = 3;
/**
* The display size for a byte.
* Example: -127
*/
static final int DISPLAY_SIZE = 4;
private final byte value;
private ValueByte(byte value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueByte other = (ValueByte) v;
return checkRange(value + other.value);
}
private static ValueByte checkRange(int x) {
if (x < Byte.MIN_VALUE || x > Byte.MAX_VALUE) {
throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1,
Integer.toString(x));
}
return ValueByte.get((byte) x);
}
@Override
public int getSignum() {
return Integer.signum(value);
}
@Override
public Value negate() {
return checkRange(-(int) value);
}
@Override
public Value subtract(Value v) {
ValueByte other = (ValueByte) v;
return checkRange(value - other.value);
}
@Override
public Value multiply(Value v) {
ValueByte other = (ValueByte) v;
return checkRange(value * other.value);
}
@Override
public Value divide(Value v) {
ValueByte other = (ValueByte) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueByte.get((byte) (value / other.value));
}
@Override
public Value modulus(Value v) {
ValueByte other = (ValueByte) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueByte.get((byte) (value % other.value));
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.BYTE;
}
@Override
public byte getByte() {
return value;
}
@Override
public int getInt() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueByte v = (ValueByte) o;
return Integer.compare(value, v.value);
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value;
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setByte(parameterIndex, value);
}
/**
* Get or create byte value for the given byte.
*
* @param i the byte
* @return the value
*/
public static ValueByte get(byte i) {
return (ValueByte) Value.cache(new ValueByte(i));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueByte && value == ((ValueByte) other).value;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueBytes.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import org.h2.engine.SysProperties;
import org.h2.util.Bits;
import org.h2.util.MathUtils;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* Implementation of the BINARY data type.
* It is also the base class for ValueJavaObject.
*/
public class ValueBytes extends Value {
private static final ValueBytes EMPTY = new ValueBytes(Utils.EMPTY_BYTES);
/**
* The value.
*/
protected byte[] value;
/**
* The hash code.
*/
protected int hash;
protected ValueBytes(byte[] v) {
this.value = v;
}
/**
* Get or create a bytes value for the given byte array.
* Clone the data.
*
* @param b the byte array
* @return the value
*/
public static ValueBytes get(byte[] b) {
if (b.length == 0) {
return EMPTY;
}
b = Utils.cloneByteArray(b);
return getNoCopy(b);
}
/**
* Get or create a bytes value for the given byte array.
* Do not clone the date.
*
* @param b the byte array
* @return the value
*/
public static ValueBytes getNoCopy(byte[] b) {
if (b.length == 0) {
return EMPTY;
}
ValueBytes obj = new ValueBytes(b);
if (b.length > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
return (ValueBytes) Value.cache(obj);
}
@Override
public int getType() {
return Value.BYTES;
}
@Override
public String getSQL() {
return "X'" + StringUtils.convertBytesToHex(getBytesNoCopy()) + "'";
}
@Override
public byte[] getBytesNoCopy() {
return value;
}
@Override
public byte[] getBytes() {
return Utils.cloneByteArray(getBytesNoCopy());
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
byte[] v2 = ((ValueBytes) v).value;
if (mode.isBinaryUnsigned()) {
return Bits.compareNotNullUnsigned(value, v2);
}
return Bits.compareNotNullSigned(value, v2);
}
@Override
public String getString() {
return StringUtils.convertBytesToHex(value);
}
@Override
public long getPrecision() {
return value.length;
}
@Override
public int hashCode() {
if (hash == 0) {
hash = Utils.getByteArrayHash(value);
}
return hash;
}
@Override
public Object getObject() {
return getBytes();
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setBytes(parameterIndex, value);
}
@Override
public int getDisplaySize() {
return MathUtils.convertLongToInt(value.length * 2L);
}
@Override
public int getMemory() {
return value.length + 24;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueBytes
&& Arrays.equals(value, ((ValueBytes) other).value);
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (value.length <= precision) {
return this;
}
int len = MathUtils.convertLongToInt(precision);
byte[] buff = Arrays.copyOf(value, len);
return get(buff);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueDate.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.util.DateTimeUtils;
/**
* Implementation of the DATE data type.
*/
public class ValueDate extends Value {
/**
* The default precision and display size of the textual representation of a date.
* Example: 2000-01-02
*/
public static final int PRECISION = 10;
private final long dateValue;
private ValueDate(long dateValue) {
this.dateValue = dateValue;
}
/**
* Get or create a date value for the given date.
*
* @param dateValue the date value
* @return the value
*/
public static ValueDate fromDateValue(long dateValue) {
return (ValueDate) Value.cache(new ValueDate(dateValue));
}
/**
* Get or create a date value for the given date.
*
* @param date the date
* @return the value
*/
public static ValueDate get(Date date) {
return fromDateValue(DateTimeUtils.dateValueFromDate(date.getTime()));
}
/**
* Calculate the date value (in the default timezone) from a given time in
* milliseconds in UTC.
*
* @param ms the milliseconds
* @return the value
*/
public static ValueDate fromMillis(long ms) {
return fromDateValue(DateTimeUtils.dateValueFromDate(ms));
}
/**
* Parse a string to a ValueDate.
*
* @param s the string to parse
* @return the date
*/
public static ValueDate parse(String s) {
try {
return fromDateValue(DateTimeUtils.parseDateValue(s, 0, s.length()));
} catch (Exception e) {
throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2,
e, "DATE", s);
}
}
public long getDateValue() {
return dateValue;
}
@Override
public Date getDate() {
return DateTimeUtils.convertDateValueToDate(dateValue);
}
@Override
public int getType() {
return Value.DATE;
}
@Override
public String getString() {
StringBuilder buff = new StringBuilder(PRECISION);
DateTimeUtils.appendDate(buff, dateValue);
return buff.toString();
}
@Override
public String getSQL() {
return "DATE '" + getString() + "'";
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getDisplaySize() {
return PRECISION;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
return Long.compare(dateValue, ((ValueDate) o).dateValue);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
return other instanceof ValueDate
&& dateValue == (((ValueDate) other).dateValue);
}
@Override
public int hashCode() {
return (int) (dateValue ^ (dateValue >>> 32));
}
@Override
public Object getObject() {
return getDate();
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setDate(parameterIndex, getDate());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueDecimal.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.util.MathUtils;
/**
* Implementation of the DECIMAL data type.
*/
public class ValueDecimal extends Value {
/**
* The value 'zero'.
*/
public static final Object ZERO = new ValueDecimal(BigDecimal.ZERO);
/**
* The value 'one'.
*/
public static final Object ONE = new ValueDecimal(BigDecimal.ONE);
/**
* The default precision for a decimal value.
*/
static final int DEFAULT_PRECISION = 65535;
/**
* The default scale for a decimal value.
*/
static final int DEFAULT_SCALE = 32767;
/**
* The default display size for a decimal value.
*/
static final int DEFAULT_DISPLAY_SIZE = 65535;
private static final int DIVIDE_SCALE_ADD = 25;
/**
* The maximum scale of a BigDecimal value.
*/
private static final int BIG_DECIMAL_SCALE_MAX = 100_000;
private final BigDecimal value;
private String valueString;
private int precision;
private ValueDecimal(BigDecimal value) {
if (value == null) {
throw new IllegalArgumentException("null");
} else if (!value.getClass().equals(BigDecimal.class)) {
throw DbException.get(ErrorCode.INVALID_CLASS_2,
BigDecimal.class.getName(), value.getClass().getName());
}
this.value = value;
}
@Override
public Value add(Value v) {
ValueDecimal dec = (ValueDecimal) v;
return ValueDecimal.get(value.add(dec.value));
}
@Override
public Value subtract(Value v) {
ValueDecimal dec = (ValueDecimal) v;
return ValueDecimal.get(value.subtract(dec.value));
}
@Override
public Value negate() {
return ValueDecimal.get(value.negate());
}
@Override
public Value multiply(Value v) {
ValueDecimal dec = (ValueDecimal) v;
return ValueDecimal.get(value.multiply(dec.value));
}
@Override
public Value divide(Value v) {
ValueDecimal dec = (ValueDecimal) v;
if (dec.value.signum() == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
BigDecimal bd = value.divide(dec.value,
value.scale() + DIVIDE_SCALE_ADD,
BigDecimal.ROUND_HALF_DOWN);
if (bd.signum() == 0) {
bd = BigDecimal.ZERO;
} else if (bd.scale() > 0) {
if (!bd.unscaledValue().testBit(0)) {
bd = bd.stripTrailingZeros();
}
}
return ValueDecimal.get(bd);
}
@Override
public ValueDecimal modulus(Value v) {
ValueDecimal dec = (ValueDecimal) v;
if (dec.value.signum() == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
BigDecimal bd = value.remainder(dec.value);
return ValueDecimal.get(bd);
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.DECIMAL;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueDecimal v = (ValueDecimal) o;
return value.compareTo(v.value);
}
@Override
public int getSignum() {
return value.signum();
}
@Override
public BigDecimal getBigDecimal() {
return value;
}
@Override
public String getString() {
if (valueString == null) {
String p = value.toPlainString();
if (p.length() < 40) {
valueString = p;
} else {
valueString = value.toString();
}
}
return valueString;
}
@Override
public long getPrecision() {
if (precision == 0) {
precision = value.precision();
}
return precision;
}
@Override
public boolean checkPrecision(long prec) {
if (prec == DEFAULT_PRECISION) {
return true;
}
return getPrecision() <= prec;
}
@Override
public int getScale() {
return value.scale();
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setBigDecimal(parameterIndex, value);
}
@Override
public Value convertScale(boolean onlyToSmallerScale, int targetScale) {
if (value.scale() == targetScale) {
return this;
}
if (onlyToSmallerScale || targetScale >= DEFAULT_SCALE) {
if (value.scale() < targetScale) {
return this;
}
}
BigDecimal bd = ValueDecimal.setScale(value, targetScale);
return ValueDecimal.get(bd);
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (getPrecision() <= precision) {
return this;
}
if (force) {
return get(BigDecimal.valueOf(value.doubleValue()));
}
throw DbException.get(
ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1,
Long.toString(precision));
}
/**
* Get or create big decimal value for the given big decimal.
*
* @param dec the bit decimal
* @return the value
*/
public static ValueDecimal get(BigDecimal dec) {
if (BigDecimal.ZERO.equals(dec)) {
return (ValueDecimal) ZERO;
} else if (BigDecimal.ONE.equals(dec)) {
return (ValueDecimal) ONE;
}
return (ValueDecimal) Value.cache(new ValueDecimal(dec));
}
@Override
public int getDisplaySize() {
// add 2 characters for '-' and '.'
return MathUtils.convertLongToInt(getPrecision() + 2);
}
@Override
public boolean equals(Object other) {
// Two BigDecimal objects are considered equal only if they are equal in
// value and scale (thus 2.0 is not equal to 2.00 when using equals;
// however -0.0 and 0.0 are). Can not use compareTo because 2.0 and 2.00
// have different hash codes
return other instanceof ValueDecimal &&
value.equals(((ValueDecimal) other).value);
}
@Override
public int getMemory() {
return value.precision() + 120;
}
/**
* Set the scale of a BigDecimal value.
*
* @param bd the BigDecimal value
* @param scale the new scale
* @return the scaled value
*/
public static BigDecimal setScale(BigDecimal bd, int scale) {
if (scale > BIG_DECIMAL_SCALE_MAX || scale < -BIG_DECIMAL_SCALE_MAX) {
throw DbException.getInvalidValueException("scale", scale);
}
return bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.