proj_name
stringclasses 157
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
49
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
---|---|---|---|---|---|---|---|---|---|
HotswapProjects_HotswapAgent | HotswapAgent/plugin/hotswap-agent-zk-plugin/src/main/java/org/hotswap/agent/plugin/zk/ZkPlugin.java | ZkPlugin | binderImplRegisterVariable | class ZkPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(ZkPlugin.class);
// clear labels cache
ReflectionCommand refreshLabels = new ReflectionCommand(this, "org.zkoss.util.resource.Labels", "reset");
@Init
Scheduler scheduler;
@Init
ClassLoader appClassLoader;
/**
* Initialize the plugin after DHtmlLayoutServlet.init() method.
*/
@OnClassLoadEvent(classNameRegexp = "org.zkoss.zk.ui.http.DHtmlLayoutServlet")
public static void layoutServletCallInitialized(CtClass ctClass) throws NotFoundException, CannotCompileException {
CtMethod init = ctClass.getDeclaredMethod("init");
init.insertAfter(PluginManagerInvoker.buildInitializePlugin(ZkPlugin.class));
LOGGER.debug("org.zkoss.zk.ui.http.DHtmlLayoutServlet enahnced with plugin initialization.");
}
/**
* Default values of caches in development mode.
* <p/>
* Note, that this is a little bit aggressive, but the user may override this by providing explicit value in zk.xml
*/
@OnClassLoadEvent(classNameRegexp = "org.zkoss.lang.Library")
public static void defaultDisableCaches(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
LOGGER.debug("org.zkoss.lang.Library enhanced to replace property '*.cache' default value to 'false'.");
CtMethod m = ctClass.getDeclaredMethod("getProperty", new CtClass[]{classPool.get("java.lang.String")});
// see http://books.zkoss.org/wiki/ZK%20Configuration%20Reference/zk.xml/The%20Library%20Properties
defaultLibraryPropertyFalse(m, "org.zkoss.web.classWebResource.cache");
defaultLibraryPropertyFalse(m, "org.zkoss.zk.WPD.cache");
defaultLibraryPropertyFalse(m, "org.zkoss.zk.WCS.cache");
// see. http://zk.datalite.cz/wiki/-/wiki/Main/DLComposer++-+MVC+Controller#section-DLComposer++-+MVC+Controller-ImplementationDetails
defaultLibraryPropertyFalse(m, "zk-dl.annotation.cache");
}
private static void defaultLibraryPropertyFalse(CtMethod m, String setPropertyFalse) throws CannotCompileException {
m.insertAfter("if (_props.get(key) == null && \"" + setPropertyFalse + "\".equals(key)) return \"false\";");
}
@OnResourceFileEvent(path = "/", filter = ".*.properties")
public void refreshProperties() {
// unable to tell if properties are ZK labels or not for custom label locator.
// however Label refresh is very cheep, do it for any properties.
scheduler.scheduleCommand(refreshLabels);
}
/**
* BeanELResolver contains reflection cache (bean properites).
*/
@OnClassLoadEvent(classNameRegexp = "org.zkoss.zel.BeanELResolver")
public static void beanELResolverRegisterVariable(CtClass ctClass) throws CannotCompileException {
String registerThis = PluginManagerInvoker.buildCallPluginMethod(ZkPlugin.class, "registerBeanELResolver",
"this", "java.lang.Object");
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter(registerThis);
}
ctClass.addMethod(CtNewMethod.make("public void __resetCache() {" +
" this.cache = new org.zkoss.zel.BeanELResolver.ConcurrentCache(CACHE_SIZE); " +
"}", ctClass));
LOGGER.debug("org.zkoss.zel.BeanELResolver - added method __resetCache().");
}
Set<Object> registeredBeanELResolvers = Collections.newSetFromMap(new WeakHashMap<Object, Boolean>());
public void registerBeanELResolver(Object beanELResolver) {
registeredBeanELResolvers.add(beanELResolver);
}
/**
* BeanELResolver contains reflection cache (bean properites).
*/
@OnClassLoadEvent(classNameRegexp = "org.zkoss.bind.impl.BinderImpl")
public static void binderImplRegisterVariable(CtClass ctClass) throws CannotCompileException {<FILL_FUNCTION_BODY>}
Set<Object> registerBinderImpls = Collections.newSetFromMap(new WeakHashMap<Object, Boolean>());
public void registerBinderImpl(Object binderImpl) {
registerBinderImpls.add(binderImpl);
}
// invalidate BeanELResolver caches after any class reload (it is cheap to rebuild from reflection)
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void invalidateClassCache() throws Exception {
scheduler.scheduleCommand(invalidateClassCache);
}
// schedule refresh in case of multiple class redefinition to merge command executions
private Command invalidateClassCache = new Command() {
@Override
public void executeCommand() {
LOGGER.debug("Refreshing ZK BeanELResolver and BinderImpl caches.");
try {
Method beanElResolverMethod = resolveClass("org.zkoss.zel.BeanELResolver").getDeclaredMethod("__resetCache");
for (Object registeredBeanELResolver : registeredBeanELResolvers) {
LOGGER.trace("Invoking org.zkoss.zel.BeanELResolver.__resetCache on {}", registeredBeanELResolver);
beanElResolverMethod.invoke(registeredBeanELResolver);
}
Method binderImplMethod = resolveClass("org.zkoss.bind.impl.BinderImpl").getDeclaredMethod("__resetCache");
for (Object registerBinderImpl : registerBinderImpls)
binderImplMethod.invoke(registerBinderImpl);
Field afterComposeMethodCache = resolveClass("org.zkoss.bind.BindComposer").getDeclaredField("_afterComposeMethodCache");
afterComposeMethodCache.setAccessible(true);
((Map)afterComposeMethodCache.get(null)).clear();
} catch (Exception e) {
LOGGER.error("Error refreshing ZK BeanELResolver and BinderImpl caches.", e);
}
}
};
private Class<?> resolveClass(String name) throws ClassNotFoundException {
return Class.forName(name, true, appClassLoader);
}
} |
String registerThis = PluginManagerInvoker.buildCallPluginMethod(ZkPlugin.class, "registerBinderImpl",
"this", "java.lang.Object");
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter(registerThis);
}
ctClass.addMethod(CtNewMethod.make("public void __resetCache() {" +
" this._initMethodCache = new org.zkoss.util.CacheMap(600,org.zkoss.util.CacheMap.DEFAULT_LIFETIME); " +
" this._commandMethodCache = new org.zkoss.util.CacheMap(600,org.zkoss.util.CacheMap.DEFAULT_LIFETIME); " +
" this._globalCommandMethodCache = new org.zkoss.util.CacheMap(600,org.zkoss.util.CacheMap.DEFAULT_LIFETIME); " +
"}", ctClass));
LOGGER.debug("org.zkoss.bind.impl.BinderImpl - added method __resetCache().");
| 1,693 | 279 | 1,972 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/AOStorage.java | AOStorage | openBTreeMap | class AOStorage extends StorageBase {
public static final String SUFFIX_AO_FILE = ".db";
public static final int SUFFIX_AO_FILE_LENGTH = SUFFIX_AO_FILE.length();
AOStorage(Map<String, Object> config) {
super(config);
if (config.containsKey(StorageSetting.IN_MEMORY.name()))
return;
String storagePath = getStoragePath();
DataUtils.checkNotNull(storagePath, "storage path");
if (!FileUtils.exists(storagePath))
FileUtils.createDirectories(storagePath);
FilePath dir = FilePath.get(storagePath);
for (FilePath fp : dir.newDirectoryStream()) {
String mapFullName = fp.getName();
if (mapFullName.startsWith(TEMP_NAME_PREFIX)) {
fp.delete();
}
}
}
@Override
protected InputStream getInputStream(String mapName, FilePath file) {
return openBTreeMap(mapName).getInputStream(file);
}
@Override
public String getStorageName() {
return AOStorageEngine.NAME;
}
public boolean isReadOnly() {
return config.containsKey(DbSetting.READ_ONLY.name());
}
@Override
public <K, V> StorageMap<K, V> openMap(String name, StorageDataType keyType,
StorageDataType valueType, Map<String, String> parameters) {
String mapType = parameters == null ? null : parameters.get(StorageSetting.MAP_TYPE.name());
return openMap(name, mapType, keyType, valueType, parameters);
}
public <K, V> StorageMap<K, V> openMap(String name, String mapType, StorageDataType keyType,
StorageDataType valueType, Map<String, String> parameters) {
if (mapType == null || mapType.equalsIgnoreCase("BTreeMap")) {
return openBTreeMap(name, keyType, valueType, parameters);
} else {
throw DataUtils.newIllegalArgumentException("Unknow map type: {0}", mapType);
}
}
public <K, V> BTreeMap<K, V> openBTreeMap(String name) {
return openBTreeMap(name, null, null, null);
}
@SuppressWarnings("unchecked")
public <K, V> BTreeMap<K, V> openBTreeMap(String name, StorageDataType keyType,
StorageDataType valueType, Map<String, String> parameters) {<FILL_FUNCTION_BODY>}
} |
StorageMap<?, ?> map = maps.get(name);
if (map == null) {
synchronized (this) {
map = maps.get(name);
if (map == null) {
CaseInsensitiveMap<Object> c = new CaseInsensitiveMap<>(config);
if (parameters != null)
c.putAll(parameters);
map = new BTreeMap<>(name, keyType, valueType, c, this);
for (StorageEventListener listener : listeners.values())
listener.afterStorageMapOpen(map);
// 执行完afterStorageMapOpen后再put,确保其他线程拿到的是一个就绪后的map
maps.put(name, map);
}
}
}
return (BTreeMap<K, V>) map;
| 666 | 197 | 863 | <methods>public void <init>(Map<java.lang.String,java.lang.Object>) ,public void backupTo(java.lang.String, java.lang.Long) ,public void backupTo(java.lang.String, java.util.zip.ZipOutputStream, java.lang.Long) ,public void close() ,public void closeImmediately() ,public void closeMap(java.lang.String) ,public static java.util.zip.ZipOutputStream createZipOutputStream(java.lang.String) throws java.io.IOException,public void drop() ,public long getDiskSpaceUsed() ,public StorageMap<?,?> getMap(java.lang.String) ,public Set<java.lang.String> getMapNames() ,public long getMemorySpaceUsed() ,public com.lealone.db.scheduler.SchedulerFactory getSchedulerFactory() ,public java.lang.String getStoragePath() ,public boolean hasMap(java.lang.String) ,public boolean isClosed() ,public boolean isInMemory() ,public java.lang.String nextTemporaryMapName() ,public void registerEventListener(com.lealone.storage.StorageEventListener) ,public void save() ,public void setSchedulerFactory(com.lealone.db.scheduler.SchedulerFactory) ,public void unregisterEventListener(com.lealone.storage.StorageEventListener) <variables>protected static final java.lang.String TEMP_NAME_PREFIX,protected boolean closed,protected final non-sealed Map<java.lang.String,java.lang.Object> config,protected final Map<com.lealone.storage.StorageEventListener,com.lealone.storage.StorageEventListener> listeners,protected final Map<java.lang.String,StorageMap<?,?>> maps,protected com.lealone.db.scheduler.SchedulerFactory schedulerFactory |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/AOStorageBuilder.java | AOStorageBuilder | openStorage | class AOStorageBuilder extends StorageBuilder {
private static final HashMap<String, AOStorage> cache = new HashMap<>();
public AOStorageBuilder() {
this(null);
}
public AOStorageBuilder(Map<String, String> defaultConfig) {
if (defaultConfig != null)
config.putAll(defaultConfig);
}
@Override
public AOStorage openStorage() {<FILL_FUNCTION_BODY>}
private SchedulerFactory getSchedulerFactory() {
SchedulerFactory sf = (SchedulerFactory) config.get(StorageSetting.SCHEDULER_FACTORY.name());
if (sf == null) {
sf = SchedulerFactory.getDefaultSchedulerFactory();
if (sf == null) {
CaseInsensitiveMap<String> config = new CaseInsensitiveMap<>(this.config.size());
for (Map.Entry<String, Object> e : this.config.entrySet()) {
config.put(e.getKey(), e.getValue().toString());
}
sf = SchedulerFactory.initDefaultSchedulerFactory(EmbeddedScheduler.class.getName(),
config);
}
}
if (!sf.isStarted())
sf.start();
return sf;
}
} |
String storagePath = (String) config.get(StorageSetting.STORAGE_PATH.name());
if (!config.containsKey(StorageSetting.IN_MEMORY.name()))
DataUtils.checkNotNull(storagePath, "storage path");
AOStorage storage = cache.get(storagePath);
if (storage == null) {
synchronized (cache) {
storage = cache.get(storagePath);
if (storage == null) {
storage = new AOStorage(config);
SchedulerFactory sf = getSchedulerFactory();
storage.setSchedulerFactory(sf);
cache.put(storagePath, storage);
}
}
}
return storage;
| 332 | 173 | 505 | <methods>public non-sealed void <init>() ,public com.lealone.storage.StorageBuilder cacheSize(int) ,public com.lealone.storage.StorageBuilder compress() ,public com.lealone.storage.StorageBuilder compressHigh() ,public com.lealone.storage.StorageBuilder encryptionKey(char[]) ,public com.lealone.storage.StorageBuilder inMemory() ,public com.lealone.storage.StorageBuilder minFillRate(int) ,public abstract com.lealone.storage.Storage openStorage() ,public com.lealone.storage.StorageBuilder pageSize(int) ,public com.lealone.storage.StorageBuilder readOnly() ,public com.lealone.storage.StorageBuilder schedulerFactory(com.lealone.db.scheduler.SchedulerFactory) ,public com.lealone.storage.StorageBuilder storagePath(java.lang.String) ,public java.lang.String toString() <variables>protected final HashMap<java.lang.String,java.lang.Object> config |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/BTreeCursor.java | BTreeCursor | hasNext | class BTreeCursor<K, V> implements StorageMapCursor<K, V> {
private final BTreeMap<K, ?> map;
private final CursorParameters<K> parameters;
private CursorPos pos;
private K key;
private V value;
public BTreeCursor(BTreeMap<K, ?> map, CursorParameters<K> parameters) {
this.map = map;
this.parameters = parameters;
// 定位到>=from的第一个leaf page
min(map.getRootPage(), parameters.from);
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public IPage getPage() {
return pos.page;
}
@Override
@SuppressWarnings("unchecked")
public boolean next() {
if (hasNext()) {
int index = pos.index++;
key = (K) pos.page.getKey(index);
if (parameters.allColumns)
value = (V) pos.page.getValue(index, true);
else
value = (V) pos.page.getValue(index, parameters.columnIndexes);
return true;
}
return false;
}
private boolean hasNext() {<FILL_FUNCTION_BODY>}
/**
* Fetch the next entry that is equal or larger than the given key, starting
* from the given page. This method retains the stack.
*
* @param p the page to start
* @param from the key to search
*/
private void min(Page p, K from) {
while (true) {
if (p.isLeaf()) {
int x = from == null ? 0 : p.binarySearch(from);
if (x < 0) {
x = -x - 1;
}
pos = new CursorPos(p, x, pos);
break;
}
int x = from == null ? 0 : p.getPageIndex(from);
pos = new CursorPos(p, x + 1, pos);
p = p.getChildPage(x);
}
}
private static class CursorPos {
/**
* The current page.
*/
final Page page;
/**
* The current index.
*/
int index;
/**
* The position in the parent page, if any.
*/
final CursorPos parent;
CursorPos(Page page, int index, CursorPos parent) {
this.page = page;
this.index = index;
this.parent = parent;
}
}
} |
while (pos != null) {
if (pos.index < pos.page.getKeyCount()) {
return true;
}
pos = pos.parent;
if (pos == null) {
return false;
}
if (pos.index < map.getChildPageCount(pos.page)) {
min(pos.page.getChildPage(pos.index++), null);
}
}
return false;
| 692 | 113 | 805 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/BTreeGC.java | GcingPage | forEachPage | class GcingPage implements Comparable<GcingPage> {
PageReference ref;
PageInfo pInfo;
GcingPage(PageReference ref, PageInfo pInfo) {
this.ref = ref;
this.pInfo = pInfo;
}
long getLastTime() {
return pInfo.getLastTime();
}
@Override
public int compareTo(GcingPage o) {
// 不能直接相减,否则可能抛异常: Comparison method violates its general contract!
return Long.compare(getLastTime(), o.getLastTime());
}
}
private void lru(TransactionEngine te, MemoryManager memoryManager) {
// 按层级收集node page,单独收集leaf page
HashMap<Integer, ArrayList<GcingPage>> nodePageMap = new HashMap<>();
ArrayList<GcingPage> leafPages = new ArrayList<>();
collect(te, map.getRootPageRef(), leafPages, nodePageMap, 1);
// leaf page按LastTime从小到大释放
releaseLeafPages(leafPages, memoryManager);
// 从最下层的node page开始释放
if (gcNodePages)
releaseNodePages(nodePageMap, memoryManager);
}
private void collect(TransactionEngine te, PageReference ref, ArrayList<GcingPage> leafPages,
HashMap<Integer, ArrayList<GcingPage>> nodePageMap, int level) {
PageInfo pInfo = ref.getPageInfo();
Page p = pInfo.page;
if (p != null && p.isNode()) {
forEachPage(p, childRef -> {
collect(te, childRef, leafPages, nodePageMap, level + 1);
});
}
if (ref.canGc(te)) {
if (ref.isNodePage()) {
if (gcNodePages) {
ArrayList<GcingPage> nodePages = nodePageMap.get(level);
if (nodePages == null) {
nodePages = new ArrayList<>();
nodePageMap.put(level, nodePages);
}
nodePages.add(new GcingPage(ref, pInfo));
}
} else {
leafPages.add(new GcingPage(ref, pInfo));
}
}
}
private void releaseLeafPages(ArrayList<GcingPage> leafPages, MemoryManager memoryManager) {
int size = leafPages.size();
if (size == 0)
return;
Collections.sort(leafPages);
int index = size / 2 + 1;
// 先释放前一半的page字段和buff字段
release(leafPages, 0, index, 0);
// 再释放后一半
if (memoryManager.needGc()) {
release(leafPages, index, size, 1); // 先释放page字段
if (memoryManager.needGc())
release(leafPages, index, size, 2); // 如果内存依然紧张再释放buff字段
}
}
private void releaseNodePages(HashMap<Integer, ArrayList<GcingPage>> nodePageMap,
MemoryManager memoryManager) {
if (!nodePageMap.isEmpty() && memoryManager.needGc()) {
ArrayList<Integer> levelList = new ArrayList<>(nodePageMap.keySet());
Collections.sort(levelList);
for (int i = levelList.size() - 1; i >= 0; i--) {
ArrayList<GcingPage> nodePages = nodePageMap.get(levelList.get(i));
int size = nodePages.size();
if (size > 0) {
release(nodePages, 0, size, 1); // 先释放page字段
if (memoryManager.needGc())
release(nodePages, 0, size, 2); // 如果内存依然紧张再释放buff字段
}
if (!memoryManager.needGc())
break;
}
}
}
private void release(ArrayList<GcingPage> list, int startIndex, int endIndex, int gcType) {
for (int i = startIndex; i < endIndex; i++) {
GcingPage gp = list.get(i);
PageInfo pInfoNew = gp.ref.gcPage(gp.pInfo, gcType);
if (pInfoNew != null)
gp.pInfo = pInfoNew;
}
}
private void forEachPage(Page p, Consumer<PageReference> action) {<FILL_FUNCTION_BODY> |
PageReference[] children = p.getChildren();
for (int i = 0, len = children.length; i < len; i++) {
PageReference childRef = children[i];
if (childRef != null) {
action.accept(childRef);
}
}
| 1,145 | 75 | 1,220 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/BTreeMap.java | RootPageReference | getMinMax | class RootPageReference extends PageReference {
public RootPageReference(BTreeStorage bs) {
super(bs);
}
@Override
public void replacePage(Page newRoot) {
newRoot.setRef(this);
if (getPage() != newRoot && newRoot.isNode()) {
for (PageReference ref : newRoot.getChildren()) {
if (ref.getPage() != null && ref.getParentRef() != this)
ref.setParentRef(this);
}
}
super.replacePage(newRoot);
}
@Override
public boolean isRoot() {
return true;
}
}
// btree的root page引用,最开始是一个leaf page,随时都会指向新的page
private final RootPageReference rootRef;
private final SchedulerFactory schedulerFactory;
public BTreeMap(String name, StorageDataType keyType, StorageDataType valueType,
Map<String, Object> config, AOStorage aoStorage) {
super(name, keyType, valueType, aoStorage);
DataUtils.checkNotNull(config, "config");
schedulerFactory = aoStorage.getSchedulerFactory();
// 只要包含就为true
readOnly = config.containsKey(DbSetting.READ_ONLY.name());
inMemory = config.containsKey(StorageSetting.IN_MEMORY.name());
this.config = config;
Object mode = config.get(StorageSetting.PAGE_STORAGE_MODE.name());
if (mode != null) {
pageStorageMode = PageStorageMode.valueOf(mode.toString().toUpperCase());
}
btreeStorage = new BTreeStorage(this);
rootRef = new RootPageReference(btreeStorage);
Chunk lastChunk = btreeStorage.getChunkManager().getLastChunk();
if (lastChunk != null) {
size.set(lastChunk.mapSize);
rootRef.getPageInfo().pos = lastChunk.rootPagePos;
Page root = rootRef.getOrReadPage();
// 提前设置,如果root page是node类型,子page就能在Page.getChildPage中找到ParentRef
rootRef.replacePage(root);
setMaxKey(lastKey());
} else {
Page root = LeafPage.createEmpty(this);
rootRef.replacePage(root);
}
}
public Page getRootPage() {
return rootRef.getOrReadPage();
}
public PageReference getRootPageRef() {
return rootRef;
}
public void newRoot(Page newRoot) {
rootRef.replacePage(newRoot);
}
public Map<String, Object> getConfig() {
return config;
}
public Object getConfig(String key) {
return config.get(key);
}
public BTreeStorage getBTreeStorage() {
return btreeStorage;
}
public PageStorageMode getPageStorageMode() {
return pageStorageMode;
}
public void setPageStorageMode(PageStorageMode pageStorageMode) {
this.pageStorageMode = pageStorageMode;
}
public SchedulerFactory getSchedulerFactory() {
return schedulerFactory;
}
@Override
public V get(K key) {
return binarySearch(key, true);
}
public V get(K key, boolean allColumns) {
return binarySearch(key, allColumns);
}
public V get(K key, int columnIndex) {
return binarySearch(key, new int[] { columnIndex });
}
@Override
public Object[] getObjects(K key, int[] columnIndexes) {
Page p = getRootPage().gotoLeafPage(key);
int index = p.binarySearch(key);
Object v = index >= 0 ? p.getValue(index, columnIndexes) : null;
return new Object[] { p, v };
}
@SuppressWarnings("unchecked")
private V binarySearch(Object key, boolean allColumns) {
Page p = getRootPage().gotoLeafPage(key);
int index = p.binarySearch(key);
return index >= 0 ? (V) p.getValue(index, allColumns) : null;
}
@SuppressWarnings("unchecked")
private V binarySearch(Object key, int[] columnIndexes) {
Page p = getRootPage().gotoLeafPage(key);
int index = p.binarySearch(key);
return index >= 0 ? (V) p.getValue(index, columnIndexes) : null;
}
@Override
public K firstKey() {
return getFirstLast(true);
}
@Override
public K lastKey() {
return getFirstLast(false);
}
/**
* Get the first (lowest) or last (largest) key.
*
* @param first whether to retrieve the first key
* @return the key, or null if the map is empty
*/
@SuppressWarnings("unchecked")
private K getFirstLast(boolean first) {
if (isEmpty()) {
return null;
}
Page p = getRootPage();
while (true) {
if (p.isLeaf()) {
return (K) p.getKey(first ? 0 : p.getKeyCount() - 1);
}
p = p.getChildPage(first ? 0 : getChildPageCount(p) - 1);
}
}
@Override
public K lowerKey(K key) {
return getMinMax(key, true, true);
}
@Override
public K floorKey(K key) {
return getMinMax(key, true, false);
}
@Override
public K higherKey(K key) {
return getMinMax(key, false, true);
}
@Override
public K ceilingKey(K key) {
return getMinMax(key, false, false);
}
/**
* Get the smallest or largest key using the given bounds.
*
* @param key the key
* @param min whether to retrieve the smallest key
* @param excluding if the given upper/lower bound is exclusive
* @return the key, or null if no such key exists
*/
private K getMinMax(K key, boolean min, boolean excluding) {
return getMinMax(getRootPage(), key, min, excluding);
}
@SuppressWarnings("unchecked")
private K getMinMax(Page p, K key, boolean min, boolean excluding) {<FILL_FUNCTION_BODY> |
if (p.isLeaf()) {
int x = p.binarySearch(key);
if (x < 0) {
x = -x - (min ? 2 : 1);
} else if (excluding) {
x += min ? -1 : 1;
}
if (x < 0 || x >= p.getKeyCount()) {
return null;
}
return (K) p.getKey(x);
}
int x = p.getPageIndex(key);
while (true) {
if (x < 0 || x >= getChildPageCount(p)) {
return null;
}
K k = getMinMax(p.getChildPage(x), key, min, excluding);
if (k != null) {
return k;
}
x += min ? -1 : 1;
}
| 1,690 | 220 | 1,910 | <methods>public long getAndAddKey(long) ,public com.lealone.storage.type.StorageDataType getKeyType() ,public long getMaxKey() ,public java.lang.String getName() ,public ConcurrentHashMap<java.lang.Object,java.lang.Object> getOldValueCache() ,public com.lealone.storage.Storage getStorage() ,public com.lealone.storage.type.StorageDataType getValueType() ,public long incrementAndGetMaxKey() ,public void setMaxKey(K) <variables>protected final non-sealed com.lealone.storage.type.StorageDataType keyType,protected final java.util.concurrent.atomic.AtomicLong maxKey,protected final non-sealed java.lang.String name,private final ConcurrentHashMap<java.lang.Object,java.lang.Object> oldValueCache,protected final non-sealed com.lealone.storage.Storage storage,protected final non-sealed com.lealone.storage.type.StorageDataType valueType |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/chunk/ChunkCompactor.java | ChunkCompactor | rewrite | class ChunkCompactor {
private final BTreeStorage btreeStorage;
private final ChunkManager chunkManager;
public ChunkCompactor(BTreeStorage btreeStorage, ChunkManager chunkManager) {
this.btreeStorage = btreeStorage;
this.chunkManager = chunkManager;
}
public void executeCompact() {
HashSet<Long> removedPages = chunkManager.getAllRemovedPages();
if (removedPages.isEmpty())
return;
// 读取被删除了至少一个page的chunk的元数据
List<Chunk> chunks = readChunks(removedPages);
// 如果chunk中的page都被标记为删除了,说明这个chunk已经不再使用了,可以直接删除它
List<Chunk> unusedChunks = findUnusedChunks(chunks, removedPages);
if (!unusedChunks.isEmpty()) {
removeUnusedChunks(unusedChunks, removedPages);
chunks.removeAll(unusedChunks);
}
// 看看哪些chunk中未被删除的page占比<=MinFillRate,然后重写它们到一个新的chunk中
rewrite(chunks, removedPages);
}
private List<Chunk> readChunks(HashSet<Long> removedPages) {
HashSet<Integer> chunkIds = new HashSet<>();
for (Long pagePos : removedPages) {
if (!PageUtils.isNodePage(pagePos))
chunkIds.add(PageUtils.getPageChunkId(pagePos));
}
return chunkManager.readChunks(chunkIds);
}
// 在这里顺便把LivePage的总长度都算好了
private List<Chunk> findUnusedChunks(List<Chunk> chunks, HashSet<Long> removedPages) {
ArrayList<Chunk> unusedChunks = new ArrayList<>();
for (Chunk c : chunks) {
c.sumOfLivePageLength = 0;
boolean unused = true;
for (Entry<Long, Integer> e : c.pagePositionToLengthMap.entrySet()) {
if (!removedPages.contains(e.getKey())) {
c.sumOfLivePageLength += e.getValue();
unused = false;
}
}
if (unused)
unusedChunks.add(c);
}
return unusedChunks;
}
private void removeUnusedChunks(List<Chunk> unusedChunks, HashSet<Long> removedPages) {
if (removedPages.isEmpty())
return;
int size = removedPages.size();
for (Chunk c : unusedChunks) {
chunkManager.removeUnusedChunk(c);
removedPages.removeAll(c.pagePositionToLengthMap.keySet());
}
if (size > removedPages.size()) {
if (chunkManager.getLastChunk() != null) {
removedPages = chunkManager.getAllRemovedPages();
chunkManager.getLastChunk().updateRemovedPages(removedPages);
}
}
}
private void rewrite(List<Chunk> chunks, HashSet<Long> removedPages) {<FILL_FUNCTION_BODY>}
// 按chunk的FillRate从小到大排序,然后选一批chunk出来重写,并且这批chunk重写后的总长度不能超过一个chunk的容量
private List<Chunk> getRewritableChunks(List<Chunk> chunks) {
int minFillRate = btreeStorage.getMinFillRate();
List<Chunk> old = new ArrayList<>();
for (Chunk c : chunks) {
if (c.getFillRate() > minFillRate)
continue;
old.add(c);
}
if (old.isEmpty())
return old;
Collections.sort(old, (o1, o2) -> {
long comp = o1.getFillRate() - o2.getFillRate();
if (comp == 0) {
comp = o1.sumOfLivePageLength - o2.sumOfLivePageLength;
}
return Long.signum(comp);
});
long bytes = 0;
int index = 0;
int size = old.size();
long maxBytesToWrite = Chunk.MAX_SIZE;
for (; index < size; index++) {
bytes += old.get(index).sumOfLivePageLength;
if (bytes > maxBytesToWrite) // 不能超过chunk的最大容量
break;
}
return index == size ? old : old.subList(0, index + 1);
}
} |
// minFillRate <= 0时相当于禁用rewrite了,removedPages为空说明没有page被删除了
if (btreeStorage.getMinFillRate() <= 0 || removedPages.isEmpty())
return;
List<Chunk> old = getRewritableChunks(chunks);
boolean saveIfNeeded = false;
for (Chunk c : old) {
for (Entry<Long, Integer> e : c.pagePositionToLengthMap.entrySet()) {
long pos = e.getKey();
if (!removedPages.contains(pos)) {
if (PageUtils.isNodePage(pos)) {
chunkManager.addRemovedPage(pos);
} else {
// 直接标记为脏页即可,不用更新元素
btreeStorage.markDirtyLeafPage(pos);
saveIfNeeded = true;
if (Page.ASSERT) {
if (!chunkManager.getRemovedPages().contains(pos)) {
DbException.throwInternalError("not dirty: " + pos);
}
}
}
}
}
}
if (saveIfNeeded) {
btreeStorage.executeSave(false);
removeUnusedChunks(old, removedPages);
}
| 1,166 | 315 | 1,481 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/chunk/ChunkManager.java | ChunkManager | getChunkFileName | class ChunkManager {
private final BTreeStorage btreeStorage;
private final ConcurrentSkipListSet<Long> removedPages = new ConcurrentSkipListSet<>();
private final ConcurrentHashMap<Integer, String> idToChunkFileNameMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Integer, Chunk> chunks = new ConcurrentHashMap<>();
private final BitField chunkIds = new BitField();
private Chunk lastChunk;
private long maxSeq;
public ChunkManager(BTreeStorage bTreeStorage) {
btreeStorage = bTreeStorage;
}
public void init(String mapBaseDir) {
int lastChunkId = 0;
String[] files = new File(mapBaseDir).list();
for (String f : files) {
if (f.endsWith(AOStorage.SUFFIX_AO_FILE)) {
// chunk文件名格式: c_[chunkId]_[sequence]
String str = f.substring(2, f.length() - AOStorage.SUFFIX_AO_FILE_LENGTH);
int pos = str.indexOf('_');
int id = Integer.parseInt(str.substring(0, pos));
long seq = Long.parseLong(str.substring(pos + 1));
if (seq > maxSeq) {
maxSeq = seq;
lastChunkId = id;
}
chunkIds.set(id);
idToChunkFileNameMap.put(id, f);
}
}
readLastChunk(lastChunkId);
}
private void readLastChunk(int lastChunkId) {
try {
if (lastChunkId > 0) {
lastChunk = readChunk(lastChunkId);
} else {
lastChunk = null;
}
} catch (IllegalStateException e) {
throw btreeStorage.panic(e);
} catch (Exception e) {
throw btreeStorage.panic(DataUtils.ERROR_READING_FAILED, "Failed to read last chunk: {0}",
lastChunkId, e);
}
}
public Chunk getLastChunk() {
return lastChunk;
}
public void setLastChunk(Chunk lastChunk) {
this.lastChunk = lastChunk;
}
public String getChunkFileName(int chunkId) {<FILL_FUNCTION_BODY>}
String createChunkFileName(int chunkId) {
// chunk文件名格式: c_[chunkId]_[sequence]
return "c_" + chunkId + "_" + nextSeq() + AOStorage.SUFFIX_AO_FILE;
}
private long nextSeq() {
return ++maxSeq;
}
public synchronized void close() {
for (Chunk c : chunks.values()) {
if (c.fileStorage != null)
c.fileStorage.close();
}
// maxSeq = 0;
// for (Integer id : idToChunkFileNameMap.keySet()) {
// chunkIds.clear(id);
// }
chunks.clear();
// idToChunkFileNameMap.clear();
removedPages.clear();
lastChunk = null;
}
private synchronized Chunk readChunk(int chunkId) {
if (chunks.containsKey(chunkId))
return chunks.get(chunkId);
Chunk chunk = new Chunk(chunkId);
chunk.read(btreeStorage);
chunks.put(chunk.id, chunk);
return chunk;
}
public Chunk getChunk(long pos) {
int chunkId = PageUtils.getPageChunkId(pos);
return getChunk(chunkId);
}
public Chunk getChunk(int chunkId) {
Chunk c = chunks.get(chunkId);
if (c == null)
c = readChunk(chunkId);
if (c == null)
throw DataUtils.newIllegalStateException(DataUtils.ERROR_FILE_CORRUPT, "Chunk {0} not found",
chunkId);
return c;
}
public Chunk createChunk() {
int id = chunkIds.nextClearBit(1);
chunkIds.set(id);
Chunk c = new Chunk(id);
c.fileName = createChunkFileName(id);
// chunks.put(id, c);
return c;
}
public void addChunk(Chunk c) {
chunkIds.set(c.id);
chunks.put(c.id, c);
idToChunkFileNameMap.put(c.id, c.fileName);
}
synchronized void removeUnusedChunk(Chunk c) {
c.fileStorage.close();
c.fileStorage.delete();
chunkIds.clear(c.id);
chunks.remove(c.id);
idToChunkFileNameMap.remove(c.id);
removedPages.removeAll(c.pagePositionToLengthMap.keySet());
if (c == lastChunk)
lastChunk = null;
}
List<Chunk> readChunks(HashSet<Integer> chunkIds) {
ArrayList<Chunk> list = new ArrayList<>(chunkIds.size());
for (int id : chunkIds) {
if (!chunks.containsKey(id)) {
readChunk(id);
}
list.add(chunks.get(id));
}
return list;
}
public InputStream getChunkInputStream(FilePath file) {
String name = file.getName();
if (name.endsWith(AOStorage.SUFFIX_AO_FILE)) {
// chunk文件名格式: c_[chunkId]_[sequence]
String str = name.substring(2, name.length() - AOStorage.SUFFIX_AO_FILE_LENGTH);
int pos = str.indexOf('_');
int chunkId = Integer.parseInt(str.substring(0, pos));
return getChunk(chunkId).fileStorage.getInputStream();
}
return null;
}
public void addRemovedPage(long pos) {
removedPages.add(pos);
}
public Set<Long> getRemovedPages() {
return removedPages;
}
public HashSet<Long> getAllRemovedPages() {
HashSet<Long> removedPages = new HashSet<>(this.removedPages);
if (lastChunk != null)
removedPages.addAll(lastChunk.getRemovedPages());
return removedPages;
}
public Set<Integer> getAllChunkIds() {
return idToChunkFileNameMap.keySet();
}
} |
String f = idToChunkFileNameMap.get(chunkId);
if (f == null)
throw DbException.getInternalError();
return f;
| 1,752 | 45 | 1,797 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/page/ColumnPage.java | ColumnPage | write | class ColumnPage extends Page {
private final AtomicInteger memory = new AtomicInteger(0);
private ByteBuffer buff;
ColumnPage(BTreeMap<?, ?> map) {
super(map);
}
@Override
public int getMemory() {
return memory.get();
}
@Override
public void read(ByteBuffer buff, int chunkId, int offset, int expectedPageLength) {
int start = buff.position();
int pageLength = buff.getInt();
checkPageLength(chunkId, pageLength, expectedPageLength);
readCheckValue(buff, chunkId, offset, pageLength);
buff.get(); // page type;
int compressType = buff.get();
// 解压完之后就结束了,因为还不知道具体的行,所以延迟对列进行反序列化
this.buff = expandPage(buff, compressType, start, pageLength);
}
// 在read方法中已经把buff读出来了,这里只是把字段从buff中解析出来
void readColumn(Object[] values, int columnIndex) {
int memory = 0;
ByteBuffer buff = this.buff.slice(); // 要支持多线程同时读,所以直接用slice
StorageDataType valueType = map.getValueType();
for (int row = 0, rowCount = values.length; row < rowCount; row++) {
valueType.readColumn(buff, values[row], columnIndex);
memory += valueType.getMemory(values[row], columnIndex);
}
if (this.memory.compareAndSet(0, memory)) {
// buff内存大小在getOrReadPage中加了,这里只加列占用的内存大小
map.getBTreeStorage().getBTreeGC().addUsedMemory(memory);
}
}
long write(Chunk chunk, DataBuffer buff, Object[] values, int columnIndex) {<FILL_FUNCTION_BODY>}
} |
PageInfo pInfoOld = getRef().getPageInfo();
beforeWrite(pInfoOld);
int start = buff.position();
int type = PageUtils.PAGE_TYPE_COLUMN;
buff.putInt(0); // 回填pageLength
StorageDataType valueType = map.getValueType();
int checkPos = buff.position();
buff.putShort((short) 0);
buff.put((byte) type);
int compressTypePos = buff.position();
int compressType = 0;
buff.put((byte) compressType); // 调用compressPage时会回填
int compressStart = buff.position();
for (int row = 0, rowCount = values.length; row < rowCount; row++) {
valueType.writeColumn(buff, values[row], columnIndex);
}
compressPage(buff, compressStart, compressType, compressTypePos);
int pageLength = buff.position() - start;
buff.putInt(start, pageLength);
writeCheckValue(buff, chunk, start, pageLength, checkPos);
return updateChunkAndPage(pInfoOld, chunk, start, pageLength, type);
| 488 | 293 | 781 | <methods>public int binarySearch(java.lang.Object) ,public com.lealone.storage.aose.btree.page.Page copy() ,public com.lealone.storage.aose.btree.page.Page copyAndInsertLeaf(int, java.lang.Object, java.lang.Object) ,public static com.lealone.storage.aose.btree.page.Page create(BTreeMap<?,?>, int) ,public com.lealone.storage.aose.btree.page.Page getChildPage(int) ,public com.lealone.storage.aose.btree.page.PageReference getChildPageReference(int) ,public com.lealone.storage.aose.btree.page.PageReference[] getChildren() ,public java.lang.Object getKey(int) ,public int getKeyCount() ,public int getMemory() ,public int getPageIndex(java.lang.Object) ,public long getPos() ,public int getRawChildPageCount() ,public com.lealone.storage.aose.btree.page.PageReference getRef() ,public java.lang.Object getValue(int) ,public java.lang.Object getValue(int, int[]) ,public java.lang.Object getValue(int, boolean) ,public com.lealone.storage.aose.btree.page.Page gotoLeafPage(java.lang.Object) ,public boolean isEmpty() ,public boolean isLeaf() ,public boolean isNode() ,public void markDirty() ,public void markDirtyBottomUp() ,public void read(java.nio.ByteBuffer, int, int, int) ,public void remove(int) ,public void setRef(com.lealone.storage.aose.btree.page.PageReference) ,public java.lang.Object setValue(int, java.lang.Object) ,public long writeUnsavedRecursive(com.lealone.storage.aose.btree.page.PageInfo, com.lealone.storage.aose.btree.chunk.Chunk, com.lealone.db.DataBuffer) <variables>public static final boolean ASSERT,protected final non-sealed BTreeMap<?,?> map,private com.lealone.storage.aose.btree.page.PageReference ref |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/page/LocalPage.java | LocalPage | binarySearch | class LocalPage extends Page {
/**
* The last result of a find operation is cached.
*/
protected int cachedCompare;
/**
* The estimated memory used.
*/
protected int memory;
/**
* The keys.
* <p>
* The array might be larger than needed, to avoid frequent re-sizing.
*/
protected Object[] keys;
protected LocalPage(BTreeMap<?, ?> map) {
super(map);
}
@Override
public Object getKey(int index) {
return keys[index];
}
@Override
public int getKeyCount() {
return keys.length;
}
/**
* Search the key in this page using a binary search. Instead of always
* starting the search in the middle, the last found index is cached.
* <p>
* If the key was found, the returned value is the index in the key array.
* If not found, the returned value is negative, where -1 means the provided
* key is smaller than any keys in this page. See also Arrays.binarySearch.
*
* @param key the key
* @return the value or null
*/
@Override
public int binarySearch(Object key) {<FILL_FUNCTION_BODY>}
@Override
boolean needSplit() {
return memory > map.getBTreeStorage().getPageSize() && keys.length > 1;
}
@Override
public void remove(int index) {
int keyLength = keys.length;
int keyIndex = index >= keyLength ? index - 1 : index;
Object old = keys[keyIndex];
addMemory(-map.getKeyType().getMemory(old));
Object[] newKeys = new Object[keyLength - 1];
DataUtils.copyExcept(keys, newKeys, keyLength, keyIndex);
keys = newKeys;
}
protected abstract void recalculateMemory();
protected int recalculateKeysMemory() {
int mem = PageUtils.PAGE_MEMORY;
StorageDataType keyType = map.getKeyType();
for (int i = 0, len = keys.length; i < len; i++) {
mem += keyType.getMemory(keys[i]);
}
return mem;
}
@Override
public int getMemory() {
return memory;
}
protected void addMemory(int mem) {
addMemory(mem, true);
}
protected void addMemory(int mem, boolean addToUsedMemory) {
memory += mem;
if (addToUsedMemory)
map.getBTreeStorage().getBTreeGC().addUsedMemory(mem);
}
protected void copy(LocalPage newPage) {
newPage.cachedCompare = cachedCompare;
newPage.setRef(getRef());
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof LocalPage) {
long pos = getPos();
if (pos != 0 && ((LocalPage) other).getPos() == pos) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
return super.hashCode();
// long pos = getPos();
// return pos != 0 ? (int) (pos | (pos >>> 32)) : super.hashCode();
}
@Override
public String toString() {
return PrettyPagePrinter.getPrettyPageInfo(this, false);
}
} |
int low = 0, high = keys.length - 1;
// the cached index minus one, so that
// for the first time (when cachedCompare is 0),
// the default value is used
int x = cachedCompare - 1;
if (x < 0 || x > high) {
x = high >>> 1;
}
Object[] k = keys;
StorageDataType keyType = map.getKeyType();
while (low <= high) {
int compare = keyType.compare(key, k[x]);
if (compare > 0) {
low = x + 1;
} else if (compare < 0) {
high = x - 1;
} else {
cachedCompare = x + 1;
return x;
}
x = (low + high) >>> 1;
}
cachedCompare = low;
return -(low + 1);
| 915 | 229 | 1,144 | <methods>public int binarySearch(java.lang.Object) ,public com.lealone.storage.aose.btree.page.Page copy() ,public com.lealone.storage.aose.btree.page.Page copyAndInsertLeaf(int, java.lang.Object, java.lang.Object) ,public static com.lealone.storage.aose.btree.page.Page create(BTreeMap<?,?>, int) ,public com.lealone.storage.aose.btree.page.Page getChildPage(int) ,public com.lealone.storage.aose.btree.page.PageReference getChildPageReference(int) ,public com.lealone.storage.aose.btree.page.PageReference[] getChildren() ,public java.lang.Object getKey(int) ,public int getKeyCount() ,public int getMemory() ,public int getPageIndex(java.lang.Object) ,public long getPos() ,public int getRawChildPageCount() ,public com.lealone.storage.aose.btree.page.PageReference getRef() ,public java.lang.Object getValue(int) ,public java.lang.Object getValue(int, int[]) ,public java.lang.Object getValue(int, boolean) ,public com.lealone.storage.aose.btree.page.Page gotoLeafPage(java.lang.Object) ,public boolean isEmpty() ,public boolean isLeaf() ,public boolean isNode() ,public void markDirty() ,public void markDirtyBottomUp() ,public void read(java.nio.ByteBuffer, int, int, int) ,public void remove(int) ,public void setRef(com.lealone.storage.aose.btree.page.PageReference) ,public java.lang.Object setValue(int, java.lang.Object) ,public long writeUnsavedRecursive(com.lealone.storage.aose.btree.page.PageInfo, com.lealone.storage.aose.btree.chunk.Chunk, com.lealone.db.DataBuffer) <variables>public static final boolean ASSERT,protected final non-sealed BTreeMap<?,?> map,private com.lealone.storage.aose.btree.page.PageReference ref |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/page/PageInfo.java | PageInfo | copy | class PageInfo {
public Page page;
public long pos;
public ByteBuffer buff;
public int pageLength;
public long markDirtyCount;
public long lastTime;
public int hits; // 只是一个预估值,不需要精确
public PageInfo() {
}
public PageInfo(Page page, long pos) {
this.page = page;
this.pos = pos;
}
public void updateTime() {
lastTime = System.currentTimeMillis();
hits++;
if (hits < 0)
hits = 1;
}
public void updateTime(PageInfo pInfoOld) {
lastTime = pInfoOld.lastTime;
hits = pInfoOld.hits;
}
public Page getPage() {
return page;
}
public long getPos() {
return pos;
}
public int getPageMemory() {
return page == null ? 0 : page.getMemory();
}
public int getBuffMemory() {
return buff == null ? 0 : buff.limit();
}
public int getTotalMemory() {
return getPageMemory() + getBuffMemory();
}
public long getLastTime() {
return lastTime;
}
public int getHits() {
return hits;
}
public void releaseBuff() {
buff = null;
}
public void releasePage() {
page = null;
}
public PageInfo copy(long newPos) {
PageInfo pInfo = copy(false);
pInfo.pos = newPos;
return pInfo;
}
public PageInfo copy(boolean gc) {<FILL_FUNCTION_BODY>}
public boolean isSplitted() {
return false;
}
public PageReference getNewRef() {
return null;
}
public PageReference getLeftRef() {
return null;
}
public PageReference getRightRef() {
return null;
}
public static class SplittedPageInfo extends PageInfo {
private final PageReference pRefNew;
private final PageReference lRef;
private final PageReference rRef;
public SplittedPageInfo(PageReference pRefNew, PageReference lRef, PageReference rRef) {
this.pRefNew = pRefNew;
this.lRef = lRef;
this.rRef = rRef;
}
@Override
public boolean isSplitted() {
return true;
}
@Override
public PageReference getNewRef() {
return pRefNew;
}
@Override
public PageReference getLeftRef() {
return lRef;
}
@Override
public PageReference getRightRef() {
return rRef;
}
}
} |
PageInfo pInfo = new PageInfo();
pInfo.page = page;
pInfo.pos = pos;
pInfo.buff = buff;
pInfo.pageLength = pageLength;
pInfo.markDirtyCount = markDirtyCount;
if (!gc) {
pInfo.lastTime = lastTime;
pInfo.hits = hits;
}
return pInfo;
| 734 | 105 | 839 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/page/PageOperations.java | Append | writeLocal | class Append<K, V> extends Put<K, V, K> {
public Append(BTreeMap<K, V> map, V value, AsyncHandler<AsyncResult<K>> resultHandler) {
super(map, null, value, resultHandler);
}
@Override
protected Page gotoLeafPage() { // 直接定位到最后一页
Page p = map.getRootPage();
while (true) {
if (p.isLeaf()) {
return p;
}
p = p.getChildPage(map.getChildPageCount(p) - 1);
}
}
@Override
protected int getKeyIndex() {
return -(p.getKeyCount() + 1);
}
@Override
@SuppressWarnings("unchecked")
protected Object writeLocal(int index, Scheduler scheduler) {<FILL_FUNCTION_BODY>}
} |
long k = map.incrementAndGetMaxKey();
if (map.getKeyType() == ValueLong.type)
key = (K) Long.valueOf(k);
else
key = (K) ValueLong.get(k);
insertLeaf(index, value); // 执行insertLeaf的过程中已经把当前页标记为脏页了
return key;
| 238 | 96 | 334 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/page/PageUtils.java | PageUtils | getPagePos | class PageUtils {
/**
* The type for leaf page.
*/
public static final int PAGE_TYPE_LEAF = 0;
/**
* The type for node page.
*/
public static final int PAGE_TYPE_NODE = 1;
/**
* The type for column page.
*/
public static final int PAGE_TYPE_COLUMN = 2;
/**
* The bit mask for compressed pages (compression level fast).
*/
public static final int PAGE_COMPRESSED = 2;
/**
* The bit mask for compressed pages (compression level high).
*/
public static final int PAGE_COMPRESSED_HIGH = 2 + 4;
/**
* The estimated number of bytes used per page object.
*/
public static final int PAGE_MEMORY = 128;
/**
* The estimated number of bytes used per child entry.
*/
public static final int PAGE_MEMORY_CHILD = 16;
/**
* Get the chunk id from the position.
*
* @param pos the position
* @return the chunk id
*/
public static int getPageChunkId(long pos) {
return (int) (pos >>> 34);
}
/**
* Get the offset from the position.
*
* @param pos the position
* @return the offset
*/
public static int getPageOffset(long pos) {
return (int) (pos >> 2);
}
/**
* Get the page type from the position.
*
* @param pos the position
* @return the page type (PAGE_TYPE_NODE or PAGE_TYPE_LEAF)
*/
public static int getPageType(long pos) {
return ((int) pos) & 3;
}
/**
* Get the position of this page. The following information is encoded in
* the position: the chunk id, the offset, and the type (node or leaf).
*
* @param chunkId the chunk id
* @param offset the offset
* @param type the page type (1 for node, 0 for leaf)
* @return the position
*/
public static long getPagePos(int chunkId, int offset, int type) {<FILL_FUNCTION_BODY>}
public static boolean isLeafPage(long pos) {
return pos > 0 && getPageType(pos) == PAGE_TYPE_LEAF;
}
public static boolean isNodePage(long pos) {
return pos > 0 && getPageType(pos) == PAGE_TYPE_NODE;
}
} |
long pos = (long) chunkId << 34; // 往右移,相当于空出来34位,chunkId占64-34=30位
pos |= (long) offset << 2; // offset占34-2=32位
pos |= type; // type占2位
return pos;
| 670 | 82 | 752 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/btree/page/PrettyPagePrinter.java | PrettyPagePrinter | getPrettyPageInfoRecursive | class PrettyPagePrinter {
public static void printPage(Page p) {
printPage(p, true);
}
public static void printPage(Page p, boolean readOffLinePage) {
System.out.println(getPrettyPageInfo(p, readOffLinePage));
}
public static String getPrettyPageInfo(Page p, boolean readOffLinePage) {
StringBuilder buff = new StringBuilder();
PrettyPageInfo info = new PrettyPageInfo();
info.readOffLinePage = readOffLinePage;
getPrettyPageInfoRecursive(p, "", info);
buff.append("PrettyPageInfo:").append('\n');
buff.append("--------------").append('\n');
buff.append("pageCount: ").append(info.pageCount).append('\n');
buff.append("leafPageCount: ").append(info.leafPageCount).append('\n');
buff.append("nodePageCount: ").append(info.nodePageCount).append('\n');
buff.append("levelCount: ").append(info.levelCount).append('\n');
buff.append('\n');
buff.append("pages:").append('\n');
buff.append("--------------------------------").append('\n');
buff.append(info.buff).append('\n');
return buff.toString();
}
private static void getPrettyPageInfoRecursive(Page p, String indent, PrettyPageInfo info) {<FILL_FUNCTION_BODY>}
private static void getPrettyNodePageInfo(Page p, StringBuilder buff, String indent,
PrettyPageInfo info) {
PageReference[] children = p.getChildren();
if (children != null) {
buff.append(indent).append("children: ").append(children.length).append('\n');
for (int i = 0, len = children.length; i < len; i++) {
buff.append('\n');
if (children[i].getPage() != null) {
getPrettyPageInfoRecursive(children[i].getPage(), indent + " ", info);
} else {
if (info.readOffLinePage) {
Page child = children[i].getOrReadPage();
getPrettyPageInfoRecursive(child, indent + " ", info);
} else {
buff.append(indent).append(" ");
buff.append("*** off-line *** ").append(children[i]).append('\n');
}
}
}
}
}
private static void getPrettyLeafPageInfo(Page p, StringBuilder buff, String indent,
PrettyPageInfo info) {
buff.append(indent).append("values: ");
for (int i = 0, len = p.getKeyCount(); i < len; i++) {
if (i > 0)
buff.append(", ");
buff.append(p.getValue(i));
}
buff.append('\n');
}
private static class PrettyPageInfo {
StringBuilder buff = new StringBuilder();
int pageCount;
int leafPageCount;
int nodePageCount;
int levelCount;
boolean readOffLinePage;
}
} |
StringBuilder buff = info.buff;
info.pageCount++;
if (p.isNode())
info.nodePageCount++;
else
info.leafPageCount++;
int levelCount = indent.length() / 2 + 1;
if (levelCount > info.levelCount)
info.levelCount = levelCount;
buff.append(indent).append("type: ").append(p.isLeaf() ? "leaf" : "node").append('\n');
buff.append(indent).append("pos: ").append(p.getPos()).append('\n');
buff.append(indent).append("chunkId: ").append(PageUtils.getPageChunkId(p.getPos()))
.append('\n');
// buff.append(indent).append("totalCount: ").append(p.getTotalCount()).append('\n');
buff.append(indent).append("memory: ").append(p.getMemory()).append('\n');
buff.append(indent).append("keyLength: ").append(p.getKeyCount()).append('\n');
if (p.getKeyCount() > 0) {
buff.append(indent).append("keys: ");
for (int i = 0, len = p.getKeyCount(); i < len; i++) {
if (i > 0)
buff.append(", ");
buff.append(p.getKey(i));
}
buff.append('\n');
if (p.isNode())
getPrettyNodePageInfo(p, buff, indent, info);
else
getPrettyLeafPageInfo(p, buff, indent, info);
}
| 822 | 421 | 1,243 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aose/src/main/java/com/lealone/storage/aose/lob/LobStreamMap.java | Stream | skip | class Stream extends InputStream {
private final LobStreamMap lobStreamMap;
private final long length;
private ByteBuffer idBuffer;
private ByteArrayInputStream buffer;
private byte[] oneByteBuffer;
private long skip;
private long pos;
Stream(LobStreamMap lobStreamMap, byte[] id) {
this.lobStreamMap = lobStreamMap;
this.length = lobStreamMap.length(id);
this.idBuffer = ByteBuffer.wrap(id);
}
@Override
public int read() throws IOException {
byte[] buffer = oneByteBuffer;
if (buffer == null) {
buffer = oneByteBuffer = new byte[1];
}
int len = read(buffer, 0, 1);
return len == -1 ? -1 : (buffer[0] & 255);
}
@Override
public long skip(long n) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
buffer = null;
idBuffer.position(idBuffer.limit());
pos = length;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (len <= 0) {
return 0;
}
while (true) {
if (buffer == null) {
try {
buffer = nextBuffer();
} catch (IllegalStateException e) {
String msg = DataUtils.formatMessage(DataUtils.ERROR_BLOCK_NOT_FOUND,
"Block not found in id {0}", Arrays.toString(idBuffer.array()));
throw new IOException(msg, e);
}
if (buffer == null) {
return -1;
}
}
int result = buffer.read(b, off, len);
if (result > 0) {
pos += result;
return result;
}
buffer = null;
}
}
private ByteArrayInputStream nextBuffer() {
while (idBuffer.hasRemaining()) {
switch (idBuffer.get()) {
case 0: {
int len = DataUtils.readVarInt(idBuffer);
if (skip >= len) {
skip -= len;
idBuffer.position(idBuffer.position() + len);
continue;
}
int p = (int) (idBuffer.position() + skip);
int l = (int) (len - skip);
idBuffer.position(p + l);
return new ByteArrayInputStream(idBuffer.array(), p, l);
}
case 1: {
int len = DataUtils.readVarInt(idBuffer);
long key = DataUtils.readVarLong(idBuffer);
if (skip >= len) {
skip -= len;
continue;
}
byte[] data = lobStreamMap.getBlock(key);
int s = (int) skip;
skip = 0;
return new ByteArrayInputStream(data, s, data.length - s);
}
case 2: {
long len = DataUtils.readVarLong(idBuffer);
long key = DataUtils.readVarLong(idBuffer);
if (skip >= len) {
skip -= len;
continue;
}
byte[] k = lobStreamMap.getBlock(key);
ByteBuffer newBuffer = ByteBuffer
.allocate(k.length + idBuffer.limit() - idBuffer.position());
newBuffer.put(k);
newBuffer.put(idBuffer);
newBuffer.flip();
idBuffer = newBuffer;
return nextBuffer();
}
default:
throw DataUtils.newIllegalArgumentException("Unsupported id {0}",
Arrays.toString(idBuffer.array()));
}
}
return null;
}
} |
n = Math.min(length - pos, n);
if (n == 0) {
return 0;
}
if (buffer != null) {
long s = buffer.skip(n);
if (s > 0) {
n = s;
} else {
buffer = null;
skip += n;
}
} else {
skip += n;
}
pos += n;
return n;
| 958 | 116 | 1,074 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/TransactionalValue.java | OldValue | commit | class OldValue {
final long tid;
final Object value;
OldValue next;
boolean useLast;
public OldValue(long tid, Object value) {
this.tid = tid;
this.value = value;
}
}
// 对于一个已经提交的值,如果当前事务因为隔离级别的原因读不到这个值,那么就返回SIGHTLESS
public static final Object SIGHTLESS = new Object();
private static final AtomicReferenceFieldUpdater<TransactionalValue, RowLock> rowLockUpdater = //
AtomicReferenceFieldUpdater.newUpdater(TransactionalValue.class, RowLock.class, "rowLock");
private static final RowLock NULL = new RowLock();
private volatile RowLock rowLock = NULL;
private Object value;
public TransactionalValue(Object value) {
this.value = value;
}
public TransactionalValue(Object value, AOTransaction t) {
this.value = value;
rowLock = new InsertRowLock(this);
rowLock.tryLock(t, this, null); // insert的场景,old value是null
}
public void resetRowLock() {
rowLock = NULL;
}
// 二级索引需要设置
public void setTransaction(AOTransaction t) {
if (rowLock == NULL) {
rowLockUpdater.compareAndSet(this, NULL, new InsertRowLock(this));
}
if (rowLock.getTransaction() == null)
rowLock.tryLock(t, this, value);
}
public AOTransaction getTransaction() {
return rowLock.getTransaction();
}
Object getOldValue() {
return rowLock.getOldValue();
}
public void setValue(Object value) {
this.value = value;
}
@Override
public Object getValue() {
return value;
}
public Object getValue(AOTransaction transaction, StorageMap<?, ?> map) {
// 先拿到LockOwner再用它获取信息,否则会产生并发问题
LockOwner lockOwner = rowLock.getLockOwner();
AOTransaction t = (AOTransaction) lockOwner.getTransaction();
if (t != null) {
// 如果拥有锁的事务是当前事务或当前事务的父事务,直接返回当前值
if (t == transaction || t == transaction.getParentTransaction())
return value;
}
// 如果事务当前执行的是更新类的语句那么自动通过READ_COMMITTED级别读取最新版本的记录
int isolationLevel = transaction.isUpdateCommand() ? Transaction.IL_READ_COMMITTED
: transaction.getIsolationLevel();
switch (isolationLevel) {
case Transaction.IL_READ_COMMITTED: {
if (t != null) {
if (t.isCommitted()) {
return value;
} else {
if (lockOwner.getOldValue() == null)
return SIGHTLESS; // 刚刚insert但是还没有提交的记录
else
return lockOwner.getOldValue();
}
}
return value;
}
case Transaction.IL_REPEATABLE_READ:
case Transaction.IL_SERIALIZABLE: {
long tid = transaction.getTransactionId();
if (t != null && t.commitTimestamp > 0 && tid >= t.commitTimestamp) {
return value;
}
ConcurrentHashMap<Object, Object> oldValueCache = map.getOldValueCache();
OldValue oldValue = (OldValue) oldValueCache.get(this);
if (oldValue != null) {
if (tid >= oldValue.tid) {
if (t != null && lockOwner.getOldValue() != null)
return lockOwner.getOldValue();
else
return value;
}
while (oldValue != null) {
if (tid >= oldValue.tid)
return oldValue.value;
oldValue = oldValue.next;
}
return SIGHTLESS; // insert成功后的记录,旧事务看不到
}
if (t != null) {
if (lockOwner.getOldValue() != null)
return lockOwner.getOldValue();
else
return SIGHTLESS; // 刚刚insert但是还没有提交的记录
} else {
return value;
}
}
case Transaction.IL_READ_UNCOMMITTED: {
return value;
}
default:
throw DbException.getInternalError();
}
}
// 如果是0代表事务已经提交,对于已提交事务,只有在写入时才写入tid=0,
// 读出来的时候为了不占用内存就不加tid字段了,这样每条已提交记录能省8个字节(long)的内存空间
public long getTid() {
AOTransaction t = rowLock.getTransaction();
return t == null ? 0 : t.transactionId;
}
// 小于0:已经删除
// 等于0:加锁失败
// 大于0:加锁成功
public int tryLock(AOTransaction t) {
// 加一个if判断,避免创建对象
if (rowLock == NULL) {
rowLockUpdater.compareAndSet(this, NULL, new RowLock());
}
if (value == null && !isLocked(t)) // 已经删除了
return -1;
if (rowLock.tryLock(t, this, value))
if (value == null) // 已经删除了
return -1;
else
return 1;
else
return 0;
}
public boolean isLocked(AOTransaction t) {
if (rowLock.getTransaction() == null)
return false;
else
return rowLock.getTransaction() != t;
}
public int addWaitingTransaction(Object key, AOTransaction t) {
return rowLock.addWaitingTransaction(key, rowLock.getTransaction(), t.getSession());
}
public void commit(boolean isInsert, StorageMap<?, ?> map) {<FILL_FUNCTION_BODY> |
AOTransaction t = rowLock.getTransaction();
if (t == null)
return;
AOTransactionEngine te = t.transactionEngine;
if (te.containsRepeatableReadTransactions()) {
ConcurrentHashMap<Object, Object> oldValueCache = map.getOldValueCache();
if (isInsert) {
OldValue v = new OldValue(t.commitTimestamp, value);
oldValueCache.put(this, v);
} else {
long maxTid = te.getMaxRepeatableReadTransactionId();
OldValue old = (OldValue) oldValueCache.get(this);
// 如果现有的版本已经足够给所有的可重复读事务使用了,那就不再加了
if (old != null && old.tid > maxTid) {
old.useLast = true;
return;
}
OldValue v = new OldValue(t.commitTimestamp, value);
if (old == null) {
OldValue ov = new OldValue(0, rowLock.getOldValue());
v.next = ov;
} else if (old.useLast) {
OldValue ov = new OldValue(old.tid + 1, rowLock.getOldValue());
ov.next = old;
v.next = ov;
} else {
v.next = old;
}
oldValueCache.put(this, v);
}
}
| 1,598 | 356 | 1,954 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/TransactionalValueType.java | TransactionalValueType | write | class TransactionalValueType implements StorageDataType {
public final StorageDataType valueType;
private final boolean isByteStorage;
public TransactionalValueType(StorageDataType valueType) {
this.valueType = valueType;
this.isByteStorage = false;
}
public TransactionalValueType(StorageDataType valueType, boolean isByteStorage) {
this.valueType = valueType;
this.isByteStorage = isByteStorage;
}
@Override
public int getMemory(Object obj) {
TransactionalValue tv = (TransactionalValue) obj;
Object v = tv.getValue();
if (v == null) // 如果记录已经删除,看看RowLock中是否还有
v = tv.getOldValue();
return 8 + valueType.getMemory(v);
}
@Override
public int compare(Object aObj, Object bObj) {
if (aObj == bObj) {
return 0;
}
TransactionalValue a = (TransactionalValue) aObj;
TransactionalValue b = (TransactionalValue) bObj;
long comp = a.getTid() - b.getTid();
if (comp == 0) {
return valueType.compare(a.getValue(), b.getValue());
}
return Long.signum(comp);
}
@Override
public void read(ByteBuffer buff, Object[] obj, int len) {
for (int i = 0; i < len; i++) {
obj[i] = read(buff);
}
}
@Override
public Object read(ByteBuffer buff) {
return TransactionalValue.read(buff, valueType, this);
}
@Override
public void write(DataBuffer buff, Object[] obj, int len) {<FILL_FUNCTION_BODY>}
@Override
public void write(DataBuffer buff, Object obj) {
TransactionalValue v = (TransactionalValue) obj;
v.write(buff, valueType, isByteStorage);
}
@Override
public void writeMeta(DataBuffer buff, Object obj) {
TransactionalValue v = (TransactionalValue) obj;
v.writeMeta(buff);
valueType.writeMeta(buff, v.getValue());
}
@Override
public Object readMeta(ByteBuffer buff, int columnCount) {
return TransactionalValue.readMeta(buff, valueType, this, columnCount);
}
@Override
public void writeColumn(DataBuffer buff, Object obj, int columnIndex) {
TransactionalValue v = (TransactionalValue) obj;
valueType.writeColumn(buff, v.getValue(), columnIndex);
}
@Override
public void readColumn(ByteBuffer buff, Object obj, int columnIndex) {
TransactionalValue v = (TransactionalValue) obj;
valueType.readColumn(buff, v.getValue(), columnIndex);
}
@Override
public void setColumns(Object oldObj, Object newObj, int[] columnIndexes) {
valueType.setColumns(oldObj, newObj, columnIndexes);
}
@Override
public ValueArray getColumns(Object obj) {
return valueType.getColumns(obj);
}
@Override
public int getColumnCount() {
return valueType.getColumnCount();
}
@Override
public int getMemory(Object obj, int columnIndex) {
TransactionalValue v = (TransactionalValue) obj;
return valueType.getMemory(v.getValue(), columnIndex);
}
} |
for (int i = 0; i < len; i++) {
write(buff, obj[i]);
}
| 905 | 33 | 938 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/lock/RowLock.java | RowLock | addLock | class RowLock extends Lock {
@Override
public String getLockType() {
return "RowLock";
}
@Override
public AOTransaction getTransaction() {
return (AOTransaction) super.getTransaction();
}
@Override
protected void addLock(Session session, Transaction t) {<FILL_FUNCTION_BODY>}
@Override
protected LockOwner createLockOwner(Transaction transaction, Object oldValue) {
return new RowLockOwner(transaction, oldValue);
}
public boolean isInsert() {
return false;
}
} |
// 单元测试时session为null
if (session != null)
session.addLock(this);
else
((AOTransaction) t).addLock(this);
| 151 | 49 | 200 | <methods>public non-sealed void <init>() ,public int addWaitingTransaction(java.lang.Object, com.lealone.transaction.Transaction, com.lealone.db.session.Session) ,public com.lealone.db.lock.LockOwner getLockOwner() ,public abstract java.lang.String getLockType() ,public java.lang.Object getOldValue() ,public com.lealone.transaction.Transaction getTransaction() ,public boolean isLockedExclusivelyBy(com.lealone.db.session.Session) ,public boolean tryLock(com.lealone.transaction.Transaction, java.lang.Object, java.lang.Object) ,public void unlock(com.lealone.db.session.Session, boolean, com.lealone.db.session.Session) ,public void unlock(com.lealone.db.session.Session, com.lealone.db.session.Session) <variables>static final com.lealone.db.lock.NullLockOwner NULL,private final AtomicReference<com.lealone.db.lock.LockOwner> ref |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/log/LogSyncService.java | LogSyncService | create | class LogSyncService extends Thread {
private static final Logger logger = LoggerFactory.getLogger(LogSyncService.class);
public static final String LOG_SYNC_TYPE_PERIODIC = "periodic";
public static final String LOG_SYNC_TYPE_INSTANT = "instant";
public static final String LOG_SYNC_TYPE_NO_SYNC = "no_sync";
private final Awaiter awaiter = new Awaiter(logger);
private final AtomicLong asyncLogQueueSize = new AtomicLong();
private final AtomicLong lastLogId = new AtomicLong();
private final Scheduler[] waitingSchedulers;
// 只要达到一定的阈值就可以立即同步了
private final int redoLogRecordSyncThreshold;
private final RedoLog redoLog;
private volatile boolean running;
private volatile CountDownLatch latchOnClose;
protected volatile long lastSyncedAt = System.currentTimeMillis();
protected long syncIntervalMillis;
public LogSyncService(Map<String, String> config) {
setName(getClass().getSimpleName());
setDaemon(RunMode.isEmbedded(config));
// 多加一个,给其他类型的调度器使用,比如集群环境下checkpoint服务线程也是个调度器
int schedulerCount = MapUtils.getSchedulerCount(config) + 1;
waitingSchedulers = new Scheduler[schedulerCount];
redoLogRecordSyncThreshold = MapUtils.getInt(config, "redo_log_record_sync_threshold", 100);
redoLog = new RedoLog(config, this);
}
public RedoLog getRedoLog() {
return redoLog;
}
public long nextLogId() {
return lastLogId.incrementAndGet();
}
public AtomicLong getAsyncLogQueueSize() {
return asyncLogQueueSize;
}
public Scheduler[] getWaitingSchedulers() {
return waitingSchedulers;
}
public boolean needSync() {
return true;
}
public boolean isPeriodic() {
return false;
}
public boolean isRunning() {
return running;
}
@Override
public void run() {
running = true;
while (running) {
long syncStarted = System.currentTimeMillis();
sync();
lastSyncedAt = syncStarted;
if (!isPeriodic()) {
// 如果是instant sync,只要一有redo log就接着马上同步,无需等待
if (asyncLogQueueSize.get() > 0)
continue;
} else if (asyncLogQueueSize.get() > redoLogRecordSyncThreshold) {
// 如果是periodic sync,只要redo log达到阈值也接着马上同步,无需等待
continue;
}
long now = System.currentTimeMillis();
long sleep = syncStarted + syncIntervalMillis - now;
if (sleep < 0)
continue;
awaiter.doAwait(sleep);
}
// 结束前最后sync一次
sync();
// 放在最后,让线程退出后再关闭
redoLog.close();
if (latchOnClose != null) {
latchOnClose.countDown();
}
}
private void sync() {
try {
redoLog.save();
} catch (Exception e) {
logger.error("Failed to sync redo log", e);
}
}
public void wakeUp() {
awaiter.wakeUp();
}
public void asyncWakeUp() {
asyncLogQueueSize.getAndIncrement();
wakeUp();
}
// 调用join可能没有效果,run方法可能在main线程中运行,所以统一用CountDownLatch
public void close() {
latchOnClose = new CountDownLatch(1);
running = false;
wakeUp();
try {
latchOnClose.await();
} catch (InterruptedException e) {
}
}
public void asyncWrite(AOTransaction t, RedoLogRecord r, long logId) {
asyncWrite(new PendingTransaction(t, r, logId));
}
protected void asyncWrite(PendingTransaction pt) {
Scheduler scheduler = pt.getScheduler();
scheduler.addPendingTransaction(pt);
waitingSchedulers[scheduler.getId()] = scheduler;
asyncLogQueueSize.getAndIncrement();
wakeUp();
}
public void syncWrite(AOTransaction t, RedoLogRecord r, long logId) {
CountDownLatch latch = new CountDownLatch(1);
addRedoLogRecord(t, r, logId, latch);
try {
latch.await();
} catch (InterruptedException e) {
throw DbException.convert(e);
}
}
public void addRedoLogRecord(AOTransaction t, RedoLogRecord r, long logId) {
addRedoLogRecord(t, r, logId, null);
}
private void addRedoLogRecord(AOTransaction t, RedoLogRecord r, long logId, CountDownLatch latch) {
PendingTransaction pt = new PendingTransaction(t, r, logId);
pt.setCompleted(true);
pt.setLatch(latch);
asyncWrite(pt);
}
public static LogSyncService create(Map<String, String> config) {<FILL_FUNCTION_BODY>}
} |
LogSyncService logSyncService;
String logSyncType = config.get("log_sync_type");
if (logSyncType == null || LOG_SYNC_TYPE_PERIODIC.equalsIgnoreCase(logSyncType))
logSyncService = new PeriodicLogSyncService(config);
else if (LOG_SYNC_TYPE_INSTANT.equalsIgnoreCase(logSyncType))
logSyncService = new InstantLogSyncService(config);
else if (LOG_SYNC_TYPE_NO_SYNC.equalsIgnoreCase(logSyncType))
logSyncService = new NoLogSyncService(config);
else
throw new IllegalArgumentException("Unknow log_sync_type: " + logSyncType);
return logSyncService;
| 1,437 | 182 | 1,619 | <methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/log/PeriodicLogSyncService.java | PeriodicLogSyncService | asyncWrite | class PeriodicLogSyncService extends LogSyncService {
private final long blockWhenSyncLagsMillis;
PeriodicLogSyncService(Map<String, String> config) {
super(config);
syncIntervalMillis = MapUtils.getLong(config, "log_sync_period", 500);
blockWhenSyncLagsMillis = (long) (syncIntervalMillis * 1.5);
}
@Override
public boolean isPeriodic() {
return true;
}
private boolean waitForSyncToCatchUp() {
// 如果当前时间是第10毫秒,上次同步时间是在第5毫秒,同步间隔是10毫秒,说时当前时间还是同步周期内,就不用阻塞了
// 如果当前时间是第16毫秒,超过了同步周期,需要阻塞
return System.currentTimeMillis() > lastSyncedAt + blockWhenSyncLagsMillis;
}
@Override
public void asyncWrite(AOTransaction t, RedoLogRecord r, long logId) {<FILL_FUNCTION_BODY>}
@Override
public void syncWrite(AOTransaction t, RedoLogRecord r, long logId) {
// 如果在同步周期内,不用等
if (!waitForSyncToCatchUp()) {
PendingTransaction pt = new PendingTransaction(t, r, logId);
t.onSynced();
pt.setCompleted(true);
// 同步调用无需t.asyncCommitComplete();
asyncWrite(pt);
} else {
super.syncWrite(t, r, logId);
}
}
} |
PendingTransaction pt = new PendingTransaction(t, r, logId);
// 如果在同步周期内,可以提前通知异步提交完成了
if (!waitForSyncToCatchUp()) {
t.onSynced(); // 不能直接pt.setSynced(true);
pt.setCompleted(true);
asyncWrite(pt);
t.asyncCommitComplete();
} else {
asyncWrite(pt);
}
| 424 | 118 | 542 | <methods>public void <init>(Map<java.lang.String,java.lang.String>) ,public void addRedoLogRecord(com.lealone.transaction.aote.AOTransaction, com.lealone.transaction.aote.log.RedoLogRecord, long) ,public void asyncWakeUp() ,public void asyncWrite(com.lealone.transaction.aote.AOTransaction, com.lealone.transaction.aote.log.RedoLogRecord, long) ,public void close() ,public static com.lealone.transaction.aote.log.LogSyncService create(Map<java.lang.String,java.lang.String>) ,public java.util.concurrent.atomic.AtomicLong getAsyncLogQueueSize() ,public com.lealone.transaction.aote.log.RedoLog getRedoLog() ,public com.lealone.db.scheduler.Scheduler[] getWaitingSchedulers() ,public boolean isPeriodic() ,public boolean isRunning() ,public boolean needSync() ,public long nextLogId() ,public void run() ,public void syncWrite(com.lealone.transaction.aote.AOTransaction, com.lealone.transaction.aote.log.RedoLogRecord, long) ,public void wakeUp() <variables>public static final java.lang.String LOG_SYNC_TYPE_INSTANT,public static final java.lang.String LOG_SYNC_TYPE_NO_SYNC,public static final java.lang.String LOG_SYNC_TYPE_PERIODIC,private final java.util.concurrent.atomic.AtomicLong asyncLogQueueSize,private final com.lealone.common.util.Awaiter awaiter,private final java.util.concurrent.atomic.AtomicLong lastLogId,protected volatile long lastSyncedAt,private volatile java.util.concurrent.CountDownLatch latchOnClose,private static final com.lealone.common.logging.Logger logger,private final non-sealed com.lealone.transaction.aote.log.RedoLog redoLog,private final non-sealed int redoLogRecordSyncThreshold,private volatile boolean running,protected long syncIntervalMillis,private final non-sealed com.lealone.db.scheduler.Scheduler[] waitingSchedulers |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/log/RedoLog.java | RedoLog | init | class RedoLog {
// key: mapName, value: map key/value ByteBuffer list
private final HashMap<String, List<ByteBuffer>> pendingRedoLog = new HashMap<>();
private final Map<String, String> config;
private final LogSyncService logSyncService;
private RedoLogChunk currentChunk;
RedoLog(Map<String, String> config, LogSyncService logSyncService) {
this.config = config;
this.logSyncService = logSyncService;
String baseDir = config.get("base_dir");
String logDir = MapUtils.getString(config, "redo_log_dir", "redo_log");
String storagePath = baseDir + File.separator + logDir;
config.put(StorageSetting.STORAGE_PATH.name(), storagePath);
if (!FileUtils.exists(storagePath))
FileUtils.createDirectories(storagePath);
}
private List<Integer> getAllChunkIds() {
return getAllChunkIds(config.get(StorageSetting.STORAGE_PATH.name()));
}
static List<Integer> getAllChunkIds(String dirStr) {
ArrayList<Integer> ids = new ArrayList<>();
int prefixLength = RedoLogChunk.CHUNK_FILE_NAME_PREFIX.length();
FilePath dir = FilePath.get(dirStr);
for (FilePath fp : dir.newDirectoryStream()) {
String fullName = fp.getName();
if (fullName.startsWith(RedoLogChunk.CHUNK_FILE_NAME_PREFIX)) {
int id = Integer.parseInt(fullName.substring(prefixLength));
ids.add(id);
}
}
Collections.sort(ids); // 必须排序,按id从小到大的顺序读取文件,才能正确的redo
return ids;
}
public void init() {<FILL_FUNCTION_BODY>}
// 第一次打开底层存储的map时调用这个方法,重新执行一次上次已经成功并且在检查点之后的事务操作
// 有可能多个线程同时调用redo,所以需要加synchronized
public synchronized void redo(StorageMap<Object, Object> map) {
List<ByteBuffer> pendingKeyValues = pendingRedoLog.remove(map.getName());
if (pendingKeyValues != null && !pendingKeyValues.isEmpty()) {
StorageDataType kt = map.getKeyType();
StorageDataType vt = ((TransactionalValueType) map.getValueType()).valueType;
// 异步redo,忽略操作结果
AsyncHandler<AsyncResult<Object>> handler = ar -> {
};
for (ByteBuffer kv : pendingKeyValues) {
Object key = kt.read(kv);
if (kv.get() == 0)
map.remove(key, handler);
else {
Object value = vt.read(kv);
TransactionalValue tv = TransactionalValue.createCommitted(value);
map.put(key, tv, handler);
}
}
}
}
void close() {
currentChunk.close();
}
void save() {
currentChunk.save();
}
public void ignoreCheckpoint() {
currentChunk.ignoreCheckpoint();
}
public void setCheckpointService(CheckpointService checkpointService) {
currentChunk.setCheckpointService(checkpointService);
}
public void addFsyncTask(FsyncTask task) {
currentChunk.addFsyncTask(task);
}
} |
List<Integer> ids = getAllChunkIds();
if (ids.isEmpty()) {
currentChunk = new RedoLogChunk(0, config, logSyncService);
} else {
int lastId = ids.get(ids.size() - 1);
for (int id : ids) {
RedoLogChunk chunk = null;
try {
chunk = new RedoLogChunk(id, config, logSyncService);
for (RedoLogRecord r : chunk.readRedoLogRecords()) {
r.initPendingRedoLog(pendingRedoLog);
}
} finally {
// 注意一定要关闭,否则对应的chunk文件将无法删除,
// 内部会打开一个FileStorage,不会因为没有引用到了而自动关闭
if (id == lastId)
currentChunk = chunk;
else if (chunk != null)
chunk.close();
}
}
}
| 917 | 246 | 1,163 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/log/RedoLogRecord.java | LazyLocalTransactionRLR | writeOperations | class LazyLocalTransactionRLR extends LocalTransactionRLR {
private final UndoLog undoLog;
private final AOTransactionEngine te;
public LazyLocalTransactionRLR(UndoLog undoLog, AOTransactionEngine te) {
super((ByteBuffer) null);
this.undoLog = undoLog;
this.te = te;
}
@Override
public void writeOperations(DataBuffer buff) {
writeOperations(buff, undoLog, te);
}
static void writeOperations(DataBuffer buff, UndoLog undoLog, AOTransactionEngine te) {<FILL_FUNCTION_BODY>}
} |
int pos = buff.position();
buff.putInt(0);
undoLog.toRedoLogRecordBuffer(te, buff);
buff.putInt(pos, buff.position() - pos - 4);
| 170 | 57 | 227 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/log/UndoLog.java | UndoLog | commit | class UndoLog {
private int logId;
private UndoLogRecord first;// 指向最早加进来的,执行commit时从first开始遍历
private UndoLogRecord last; // 总是指向新增加的,执行rollback时从first开始遍历
public int getLogId() {
return logId;
}
public UndoLogRecord getFirst() {
return first;
}
public int size() {
return logId;
}
public boolean isEmpty() {
return logId == 0;
}
public boolean isNotEmpty() {
return logId != 0;
}
public UndoLogRecord add(StorageMap<?, ?> map, Object key, Object oldValue,
TransactionalValue newTV) {
UndoLogRecord r = new UndoLogRecord(map, key, oldValue, newTV);
if (first == null) {
first = last = r;
} else {
last.next = r;
r.prev = last;
last = r;
}
logId++;
return r;
}
private UndoLogRecord removeLast() {
UndoLogRecord r = last;
if (last != null) {
if (last.prev != null)
last.prev.next = null;
last = last.prev;
if (last == null) {
first = null;
}
--logId;
}
return r;
}
public void commit(AOTransactionEngine te) {<FILL_FUNCTION_BODY>}
public void rollbackTo(AOTransactionEngine te, int toLogId) {
while (logId > toLogId) {
UndoLogRecord r = removeLast();
r.rollback(te);
}
}
// 将当前一系列的事务操作日志转换成单条RedoLogRecord
public DataBuffer toRedoLogRecordBuffer(AOTransactionEngine te, DataBufferFactory dbFactory) {
DataBuffer buffer = dbFactory.create();
toRedoLogRecordBuffer(te, buffer);
buffer.getAndFlipBuffer();
return buffer;
}
public void toRedoLogRecordBuffer(AOTransactionEngine te, DataBuffer buffer) {
UndoLogRecord r = first;
while (r != null) {
r.writeForRedo(buffer, te);
r = r.next;
}
}
} |
UndoLogRecord r = first;
while (r != null) {
r.commit(te);
r = r.next;
}
| 629 | 42 | 671 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/log/UndoLogRecord.java | UndoLogRecord | commit | class UndoLogRecord {
private final StorageMap<Object, ?> map;
private final Object key;
private final Object oldValue;
private final Object newValue; // 使用LazyRedoLogRecord时需要用它,不能直接使用newTV.getValue(),因为会变动
private final TransactionalValue newTV;
private boolean undone;
UndoLogRecord next;
UndoLogRecord prev;
@SuppressWarnings("unchecked")
public UndoLogRecord(StorageMap<?, ?> map, Object key, Object oldValue, TransactionalValue newTV) {
this.map = (StorageMap<Object, ?>) map;
this.key = key;
this.oldValue = oldValue;
this.newValue = newTV.getValue();
this.newTV = newTV;
}
public void setUndone(boolean undone) {
this.undone = undone;
}
private boolean ignore() {
// 事务取消或map关闭或删除时直接忽略
return undone || map.isClosed();
}
// 调用这个方法时事务已经提交,redo日志已经写完,这里只是在内存中更新到最新值
// 不需要调用map.markDirty(key),这很耗时,在下一步通过markDirtyPages()调用
public void commit(AOTransactionEngine te) {<FILL_FUNCTION_BODY>}
// 当前事务开始rollback了,调用这个方法在内存中撤销之前的更新
public void rollback(AOTransactionEngine te) {
if (ignore())
return;
if (oldValue == null) {
map.remove(key);
} else {
newTV.rollback(oldValue);
}
}
// 用于redo时,不关心oldValue
public void writeForRedo(DataBuffer writeBuffer, AOTransactionEngine te) {
if (ignore())
return;
// 这一步很重要!!!
// 对于update和delete,要标记一下脏页,否则执行checkpoint保存数据时无法实别脏页
if (oldValue != null) {
map.markDirty(key);
}
ValueString.type.write(writeBuffer, map.getName());
int keyValueLengthStartPos = writeBuffer.position();
writeBuffer.putInt(0);
map.getKeyType().write(writeBuffer, key);
if (newValue == null)
writeBuffer.put((byte) 0);
else {
writeBuffer.put((byte) 1);
// 如果这里运行时出现了cast异常,可能是上层应用没有通过TransactionMap提供的api来写入最初的数据
((TransactionalValueType) map.getValueType()).valueType.write(writeBuffer, newValue);
}
writeBuffer.putInt(keyValueLengthStartPos, writeBuffer.position() - keyValueLengthStartPos - 4);
}
} |
if (ignore())
return;
if (oldValue == null) { // insert
newTV.commit(true, map);
} else if (newTV != null && newTV.getValue() == null) { // delete
if (!te.containsRepeatableReadTransactions()) {
map.remove(key);
} else {
map.decrementSize(); // 要减去1
newTV.commit(false, map);
}
} else { // update
newTV.commit(false, map);
}
| 756 | 138 | 894 | <no_super_class> |
lealone_Lealone | Lealone/lealone-aote/src/main/java/com/lealone/transaction/aote/tm/SingleThreadTransactionManager.java | SingleThreadTransactionManager | currentTransactions | class SingleThreadTransactionManager extends TransactionManager {
private final BitField bf = new BitField(8);
private AOTransaction[] transactions;
private int currentTransactionCount;
public SingleThreadTransactionManager(AOTransactionEngine te) {
super(te);
transactions = new AOTransaction[8];
}
@Override
public AOTransaction removeTransaction(long tid, int bitIndex) {
currentTransactionCount--;
bf.clear(bitIndex);
AOTransaction t = transactions[bitIndex];
transactions[bitIndex] = null;
super.removeTransaction(t);
return t;
}
@Override
public void addTransaction(AOTransaction t) {
currentTransactionCount++;
int index = bf.nextClearBit(0);
bf.set(index);
if (index >= transactions.length) {
AOTransaction[] newTransactions = new AOTransaction[transactions.length * 2];
System.arraycopy(transactions, 0, newTransactions, 0, transactions.length);
transactions = newTransactions;
}
t.setBitIndex(index);
transactions[index] = t;
}
@Override
public void currentTransactions(List<AOTransaction> list) {<FILL_FUNCTION_BODY>}
@Override
public int currentTransactionCount() {
return currentTransactionCount;
}
} |
AOTransaction[] transactions = this.transactions;
for (int i = 0, length = transactions.length; i < length; i++) {
AOTransaction t = transactions[i];
if (t != null)
list.add(t);
}
| 358 | 70 | 428 | <methods>public void <init>(com.lealone.transaction.aote.AOTransactionEngine) ,public abstract void addTransaction(com.lealone.transaction.aote.AOTransaction) ,public static com.lealone.transaction.aote.tm.TransactionManager create(com.lealone.transaction.aote.AOTransactionEngine, boolean) ,public abstract int currentTransactionCount() ,public abstract void currentTransactions(List<com.lealone.transaction.aote.AOTransaction>) ,public abstract com.lealone.transaction.aote.AOTransaction removeTransaction(long, int) <variables>protected final non-sealed com.lealone.transaction.aote.AOTransactionEngine te |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/ClientScheduler.java | ClientScheduler | checkTimeout | class ClientScheduler extends NetScheduler {
private static final Logger logger = LoggerFactory.getLogger(ClientScheduler.class);
// 杂七杂八的任务,数量不多,执行完就删除
private final ConcurrentLinkedQueue<AsyncTask> miscTasks = new ConcurrentLinkedQueue<>();
private final NetClient netClient;
public ClientScheduler(int id, int schedulerCount, Map<String, String> config) {
super(id, "CScheduleService-" + id,
MapUtils.getInt(config, ConnectionSetting.NET_CLIENT_COUNT.name(), schedulerCount),
config, false);
NetFactory netFactory = NetFactory.getFactory(config);
netClient = netFactory.createNetClient();
netEventLoop.setNetClient(netClient);
getThread().setDaemon(true);
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public long getLoad() {
return super.getLoad() + miscTasks.size();
}
@Override
public void handle(AsyncTask task) {
miscTasks.add(task);
wakeUp();
}
@Override
protected void runMiscTasks() {
runMiscTasks(miscTasks);
}
@Override
public void run() {
long lastTime = System.currentTimeMillis();
while (!stopped) {
runMiscTasks();
runEventLoop();
long currentTime = System.currentTimeMillis();
if (currentTime - lastTime > 1000) {
lastTime = currentTime;
checkTimeout(currentTime);
}
}
onStopped();
}
private void checkTimeout(long currentTime) {<FILL_FUNCTION_BODY>}
@Override
public void executeNextStatement() {
// 客户端阻塞在同步方法时运行事件循环执行回调
runEventLoop();
}
private static volatile SchedulerFactory clientSchedulerFactory;
public static Scheduler getScheduler(ConnectionInfo ci, Map<String, String> config) {
if (clientSchedulerFactory == null) {
synchronized (ClientScheduler.class) {
if (clientSchedulerFactory == null) {
clientSchedulerFactory = SchedulerFactoryBase
.createSchedulerFactory(ClientScheduler.class.getName(), config);
}
}
}
return SchedulerFactoryBase.getScheduler(clientSchedulerFactory, ci);
}
} |
try {
netClient.checkTimeout(currentTime);
} catch (Throwable t) {
logger.warn("Failed to checkTimeout", t);
}
| 643 | 44 | 687 | <methods>public void <init>(int, java.lang.String, int, Map<java.lang.String,java.lang.String>, boolean) ,public com.lealone.db.DataBufferFactory getDataBufferFactory() ,public com.lealone.net.NetEventLoop getNetEventLoop() ,public java.nio.channels.Selector getSelector() ,public void registerAccepter(com.lealone.server.ProtocolServer, java.nio.channels.ServerSocketChannel) ,public void wakeUp() <variables>protected final non-sealed com.lealone.net.NetEventLoop netEventLoop |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/ClientServiceProxy.java | ClientServiceProxy | prepareStatement | class ClientServiceProxy {
private static ConcurrentHashMap<String, Connection> connMap = new ConcurrentHashMap<>(1);
public static PreparedStatement prepareStatement(String url, String sql) {<FILL_FUNCTION_BODY>}
public static RuntimeException failed(String serviceName, Throwable cause) {
return new RuntimeException("Failed to execute service: " + serviceName, cause);
}
public static boolean isEmbedded(String url) {
return url == null || new ConnectionInfo(url).isEmbedded();
}
public static String getUrl() {
return System.getProperty(Constants.JDBC_URL_KEY);
}
} |
try {
Connection conn = connMap.get(url);
if (conn == null) {
synchronized (connMap) {
conn = connMap.get(url);
if (conn == null) {
Properties info = new Properties();
info.put(ConnectionSetting.IS_SERVICE_CONNECTION.name(), "true");
conn = LealoneClient.getConnection(url, info).get();
connMap.put(url, conn);
}
}
}
return conn.prepareStatement(sql);
} catch (SQLException e) {
throw new RuntimeException("Failed to prepare statement: " + sql, e);
}
| 174 | 166 | 340 | <no_super_class> |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/command/ClientPreparedSQLCommand.java | ClientPreparedSQLCommand | getMetaData | class ClientPreparedSQLCommand extends ClientSQLCommand {
private ArrayList<CommandParameter> parameters;
public ClientPreparedSQLCommand(ClientSession session, String sql, int fetchSize) {
super(session, sql, fetchSize);
// commandId重新prepare时会变,但是parameters不会变
parameters = Utils.newSmallArrayList();
}
@Override
public int getType() {
return CLIENT_PREPARED_SQL_COMMAND;
}
@Override
public Future<Boolean> prepare(boolean readParams) {
AsyncCallback<Boolean> ac = session.createCallback();
// Prepared SQL的ID,每次执行时都发给后端
commandId = session.getNextId();
if (readParams) {
PreparedStatementPrepareReadParams packet = new PreparedStatementPrepareReadParams(commandId,
sql);
Future<PreparedStatementPrepareReadParamsAck> f = session.send(packet);
f.onComplete(ar -> {
if (ar.isFailed()) {
ac.setAsyncResult(ar.getCause());
} else {
PreparedStatementPrepareReadParamsAck ack = ar.getResult();
isQuery = ack.isQuery;
parameters = new ArrayList<>(ack.params);
ac.setAsyncResult(isQuery);
}
});
} else {
PreparedStatementPrepare packet = new PreparedStatementPrepare(commandId, sql);
Future<PreparedStatementPrepareAck> f = session.send(packet);
f.onComplete(ar -> {
if (ar.isFailed()) {
ac.setAsyncResult(ar.getCause());
} else {
PreparedStatementPrepareAck ack = ar.getResult();
isQuery = ack.isQuery;
ac.setAsyncResult(isQuery);
}
});
}
return ac;
}
private void prepareIfRequired() {
session.checkClosed();
if (commandId <= session.getCurrentId() - SysProperties.SERVER_CACHED_OBJECTS) {
// object is too old - we need to prepare again
prepare(false);
}
}
@Override
public ArrayList<CommandParameter> getParameters() {
return parameters;
}
@Override
public Future<Result> getMetaData() {<FILL_FUNCTION_BODY>}
@Override
protected Future<Result> query(int maxRows, boolean scrollable, int fetch, int resultId) {
Packet packet = new PreparedStatementQuery(resultId, maxRows, fetch, scrollable, commandId,
getValues());
return session.<Result, StatementQueryAck> send(packet, ack -> {
return getQueryResult(ack, fetch, resultId);
});
}
@Override
public Future<Integer> executeUpdate() {
try {
Packet packet = new PreparedStatementUpdate(commandId, getValues());
// 如果不给send方法传递packetId,它会自己创建一个,所以这里的调用是安全的
return session.<Integer, StatementUpdateAck> send(packet, ack -> {
return ack.updateCount;
});
} catch (Throwable t) {
return failedFuture(t);
}
}
private Value[] getValues() {
checkParameters();
prepareIfRequired();
int size = parameters.size();
Value[] values = new Value[size];
for (int i = 0; i < size; i++) {
values[i] = parameters.get(i).getValue();
}
return values;
}
private void checkParameters() {
for (CommandParameter p : parameters) {
p.checkSet();
}
}
@Override
public void close() {
if (session == null || session.isClosed()) {
return;
}
int packetId = session.getNextId();
session.traceOperation("COMMAND_CLOSE", packetId);
try {
session.send(new PreparedStatementClose(commandId));
} catch (Exception e) {
session.getTrace().error(e, "close session");
}
if (parameters != null) {
try {
for (CommandParameter p : parameters) {
Value v = p.getValue();
if (v != null) {
v.close();
}
}
} catch (DbException e) {
session.getTrace().error(e, "close command parameters");
}
parameters = null;
}
session = null;
}
@Override
public String toString() {
return sql + Trace.formatParams(getParameters());
}
public AsyncCallback<int[]> executeBatchPreparedSQLCommands(List<Value[]> batchParameters) {
AsyncCallback<int[]> ac = session.createCallback();
try {
Future<BatchStatementUpdateAck> f = session.send(new BatchStatementPreparedUpdate(commandId,
batchParameters.size(), batchParameters));
f.onComplete(ar -> {
if (ar.isSucceeded()) {
ac.setAsyncResult(ar.getResult().results);
} else {
ac.setAsyncResult(ar.getCause());
}
});
} catch (Exception e) {
ac.setAsyncResult(e);
}
return ac;
}
} |
if (!isQuery) {
return Future.succeededFuture(null);
}
prepareIfRequired();
AsyncCallback<Result> ac = session.createCallback();
try {
Future<PreparedStatementGetMetaDataAck> f = session
.send(new PreparedStatementGetMetaData(commandId));
f.onComplete(ar -> {
if (ar.isSucceeded()) {
try {
PreparedStatementGetMetaDataAck ack = ar.getResult();
ClientResult result = new RowCountDeterminedClientResult(session,
(TransferInputStream) ack.in, -1, ack.columnCount, 0, 0);
ac.setAsyncResult(result);
} catch (Throwable t) {
ac.setAsyncResult(t);
}
} else {
ac.setAsyncResult(ar.getCause());
}
});
} catch (Throwable t) {
ac.setAsyncResult(t);
}
return ac;
| 1,390 | 261 | 1,651 | <methods>public void <init>(com.lealone.client.session.ClientSession, java.lang.String, int) ,public void cancel() ,public void close() ,public AsyncCallback<int[]> executeBatchSQLCommands(List<java.lang.String>) ,public Future<com.lealone.db.result.Result> executeQuery(int, boolean) ,public Future<java.lang.Integer> executeUpdate() ,public int getFetchSize() ,public Future<com.lealone.db.result.Result> getMetaData() ,public ArrayList<com.lealone.db.CommandParameter> getParameters() ,public int getType() ,public boolean isQuery() ,public Future<java.lang.Boolean> prepare(boolean) ,public void setFetchSize(int) ,public java.lang.String toString() <variables>protected int commandId,protected int fetchSize,protected boolean isQuery,protected com.lealone.client.session.ClientSession session,protected final non-sealed java.lang.String sql |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/command/ClientSQLCommand.java | ClientSQLCommand | executeUpdate | class ClientSQLCommand implements SQLCommand {
// 通过设为null来判断是否关闭了当前命令,所以没有加上final
protected ClientSession session;
protected final String sql;
protected int fetchSize;
protected int commandId;
protected boolean isQuery;
public ClientSQLCommand(ClientSession session, String sql, int fetchSize) {
this.session = session;
this.sql = sql;
this.fetchSize = fetchSize;
}
@Override
public int getType() {
return CLIENT_SQL_COMMAND;
}
@Override
public int getFetchSize() {
return fetchSize;
}
@Override
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
}
@Override
public boolean isQuery() {
return isQuery;
}
@Override
public ArrayList<CommandParameter> getParameters() {
return new ArrayList<>(0);
}
@Override
public Future<Result> getMetaData() {
return Future.succeededFuture(null);
}
@Override
public Future<Result> executeQuery(int maxRows, boolean scrollable) {
try {
isQuery = true;
int fetch;
if (scrollable) {
fetch = Integer.MAX_VALUE;
} else {
fetch = fetchSize;
}
int resultId = session.getNextId();
return query(maxRows, scrollable, fetch, resultId);
} catch (Throwable t) {
return failedFuture(t);
}
}
protected Future<Result> query(int maxRows, boolean scrollable, int fetch, int resultId) {
int packetId = commandId = session.getNextId();
Packet packet = new StatementQuery(resultId, maxRows, fetch, scrollable, sql);
return session.<Result, StatementQueryAck> send(packet, packetId, ack -> {
return getQueryResult(ack, fetch, resultId);
});
}
protected ClientResult getQueryResult(StatementQueryAck ack, int fetch, int resultId) {
int columnCount = ack.columnCount;
int rowCount = ack.rowCount;
ClientResult result = null;
try {
TransferInputStream in = (TransferInputStream) ack.in;
in.setSession(session);
if (rowCount < 0)
result = new RowCountUndeterminedClientResult(session, in, resultId, columnCount, fetch);
else
result = new RowCountDeterminedClientResult(session, in, resultId, columnCount, rowCount,
fetch);
} catch (IOException e) {
throw DbException.convert(e);
}
return result;
}
@Override
public Future<Integer> executeUpdate() {<FILL_FUNCTION_BODY>}
@Override
public Future<Boolean> prepare(boolean readParams) {
throw DbException.getInternalError();
}
@Override
public void close() {
session = null;
}
@Override
public void cancel() {
session.cancelStatement(commandId);
}
@Override
public String toString() {
return sql;
}
public AsyncCallback<int[]> executeBatchSQLCommands(List<String> batchCommands) {
AsyncCallback<int[]> ac = session.createCallback();
commandId = session.getNextId();
try {
Future<BatchStatementUpdateAck> f = session
.send(new BatchStatementUpdate(batchCommands.size(), batchCommands), commandId);
f.onComplete(ar -> {
if (ar.isSucceeded()) {
ac.setAsyncResult(ar.getResult().results);
} else {
ac.setAsyncResult(ar.getCause());
}
});
} catch (Exception e) {
ac.setAsyncResult(e);
}
return ac;
}
protected static <T> Future<T> failedFuture(Throwable t) {
return Future.failedFuture(t);
}
} |
try {
int packetId = commandId = session.getNextId();
Packet packet = new StatementUpdate(sql);
return session.<Integer, StatementUpdateAck> send(packet, packetId, ack -> {
return ack.updateCount;
});
} catch (Throwable t) {
return failedFuture(t);
}
| 1,056 | 95 | 1,151 | <no_super_class> |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcAsyncCallback.java | JdbcAsyncCallback | get | class JdbcAsyncCallback<T> extends ConcurrentAsyncCallback<T> {
public T get(JdbcWrapper jw) throws SQLException {<FILL_FUNCTION_BODY>}
} |
try {
return get();
} catch (Exception e) {
throw jw.logAndConvert(e); // 抛出SQLException
}
| 49 | 42 | 91 | <methods>public void <init>() ,public synchronized Future<T> onComplete(AsyncHandler<AsyncResult<T>>) ,public synchronized Future<T> onFailure(AsyncHandler<java.lang.Throwable>) ,public synchronized Future<T> onSuccess(AsyncHandler<T>) ,public final void run(com.lealone.net.NetInputStream) ,public synchronized void setAsyncResult(AsyncResult<T>) ,public void setDbException(com.lealone.common.exceptions.DbException, boolean) <variables>private volatile AsyncResult<T> asyncResult,private volatile AsyncHandler<AsyncResult<T>> completeHandler,private volatile AsyncHandler<java.lang.Throwable> failureHandler,private final AtomicReference<com.lealone.db.async.ConcurrentAsyncCallback.LatchObject> latchObjectRef,private volatile boolean runEnd,private volatile AsyncHandler<T> successHandler |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcBatchUpdateException.java | JdbcBatchUpdateException | printStackTrace | class JdbcBatchUpdateException extends BatchUpdateException {
private static final long serialVersionUID = 1L;
/**
* INTERNAL
*/
JdbcBatchUpdateException(SQLException next, int[] updateCounts) {
super(next.getMessage(), next.getSQLState(), next.getErrorCode(), updateCounts);
setNextException(next);
}
/**
* INTERNAL
*/
@Override
public void printStackTrace() {<FILL_FUNCTION_BODY>}
/**
* INTERNAL
*/
@Override
public void printStackTrace(PrintWriter s) {
if (s != null) {
super.printStackTrace(s);
if (getNextException() != null) {
getNextException().printStackTrace(s);
}
}
}
/**
* INTERNAL
*/
@Override
public void printStackTrace(PrintStream s) {
if (s != null) {
super.printStackTrace(s);
if (getNextException() != null) {
getNextException().printStackTrace(s);
}
}
}
} |
// The default implementation already does that,
// but we do it again to avoid problems.
// If it is not implemented, somebody might implement it
// later on which would be a problem if done in the wrong way.
printStackTrace(System.err);
| 302 | 65 | 367 | <methods>public void <init>() ,public void <init>(int[]) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, int[]) ,public void <init>(int[], java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, int[]) ,public void <init>(java.lang.String, int[], java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, int, int[]) ,public void <init>(java.lang.String, java.lang.String, int[], java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, int, int[], java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, int, long[], java.lang.Throwable) ,public long[] getLargeUpdateCounts() ,public int[] getUpdateCounts() <variables>private long[] longUpdateCounts,private static final long serialVersionUID,private int[] updateCounts |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcBlob.java | JdbcBlob | setBinaryStream | class JdbcBlob extends BlobBase {
private final JdbcConnection conn;
/**
* INTERNAL
*/
public JdbcBlob(JdbcConnection conn, Value value, int id) {
this.conn = conn;
this.value = value;
this.trace = conn.getTrace(TraceObjectType.BLOB, id);
}
@Override
protected void checkClosed() {
conn.checkClosed();
super.checkClosed();
}
@Override
public int setBytes(long pos, byte[] bytes) throws SQLException {
try {
if (isDebugEnabled()) {
debugCode("setBytes(" + pos + ", " + quoteBytes(bytes) + ");");
}
checkClosed();
if (pos != 1) {
throw DbException.getInvalidValueException("pos", pos);
}
value = conn.createBlob(new ByteArrayInputStream(bytes), -1);
return bytes.length;
} catch (Exception e) {
throw logAndConvert(e);
}
}
@Override
public OutputStream setBinaryStream(long pos) throws SQLException {<FILL_FUNCTION_BODY>}
} |
try {
if (isDebugEnabled()) {
debugCode("setBinaryStream(" + pos + ");");
}
checkClosed();
if (pos != 1) {
throw DbException.getInvalidValueException("pos", pos);
}
if (value.getPrecision() != 0) {
throw DbException.getInvalidValueException("length", value.getPrecision());
}
final JdbcConnection c = conn;
final PipedInputStream in = new PipedInputStream();
final Task task = new Task() {
@Override
public void call() {
value = c.createBlob(in, -1);
}
};
PipedOutputStream out = new PipedOutputStream(in) {
@Override
public void close() throws IOException {
super.close();
try {
task.get();
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
}
};
task.execute();
return new BufferedOutputStream(out);
} catch (Exception e) {
throw logAndConvert(e);
}
| 308 | 287 | 595 | <methods>public non-sealed void <init>() ,public void free() ,public java.io.InputStream getBinaryStream() throws java.sql.SQLException,public java.io.InputStream getBinaryStream(long, long) throws java.sql.SQLException,public byte[] getBytes(long, int) throws java.sql.SQLException,public com.lealone.db.value.Value getValue() ,public long length() throws java.sql.SQLException,public long position(byte[], long) throws java.sql.SQLException,public long position(java.sql.Blob, long) throws java.sql.SQLException,public abstract java.io.OutputStream setBinaryStream(long) throws java.sql.SQLException,public abstract int setBytes(long, byte[]) throws java.sql.SQLException,public int setBytes(long, byte[], int, int) throws java.sql.SQLException,public java.lang.String toString() ,public void truncate(long) throws java.sql.SQLException<variables>protected com.lealone.db.value.Value value |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcClob.java | JdbcClob | setCharacterStream | class JdbcClob extends ClobBase {
private final JdbcConnection conn;
/**
* INTERNAL
*/
public JdbcClob(JdbcConnection conn, Value value, int id) {
this.conn = conn;
this.value = value;
this.trace = conn.getTrace(TraceObjectType.CLOB, id);
}
@Override
protected void checkClosed() {
conn.checkClosed();
super.checkClosed();
}
@Override
public Writer setCharacterStream(long pos) throws SQLException {<FILL_FUNCTION_BODY>}
@Override
public int setString(long pos, String str) throws SQLException {
try {
if (isDebugEnabled()) {
debugCode("setString(" + pos + ", " + quote(str) + ");");
}
checkClosed();
if (pos != 1) {
throw DbException.getInvalidValueException("pos", pos);
} else if (str == null) {
throw DbException.getInvalidValueException("str", str);
}
value = conn.createClob(new StringReader(str), -1);
return str.length();
} catch (Exception e) {
throw logAndConvert(e);
}
}
} |
try {
if (isDebugEnabled()) {
debugCodeCall("setCharacterStream(" + pos + ");");
}
checkClosed();
if (pos != 1) {
throw DbException.getInvalidValueException("pos", pos);
}
if (value.getPrecision() != 0) {
throw DbException.getInvalidValueException("length", value.getPrecision());
}
final JdbcConnection c = conn;
// PipedReader / PipedWriter are a lot slower
// than PipedInputStream / PipedOutputStream
// (Sun/Oracle Java 1.6.0_20)
final PipedInputStream in = new PipedInputStream();
final Task task = new Task() {
@Override
public void call() {
value = c.createClob(IOUtils.getReader(in), -1);
}
};
PipedOutputStream out = new PipedOutputStream(in) {
@Override
public void close() throws IOException {
super.close();
try {
task.get();
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
}
};
task.execute();
return IOUtils.getBufferedWriter(out);
} catch (Exception e) {
throw logAndConvert(e);
}
| 332 | 345 | 677 | <methods>public non-sealed void <init>() ,public void free() ,public java.io.InputStream getAsciiStream() throws java.sql.SQLException,public java.io.Reader getCharacterStream() throws java.sql.SQLException,public java.io.Reader getCharacterStream(long, long) throws java.sql.SQLException,public java.lang.String getSubString(long, int) throws java.sql.SQLException,public com.lealone.db.value.Value getValue() ,public long length() throws java.sql.SQLException,public long position(java.lang.String, long) throws java.sql.SQLException,public long position(java.sql.Clob, long) throws java.sql.SQLException,public java.io.OutputStream setAsciiStream(long) throws java.sql.SQLException,public abstract java.io.Writer setCharacterStream(long) throws java.sql.SQLException,public abstract int setString(long, java.lang.String) throws java.sql.SQLException,public int setString(long, java.lang.String, int, int) throws java.sql.SQLException,public java.lang.String toString() ,public void truncate(long) throws java.sql.SQLException<variables>protected com.lealone.db.value.Value value |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcDataSource.java | JdbcDataSource | getConnection | class JdbcDataSource extends JdbcWrapper
implements DataSource, Serializable, Referenceable, XADataSource {
private static final long serialVersionUID = 1288136338451857771L;
private transient JdbcDataSourceFactory factory;
private transient PrintWriter logWriter;
private int loginTimeout;
private String userName = "";
private char[] passwordChars = {};
private String url = "";
private String description;
static {
JdbcDriver.load();
}
/**
* The public constructor.
*/
public JdbcDataSource() {
initFactory();
int id = getNextTraceId(TraceObjectType.DATA_SOURCE);
this.trace = factory.getTrace(TraceObjectType.DATA_SOURCE, id);
}
/**
* Called when de-serializing the object.
*
* @param in the input stream
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
initFactory();
in.defaultReadObject();
}
private void initFactory() {
factory = new JdbcDataSourceFactory();
}
/**
* Get the login timeout in seconds, 0 meaning no timeout.
*
* @return the timeout in seconds
*/
@Override
public int getLoginTimeout() {
debugCodeCall("getLoginTimeout");
return loginTimeout;
}
/**
* Set the login timeout in seconds, 0 meaning no timeout.
* The default value is 0.
* This value is ignored by this database.
*
* @param timeout the timeout in seconds
*/
@Override
public void setLoginTimeout(int timeout) {
debugCodeCall("setLoginTimeout", timeout);
this.loginTimeout = timeout;
}
/**
* Get the current log writer for this object.
*
* @return the log writer
*/
@Override
public PrintWriter getLogWriter() {
debugCodeCall("getLogWriter");
return logWriter;
}
/**
* Set the current log writer for this object.
* This value is ignored by this database.
*
* @param out the log writer
*/
@Override
public void setLogWriter(PrintWriter out) {
debugCodeCall("setLogWriter(out)");
logWriter = out;
}
/**
* Open a new connection using the current URL, user name and password.
*
* @return the connection
*/
@Override
public Connection getConnection() throws SQLException {
debugCodeCall("getConnection");
return getJdbcConnection(userName, StringUtils.cloneCharArray(passwordChars));
}
/**
* Open a new connection using the current URL and the specified user name
* and password.
*
* @param user the user name
* @param password the password
* @return the connection
*/
@Override
public Connection getConnection(String user, String password) throws SQLException {<FILL_FUNCTION_BODY>}
private JdbcConnection getJdbcConnection(String user, char[] password) throws SQLException {
if (isDebugEnabled()) {
debugCode("getJdbcConnection(" + quote(user) + ", new char[0]);");
}
Properties info = new Properties();
info.setProperty("user", user);
info.put("password", convertToString(password));
Connection conn = JdbcDriver.load().connect(url, info);
if (conn == null) {
throw new SQLException("No suitable driver found for " + url, "08001", 8001);
} else if (!(conn instanceof JdbcConnection)) {
throw new SQLException("Connecting with old version is not supported: " + url, "08001",
8001);
}
return (JdbcConnection) conn;
}
/**
* Get the current URL.
*
* @return the URL
*/
public String getURL() {
debugCodeCall("getURL");
return url;
}
/**
* Set the current URL.
*
* @param url the new URL
*/
public void setURL(String url) {
debugCodeCall("setURL", url);
this.url = url;
}
/**
* Set the current password.
*
* @param password the new password.
*/
public void setPassword(String password) {
debugCodeCall("setPassword", "");
this.passwordChars = convertToCharArray(password);
}
/**
* Set the current password in the form of a char array.
*
* @param password the new password in the form of a char array.
*/
public void setPasswordChars(char[] password) {
if (isDebugEnabled()) {
debugCode("setPasswordChars(new char[0]);");
}
this.passwordChars = password;
}
private static char[] convertToCharArray(String s) {
return s == null ? null : s.toCharArray();
}
private static String convertToString(char[] a) {
return a == null ? null : new String(a);
}
/**
* Get the current password.
*
* @return the password
*/
public String getPassword() {
debugCodeCall("getPassword");
return convertToString(passwordChars);
}
/**
* Get the current user name.
*
* @return the user name
*/
public String getUser() {
debugCodeCall("getUser");
return userName;
}
/**
* Set the current user name.
*
* @param user the new user name
*/
public void setUser(String user) {
debugCodeCall("setUser", user);
this.userName = user;
}
/**
* Get the current description.
*
* @return the description
*/
public String getDescription() {
debugCodeCall("getDescription");
return description;
}
/**
* Set the description.
*
* @param description the new description
*/
public void setDescription(String description) {
debugCodeCall("getDescription", description);
this.description = description;
}
/**
* Get a new reference for this object, using the current settings.
*
* @return the new reference
*/
@Override
public Reference getReference() {
debugCodeCall("getReference");
String factoryClassName = JdbcDataSourceFactory.class.getName();
Reference ref = new Reference(getClass().getName(), factoryClassName, null);
ref.add(new StringRefAddr("url", url));
ref.add(new StringRefAddr("user", userName));
ref.add(new StringRefAddr("password", convertToString(passwordChars)));
ref.add(new StringRefAddr("loginTimeout", String.valueOf(loginTimeout)));
ref.add(new StringRefAddr("description", description));
return ref;
}
/**
* [Not supported]
*/
// ## Java 1.7 ##
@Override
public Logger getParentLogger() {
return null;
}
/**
* INTERNAL
*/
@Override
public String toString() {
return getTraceObjectName() + ": url=" + url + " user=" + userName;
}
@Override
public XAConnection getXAConnection() throws SQLException {
return null;
}
@Override
public XAConnection getXAConnection(String user, String password) throws SQLException {
return null;
}
} |
if (isDebugEnabled()) {
debugCode("getConnection(" + quote(user) + ", \"\");");
}
return getJdbcConnection(user, convertToCharArray(password));
| 1,957 | 51 | 2,008 | <methods>public non-sealed void <init>() ,public boolean isWrapperFor(Class<?>) throws java.sql.SQLException,public java.sql.SQLException logAndConvert(java.lang.Exception) ,public static void setAsyncResult(AsyncCallback<?>, java.lang.Throwable) ,public T unwrap(Class<T>) throws java.sql.SQLException<variables> |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcDataSourceFactory.java | JdbcDataSourceFactory | getObjectInstance | class JdbcDataSourceFactory implements ObjectFactory {
private static TraceSystem cachedTraceSystem;
private final Trace trace;
static {
JdbcDriver.load();
}
/**
* The public constructor to create new factory objects.
*/
public JdbcDataSourceFactory() {
trace = getTraceSystem().getTrace("jdbcx");
}
/**
* Creates a new object using the specified location or reference
* information.
*
* @param obj the reference (this factory only supports objects of type
* javax.naming.Reference)
* @param name unused
* @param nameCtx unused
* @param environment unused
* @return the new JdbcDataSource, or null if the reference class name is
* not JdbcDataSource.
*/
@Override
public synchronized Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?, ?> environment) {<FILL_FUNCTION_BODY>}
/**
* INTERNAL
*/
public static TraceSystem getTraceSystem() {
synchronized (JdbcDataSourceFactory.class) {
if (cachedTraceSystem == null) {
cachedTraceSystem = new TraceSystem(SysProperties.CLIENT_TRACE_DIRECTORY
+ Constants.PROJECT_NAME + "datasource" + Constants.SUFFIX_TRACE_FILE);
cachedTraceSystem.setLevelFile(SysProperties.DATASOURCE_TRACE_LEVEL);
}
return cachedTraceSystem;
}
}
Trace getTrace() {
return trace;
}
Trace getTrace(TraceObjectType traceObjectType, int traceObjectId) {
return cachedTraceSystem.getTrace(TraceModuleType.JDBCX, traceObjectType, traceObjectId);
}
} |
if (trace.isDebugEnabled()) {
trace.debug("getObjectInstance obj={0} name={1} nameCtx={2} environment={3}", obj, name,
nameCtx, environment);
}
if (obj instanceof Reference) {
Reference ref = (Reference) obj;
if (ref.getClassName().equals(JdbcDataSource.class.getName())) {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL((String) ref.get("url").getContent());
dataSource.setUser((String) ref.get("user").getContent());
dataSource.setPassword((String) ref.get("password").getContent());
dataSource.setDescription((String) ref.get("description").getContent());
String s = (String) ref.get("loginTimeout").getContent();
dataSource.setLoginTimeout(Integer.parseInt(s));
return dataSource;
}
}
return null;
| 467 | 244 | 711 | <no_super_class> |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcDriver.java | JdbcDriver | getConnection | class JdbcDriver implements java.sql.Driver {
private static final JdbcDriver INSTANCE = new JdbcDriver();
private static volatile boolean registered;
static {
load();
}
/**
* Open a database connection.
* This method should not be called by an application.
* Instead, the method DriverManager.getConnection should be used.
*
* @param url the database URL
* @param info the connection properties
* @return the new connection or null if the URL is not supported
*/
@Override
public Connection connect(String url, Properties info) throws SQLException {
try {
return getConnection(url, info).get();
} catch (Exception e) {
throw DbException.toSQLException(e);
}
}
/**
* Check if the driver understands this URL.
* This method should not be called by an application.
*
* @param url the database URL
* @return if the driver understands the URL
*/
@Override
public boolean acceptsURL(String url) {
if (url != null && url.startsWith(Constants.URL_PREFIX)) {
return true;
}
return false;
}
/**
* Get the major version number of the driver.
* This method should not be called by an application.
*
* @return the major version number
*/
@Override
public int getMajorVersion() {
return Constants.VERSION_MAJOR;
}
/**
* Get the minor version number of the driver.
* This method should not be called by an application.
*
* @return the minor version number
*/
@Override
public int getMinorVersion() {
return Constants.VERSION_MINOR;
}
/**
* Get the list of supported properties.
* This method should not be called by an application.
*
* @param url the database URL
* @param info the connection properties
* @return a zero length array
*/
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) {
return new DriverPropertyInfo[0];
}
/**
* Check if this driver is compliant to the JDBC specification.
* This method should not be called by an application.
*
* @return true
*/
@Override
public boolean jdbcCompliant() {
return true;
}
/**
* [Not supported]
*/
// ## Java 1.7 ##
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw DbException.getUnsupportedException("getParentLogger()");
}
/**
* INTERNAL
*/
public static synchronized JdbcDriver load() {
if (!registered) {
registered = true;
try {
DriverManager.registerDriver(INSTANCE);
} catch (SQLException e) {
DbException.traceThrowable(e);
}
}
return INSTANCE;
}
/**
* INTERNAL
*/
public static synchronized void unload() {
if (registered) {
registered = false;
try {
DriverManager.deregisterDriver(INSTANCE);
} catch (SQLException e) {
DbException.traceThrowable(e);
}
}
}
public static Future<JdbcConnection> getConnection(String url) {
return getConnection(url, null);
}
public static Future<JdbcConnection> getConnection(String url, String user, String password) {
Properties info = new Properties();
if (user != null) {
info.put("user", user);
}
if (password != null) {
info.put("password", password);
}
return getConnection(url, info);
}
public static Future<JdbcConnection> getConnection(String url, Properties info) {
if (!INSTANCE.acceptsURL(url)) {
return Future.succeededFuture(null); // 不抛异常,只是返回null
}
if (info == null) {
info = new Properties();
}
try {
ConnectionInfo ci = new ConnectionInfo(url, info);
return getConnection(ci);
} catch (Throwable t) {
return Future.failedFuture(DbException.toSQLException(t));
}
}
public static Future<JdbcConnection> getConnection(ConnectionInfo ci) {<FILL_FUNCTION_BODY>}
} |
AsyncCallback<JdbcConnection> ac = AsyncCallback.createConcurrentCallback();
try {
ci.getSessionFactory().createSession(ci).onComplete(ar -> {
if (ar.isSucceeded()) {
JdbcConnection conn = new JdbcConnection(ar.getResult(), ci);
ac.setAsyncResult(conn);
} else {
ac.setAsyncResult(ar.getCause());
}
});
} catch (Throwable t) { // getSessionFactory也可能抛异常
ac.setAsyncResult(t);
}
return ac;
| 1,153 | 151 | 1,304 | <no_super_class> |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcParameterMetaData.java | JdbcParameterMetaData | getPrecision | class JdbcParameterMetaData extends JdbcWrapper implements ParameterMetaData {
private final JdbcPreparedStatement prep;
private final List<? extends CommandParameter> parameters;
private final int paramCount;
JdbcParameterMetaData(JdbcPreparedStatement prep, SQLCommand command, int id) {
this.prep = prep;
this.parameters = command.getParameters();
this.paramCount = parameters.size();
this.trace = prep.conn.getTrace(TraceObjectType.PARAMETER_META_DATA, id);
}
/**
* Returns the number of parameters.
*
* @return the number
*/
@Override
public int getParameterCount() throws SQLException {
try {
debugCodeCall("getParameterCount");
checkClosed();
return paramCount;
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Returns the parameter mode.
* Always returns parameterModeIn.
*
* @param param the column index (1,2,...)
* @return parameterModeIn
*/
@Override
public int getParameterMode(int param) throws SQLException {
try {
debugCodeCall("getParameterMode", param);
getParameter(param);
return parameterModeIn;
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Returns the parameter type.
* java.sql.Types.VARCHAR is returned if the data type is not known.
*
* @param param the column index (1,2,...)
* @return the data type
*/
@Override
public int getParameterType(int param) throws SQLException {
try {
debugCodeCall("getParameterType", param);
CommandParameter p = getParameter(param);
int type = p.getType();
if (type == Value.UNKNOWN) {
type = Value.STRING;
}
return DataType.getDataType(type).sqlType;
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Returns the parameter precision.
* The value 0 is returned if the precision is not known.
*
* @param param the column index (1,2,...)
* @return the precision
*/
@Override
public int getPrecision(int param) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* Returns the parameter scale.
* The value 0 is returned if the scale is not known.
*
* @param param the column index (1,2,...)
* @return the scale
*/
@Override
public int getScale(int param) throws SQLException {
try {
debugCodeCall("getScale", param);
CommandParameter p = getParameter(param);
return p.getScale();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Checks if this is nullable parameter.
* Returns ResultSetMetaData.columnNullableUnknown..
*
* @param param the column index (1,2,...)
* @return ResultSetMetaData.columnNullableUnknown
*/
@Override
public int isNullable(int param) throws SQLException {
try {
debugCodeCall("isNullable", param);
return getParameter(param).getNullable();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Checks if this parameter is signed.
* It always returns true.
*
* @param param the column index (1,2,...)
* @return true
*/
@Override
public boolean isSigned(int param) throws SQLException {
try {
debugCodeCall("isSigned", param);
getParameter(param);
return true;
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Returns the Java class name of the parameter.
* "java.lang.String" is returned if the type is not known.
*
* @param param the column index (1,2,...)
* @return the Java class name
*/
@Override
public String getParameterClassName(int param) throws SQLException {
try {
debugCodeCall("getParameterClassName", param);
CommandParameter p = getParameter(param);
int type = p.getType();
if (type == Value.UNKNOWN) {
type = Value.STRING;
}
return DataType.getTypeClassName(type);
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Returns the parameter type name.
* "VARCHAR" is returned if the type is not known.
*
* @param param the column index (1,2,...)
* @return the type name
*/
@Override
public String getParameterTypeName(int param) throws SQLException {
try {
debugCodeCall("getParameterTypeName", param);
CommandParameter p = getParameter(param);
int type = p.getType();
if (type == Value.UNKNOWN) {
type = Value.STRING;
}
return DataType.getDataType(type).name;
} catch (Exception e) {
throw logAndConvert(e);
}
}
private CommandParameter getParameter(int param) {
checkClosed();
if (param < 1 || param > paramCount) {
throw DbException.getInvalidValueException("param", param);
}
return parameters.get(param - 1);
}
private void checkClosed() {
prep.checkClosed();
}
/**
* INTERNAL
*/
@Override
public String toString() {
return getTraceObjectName() + ": parameterCount=" + paramCount;
}
} |
try {
debugCodeCall("getPrecision", param);
CommandParameter p = getParameter(param);
return MathUtils.convertLongToInt(p.getPrecision());
} catch (Exception e) {
throw logAndConvert(e);
}
| 1,506 | 68 | 1,574 | <methods>public non-sealed void <init>() ,public boolean isWrapperFor(Class<?>) throws java.sql.SQLException,public java.sql.SQLException logAndConvert(java.lang.Exception) ,public static void setAsyncResult(AsyncCallback<?>, java.lang.Throwable) ,public T unwrap(Class<T>) throws java.sql.SQLException<variables> |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcSavepoint.java | JdbcSavepoint | getSavepointId | class JdbcSavepoint extends TraceObject implements Savepoint {
private static final String SYSTEM_SAVEPOINT_PREFIX = "SYSTEM_SAVEPOINT_";
private final int savepointId;
private final String name;
private JdbcConnection conn;
JdbcSavepoint(JdbcConnection conn, int savepointId, String name, Trace trace, int id) {
this.conn = conn;
this.savepointId = savepointId;
this.name = name;
this.trace = conn.getTrace(TraceObjectType.SAVEPOINT, id);
}
/**
* Release this savepoint. This method only set the connection to null and
* does not execute a statement.
*/
void release() {
this.conn = null;
}
/**
* Get the savepoint name for this name or id.
* If the name is null, the id is used.
*
* @param name the name (may be null)
* @param id the id
* @return the savepoint name
*/
static String getName(String name, int id) {
if (name != null) {
return StringUtils.quoteJavaString(name);
}
return SYSTEM_SAVEPOINT_PREFIX + id;
}
/**
* Roll back to this savepoint.
*/
void rollback() throws SQLException {
checkValid();
conn.createStatement().executeUpdateAsync("ROLLBACK TO SAVEPOINT " + getName(name, savepointId));
}
private void checkValid() {
if (conn == null) {
throw DbException.get(ErrorCode.SAVEPOINT_IS_INVALID_1, getName(name, savepointId));
}
}
/**
* Get the generated id of this savepoint.
* @return the id
*/
@Override
public int getSavepointId() throws SQLException {<FILL_FUNCTION_BODY>}
/**
* Get the name of this savepoint.
* @return the name
*/
@Override
public String getSavepointName() throws SQLException {
try {
debugCodeCall("getSavepointName");
checkValid();
if (name == null) {
throw DbException.get(ErrorCode.SAVEPOINT_IS_UNNAMED);
}
return name;
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* INTERNAL
*/
@Override
public String toString() {
return getTraceObjectName() + ": id=" + savepointId + " name=" + name;
}
} |
try {
debugCodeCall("getSavepointId");
checkValid();
if (name != null) {
throw DbException.get(ErrorCode.SAVEPOINT_IS_NAMED);
}
return savepointId;
} catch (Exception e) {
throw logAndConvert(e);
}
| 685 | 87 | 772 | <methods>public non-sealed void <init>() ,public static int getNextTraceId(com.lealone.common.trace.TraceObjectType) ,public int getTraceId() ,public java.lang.String getTraceObjectName() <variables>private static final non-sealed java.util.concurrent.atomic.AtomicInteger[] ID,protected com.lealone.common.trace.Trace trace |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/jdbc/JdbcWrapper.java | JdbcWrapper | unwrap | class JdbcWrapper extends TraceObject implements Wrapper {
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException {<FILL_FUNCTION_BODY>}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface != null && iface.isAssignableFrom(getClass());
}
@Override
public SQLException logAndConvert(Exception ex) { // 只是把protected变成public,允许在其他代码中调用
return super.logAndConvert(ex);
}
public static void setAsyncResult(AsyncCallback<?> ac, Throwable cause) {
// 转换成SQLException
ac.setAsyncResult(DbException.toSQLException(cause));
}
} |
try {
if (isWrapperFor(iface)) {
return (T) this;
}
throw DbException.getInvalidValueException("iface", iface);
} catch (Exception e) {
throw logAndConvert(e);
}
| 214 | 69 | 283 | <methods>public non-sealed void <init>() ,public static int getNextTraceId(com.lealone.common.trace.TraceObjectType) ,public int getTraceId() ,public java.lang.String getTraceObjectName() <variables>private static final non-sealed java.util.concurrent.atomic.AtomicInteger[] ID,protected com.lealone.common.trace.Trace trace |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/result/ClientResult.java | ClientResult | sendFetch | class ClientResult implements Result {
protected int fetchSize;
protected ClientSession session;
protected TransferInputStream in;
protected int resultId; // 如果为负数,表示后端没有缓存任何东西
protected final ClientResultColumn[] columns;
protected Value[] currentRow;
protected final int rowCount;
protected int rowId, rowOffset;
protected ArrayList<Value[]> result;
public ClientResult(ClientSession session, TransferInputStream in, int resultId, int columnCount,
int rowCount, int fetchSize) throws IOException {
this.session = session;
this.in = in;
this.resultId = resultId;
this.columns = new ClientResultColumn[columnCount];
this.rowCount = rowCount;
for (int i = 0; i < columnCount; i++) {
columns[i] = new ClientResultColumn(in);
}
rowId = -1;
result = Utils.newSmallArrayList();
this.fetchSize = fetchSize;
fetchRows(false);
}
@Override
public abstract boolean next();
protected abstract void fetchRows(boolean sendFetch);
@Override
public String getAlias(int i) {
return columns[i].alias;
}
@Override
public String getSchemaName(int i) {
return columns[i].schemaName;
}
@Override
public String getTableName(int i) {
return columns[i].tableName;
}
@Override
public String getColumnName(int i) {
return columns[i].columnName;
}
@Override
public int getColumnType(int i) {
return columns[i].columnType;
}
@Override
public long getColumnPrecision(int i) {
return columns[i].precision;
}
@Override
public int getColumnScale(int i) {
return columns[i].scale;
}
@Override
public int getDisplaySize(int i) {
return columns[i].displaySize;
}
@Override
public boolean isAutoIncrement(int i) {
return columns[i].autoIncrement;
}
@Override
public int getNullable(int i) {
return columns[i].nullable;
}
@Override
public void reset() {
rowId = -1;
currentRow = null;
if (session == null) {
return;
}
if (resultId > 0) {
session.checkClosed();
try {
session.send(new ResultReset(resultId));
} catch (Exception e) {
throw DbException.convert(e);
}
}
}
@Override
public Value[] currentRow() {
return currentRow;
}
@Override
public int getRowId() {
return rowId;
}
@Override
public int getVisibleColumnCount() {
return columns.length;
}
@Override
public int getRowCount() {
return rowCount;
}
public int getCurrentRowCount() {
return result.size();
}
// 调度线程和外部线程都会调用
protected void sendClose() {
if (session == null) {
return;
}
try {
if (resultId > 0) {
if (session != null) {
session.send(new ResultClose(resultId));
session = null;
}
} else {
session = null;
}
} catch (Exception e) {
session.getTrace().error(e, "close");
}
}
protected void sendFetch(int fetchSize) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void close() {
result = null;
sendClose();
}
protected void remapIfOld() {
if (session == null) {
return;
}
try {
if (resultId > 0
&& resultId <= session.getCurrentId() - SysProperties.SERVER_CACHED_OBJECTS / 2) {
// object is too old - we need to map it to a new id
int newId = session.getNextId();
session.send(new ResultChangeId(resultId, newId)); // 不需要响应
resultId = newId;
}
} catch (Exception e) {
throw DbException.convert(e);
}
}
@Override
public String toString() {
return "columns: " + columns.length + " rows: " + rowCount + " pos: " + rowId;
}
@Override
public int getFetchSize() {
return fetchSize;
}
@Override
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
}
@Override
public boolean needToClose() {
return true;
}
} |
// 释放buffer
in.closeInputStream();
JdbcAsyncCallback<Boolean> ac = new JdbcAsyncCallback<>();
session.<ResultFetchRowsAck> send(new ResultFetchRows(resultId, fetchSize)).onComplete(ar -> {
if (ar.isSucceeded()) {
in = (TransferInputStream) ar.getResult().in;
ac.setAsyncResult(true);
} else {
ac.setAsyncResult(ar.getCause());
}
});
ac.get();
| 1,273 | 137 | 1,410 | <no_super_class> |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/result/RowCountDeterminedClientResult.java | RowCountDeterminedClientResult | fetchRows | class RowCountDeterminedClientResult extends ClientResult {
public RowCountDeterminedClientResult(ClientSession session, TransferInputStream in, int resultId,
int columnCount, int rowCount, int fetchSize) throws IOException {
super(session, in, resultId, columnCount, rowCount, fetchSize);
}
@Override
public boolean next() {
if (rowId < rowCount) {
rowId++;
remapIfOld();
if (rowId < rowCount) {
if (rowId - rowOffset >= result.size()) {
fetchRows(true);
}
currentRow = result.get(rowId - rowOffset);
return true;
}
currentRow = null;
}
return false;
}
@Override
protected void fetchRows(boolean sendFetch) {<FILL_FUNCTION_BODY>}
} |
session.checkClosed();
try {
rowOffset += result.size();
result.clear();
int fetch = Math.min(fetchSize, rowCount - rowOffset);
if (sendFetch) {
sendFetch(fetch);
}
for (int r = 0; r < fetch; r++) {
boolean row = in.readBoolean();
if (!row) {
break;
}
int len = columns.length;
Value[] values = new Value[len];
for (int i = 0; i < len; i++) {
Value v = in.readValue();
values[i] = v;
}
result.add(values);
}
if (rowOffset + result.size() >= rowCount) {
sendClose();
}
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
| 222 | 229 | 451 | <methods>public void <init>(com.lealone.client.session.ClientSession, com.lealone.net.TransferInputStream, int, int, int, int) throws java.io.IOException,public void close() ,public com.lealone.db.value.Value[] currentRow() ,public java.lang.String getAlias(int) ,public java.lang.String getColumnName(int) ,public long getColumnPrecision(int) ,public int getColumnScale(int) ,public int getColumnType(int) ,public int getCurrentRowCount() ,public int getDisplaySize(int) ,public int getFetchSize() ,public int getNullable(int) ,public int getRowCount() ,public int getRowId() ,public java.lang.String getSchemaName(int) ,public java.lang.String getTableName(int) ,public int getVisibleColumnCount() ,public boolean isAutoIncrement(int) ,public boolean needToClose() ,public abstract boolean next() ,public void reset() ,public void setFetchSize(int) ,public java.lang.String toString() <variables>protected final non-sealed com.lealone.client.result.ClientResultColumn[] columns,protected com.lealone.db.value.Value[] currentRow,protected int fetchSize,protected com.lealone.net.TransferInputStream in,protected ArrayList<com.lealone.db.value.Value[]> result,protected int resultId,protected final non-sealed int rowCount,protected int rowId,protected int rowOffset,protected com.lealone.client.session.ClientSession session |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/result/RowCountUndeterminedClientResult.java | RowCountUndeterminedClientResult | fetchRows | class RowCountUndeterminedClientResult extends ClientResult {
// 不能在这初始化为false,在super的构造函数中会调用fetchRows有可能把isEnd设为true了,
// 如果初始化为false,相当于在调用完super(...)后再执行isEnd = false,这时前面的值就被覆盖了。
private boolean isEnd;
public RowCountUndeterminedClientResult(ClientSession session, TransferInputStream in, int resultId,
int columnCount, int fetchSize) throws IOException {
super(session, in, resultId, columnCount, -1, fetchSize);
}
@Override
public boolean next() {
if (isEnd && rowId - rowOffset >= result.size() - 1) {
currentRow = null;
return false;
}
rowId++;
if (!isEnd) {
remapIfOld();
if (rowId - rowOffset >= result.size()) {
fetchRows(true);
if (isEnd && result.isEmpty()) {
currentRow = null;
return false;
}
}
}
currentRow = result.get(rowId - rowOffset);
return true;
}
@Override
public int getRowCount() {
return Integer.MAX_VALUE; // 不能返回-1,JdbcResultSet那边会抛异常
}
@Override
protected void fetchRows(boolean sendFetch) {<FILL_FUNCTION_BODY>}
} |
session.checkClosed();
try {
rowOffset += result.size();
result.clear();
if (sendFetch) {
sendFetch(fetchSize);
}
for (int r = 0; r < fetchSize; r++) {
boolean row = in.readBoolean();
if (!row) {
isEnd = true;
break;
}
int len = columns.length;
Value[] values = new Value[len];
for (int i = 0; i < len; i++) {
Value v = in.readValue();
values[i] = v;
}
result.add(values);
}
if (isEnd)
sendClose();
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
| 380 | 209 | 589 | <methods>public void <init>(com.lealone.client.session.ClientSession, com.lealone.net.TransferInputStream, int, int, int, int) throws java.io.IOException,public void close() ,public com.lealone.db.value.Value[] currentRow() ,public java.lang.String getAlias(int) ,public java.lang.String getColumnName(int) ,public long getColumnPrecision(int) ,public int getColumnScale(int) ,public int getColumnType(int) ,public int getCurrentRowCount() ,public int getDisplaySize(int) ,public int getFetchSize() ,public int getNullable(int) ,public int getRowCount() ,public int getRowId() ,public java.lang.String getSchemaName(int) ,public java.lang.String getTableName(int) ,public int getVisibleColumnCount() ,public boolean isAutoIncrement(int) ,public boolean needToClose() ,public abstract boolean next() ,public void reset() ,public void setFetchSize(int) ,public java.lang.String toString() <variables>protected final non-sealed com.lealone.client.result.ClientResultColumn[] columns,protected com.lealone.db.value.Value[] currentRow,protected int fetchSize,protected com.lealone.net.TransferInputStream in,protected ArrayList<com.lealone.db.value.Value[]> result,protected int resultId,protected final non-sealed int rowCount,protected int rowId,protected int rowOffset,protected com.lealone.client.session.ClientSession session |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/session/AutoReconnectSession.java | AutoReconnectSession | reconnect | class AutoReconnectSession extends DelegatedSession {
private ConnectionInfo ci;
private String newTargetNodes;
AutoReconnectSession(ConnectionInfo ci) {
this.ci = ci;
}
@Override
public void setAutoCommit(boolean autoCommit) {
super.setAutoCommit(autoCommit);
if (newTargetNodes != null) {
reconnect();
}
}
@Override
public void runModeChanged(String newTargetNodes) {
this.newTargetNodes = newTargetNodes;
if (session.isAutoCommit()) {
reconnect();
}
}
private void reconnect() {<FILL_FUNCTION_BODY>}
@Override
public void reconnectIfNeeded() {
if (newTargetNodes != null) {
reconnect();
}
}
} |
Session oldSession = this.session;
this.ci = this.ci.copy(newTargetNodes);
ci.getSessionFactory().createSession(ci).onSuccess(s -> {
AutoReconnectSession a = (AutoReconnectSession) s;
session = a.session;
oldSession.close();
newTargetNodes = null;
});
| 225 | 91 | 316 | <methods>public void <init>() ,public void <init>(com.lealone.db.session.Session) ,public void cancel() ,public void cancelStatement(int) ,public void checkClosed() ,public void close() ,public AsyncCallback<T> createCallback() ,public com.lealone.sql.SQLCommand createSQLCommand(java.lang.String, int, boolean) ,public com.lealone.db.ConnectionInfo getConnectionInfo() ,public com.lealone.db.DataHandler getDataHandler() ,public int getId() ,public byte[] getLobMacSalt() ,public java.lang.String getLocalHostAndPort() ,public int getNetworkTimeout() ,public com.lealone.db.RunMode getRunMode() ,public com.lealone.db.scheduler.Scheduler getScheduler() ,public com.lealone.db.session.SessionStatus getStatus() ,public java.lang.String getTargetNodes() ,public com.lealone.common.trace.Trace getTrace(com.lealone.common.trace.TraceModuleType, com.lealone.common.trace.TraceObjectType) ,public com.lealone.common.trace.Trace getTrace(com.lealone.common.trace.TraceModuleType, com.lealone.common.trace.TraceObjectType, int) ,public java.lang.String getURL() ,public com.lealone.sql.PreparedSQLStatement.YieldableCommand getYieldableCommand() ,public com.lealone.sql.PreparedSQLStatement.YieldableCommand getYieldableCommand(boolean, com.lealone.db.session.Session.TimeoutListener) ,public void init() ,public boolean isAutoCommit() ,public boolean isClosed() ,public boolean isInvalid() ,public boolean isRunModeChanged() ,public boolean isSingleThreadCallback() ,public boolean isValid() ,public void reconnectIfNeeded() ,public void runModeChanged(java.lang.String) ,public Future<R> send(com.lealone.server.protocol.Packet, AckPacketHandler<R,P>) ,public Future<R> send(com.lealone.server.protocol.Packet, int, AckPacketHandler<R,P>) ,public void setAutoCommit(boolean) ,public void setInvalid(boolean) ,public void setLobMacSalt(byte[]) ,public void setNetworkTimeout(int) ,public void setRunMode(com.lealone.db.RunMode) ,public void setScheduler(com.lealone.db.scheduler.Scheduler) ,public void setSession(com.lealone.db.session.Session) ,public void setSingleThreadCallback(boolean) ,public void setStatus(com.lealone.db.session.SessionStatus) ,public void setTargetNodes(java.lang.String) ,public void setYieldableCommand(com.lealone.sql.PreparedSQLStatement.YieldableCommand) <variables>protected com.lealone.db.session.Session session |
lealone_Lealone | Lealone/lealone-client/src/main/java/com/lealone/client/session/ClientSessionFactory.java | ClientSessionFactory | createSession | class ClientSessionFactory extends SessionFactoryBase {
private static final ClientSessionFactory instance = new ClientSessionFactory();
public static ClientSessionFactory getInstance() {
return instance;
}
@Override
public Future<Session> createSession(ConnectionInfo ci, boolean allowRedirect) {
if (!ci.isRemote()) {
throw DbException.getInternalError();
}
AsyncCallback<Session> ac;
NetClient netClient;
CaseInsensitiveMap<String> config = ci.getConfig();
NetFactory netFactory = NetFactory.getFactory(config);
if (netFactory.isBio()) {
ac = AsyncCallback.create(true);
netClient = netFactory.createNetClient();
ci.setSingleThreadCallback(true);
createSession(ci, allowRedirect, ac, config, netClient);
} else {
Scheduler scheduler = ci.getScheduler();
if (scheduler == null)
scheduler = ClientScheduler.getScheduler(ci, config);
NetEventLoop eventLoop = (NetEventLoop) scheduler.getNetEventLoop();
netClient = eventLoop.getNetClient();
ac = AsyncCallback.create(ci.isSingleThreadCallback());
scheduler.handle(() -> {
createSession(ci, allowRedirect, ac, config, netClient);
});
}
return ac;
}
private static void createSession(ConnectionInfo ci, boolean allowRedirect,
AsyncCallback<Session> ac, CaseInsensitiveMap<String> config, NetClient netClient) {
String[] servers = StringUtils.arraySplit(ci.getServers(), ',');
Random random = new Random(System.currentTimeMillis());
AutoReconnectSession parent = new AutoReconnectSession(ci);
createSession(parent, ci, servers, allowRedirect, random, ac, config, netClient);
}
// servers是接入节点,可以有多个,会随机选择一个进行连接,这个被选中的接入节点可能不是所要连接的数居库所在的节点,
// 这时接入节点会返回数据库的真实所在节点,最后再根据数据库的运行模式打开合适的连接即可,
// 复制模式需要打开所有节点,其他运行模式只需要打开一个。
// 如果第一次从servers中随机选择的一个连接失败了,会尝试其他的,当所有尝试都失败了才会抛出异常。
private static void createSession(AutoReconnectSession parent, ConnectionInfo ci, String[] servers,
boolean allowRedirect, Random random, AsyncCallback<Session> topAc,
CaseInsensitiveMap<String> config, NetClient netClient) {<FILL_FUNCTION_BODY>}
private static void createClientSession(AutoReconnectSession parent, ConnectionInfo ci,
String server, AsyncCallback<ClientSession> ac, CaseInsensitiveMap<String> config,
NetClient netClient) {
NetNode node = NetNode.createTCP(server);
// 多个客户端session会共用同一条TCP连接
netClient.createConnection(config, node, ci.getScheduler()).onComplete(ar -> {
if (ar.isSucceeded()) {
AsyncConnection conn = ar.getResult();
if (!(conn instanceof TcpClientConnection)) {
RuntimeException e = DbException
.getInternalError("not tcp client connection: " + conn.getClass().getName());
ac.setAsyncResult(e);
return;
}
TcpClientConnection tcpConnection = (TcpClientConnection) conn;
// 每一个通过网络传输的协议包都会带上sessionId,
// 这样就能在同一条TCP连接中区分不同的客户端session了
int sessionId = tcpConnection.getNextId();
ClientSession clientSession = new ClientSession(tcpConnection, ci, server, parent,
sessionId);
clientSession.setSingleThreadCallback(ci.isSingleThreadCallback());
tcpConnection.addSession(sessionId, clientSession);
SessionInit packet = new SessionInit(ci);
AckPacketHandler<ClientSession, SessionInitAck> ackPacketHandler = ack -> {
clientSession.setProtocolVersion(ack.clientVersion);
clientSession.setAutoCommit(ack.autoCommit);
clientSession.setTargetNodes(ack.targetNodes);
clientSession.setRunMode(ack.runMode);
clientSession.setInvalid(ack.invalid);
clientSession.setConsistencyLevel(ack.consistencyLevel);
return clientSession;
};
Future<ClientSession> f = clientSession.send(packet, ackPacketHandler);
f.onComplete(ar2 -> {
ac.setAsyncResult(ar2);
});
} else {
ac.setAsyncResult(ar.getCause());
}
});
}
private static void redirectIfNeeded(AutoReconnectSession parent, ClientSession clientSession,
ConnectionInfo ci, AsyncCallback<Session> topAc, CaseInsensitiveMap<String> config,
NetClient netClient) {
if (clientSession.isInvalid()) {
switch (clientSession.getRunMode()) {
case CLIENT_SERVER:
case SHARDING: {
ConnectionInfo ci2 = ci.copy(clientSession.getTargetNodes());
// 关闭当前session,因为连到的节点不是所要的
clientSession.close();
createSession(ci2, false, topAc, config, netClient);
break;
}
default:
topAc.setAsyncResult(DbException.getInternalError());
}
} else {
sessionCreated(parent, clientSession, ci, topAc);
}
}
private static void sessionCreated(AutoReconnectSession parent, ClientSession clientSession,
ConnectionInfo ci, AsyncCallback<Session> topAc) {
parent.setSession(clientSession);
parent.setScheduler(ci.getScheduler());
topAc.setAsyncResult(parent);
}
} |
int randomIndex = random.nextInt(servers.length);
String server = servers[randomIndex];
AsyncCallback<ClientSession> ac = AsyncCallback.createSingleThreadCallback();
ac.onComplete(ar -> {
if (ar.isSucceeded()) {
ClientSession clientSession = ar.getResult();
// 看看是否需要根据运行模式从当前接入节点转到数据库所在的节点
if (allowRedirect) {
redirectIfNeeded(parent, clientSession, ci, topAc, config, netClient);
} else {
sessionCreated(parent, clientSession, ci, topAc);
}
} else {
// 如果已经是最后一个了那就可以直接抛异常了,否则再选其他的
if (servers.length == 1) {
Throwable e = DbException.getCause(ar.getCause());
e = DbException.get(ErrorCode.CONNECTION_BROKEN_1, e, server);
topAc.setAsyncResult(e);
} else {
int len = servers.length;
String[] newServers = new String[len - 1];
for (int i = 0, j = 0; j < len; j++) {
if (j != randomIndex)
newServers[i++] = servers[j];
}
createSession(parent, ci, newServers, allowRedirect, random, topAc, config,
netClient);
}
}
});
createClientSession(parent, ci, server, ac, config, netClient);
| 1,489 | 395 | 1,884 | <methods>public void <init>() ,public Class<? extends com.lealone.db.Plugin> getPluginClass() <variables> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/compress/CompressDeflate.java | CompressDeflate | expand | class CompressDeflate implements Compressor {
private int level = Deflater.DEFAULT_COMPRESSION;
private int strategy = Deflater.DEFAULT_STRATEGY;
@Override
public int getAlgorithm() {
return Compressor.DEFLATE;
}
@Override
public void setOptions(String options) {
if (options == null) {
return;
}
try {
StringTokenizer tokenizer = new StringTokenizer(options);
while (tokenizer.hasMoreElements()) {
String option = tokenizer.nextToken();
if ("level".equals(option) || "l".equals(option)) {
level = Integer.parseInt(tokenizer.nextToken());
} else if ("strategy".equals(option) || "s".equals(option)) {
strategy = Integer.parseInt(tokenizer.nextToken());
}
Deflater deflater = new Deflater(level);
deflater.setStrategy(strategy);
}
} catch (Exception e) {
throw DbException.get(ErrorCode.UNSUPPORTED_COMPRESSION_OPTIONS_1, options);
}
}
@Override
public int compress(byte[] in, int inLen, byte[] out, int outPos) {
Deflater deflater = new Deflater(level);
deflater.setStrategy(strategy);
deflater.setInput(in, 0, inLen);
deflater.finish();
int compressed = deflater.deflate(out, outPos, out.length - outPos);
while (compressed == 0) {
// the compressed length is 0, meaning compression didn't work
// (sounds like a JDK bug)
// try again, using the default strategy and compression level
strategy = Deflater.DEFAULT_STRATEGY;
level = Deflater.DEFAULT_COMPRESSION;
return compress(in, inLen, out, outPos);
}
deflater.end();
return outPos + compressed;
}
@Override
public void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos, int outLen) {<FILL_FUNCTION_BODY>}
} |
Inflater decompresser = new Inflater();
decompresser.setInput(in, inPos, inLen);
decompresser.finished();
try {
int len = decompresser.inflate(out, outPos, outLen);
if (len != outLen) {
throw new DataFormatException(len + " " + outLen);
}
} catch (DataFormatException e) {
throw DbException.get(ErrorCode.COMPRESSION_ERROR, e);
}
decompresser.end();
| 552 | 139 | 691 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/compress/CompressNo.java | CompressNo | compress | class CompressNo implements Compressor {
@Override
public int getAlgorithm() {
return Compressor.NO;
}
@Override
public void setOptions(String options) {
// nothing to do
}
@Override
public int compress(byte[] in, int inLen, byte[] out, int outPos) {<FILL_FUNCTION_BODY>}
@Override
public void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos, int outLen) {
System.arraycopy(in, inPos, out, outPos, outLen);
}
} |
System.arraycopy(in, 0, out, outPos, inLen);
return outPos + inLen;
| 162 | 32 | 194 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/compress/LZFInputStream.java | LZFInputStream | readInt | class LZFInputStream extends InputStream {
private final InputStream in;
private CompressLZF decompress = new CompressLZF();
private int pos;
private int bufferLength;
private byte[] inBuffer;
private byte[] buffer;
public LZFInputStream(InputStream in) throws IOException {
this.in = in;
if (readInt() != LZFOutputStream.MAGIC) {
throw new IOException("Not an LZFInputStream");
}
}
private static byte[] ensureSize(byte[] buff, int len) {
return buff == null || buff.length < len ? DataUtils.newBytes(len) : buff;
}
private void fillBuffer() throws IOException {
if (buffer != null && pos < bufferLength) {
return;
}
int len = readInt();
if (decompress == null) {
// EOF
this.bufferLength = 0;
} else if (len < 0) {
len = -len;
buffer = ensureSize(buffer, len);
readFully(buffer, len);
this.bufferLength = len;
} else {
inBuffer = ensureSize(inBuffer, len);
int size = readInt();
readFully(inBuffer, len);
buffer = ensureSize(buffer, size);
try {
decompress.expand(inBuffer, 0, len, buffer, 0, size);
} catch (ArrayIndexOutOfBoundsException e) {
throw DbException.convertToIOException(e);
}
this.bufferLength = size;
}
pos = 0;
}
private void readFully(byte[] buff, int len) throws IOException {
int off = 0;
while (len > 0) {
int l = in.read(buff, off, len);
len -= l;
off += l;
}
}
private int readInt() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int read() throws IOException {
fillBuffer();
if (pos >= bufferLength) {
return -1;
}
return buffer[pos++] & 255;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
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[] b, int off, int len) throws IOException {
fillBuffer();
if (pos >= bufferLength) {
return -1;
}
int max = Math.min(len, bufferLength - pos);
max = Math.min(max, b.length - off);
System.arraycopy(buffer, pos, b, off, max);
pos += max;
return max;
}
@Override
public void close() throws IOException {
in.close();
}
} |
int x = in.read();
if (x < 0) {
decompress = null;
return 0;
}
x = (x << 24) + (in.read() << 16) + (in.read() << 8) + in.read();
return x;
| 850 | 76 | 926 | <methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/compress/LZFOutputStream.java | LZFOutputStream | ensureOutput | class LZFOutputStream extends OutputStream {
/**
* The file header of a LZF file.
*/
static final int MAGIC = ('H' << 24) | ('2' << 16) | ('I' << 8) | 'S';
private final OutputStream out;
private final CompressLZF compress = new CompressLZF();
private final byte[] buffer;
private int pos;
private byte[] outBuffer;
public LZFOutputStream(OutputStream out) throws IOException {
this.out = out;
int len = Constants.IO_BUFFER_SIZE_COMPRESS;
buffer = new byte[len];
ensureOutput(len);
writeInt(MAGIC);
}
private void ensureOutput(int len) {<FILL_FUNCTION_BODY>}
@Override
public void write(int b) throws IOException {
if (pos >= buffer.length) {
flush();
}
buffer[pos++] = (byte) b;
}
private void compressAndWrite(byte[] buff, int len) throws IOException {
if (len > 0) {
ensureOutput(len);
int compressed = compress.compress(buff, len, outBuffer, 0);
if (compressed > len) {
writeInt(-len);
out.write(buff, 0, len);
} else {
writeInt(compressed);
writeInt(len);
out.write(outBuffer, 0, compressed);
}
}
}
private void writeInt(int x) throws IOException {
out.write((byte) (x >> 24));
out.write((byte) (x >> 16));
out.write((byte) (x >> 8));
out.write((byte) x);
}
@Override
public void write(byte[] buff, int off, int len) throws IOException {
while (len > 0) {
int copy = Math.min(buffer.length - pos, len);
System.arraycopy(buff, off, buffer, pos, copy);
pos += copy;
if (pos >= buffer.length) {
flush();
}
off += copy;
len -= copy;
}
}
@Override
public void flush() throws IOException {
compressAndWrite(buffer, pos);
pos = 0;
}
@Override
public void close() throws IOException {
flush();
out.close();
}
} |
// TODO calculate the maximum overhead (worst case) for the output buffer
int outputLen = (len < 100 ? len + 100 : len) * 2;
if (outBuffer == null || outBuffer.length < outputLen) {
outBuffer = new byte[outputLen];
}
| 629 | 78 | 707 | <methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/exceptions/JdbcSQLException.java | JdbcSQLException | setSQL | class JdbcSQLException extends SQLException {
// /**
// * If the SQL statement contains this text, then it is never added to the
// * SQL exception. Hiding the SQL statement may be important if it contains a
// * passwords, such as a CREATE LINKED TABLE statement.
// */
// public static final String HIDE_SQL = "--hide--";
private static final long serialVersionUID = 1L;
private final String originalMessage;
private final Throwable cause;
private final String stackTrace;
private String message;
private String sql;
/**
* Creates a SQLException.
*
* @param message the reason
* @param sql the SQL statement
* @param state the SQL state
* @param errorCode the error code
* @param cause the exception that was the reason for this exception
* @param stackTrace the stack trace
*/
public JdbcSQLException(String message, String sql, String state, int errorCode, Throwable cause,
String stackTrace) {
super(message, state, errorCode, cause);
this.originalMessage = message;
this.cause = cause;
this.stackTrace = stackTrace;
setSQL(sql, false);
buildMessage();
}
/**
* Get the detail error message.
*
* @return the message
*/
@Override
public String getMessage() {
return message;
}
/**
* INTERNAL
*/
public String getOriginalMessage() {
return originalMessage;
}
/**
* INTERNAL
*/
public Throwable getOriginalCause() {
return cause;
}
/**
* Returns the SQL statement.
* SQL statements that contain '--hide--' are not listed.
*
* @return the SQL statement
*/
public String getSQL() {
return sql;
}
/**
* INTERNAL
*/
public void setSQL(String sql) {
setSQL(sql, true);
}
private void setSQL(String sql, boolean build) {<FILL_FUNCTION_BODY>}
private void buildMessage() {
StringBuilder buff = new StringBuilder(originalMessage == null ? "- " : originalMessage);
if (sql != null) {
buff.append("; SQL statement:\n").append(sql);
}
buff.append(" [").append(getErrorCode()).append('-').append(Constants.BUILD_ID).append(']');
message = buff.toString();
}
/**
* Returns the class name, the message, and in the server mode, the stack
* trace of the server
*
* @return the string representation
*/
@Override
public String toString() {
if (stackTrace == null) {
return super.toString();
}
return stackTrace;
}
/**
* Prints the stack trace to the standard error stream.
*/
@Override
public void printStackTrace() {
// The default implementation already does that,
// but we do it again to avoid problems.
// If it is not implemented, somebody might implement it
// later on which would be a problem if done in the wrong way.
printStackTrace(System.err);
}
/**
* Prints the stack trace to the specified print writer.
*
* @param s the print writer
*/
@Override
public void printStackTrace(PrintWriter s) {
if (s != null) {
super.printStackTrace(s);
// getNextException().printStackTrace(s) would be very very slow
// if many exceptions are joined
SQLException next = getNextException();
for (int i = 0; i < 100 && next != null; i++) {
s.println(next.toString());
next = next.getNextException();
}
if (next != null) {
s.println("(truncated)");
}
}
}
/**
* Prints the stack trace to the specified print stream.
*
* @param s the print stream
*/
@Override
public void printStackTrace(PrintStream s) {
if (s != null) {
super.printStackTrace(s);
// getNextException().printStackTrace(s) would be very very slow
// if many exceptions are joined
SQLException next = getNextException();
for (int i = 0; i < 100 && next != null; i++) {
s.println(next.toString());
next = next.getNextException();
}
if (next != null) {
s.println("(truncated)");
}
}
}
} |
// if (sql != null && sql.contains(HIDE_SQL)) {
// sql = "-";
// }
this.sql = sql;
if (build) {
buildMessage();
}
| 1,200 | 57 | 1,257 | <methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String) ,public void <init>(java.lang.String, java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, int) ,public void <init>(java.lang.String, java.lang.String, java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, int, java.lang.Throwable) ,public int getErrorCode() ,public java.sql.SQLException getNextException() ,public java.lang.String getSQLState() ,public Iterator<java.lang.Throwable> iterator() ,public void setNextException(java.sql.SQLException) <variables>private java.lang.String SQLState,private volatile java.sql.SQLException next,private static final AtomicReferenceFieldUpdater<java.sql.SQLException,java.sql.SQLException> nextUpdater,private static final long serialVersionUID,private int vendorCode |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/logging/LoggerFactory.java | LoggerFactory | getLoggerFactory | class LoggerFactory {
protected abstract Logger createLogger(String name);
public static final String LOGGER_FACTORY_CLASS_NAME = "lealone.logger.factory";
private static final ConcurrentHashMap<String, Logger> loggers = new ConcurrentHashMap<>();
private static final LoggerFactory loggerFactory = getLoggerFactory();
// 优先使用自定义的LoggerFactory,然后是log4j2,最后是Console
private static LoggerFactory getLoggerFactory() {<FILL_FUNCTION_BODY>}
public static Logger getLogger(Class<?> clazz) {
String name = clazz.isAnonymousClass() ? clazz.getEnclosingClass().getCanonicalName()
: clazz.getCanonicalName();
return getLogger(name);
}
public static Logger getLogger(String name) {
Logger logger = loggers.get(name);
if (logger == null) {
logger = loggerFactory.createLogger(name);
Logger oldLogger = loggers.putIfAbsent(name, logger);
if (oldLogger != null) {
logger = oldLogger;
}
}
return logger;
}
public static void removeLogger(String name) {
loggers.remove(name);
}
} |
String factoryClassName = null;
try {
factoryClassName = System.getProperty(LOGGER_FACTORY_CLASS_NAME);
} catch (Exception e) {
}
if (factoryClassName != null) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
Class<?> clz = loader.loadClass(factoryClassName);
return Utils.newInstance(clz);
} catch (Exception e) {
throw new IllegalArgumentException(
"Error instantiating class \"" + factoryClassName + "\"", e);
}
} else if (LoggerFactory.class
.getResource("/org/apache/logging/log4j/spi/ExtendedLogger.class") != null) {
return new Log4j2LoggerFactory();
} else {
return new ConsoleLoggerFactory();
}
| 327 | 217 | 544 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/logging/impl/ConsoleLogger.java | ConsoleLogger | log | class ConsoleLogger implements Logger {
@Override
public boolean isWarnEnabled() {
return true;
}
@Override
public boolean isInfoEnabled() {
return true;
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public boolean isTraceEnabled() {
return false;
}
@Override
public void fatal(Object message) {
log(message);
}
@Override
public void fatal(Object message, Throwable t) {
log(message, t);
}
@Override
public void error(Object message) {
log(message);
}
@Override
public void error(Object message, Object... params) {
log(message, params);
}
@Override
public void error(Object message, Throwable t) {
log(message, t);
}
@Override
public void error(Object message, Throwable t, Object... params) {
log(message, t, params);
}
@Override
public void warn(Object message) {
log(message);
}
@Override
public void warn(Object message, Object... params) {
log(message, params);
}
@Override
public void warn(Object message, Throwable t) {
log(message, t);
}
@Override
public void warn(Object message, Throwable t, Object... params) {
log(message, t, params);
}
@Override
public void info(Object message) {
log(message);
}
@Override
public void info(Object message, Object... params) {
log(message, params);
}
@Override
public void info(Object message, Throwable t) {
log(message, t);
}
@Override
public void info(Object message, Throwable t, Object... params) {
log(message, t, params);
}
@Override
public void debug(Object message) {
log(message);
}
@Override
public void debug(Object message, Object... params) {
log(message, params);
}
@Override
public void debug(Object message, Throwable t) {
log(message, t);
}
@Override
public void debug(Object message, Throwable t, Object... params) {
log(message, t, params);
}
@Override
public void trace(Object message) {
log(message);
}
@Override
public void trace(Object message, Object... params) {
log(message, params);
}
@Override
public void trace(Object message, Throwable t) {
log(message, t);
}
@Override
public void trace(Object message, Throwable t, Object... params) {
log(message, t, params);
}
private void log(Object message) {
System.out.println(message);
}
private void log(Object message, Object... params) {<FILL_FUNCTION_BODY>}
private void log(Object message, Throwable t) {
log(message);
if (t != null)
DbException.getCause(t).printStackTrace(System.err);
}
private void log(Object message, Throwable t, Object... params) {
log(message, params);
if (t != null)
DbException.getCause(t).printStackTrace(System.err);
}
} |
char[] chars = message.toString().toCharArray();
int length = chars.length;
StringBuilder s = new StringBuilder(length);
for (int i = 0; i < length; i++) {
if (chars[i] == '{' && chars[i + 1] == '}') {
s.append("%s");
i++;
} else {
s.append(chars[i]);
}
}
System.out.println(String.format(s.toString(), params));
| 929 | 135 | 1,064 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/logging/impl/Log4j2Logger.java | Log4j2Logger | log | class Log4j2Logger implements Logger {
private final static String FQCN = Logger.class.getCanonicalName();
private final ExtendedLogger logger;
Log4j2Logger(String name) {
logger = (ExtendedLogger) org.apache.logging.log4j.LogManager.getLogger(name);
}
@Override
public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
@Override
public void fatal(Object message) {
log(Level.FATAL, message);
}
@Override
public void fatal(Object message, Throwable t) {
log(Level.FATAL, message, t);
}
@Override
public void error(Object message) {
log(Level.ERROR, message);
}
@Override
public void error(Object message, Object... params) {
log(Level.ERROR, message.toString(), params);
}
@Override
public void error(Object message, Throwable t) {
log(Level.ERROR, message, t);
}
@Override
public void error(Object message, Throwable t, Object... params) {
log(Level.ERROR, message.toString(), t, params);
}
@Override
public void warn(Object message) {
log(Level.WARN, message);
}
@Override
public void warn(Object message, Object... params) {
log(Level.WARN, message.toString(), params);
}
@Override
public void warn(Object message, Throwable t) {
log(Level.WARN, message, t);
}
@Override
public void warn(Object message, Throwable t, Object... params) {
log(Level.WARN, message.toString(), t, params);
}
@Override
public void info(Object message) {
log(Level.INFO, message);
}
@Override
public void info(Object message, Object... params) {
log(Level.INFO, message.toString(), params);
}
@Override
public void info(Object message, Throwable t) {
log(Level.INFO, message, t);
}
@Override
public void info(Object message, Throwable t, Object... params) {
log(Level.INFO, message.toString(), t, params);
}
@Override
public void debug(Object message) {
log(Level.DEBUG, message);
}
@Override
public void debug(Object message, Object... params) {
log(Level.DEBUG, message.toString(), params);
}
@Override
public void debug(Object message, Throwable t) {
log(Level.DEBUG, message, t);
}
@Override
public void debug(Object message, Throwable t, Object... params) {
log(Level.DEBUG, message.toString(), t, params);
}
@Override
public void trace(Object message) {
log(Level.TRACE, message);
}
@Override
public void trace(Object message, Object... params) {
log(Level.TRACE, message.toString(), params);
}
@Override
public void trace(Object message, Throwable t) {
log(Level.TRACE, message.toString(), t);
}
@Override
public void trace(Object message, Throwable t, Object... params) {
log(Level.TRACE, message.toString(), t, params);
}
private void log(Level level, Object message) {
log(level, message, null);
}
private void log(Level level, Object message, Throwable t) {<FILL_FUNCTION_BODY>}
private void log(Level level, String message, Object... params) {
logger.logIfEnabled(FQCN, level, null, message, params);
}
private void log(Level level, String message, Throwable t, Object... params) {
t = DbException.getCause(t);
logger.logIfEnabled(FQCN, level, null, new FormattedMessage(message, params), t);
}
} |
t = DbException.getCause(t);
if (message instanceof Message) {
logger.logIfEnabled(FQCN, level, null, (Message) message, t);
} else {
logger.logIfEnabled(FQCN, level, null, message, t);
}
| 1,145 | 77 | 1,222 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/security/CipherFactory.java | CipherFactory | getBlockCipher | class CipherFactory {
private CipherFactory() {
// utility class
}
/**
* Get a new block cipher object for the given algorithm.
*
* @param algorithm the algorithm
* @return a new cipher object
*/
public static BlockCipher getBlockCipher(String algorithm) {<FILL_FUNCTION_BODY>}
} |
algorithm = algorithm.toUpperCase();
switch (algorithm) {
case "XTEA":
return new XTEA();
case "AES":
return new AES();
case "FOG":
return new Fog();
default:
throw DbException.get(ErrorCode.UNSUPPORTED_CIPHER, algorithm);
}
| 96 | 95 | 191 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/security/Fog.java | Fog | decryptBlock | class Fog implements BlockCipher {
private int key;
@Override
public void setKey(byte[] key) {
this.key = (int) Utils.readLong(key, 0);
}
@Override
public int getKeyLength() {
return 16;
}
@Override
public void encrypt(byte[] bytes, int off, int len) {
for (int i = off; i < off + len; i += 16) {
encryptBlock(bytes, bytes, i);
}
}
@Override
public void decrypt(byte[] bytes, int off, int len) {
for (int i = off; i < off + len; i += 16) {
decryptBlock(bytes, bytes, i);
}
}
private void encryptBlock(byte[] in, byte[] out, int off) {
int x0 = (in[off] << 24) | ((in[off + 1] & 255) << 16) | ((in[off + 2] & 255) << 8)
| (in[off + 3] & 255);
int x1 = (in[off + 4] << 24) | ((in[off + 5] & 255) << 16) | ((in[off + 6] & 255) << 8)
| (in[off + 7] & 255);
int x2 = (in[off + 8] << 24) | ((in[off + 9] & 255) << 16) | ((in[off + 10] & 255) << 8)
| (in[off + 11] & 255);
int x3 = (in[off + 12] << 24) | ((in[off + 13] & 255) << 16) | ((in[off + 14] & 255) << 8)
| (in[off + 15] & 255);
int k = key;
int s = x1 & 31;
x0 ^= k;
x0 = (x0 << s) | (x0 >>> (32 - s));
x2 ^= k;
x2 = (x2 << s) | (x2 >>> (32 - s));
s = x0 & 31;
x1 ^= k;
x1 = (x1 << s) | (x1 >>> (32 - s));
x3 ^= k;
x3 = (x3 << s) | (x3 >>> (32 - s));
out[off] = (byte) (x0 >> 24);
out[off + 1] = (byte) (x0 >> 16);
out[off + 2] = (byte) (x0 >> 8);
out[off + 3] = (byte) x0;
out[off + 4] = (byte) (x1 >> 24);
out[off + 5] = (byte) (x1 >> 16);
out[off + 6] = (byte) (x1 >> 8);
out[off + 7] = (byte) x1;
out[off + 8] = (byte) (x2 >> 24);
out[off + 9] = (byte) (x2 >> 16);
out[off + 10] = (byte) (x2 >> 8);
out[off + 11] = (byte) x2;
out[off + 12] = (byte) (x3 >> 24);
out[off + 13] = (byte) (x3 >> 16);
out[off + 14] = (byte) (x3 >> 8);
out[off + 15] = (byte) x3;
}
private void decryptBlock(byte[] in, byte[] out, int off) {<FILL_FUNCTION_BODY>}
} |
int x0 = (in[off] << 24) | ((in[off + 1] & 255) << 16) | ((in[off + 2] & 255) << 8)
| (in[off + 3] & 255);
int x1 = (in[off + 4] << 24) | ((in[off + 5] & 255) << 16) | ((in[off + 6] & 255) << 8)
| (in[off + 7] & 255);
int x2 = (in[off + 8] << 24) | ((in[off + 9] & 255) << 16) | ((in[off + 10] & 255) << 8)
| (in[off + 11] & 255);
int x3 = (in[off + 12] << 24) | ((in[off + 13] & 255) << 16) | ((in[off + 14] & 255) << 8)
| (in[off + 15] & 255);
int k = key;
int s = 32 - (x0 & 31);
x1 = (x1 << s) | (x1 >>> (32 - s));
x1 ^= k;
x3 = (x3 << s) | (x3 >>> (32 - s));
x3 ^= k;
s = 32 - (x1 & 31);
x0 = (x0 << s) | (x0 >>> (32 - s));
x0 ^= k;
x2 = (x2 << s) | (x2 >>> (32 - s));
x2 ^= k;
out[off] = (byte) (x0 >> 24);
out[off + 1] = (byte) (x0 >> 16);
out[off + 2] = (byte) (x0 >> 8);
out[off + 3] = (byte) x0;
out[off + 4] = (byte) (x1 >> 24);
out[off + 5] = (byte) (x1 >> 16);
out[off + 6] = (byte) (x1 >> 8);
out[off + 7] = (byte) x1;
out[off + 8] = (byte) (x2 >> 24);
out[off + 9] = (byte) (x2 >> 16);
out[off + 10] = (byte) (x2 >> 8);
out[off + 11] = (byte) x2;
out[off + 12] = (byte) (x3 >> 24);
out[off + 13] = (byte) (x3 >> 16);
out[off + 14] = (byte) (x3 >> 8);
out[off + 15] = (byte) x3;
| 994 | 741 | 1,735 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/trace/DefaultTrace.java | DefaultTrace | infoSQL | class DefaultTrace implements Trace {
private final TraceWriter traceWriter;
private String module;
private final String traceObjectName;
private final String lineSeparator;
private final int id;
private int traceLevel = TraceSystem.PARENT;
DefaultTrace(TraceWriter traceWriter, String module) {
this(traceWriter, module, null, -1);
}
DefaultTrace(TraceWriter traceWriter, String module, String traceObjectName, int id) {
this.traceWriter = traceWriter;
this.module = module;
this.traceObjectName = traceObjectName;
this.id = id;
this.lineSeparator = System.lineSeparator();
}
@Override
public int getTraceId() {
return id;
}
@Override
public String getTraceObjectName() {
return traceObjectName;
}
@Override
public DefaultTrace setType(TraceModuleType type) {
module = type.name().toLowerCase();
return this;
}
/**
* Set the trace level of this component.
* This setting overrides the parent trace level.
*
* @param level the new level
*/
public void setLevel(int level) {
this.traceLevel = level;
}
private boolean isEnabled(int level) {
if (this.traceLevel == TraceSystem.PARENT) {
return traceWriter.isEnabled(level);
}
return level <= this.traceLevel;
}
@Override
public boolean isInfoEnabled() {
return isEnabled(TraceSystem.INFO);
}
@Override
public boolean isDebugEnabled() {
return isEnabled(TraceSystem.DEBUG);
}
@Override
public void error(Throwable t, String s) {
if (isEnabled(TraceSystem.ERROR)) {
traceWriter.write(TraceSystem.ERROR, module, s, t);
}
}
@Override
public void error(Throwable t, String s, Object... params) {
if (isEnabled(TraceSystem.ERROR)) {
s = MessageFormat.format(s, params);
traceWriter.write(TraceSystem.ERROR, module, s, t);
}
}
@Override
public void info(String s) {
if (isEnabled(TraceSystem.INFO)) {
traceWriter.write(TraceSystem.INFO, module, s, null);
}
}
@Override
public void info(String s, Object... params) {
if (isEnabled(TraceSystem.INFO)) {
s = MessageFormat.format(s, params);
traceWriter.write(TraceSystem.INFO, module, s, null);
}
}
@Override
public void info(Throwable t, String s) {
if (isEnabled(TraceSystem.INFO)) {
traceWriter.write(TraceSystem.INFO, module, s, t);
}
}
@Override
public void infoSQL(String sql, String params, int count, long time) {<FILL_FUNCTION_BODY>}
@Override
public void infoCode(String format, Object... args) {
if (isEnabled(TraceSystem.INFO)) {
String code = String.format(format, args);
traceWriter.write(TraceSystem.INFO, module, lineSeparator + "/**/" + code, null);
}
}
@Override
public void debug(String s) {
if (isEnabled(TraceSystem.DEBUG)) {
traceWriter.write(TraceSystem.DEBUG, module, s, null);
}
}
@Override
public void debug(String s, Object... params) {
if (isEnabled(TraceSystem.DEBUG)) {
s = MessageFormat.format(s, params);
traceWriter.write(TraceSystem.DEBUG, module, s, null);
}
}
@Override
public void debug(Throwable t, String s) {
if (isEnabled(TraceSystem.DEBUG)) {
traceWriter.write(TraceSystem.DEBUG, module, s, t);
}
}
@Override
public void debugCode(String java) {
if (isEnabled(TraceSystem.DEBUG)) {
traceWriter.write(TraceSystem.DEBUG, module, lineSeparator + "/**/" + java, null);
}
}
} |
if (!isEnabled(TraceSystem.INFO)) {
return;
}
StringBuilder buff = new StringBuilder(sql.length() + params.length() + 20);
buff.append(lineSeparator).append("/*SQL");
boolean space = false;
if (params.length() > 0) {
// This looks like a bug, but it is intentional:
// If there are no parameters, the SQL statement is
// the rest of the line. If there are parameters, they
// are appended at the end of the line. Knowing the size
// of the statement simplifies separating the SQL statement
// from the parameters (no need to parse).
space = true;
buff.append(" l:").append(sql.length());
}
if (count > 0) {
space = true;
buff.append(" #:").append(count);
}
if (time > 0) {
space = true;
buff.append(" t:").append(time);
}
if (!space) {
buff.append(' ');
}
buff.append("*/").append(StringUtils.javaEncode(sql)).append(StringUtils.javaEncode(params))
.append(';');
sql = buff.toString();
traceWriter.write(TraceSystem.INFO, module, sql, null);
| 1,098 | 332 | 1,430 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/trace/DefaultTraceWriter.java | DefaultTraceWriter | writeFile | class DefaultTraceWriter implements TraceWriter {
/**
* The default maximum trace file size. It is currently 64 MB. Additionally,
* there could be a .old file of the same size.
*/
private static final int DEFAULT_MAX_FILE_SIZE = 64 * 1024 * 1024;
private static final int CHECK_SIZE_EACH_WRITES = 4096;
private int levelSystemOut = TraceSystem.DEFAULT_TRACE_LEVEL_SYSTEM_OUT;
private int levelFile = TraceSystem.DEFAULT_TRACE_LEVEL_FILE;
private int levelMax;
private int maxFileSize = DEFAULT_MAX_FILE_SIZE;
private String fileName;
private SimpleDateFormat dateFormat;
private Writer fileWriter;
private PrintWriter printWriter;
private int checkSize;
private boolean closed;
private boolean writingErrorLogged;
private TraceWriter writer = this;
private final PrintStream sysOut = System.out;
public DefaultTraceWriter(String fileName) {
this.fileName = fileName;
updateLevel();
}
TraceWriter getTraceWriter() {
return writer;
}
private void updateLevel() {
levelMax = Math.max(levelSystemOut, levelFile);
}
void setFileName(String name) {
this.fileName = name;
}
void setMaxFileSize(int max) {
this.maxFileSize = max;
}
void setLevelSystemOut(int level) {
levelSystemOut = level;
updateLevel();
}
void setLevelFile(int level) {
if (level == TraceSystem.ADAPTER) {
writer = new TraceWriterAdapter();
String name = fileName;
if (name != null) {
if (name.endsWith(Constants.SUFFIX_TRACE_FILE)) {
name = name.substring(0, name.length() - Constants.SUFFIX_TRACE_FILE.length());
}
int idx = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
if (idx >= 0) {
name = name.substring(idx + 1);
}
writer.setName(name);
}
}
levelFile = level;
updateLevel();
}
/**
* Close the writers, and the files if required. It is still possible to
* write after closing, however after each write the file is closed again
* (slowing down tracing).
*/
void close() {
closeWriter();
closed = true;
}
@Override
public void setName(String name) {
// nothing to do (the file name is already set)
}
@Override
public boolean isEnabled(int level) {
return level <= this.levelMax;
}
@Override
public void write(int level, String module, String s, Throwable t) {
if (level <= levelSystemOut || level > this.levelMax) {
// level <= levelSystemOut: the system out level is set higher
// level > this.level: the level for this module is set higher
sysOut.println(format(module, s));
if (t != null && levelSystemOut == TraceSystem.DEBUG) {
t.printStackTrace(sysOut);
}
}
if (fileName != null) {
if (level <= levelFile) {
writeFile(format(module, s), t);
}
}
}
private synchronized String format(String module, String s) {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
}
return dateFormat.format(System.currentTimeMillis()) + module + ": " + s;
}
private synchronized void writeFile(String s, Throwable t) {<FILL_FUNCTION_BODY>}
private void logWritingError(Exception e) {
if (writingErrorLogged) {
return;
}
writingErrorLogged = true;
Exception se = DbException.get(ErrorCode.TRACE_FILE_ERROR_2, e, fileName, e.toString());
// print this error only once
fileName = null;
sysOut.println(se);
se.printStackTrace();
}
private boolean openWriter() {
if (printWriter == null) {
try {
FileUtils.createDirectories(FileUtils.getParent(fileName));
if (FileUtils.exists(fileName) && !FileUtils.canWrite(fileName)) {
// read only database: don't log error if the trace file
// can't be opened
return false;
}
fileWriter = IOUtils.getBufferedWriter(FileUtils.newOutputStream(fileName, true));
printWriter = new PrintWriter(fileWriter, true);
} catch (Exception e) {
logWritingError(e);
return false;
}
}
return true;
}
private synchronized void closeWriter() {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
printWriter = null;
}
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
// ignore
}
fileWriter = null;
}
}
} |
try {
if (checkSize++ >= CHECK_SIZE_EACH_WRITES) {
checkSize = 0;
closeWriter();
if (maxFileSize > 0 && FileUtils.size(fileName) > maxFileSize) {
String old = fileName + ".old";
FileUtils.delete(old);
FileUtils.move(fileName, old);
}
}
if (!openWriter()) {
return;
}
printWriter.println(s);
if (t != null) {
if (levelFile == TraceSystem.ERROR && t instanceof JdbcSQLException) {
JdbcSQLException se = (JdbcSQLException) t;
int code = se.getErrorCode();
if (ErrorCode.isCommon(code)) {
printWriter.println(t.toString());
} else {
t.printStackTrace(printWriter);
}
} else {
t.printStackTrace(printWriter);
}
}
printWriter.flush();
if (closed) {
closeWriter();
}
} catch (Exception e) {
logWritingError(e);
}
| 1,385 | 291 | 1,676 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/trace/TraceSystem.java | TraceSystem | getTrace | class TraceSystem {
/**
* The parent trace level should be used.
*/
public static final int PARENT = -1;
/**
* This trace level means nothing should be written.
*/
public static final int OFF = 0;
/**
* This trace level means only errors should be written.
*/
public static final int ERROR = 1;
/**
* This trace level means errors and informational messages should be
* written.
*/
public static final int INFO = 2;
/**
* This trace level means all type of messages should be written.
*/
public static final int DEBUG = 3;
/**
* This trace level means all type of messages should be written, but
* instead of using the trace file the messages should be written to SLF4J.
*/
public static final int ADAPTER = 4;
/**
* The default level for system out trace messages.
*/
public static final int DEFAULT_TRACE_LEVEL_SYSTEM_OUT = OFF;
/**
* The default level for file trace messages.
*/
public static final int DEFAULT_TRACE_LEVEL_FILE = ERROR;
private final DefaultTraceWriter writer;
public TraceSystem() {
this(null);
}
/**
* Create a new trace system object.
*
* @param fileName the file name
*/
public TraceSystem(String fileName) {
writer = new DefaultTraceWriter(fileName);
}
/**
* Create a trace object for this module. Trace modules with names are not cached.
*
* @param module the module name
* @return the trace object
*/
public Trace getTrace(String module) {
return new DefaultTrace(writer, module);
}
/**
* Create a trace object for this module type.
*
* @param traceModuleType the module type
* @return the trace object
*/
public Trace getTrace(TraceModuleType traceModuleType) {<FILL_FUNCTION_BODY>}
public Trace getTrace(TraceModuleType traceModuleType, TraceObjectType traceObjectType, int id) {
String module = traceModuleType.name().toLowerCase();
String traceObjectName = traceObjectType.getShortName() + id;
return new DefaultTrace(writer, module, traceObjectName, id);
}
/**
* Set the trace file name.
*
* @param name the file name
*/
public void setFileName(String name) {
writer.setFileName(name);
}
/**
* Set the maximum trace file size in bytes.
*
* @param max the maximum size
*/
public void setMaxFileSize(int max) {
writer.setMaxFileSize(max);
}
/**
* Set the trace level to use for System.out
*
* @param level the new level
*/
public void setLevelSystemOut(int level) {
writer.setLevelSystemOut(level);
}
/**
* Set the file trace level.
*
* @param level the new level
*/
public void setLevelFile(int level) {
writer.setLevelFile(level);
}
/**
* Close the trace system.
*/
public void close() {
writer.close();
}
} |
String module = traceModuleType.name().toLowerCase();
String traceObjectName = "";
return new DefaultTrace(writer, module, traceObjectName, -1);
| 857 | 44 | 901 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/trace/TraceWriterAdapter.java | TraceWriterAdapter | write | class TraceWriterAdapter implements TraceWriter {
private String name;
private final Logger logger = LoggerFactory.getLogger("lealone");
@Override
public void setName(String name) {
this.name = name;
}
@Override
public boolean isEnabled(int level) {
switch (level) {
case TraceSystem.DEBUG:
return logger.isDebugEnabled();
case TraceSystem.INFO:
return logger.isInfoEnabled();
case TraceSystem.ERROR:
return true;
default:
return false;
}
}
@Override
public void write(int level, String module, String s, Throwable t) {<FILL_FUNCTION_BODY>}
} |
if (isEnabled(level)) {
if (name != null) {
s = name + ":" + module + " " + s;
} else {
s = module + " " + s;
}
switch (level) {
case TraceSystem.DEBUG:
logger.debug(s, t);
break;
case TraceSystem.INFO:
logger.info(s, t);
break;
case TraceSystem.ERROR:
logger.error(s, t);
break;
default:
}
}
| 191 | 144 | 335 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/Awaiter.java | Awaiter | doAwait | class Awaiter {
private final Logger logger;
private final Semaphore semaphore = new Semaphore(1);
private final AtomicBoolean waiting = new AtomicBoolean(false);
private volatile boolean haveWork;
public Awaiter(Logger logger) {
this.logger = logger;
}
public void doAwait(long timeout) {<FILL_FUNCTION_BODY>}
public void wakeUp() {
haveWork = true;
if (waiting.compareAndSet(true, false)) {
semaphore.release(1);
}
}
public void wakeUp(boolean force) {
haveWork = true;
if (force) {
waiting.set(false);
semaphore.release(1);
} else {
if (waiting.compareAndSet(true, false)) {
semaphore.release(1);
}
}
}
} |
if (waiting.compareAndSet(false, true)) {
if (haveWork) {
haveWork = false;
} else {
try {
semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
semaphore.drainPermits();
} catch (Exception e) {
logger.warn("Semaphore tryAcquire exception", e);
}
}
waiting.set(false);
}
| 239 | 117 | 356 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/BitField.java | BitField | nextClearBit | 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) {<FILL_FUNCTION_BODY>}
/**
* 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;
long[] d = new long[newSize];
System.arraycopy(data, 0, d, 0, data.length);
data = d;
}
}
/**
* 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;
}
} |
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;
| 1,296 | 132 | 1,428 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/CamelCaseHelper.java | CamelCaseHelper | toUnderscoreFromCamel | class CamelCaseHelper {
/**
* To underscore from camel case using digits compressed true and force upper case false.
*/
public static String toUnderscoreFromCamel(String camelCase) {
return toUnderscoreFromCamel(camelCase, true, false);
}
/**
* Convert and return the string to underscore from camel case.
*/
public static String toUnderscoreFromCamel(String camelCase, boolean digitsCompressed,
boolean forceUpperCase) {<FILL_FUNCTION_BODY>}
/**
* To camel from underscore.
*
* @param underscore the underscore
* @return the string
*/
public static String toCamelFromUnderscore(String underscore) {
String[] vals = underscore.split("_");
if (vals.length == 1) {
return isUpperCase(underscore) ? underscore.toLowerCase() : underscore;
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < vals.length; i++) {
String lower = vals[i].toLowerCase();
if (i > 0) {
char c = Character.toUpperCase(lower.charAt(0));
result.append(c);
result.append(lower.substring(1));
} else {
result.append(lower);
}
}
return result.toString();
}
private static boolean isUpperCase(String underscore) {
for (int i = 0; i < underscore.length(); i++) {
if (Character.isLowerCase(underscore.charAt(i))) {
return false;
}
}
return true;
}
public static String toClassNameFromUnderscore(String underscore) {
StringBuilder result = new StringBuilder();
String[] vals = underscore.split("_");
for (int i = 0; i < vals.length; i++) {
toClassName(result, vals[i]);
}
return result.toString();
}
private static void toClassName(StringBuilder buff, String str) {
for (int i = 0, len = str.length(); i < len; i++) {
char c = str.charAt(i);
if (i == 0) {
if (Character.isLowerCase(c)) {
c = Character.toUpperCase(c);
}
} else {
if (Character.isUpperCase(c)) {
c = Character.toLowerCase(c);
}
}
buff.append(c);
}
}
} |
int lastUpper = -1;
StringBuilder sb = new StringBuilder(camelCase.length() + 4);
for (int i = 0; i < camelCase.length(); i++) {
char c = camelCase.charAt(i);
if ('_' == c) {
// Underscores should just be passed through
sb.append(c);
lastUpper = i;
} else if (Character.isDigit(c)) {
if (i > lastUpper + 1 && !digitsCompressed) {
sb.append("_");
}
sb.append(c);
lastUpper = i;
} else if (Character.isUpperCase(c)) {
if (i > lastUpper + 1) {
sb.append("_");
}
sb.append(Character.toLowerCase(c));
lastUpper = i;
} else {
sb.append(c);
}
}
String ret = sb.toString();
if (forceUpperCase) {
ret = ret.toUpperCase();
}
return ret;
| 686 | 288 | 974 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/CaseInsensitiveMap.java | CaseInsensitiveMap | putAll | class CaseInsensitiveMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = 1L;
public CaseInsensitiveMap() {
}
public CaseInsensitiveMap(int initialCapacity) {
super(initialCapacity);
}
public CaseInsensitiveMap(Map<? extends String, ? extends V> m) {
this(m.size());
putAll(m);
}
public CaseInsensitiveMap(Properties prop) {
this(prop.size());
putAll(prop);
}
@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 void putAll(Map<? extends String, ? extends V> m) {
for (Map.Entry<? extends String, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@SuppressWarnings("unchecked")
public void putAll(Properties prop) {<FILL_FUNCTION_BODY>}
@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());
}
public void removeAll(Collection<?> c) {
for (Object e : c) {
remove(e);
}
}
} |
for (Entry<Object, Object> e : prop.entrySet()) {
put(e.getKey().toString(), (V) e.getValue().toString());
}
| 454 | 44 | 498 | <methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends V>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public V compute(java.lang.String, BiFunction<? super java.lang.String,? super V,? extends V>) ,public V computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends V>) ,public V computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super V,? extends V>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,V>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super V>) ,public V get(java.lang.Object) ,public V getOrDefault(java.lang.Object, V) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public V merge(java.lang.String, V, BiFunction<? super V,? super V,? extends V>) ,public V put(java.lang.String, V) ,public void putAll(Map<? extends java.lang.String,? extends V>) ,public V putIfAbsent(java.lang.String, V) ,public V remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public V replace(java.lang.String, V) ,public boolean replace(java.lang.String, V, V) ,public void replaceAll(BiFunction<? super java.lang.String,? super V,? extends V>) ,public int size() ,public Collection<V> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,V>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,V>[] table,int threshold |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/ExpiringMap.java | CacheableObject | getValue | class CacheableObject<T> {
public final T value;
public final long timeout;
private final long createdAt;
private long last;
private CacheableObject(T value, long timeout) {
assert value != null;
this.value = value;
this.timeout = timeout;
last = createdAt = System.nanoTime();
}
private boolean isReadyToDieAt(long atNano) {
return atNano - last > TimeUnit.MILLISECONDS.toNanos(timeout);
}
}
private final Map<K, CacheableObject<V>> cache;
private final long defaultExpiration;
private final AsyncTaskHandler asyncTaskHandler;
private final AsyncPeriodicTask task;
/**
*
* @param defaultExpiration the TTL for objects in the cache in milliseconds
*/
public ExpiringMap(AsyncTaskHandler asyncTaskHandler, long defaultExpiration, boolean isThreadSafe,
final Function<ExpiringMap.CacheableObject<V>, ?> postExpireHook) {
// if (defaultExpiration <= 0) {
// throw new IllegalArgumentException("Argument specified must be a positive number");
// }
if (isThreadSafe)
cache = new HashMap<>();
else
cache = new ConcurrentHashMap<>();
this.defaultExpiration = defaultExpiration;
this.asyncTaskHandler = asyncTaskHandler;
task = new AsyncPeriodicTask(1000, () -> {
long start = System.nanoTime();
int n = 0;
for (Map.Entry<K, CacheableObject<V>> entry : cache.entrySet()) {
if (entry.getValue().isReadyToDieAt(start)) {
if (cache.remove(entry.getKey()) != null) {
n++;
if (postExpireHook != null)
postExpireHook.apply(entry.getValue());
}
}
}
if (logger.isTraceEnabled())
logger.trace("Expired {} entries", n);
});
if (defaultExpiration > 0)
asyncTaskHandler.addPeriodicTask(task);
}
public AsyncPeriodicTask getAsyncPeriodicTask() {
return task;
}
public void reset() {
cache.clear();
}
public void close() {
for (CacheableObject<V> c : cache.values()) {
if (c.value instanceof AutoCloseable) {
try {
((AutoCloseable) c.value).close();
} catch (Throwable t) {
// ignore
}
}
}
cache.clear();
asyncTaskHandler.removePeriodicTask(task);
}
public V put(K key, V value) {
return put(key, value, defaultExpiration);
}
public V put(K key, V value, long timeout) {
CacheableObject<V> previous = cache.put(key, new CacheableObject<V>(value, timeout));
return (previous == null) ? null : previous.value;
}
public V get(K key) {
return get(key, false);
}
public V remove(K key) {
return remove(key, false);
}
/**
* @return System.nanoTime() when key was put into the map.
*/
public long getAge(K key) {
CacheableObject<V> co = cache.get(key);
return co == null ? 0 : co.createdAt;
}
public int size() {
return cache.size();
}
public boolean containsKey(K key) {
return cache.containsKey(key);
}
public boolean isEmpty() {
return cache.isEmpty();
}
public Set<K> keySet() {
return cache.keySet();
}
/**
* Get an object from the map if it is stored.
*
* @param key the key 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 V get(K key, boolean ifAvailable) {
CacheableObject<V> co = cache.get(key);
return getValue(co, ifAvailable);
}
/**
* Remove an object from the map.
*
* @param key the key 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 V remove(K key, boolean ifAvailable) {
CacheableObject<V> co = cache.remove(key);
return getValue(co, ifAvailable);
}
private V getValue(CacheableObject<V> co, boolean ifAvailable) {<FILL_FUNCTION_BODY> |
if (co == null) {
if (!ifAvailable) {
throw DbException.get(ErrorCode.OBJECT_CLOSED);
}
return null;
} else {
co.last = System.nanoTime();
return co.value;
}
| 1,257 | 74 | 1,331 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/JdbcUtils.java | JdbcUtils | closeSilently | class JdbcUtils {
private JdbcUtils() {
// utility class
}
public static void closeSilently(AutoCloseable closeable) {<FILL_FUNCTION_BODY>}
} |
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
// ignore
}
}
| 54 | 44 | 98 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/MapUtils.java | MapUtils | getString | class MapUtils {
private MapUtils() {
// utility class
}
public static int getInt(Map<String, String> map, String key, int def) {
if (map == null)
return def;
String value = map.get(key);
return Utils.toInt(value, def);
}
public static long getLongMB(Map<String, String> map, String key, long def) {
if (map == null)
return def;
String value = map.get(key);
return Utils.toLongMB(value, def);
}
public static long getLong(Map<String, String> map, String key, long def) {
if (map == null)
return def;
String value = map.get(key);
return Utils.toLong(value, def);
}
public static boolean getBoolean(Map<String, String> map, String key, boolean def) {
if (map == null)
return def;
String value = map.get(key);
return Utils.toBoolean(value, def);
}
public static String getString(Map<String, String> map, String key, String def) {<FILL_FUNCTION_BODY>}
public static int getSchedulerCount(Map<String, String> map) {
if (map != null && map.containsKey("scheduler_count"))
return Math.max(1, Integer.parseInt(map.get("scheduler_count")));
else
return Runtime.getRuntime().availableProcessors();
}
} |
if (map == null)
return def;
String value = map.get(key);
if (value == null)
return def;
else
return value;
| 398 | 48 | 446 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/ScriptReader.java | ScriptReader | readStatementLoop | class ScriptReader {
private final Reader reader;
private char[] buffer;
private int bufferPos;
private int bufferStart = -1;
private int bufferEnd;
private boolean endOfFile;
private boolean insideRemark;
private boolean blockRemark;
private boolean skipRemarks;
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.
*/
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 {<FILL_FUNCTION_BODY>}
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) {
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;
}
} |
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(false);
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);
| 977 | 776 | 1,753 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/ShutdownHookUtils.java | ShutdownHookUtils | removeAllShutdownHooks | class ShutdownHookUtils {
private static final HashSet<Thread> hooks = new HashSet<>();
public static synchronized Thread addShutdownHook(Object object, Runnable hook) {
String hookName = object.getClass().getSimpleName() + "-ShutdownHook-" + hooks.size();
return addShutdownHook(hookName, hook, false);
}
public static synchronized Thread addShutdownHook(String hookName, Runnable hook) {
return addShutdownHook(hookName, hook, true);
}
public static synchronized Thread addShutdownHook(String hookName, Runnable hook,
boolean addPostfix) {
if (addPostfix)
hookName += "-ShutdownHook";
Thread t = new Thread(hook, hookName);
return addShutdownHook(t);
}
public static synchronized Thread addShutdownHook(Thread hook) {
hooks.add(hook);
Runtime.getRuntime().addShutdownHook(hook);
return hook;
}
public static synchronized void removeShutdownHook(Thread hook) {
hooks.remove(hook);
Runtime.getRuntime().removeShutdownHook(hook);
}
public static synchronized void removeAllShutdownHooks() {<FILL_FUNCTION_BODY>}
} |
for (Thread hook : hooks) {
Runtime.getRuntime().removeShutdownHook(hook);
}
hooks.clear();
| 329 | 38 | 367 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/SortedProperties.java | SortedProperties | store | class SortedProperties extends Properties {
private static final long serialVersionUID = 1L;
@Override
public synchronized Enumeration<Object> keys() {
Vector<String> v = new Vector<String>();
for (Object o : keySet()) {
v.add(o.toString());
}
Collections.sort(v);
return new Vector<Object>(v).elements();
}
/**
* 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)) {
InputStream in = null;
try {
in = FileUtils.newInputStream(fileName);
prop.load(in);
} finally {
if (in != null) {
in.close();
}
}
}
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 {<FILL_FUNCTION_BODY>}
/**
* 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<Object, Object>(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')) {
int idx = line.indexOf('=');
if (idx > 0) {
p.put(line.substring(0, idx), line.substring(idx + 1));
}
}
return p;
}
} |
ByteArrayOutputStream out = new ByteArrayOutputStream();
store(out, null);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
InputStreamReader reader = new InputStreamReader(in, "ISO8859-1");
LineNumberReader r = new LineNumberReader(reader);
Writer w;
try {
w = new OutputStreamWriter(FileUtils.newOutputStream(fileName, false));
} catch (Exception e) {
throw DbException.convertToIOException(e);
}
PrintWriter writer = new PrintWriter(new BufferedWriter(w));
while (true) {
String line = r.readLine();
if (line == null) {
break;
}
if (!line.startsWith("#")) {
writer.print(line + "\n");
}
}
writer.close();
| 589 | 218 | 807 | <methods>public void <init>() ,public void <init>(int) ,public void <init>(java.util.Properties) ,public synchronized void clear() ,public synchronized java.lang.Object clone() ,public synchronized java.lang.Object compute(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfAbsent(java.lang.Object, Function<? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfPresent(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<java.lang.Object> elements() ,public Set<Entry<java.lang.Object,java.lang.Object>> entrySet() ,public synchronized boolean equals(java.lang.Object) ,public synchronized void forEach(BiConsumer<? super java.lang.Object,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public java.lang.String getProperty(java.lang.String) ,public java.lang.String getProperty(java.lang.String, java.lang.String) ,public synchronized int hashCode() ,public boolean isEmpty() ,public Set<java.lang.Object> keySet() ,public Enumeration<java.lang.Object> keys() ,public void list(java.io.PrintStream) ,public void list(java.io.PrintWriter) ,public synchronized void load(java.io.Reader) throws java.io.IOException,public synchronized void load(java.io.InputStream) throws java.io.IOException,public synchronized void loadFromXML(java.io.InputStream) throws java.io.IOException, java.util.InvalidPropertiesFormatException,public synchronized java.lang.Object merge(java.lang.Object, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public Enumeration<?> propertyNames() ,public synchronized java.lang.Object put(java.lang.Object, java.lang.Object) ,public synchronized void putAll(Map<?,?>) ,public synchronized java.lang.Object putIfAbsent(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object remove(java.lang.Object) ,public synchronized boolean remove(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object replace(java.lang.Object, java.lang.Object) ,public synchronized boolean replace(java.lang.Object, java.lang.Object, java.lang.Object) ,public synchronized void replaceAll(BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public void save(java.io.OutputStream, java.lang.String) ,public synchronized java.lang.Object setProperty(java.lang.String, java.lang.String) ,public int size() ,public void store(java.io.Writer, java.lang.String) throws java.io.IOException,public void store(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.nio.charset.Charset) throws java.io.IOException,public Set<java.lang.String> stringPropertyNames() ,public synchronized java.lang.String toString() ,public Collection<java.lang.Object> values() <variables>private static final jdk.internal.misc.Unsafe UNSAFE,protected volatile java.util.Properties defaults,private volatile transient ConcurrentHashMap<java.lang.Object,java.lang.Object> map,private static final long serialVersionUID |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/StatementBuilder.java | StatementBuilder | appendOnlyFirst | 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 StatementBuilder appendOnlyFirst(String s) {<FILL_FUNCTION_BODY>}
/**
* Append a text, except when this method is called the first time.
*
* @param s the text to append
*/
public StatementBuilder appendExceptFirst(String s) {
if (index++ > 0) {
builder.append(s);
}
return this;
}
@Override
public String toString() {
return builder.toString();
}
/**
* Get the length.
*
* @return the length
*/
public int length() {
return builder.length();
}
} |
if (index == 0) {
builder.append(s);
}
return this;
| 556 | 28 | 584 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/Task.java | Task | getException | class Task implements Runnable {
/**
* A flag indicating the get() method has been called.
*/
protected volatile boolean stop;
/**
* The result, if any.
*/
protected Object result;
private Thread thread;
private 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;
}
}
/**
* Start the thread.
*
* @return this
*/
public Task execute() {
return execute(getClass().getName());
}
/**
* 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;
}
/**
* Get the exception that was thrown in the call (if any).
*
* @return the exception or null
*/
public Exception getException() {<FILL_FUNCTION_BODY>}
} |
stop = true;
if (thread == null) {
throw new IllegalStateException("Thread not started");
}
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
if (ex != null) {
return ex;
}
return null;
| 444 | 84 | 528 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/common/util/TempFileDeleter.java | TempFileDeleter | deleteUnused | class TempFileDeleter {
private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
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<Object>(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() {<FILL_FUNCTION_BODY>}
/**
* 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();
}
} |
while (queue != null) {
Reference<? extends Object> ref = queue.poll();
if (ref == null) {
break;
}
deleteFile(ref, null);
}
| 839 | 56 | 895 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/LocalDataHandler.java | LocalDataHandler | getLobStorage | class LocalDataHandler implements DataHandler {
private final String cipher;
private final byte[] fileEncryptionKey;
private LobReader lobReader;
private LobStorage lobStorage;
public LocalDataHandler() {
this(null);
}
public LocalDataHandler(String cipher) {
this.cipher = cipher;
fileEncryptionKey = cipher == null ? null : MathUtils.secureRandomBytes(32);
}
public void setLobReader(LobReader lobReader) {
this.lobReader = lobReader;
}
@Override
public String getDatabasePath() {
return "";
}
@Override
public FileStorage openFile(String name, String mode, boolean mustExist) {
if (mustExist && !FileUtils.exists(name)) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name);
}
FileStorage fileStorage = FileStorage.open(this, name, mode, cipher, fileEncryptionKey);
fileStorage.setCheckedWriting(false);
return fileStorage;
}
@Override
public TempFileDeleter getTempFileDeleter() {
return TempFileDeleter.getInstance();
}
@Override
public void checkPowerOff() {
// ok
}
@Override
public void checkWritingAllowed() {
// ok
}
@Override
public int getMaxLengthInplaceLob() {
return SysProperties.LOB_CLIENT_MAX_SIZE_MEMORY;
}
@Override
public String getLobCompressionAlgorithm(int type) {
return null;
}
@Override
public LobStorage getLobStorage() {<FILL_FUNCTION_BODY>}
} |
if (lobStorage == null) {
lobStorage = new LobLocalStorage(this, lobReader);
}
return lobStorage;
| 461 | 39 | 500 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/MemoryManager.java | MemoryManager | getFullGcThreshold | class MemoryManager {
private static final MemoryManager globalMemoryManager = new MemoryManager(getGlobalMaxMemory());
private static final long fullGcThreshold = getFullGcThreshold();
public static boolean needFullGc() {
return globalMemoryManager.getUsedMemory() > fullGcThreshold;
}
private static long getFullGcThreshold() {<FILL_FUNCTION_BODY>}
private static long getGlobalMaxMemory() {
MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
return mu.getMax();
}
public static MemoryManager getGlobalMemoryManager() {
return globalMemoryManager;
}
public static interface MemoryListener {
void wakeUp();
}
private static MemoryListener globalMemoryListener;
public static void setGlobalMemoryListener(MemoryListener globalMemoryListener) {
MemoryManager.globalMemoryListener = globalMemoryListener;
}
public static void wakeUpGlobalMemoryListener() {
if (globalMemoryListener != null)
globalMemoryListener.wakeUp();
}
private final AtomicLong usedMemory = new AtomicLong(0);
private long gcThreshold;
private boolean forceGc;
public MemoryManager(long maxMemory) {
setMaxMemory(maxMemory);
}
public void setMaxMemory(long maxMemory) {
if (maxMemory <= 0)
maxMemory = getGlobalMaxMemory();
gcThreshold = maxMemory / 2; // 占用内存超过一半时就可以触发GC
}
public long getMaxMemory() {
return gcThreshold * 2;
}
public long getUsedMemory() {
return usedMemory.get();
}
public void addUsedMemory(long delta) { // 正负都有可能
usedMemory.addAndGet(delta);
}
public boolean needGc() {
if (forceGc)
return true;
if (usedMemory.get() > gcThreshold)
return true;
// 看看全部使用的内存是否超过阈值
if (this != globalMemoryManager && globalMemoryManager.needGc())
return true;
return false;
}
public void forceGc(boolean b) {
forceGc = b;
}
} |
long max = getGlobalMaxMemory();
long gcThreshold = max / 10 * 6;
// 小于512M时把阈值调低一些
if (max < 512 * 1024 * 1024)
gcThreshold = max / 10 * 3;
return SystemPropertyUtils.getLong("lealone.memory.fullGcThreshold", gcThreshold);
| 588 | 112 | 700 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/PluginBase.java | PluginBase | init | class PluginBase implements Plugin {
protected String name;
protected Map<String, String> config;
protected State state = State.NONE;
public PluginBase() {
}
public PluginBase(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Map<String, String> getConfig() {
return config;
}
@Override
public boolean isInited() {
return state != State.NONE;
}
@Override
public boolean isStarted() {
return state == State.STARTED;
}
@Override
public boolean isStopped() {
return state == State.STOPPED;
}
@Override
public synchronized void init(Map<String, String> config) {<FILL_FUNCTION_BODY>}
@Override
public synchronized void close() {
Class<Plugin> pluginClass = getPluginClass0();
Plugin p = PluginManager.getPlugin(pluginClass, getName());
if (p != null)
PluginManager.deregister(pluginClass, p);
state = State.NONE;
}
@Override
public void start() {
state = State.STARTED;
}
@Override
public void stop() {
state = State.STOPPED;
}
@Override
public State getState() {
return state;
}
@SuppressWarnings("unchecked")
private Class<Plugin> getPluginClass0() {
return (Class<Plugin>) getPluginClass();
}
public Class<? extends Plugin> getPluginClass() {
return Plugin.class;
}
} |
if (!isInited()) {
this.config = config;
String pluginName = MapUtils.getString(config, "plugin_name", null);
if (pluginName != null)
setName(pluginName); // 使用create plugin创建插件对象时用命令指定的名称覆盖默认值
Class<Plugin> pluginClass = getPluginClass0();
PluginManager.register(pluginClass, this);
state = State.INITED;
}
| 485 | 120 | 605 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/PluginManager.java | PluginManager | getPlugin | class PluginManager<T extends Plugin> {
private static final Logger logger = LoggerFactory.getLogger(PluginManager.class);
private final Class<T> pluginClass;
private final Map<String, T> plugins = new ConcurrentHashMap<>();
private volatile boolean loaded = false;
protected PluginManager(Class<T> pluginClass) {
this.pluginClass = pluginClass;
}
public T getPlugin(String name) {<FILL_FUNCTION_BODY>}
public Collection<T> getPlugins() {
return plugins.values();
}
public void registerPlugin(T plugin, String... alias) {
plugins.put(plugin.getName().toUpperCase(), plugin);
// plugins.put(plugin.getClass().getName().toUpperCase(), plugin);
if (alias != null && alias.length > 0) {
for (String a : alias)
plugins.put(a.toUpperCase(), plugin);
}
}
public void deregisterPlugin(T plugin, String... alias) {
plugins.remove(plugin.getName().toUpperCase());
// plugins.remove(plugin.getClass().getName().toUpperCase());
if (alias != null && alias.length > 0) {
for (String a : alias)
plugins.remove(a.toUpperCase());
}
if (plugins.isEmpty())
loaded = false; // 可以重新加载
}
private synchronized void loadPlugins() {
if (loaded)
return;
Iterator<T> iterator = ServiceLoader.load(pluginClass).iterator();
while (iterator.hasNext()) {
try {
// 执行next时ServiceLoader内部会自动为每一个实现Plugin接口的类生成一个新实例
// 所以Plugin接口的实现类必需有一个public的无参数构造函数
T p = iterator.next();
registerPlugin(p);
} catch (Throwable t) {
// 只是发出警告
logger.warn("Failed to load plugin: " + pluginClass.getName(), t);
}
}
// 注意在load完之后再设为true,否则其他线程可能会因为不用等待load完成从而得到一个NPE
loaded = true;
}
private static final Map<Class<?>, PluginManager<?>> instances = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
private static <P extends Plugin> PluginManager<P> getInstance(P plugin) {
return (PluginManager<P>) getInstance(plugin.getClass());
}
@SuppressWarnings("unchecked")
private static <P extends Plugin> PluginManager<P> getInstance(Class<P> pluginClass) {
PluginManager<?> instance = instances.get(pluginClass);
if (instance == null) {
instance = new PluginManager<>(pluginClass);
PluginManager<?> old = instances.putIfAbsent(pluginClass, instance);
if (old != null) {
instance = old;
}
}
return (PluginManager<P>) instance;
}
public static <P extends Plugin> P getPlugin(Class<P> pluginClass, String name) {
return getInstance(pluginClass).getPlugin(name);
}
public static <P extends Plugin> Collection<P> getPlugins(Class<P> pluginClass) {
return getInstance(pluginClass).getPlugins();
}
public static <P extends Plugin> void register(P plugin, String... alias) {
getInstance(plugin).registerPlugin(plugin, alias);
}
public static <P extends Plugin> void register(Class<P> pluginClass, P plugin, String... alias) {
getInstance(pluginClass).registerPlugin(plugin, alias);
}
public static <P extends Plugin> void deregister(P plugin, String... alias) {
getInstance(plugin).deregisterPlugin(plugin, alias);
}
public static <P extends Plugin> void deregister(Class<P> pluginClass, P plugin, String... alias) {
getInstance(pluginClass).deregisterPlugin(plugin, alias);
}
} |
if (name == null)
throw new NullPointerException("name is null");
if (!loaded)
loadPlugins();
return plugins.get(name.toUpperCase());
| 1,060 | 50 | 1,110 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/async/AsyncCallback.java | AsyncCallback | handleTimeout | class AsyncCallback<T> implements Future<T> {
public AsyncCallback() {
}
public void setDbException(DbException e, boolean cancel) {
}
public void run(NetInputStream in) {
}
protected void runInternal(NetInputStream in) throws Exception {
}
protected abstract T await(long timeoutMillis);
@Override
public T get() {
long timeoutMillis = networkTimeout > 0 ? networkTimeout : -1;
return await(timeoutMillis);
}
@Override
public T get(long timeoutMillis) {
return await(timeoutMillis);
}
@Override
public Future<T> onSuccess(AsyncHandler<T> handler) {
return this;
}
@Override
public Future<T> onFailure(AsyncHandler<Throwable> handler) {
return this;
}
@Override
public Future<T> onComplete(AsyncHandler<AsyncResult<T>> handler) {
return this;
}
public void setAsyncResult(Throwable cause) {
setAsyncResult(new AsyncResult<>(cause));
}
public void setAsyncResult(T result) {
setAsyncResult(new AsyncResult<>(result));
}
public void setAsyncResult(AsyncResult<T> asyncResult) {
}
private Packet packet;
private long startTime;
private int networkTimeout;
public void setPacket(Packet packet) {
this.packet = packet;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public int getNetworkTimeout() {
return networkTimeout;
}
public void setNetworkTimeout(int networkTimeout) {
this.networkTimeout = networkTimeout;
}
public void checkTimeout(long currentTime) {
if (networkTimeout <= 0 || startTime <= 0 || startTime + networkTimeout > currentTime)
return;
handleTimeout();
}
protected void handleTimeout() {<FILL_FUNCTION_BODY>}
public static <T> AsyncCallback<T> createSingleThreadCallback() {
return new SingleThreadAsyncCallback<>();
}
public static <T> AsyncCallback<T> createConcurrentCallback() {
return new ConcurrentAsyncCallback<>();
}
public static <T> AsyncCallback<T> create(boolean isSingleThread) {
return isSingleThread ? createSingleThreadCallback() : createConcurrentCallback();
}
} |
String msg = "ack timeout, request start time: " + new java.sql.Timestamp(startTime) //
+ ", network timeout: " + networkTimeout + "ms" //
+ ", request packet: " + packet;
DbException e = DbException.get(ErrorCode.NETWORK_TIMEOUT_1, msg);
setAsyncResult(e);
networkTimeout = 0;
| 662 | 98 | 760 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/async/AsyncPeriodicTask.java | AsyncPeriodicTask | run | class AsyncPeriodicTask extends LinkableBase<AsyncPeriodicTask> implements AsyncTask {
private final long delay;
private Runnable runnable;
private long last;
private boolean canceled;
public AsyncPeriodicTask(long delay, Runnable runnable) {
this(delay, delay, runnable);
}
public AsyncPeriodicTask(long initialDelay, long delay, Runnable runnable) {
this.delay = delay;
this.runnable = runnable;
if (initialDelay > 0) {
last = System.currentTimeMillis() + initialDelay;
} else {
last = System.currentTimeMillis() + delay;
}
}
@Override
public boolean isPeriodic() {
return true;
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
public void cancel() {
canceled = true;
}
public boolean isCancelled() {
return canceled;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
public long getDelay() {
return delay;
}
public void setRunnable(Runnable runnable) {
this.runnable = runnable;
}
public void resetLast() {
last = 0;
}
} |
if (canceled)
return;
long now = System.currentTimeMillis();
if (now > last) {
last = now + delay;
runnable.run();
}
| 365 | 54 | 419 | <methods>public non-sealed void <init>() ,public com.lealone.db.async.AsyncPeriodicTask getNext() ,public void setNext(com.lealone.db.async.AsyncPeriodicTask) <variables>public com.lealone.db.async.AsyncPeriodicTask next |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/async/AsyncResult.java | AsyncResult | setResult | class AsyncResult<T> {
protected T result;
protected Throwable cause;
protected boolean succeeded;
protected boolean failed;
public AsyncResult() {
}
public AsyncResult(T result) {
setResult(result);
}
public AsyncResult(Throwable cause) {
setCause(cause);
}
public T getResult() {
return result;
}
public void setResult(T result) {<FILL_FUNCTION_BODY>}
public Throwable getCause() {
return cause;
}
public void setCause(Throwable cause) {
this.cause = cause;
failed = true;
succeeded = false;
}
public boolean isSucceeded() {
return succeeded;
}
public void setSucceeded(boolean succeeded) {
this.succeeded = succeeded;
}
public boolean isFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
} |
this.result = result;
failed = false;
succeeded = true;
| 283 | 23 | 306 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/async/ConcurrentAsyncCallback.java | LatchObject | await | class LatchObject {
final CountDownLatch latch;
public LatchObject(CountDownLatch latch) {
this.latch = latch;
}
}
public ConcurrentAsyncCallback() {
}
@Override
public void setDbException(DbException e, boolean cancel) {
setAsyncResult(e);
if (cancel)
countDown();
}
@Override
public final void run(NetInputStream in) {
// 放在最前面,不能放在最后面,
// 否则调用了countDown,但是在设置runEnd为true前,调用await的线程读到的是false就会抛异常
runEnd = true;
// if (asyncResult == null) {
try {
runInternal(in);
} catch (Throwable t) {
setAsyncResult(t);
}
// }
}
@Override
protected T await(long timeoutMillis) {<FILL_FUNCTION_BODY> |
Scheduler scheduler = SchedulerThread.currentScheduler();
if (scheduler != null)
scheduler.executeNextStatement();
if (latchObjectRef.compareAndSet(null, new LatchObject(new CountDownLatch(1)))) {
CountDownLatch latch = latchObjectRef.get().latch;
try {
if (timeoutMillis > 0)
latch.await(timeoutMillis, TimeUnit.MILLISECONDS);
else
latch.await();
if (asyncResult != null && asyncResult.isFailed())
throw DbException.convert(asyncResult.getCause());
// 如果没有执行过run,抛出合适的异常
if (!runEnd) {
handleTimeout();
}
} catch (InterruptedException e) {
throw DbException.convert(e);
}
if (asyncResult != null)
return asyncResult.getResult();
else
return null;
} else {
if (asyncResult.isFailed())
throw DbException.convert(asyncResult.getCause());
else
return asyncResult.getResult();
}
| 252 | 296 | 548 | <methods>public void <init>() ,public void checkTimeout(long) ,public static AsyncCallback<T> create(boolean) ,public static AsyncCallback<T> createConcurrentCallback() ,public static AsyncCallback<T> createSingleThreadCallback() ,public T get() ,public T get(long) ,public int getNetworkTimeout() ,public long getStartTime() ,public Future<T> onComplete(AsyncHandler<AsyncResult<T>>) ,public Future<T> onFailure(AsyncHandler<java.lang.Throwable>) ,public Future<T> onSuccess(AsyncHandler<T>) ,public void run(com.lealone.net.NetInputStream) ,public void setAsyncResult(java.lang.Throwable) ,public void setAsyncResult(T) ,public void setAsyncResult(AsyncResult<T>) ,public void setDbException(com.lealone.common.exceptions.DbException, boolean) ,public void setNetworkTimeout(int) ,public void setPacket(com.lealone.server.protocol.Packet) ,public void setStartTime(long) <variables>private int networkTimeout,private com.lealone.server.protocol.Packet packet,private long startTime |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/async/SingleThreadAsyncCallback.java | SingleThreadAsyncCallback | await | class SingleThreadAsyncCallback<T> extends AsyncCallback<T> {
private AsyncHandler<AsyncResult<T>> completeHandler;
private AsyncHandler<T> successHandler;
private AsyncHandler<Throwable> failureHandler;
private AsyncResult<T> asyncResult;
public SingleThreadAsyncCallback() {
}
@Override
public void setDbException(DbException e, boolean cancel) {
setAsyncResult(e);
}
@Override
public void run(NetInputStream in) {
try {
runInternal(in);
} catch (Throwable t) {
setAsyncResult(t);
}
}
@Override
protected T await(long timeoutMillis) {<FILL_FUNCTION_BODY>}
@Override
public Future<T> onSuccess(AsyncHandler<T> handler) {
successHandler = handler;
if (asyncResult != null && asyncResult.isSucceeded()) {
handler.handle(asyncResult.getResult());
}
return this;
}
@Override
public Future<T> onFailure(AsyncHandler<Throwable> handler) {
failureHandler = handler;
if (asyncResult != null && asyncResult.isFailed()) {
handler.handle(asyncResult.getCause());
}
return this;
}
@Override
public Future<T> onComplete(AsyncHandler<AsyncResult<T>> handler) {
completeHandler = handler;
if (asyncResult != null) {
handler.handle(asyncResult);
}
return this;
}
@Override
public void setAsyncResult(AsyncResult<T> asyncResult) {
this.asyncResult = asyncResult;
if (completeHandler != null)
completeHandler.handle(asyncResult);
if (successHandler != null && asyncResult != null && asyncResult.isSucceeded())
successHandler.handle(asyncResult.getResult());
if (failureHandler != null && asyncResult != null && asyncResult.isFailed())
failureHandler.handle(asyncResult.getCause());
}
} |
Scheduler scheduler = SchedulerThread.currentScheduler();
if (scheduler != null) {
scheduler.executeNextStatement();
// 如果被锁住了,需要重试
if (asyncResult == null) {
while (asyncResult == null) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
scheduler.executeNextStatement();
}
}
if (asyncResult.isSucceeded())
return asyncResult.getResult();
else
throw DbException.convert(asyncResult.getCause());
} else {
throw DbException.getInternalError();
}
| 538 | 176 | 714 | <methods>public void <init>() ,public void checkTimeout(long) ,public static AsyncCallback<T> create(boolean) ,public static AsyncCallback<T> createConcurrentCallback() ,public static AsyncCallback<T> createSingleThreadCallback() ,public T get() ,public T get(long) ,public int getNetworkTimeout() ,public long getStartTime() ,public Future<T> onComplete(AsyncHandler<AsyncResult<T>>) ,public Future<T> onFailure(AsyncHandler<java.lang.Throwable>) ,public Future<T> onSuccess(AsyncHandler<T>) ,public void run(com.lealone.net.NetInputStream) ,public void setAsyncResult(java.lang.Throwable) ,public void setAsyncResult(T) ,public void setAsyncResult(AsyncResult<T>) ,public void setDbException(com.lealone.common.exceptions.DbException, boolean) ,public void setNetworkTimeout(int) ,public void setPacket(com.lealone.server.protocol.Packet) ,public void setStartTime(long) <variables>private int networkTimeout,private com.lealone.server.protocol.Packet packet,private long startTime |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/link/LinkableList.java | LinkableList | remove | class LinkableList<E extends Linkable<E>> {
private E head;
private E tail;
private int size;
public E getHead() {
return head;
}
public void setHead(E head) {
this.head = head;
}
public E getTail() {
return tail;
}
public void setTail(E tail) {
this.tail = tail;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return size;
}
public void decrementSize() {
size--;
}
public void add(E e) {
size++;
if (head == null) {
head = tail = e;
} else {
tail.setNext(e);
tail = e;
}
}
public void remove(E e) {<FILL_FUNCTION_BODY>}
} |
boolean found = false;
if (head == e) { // 删除头
found = true;
head = e.getNext();
if (head == null)
tail = null;
} else {
E n = head;
E last = n;
while (n != null) {
if (e == n) {
found = true;
last.setNext(n.getNext());
break;
}
last = n;
n = n.getNext();
}
// 删除尾
if (tail == e) {
found = true;
tail = last;
}
}
if (found)
size--;
| 252 | 179 | 431 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/lock/Lock.java | Lock | tryLock | class Lock {
static final NullLockOwner NULL = new NullLockOwner();
private final AtomicReference<LockOwner> ref = new AtomicReference<>(NULL);
public abstract String getLockType();
public Transaction getTransaction() {
return ref.get().getTransaction();
}
public Object getOldValue() {
return ref.get().getOldValue();
}
public boolean isLockedExclusivelyBy(Session session) {
return ref.get().getTransaction() == session.getTransaction();
}
protected LockOwner createLockOwner(Transaction transaction, Object oldValue) {
return new SimpleLockOwner(transaction);
}
// 子类可以用自己的方式增加锁
protected void addLock(Session session, Transaction t) {
session.addLock(this);
}
public boolean tryLock(Transaction t, Object key, Object oldValue) {<FILL_FUNCTION_BODY>}
public int addWaitingTransaction(Object key, Transaction lockedByTransaction, Session session) {
if (lockedByTransaction == null)
return Transaction.OPERATION_NEED_RETRY;
return lockedByTransaction.addWaitingTransaction(key, session, null);
}
// 允许子类可以覆盖此方法
public void unlock(Session oldSession, boolean succeeded, Session newSession) {
unlock(oldSession, newSession);
}
public void unlock(Session oldSession, Session newSession) {
ref.set(NULL);
}
public LockOwner getLockOwner() {
return ref.get();
}
} |
Session session = t.getSession();
while (true) {
// 首次调用tryLock时为null
if (ref.get() == NULL) {
LockOwner owner = createLockOwner(t, oldValue);
if (ref.compareAndSet(NULL, owner)) {
addLock(session, t);
return true;
}
}
// 避免重复加锁
Transaction old = ref.get().getTransaction();
if (old == t || old == t.getParentTransaction())
return true;
// 被其他事务占用时需要等待
if (ref.get().getTransaction() != null) {
if (addWaitingTransaction(key, ref.get().getTransaction(),
session) == Transaction.OPERATION_NEED_WAIT) {
return false;
}
}
}
| 402 | 219 | 621 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/EmbeddedScheduler.java | SessionInfo | executeNextStatement | class SessionInfo extends LinkableBase<SessionInfo> {
final Session session;
public SessionInfo(Session session) {
this.session = session;
}
}
@Override
public void addSession(Session session) {
sessions.add(new SessionInfo(session));
session.init();
}
@Override
public void removeSession(Session session) {
if (sessions.isEmpty())
return;
SessionInfo si = sessions.getHead();
while (si != null) {
if (si.session == session) {
sessions.remove(si);
break;
}
si = si.next;
}
}
// --------------------- 实现 SQLStatement 相关的代码 ---------------------
@Override
public void executeNextStatement() {<FILL_FUNCTION_BODY> |
int priority = PreparedSQLStatement.MIN_PRIORITY - 1; // 最小优先级减一,保证能取到最小的
YieldableCommand last = null;
while (true) {
YieldableCommand c;
if (nextBestCommand != null) {
c = nextBestCommand;
nextBestCommand = null;
} else {
c = getNextBestCommand(null, priority, true);
}
if (c == null) {
runMiscTasks();
c = getNextBestCommand(null, priority, true);
}
if (c == null) {
runPageOperationTasks();
runPendingTransactions();
runMiscTasks();
c = getNextBestCommand(null, priority, true);
if (c == null) {
break;
}
}
try {
currentSession = c.getSession();
c.run();
// 说明没有新的命令了,一直在轮循
if (last == c) {
runPageOperationTasks();
runPendingTransactions();
runMiscTasks();
}
last = c;
} catch (Throwable e) {
logger.warn("Failed to statement: " + c, e);
}
}
| 215 | 319 | 534 | <methods>public void <init>(int, java.lang.String, int, Map<java.lang.String,java.lang.String>) ,public void accept(java.nio.channels.SelectionKey) ,public void addPendingTransaction(com.lealone.transaction.PendingTransaction) ,public void addPeriodicTask(com.lealone.db.async.AsyncPeriodicTask) ,public void addSession(com.lealone.db.session.Session) ,public void addSessionInfo(java.lang.Object) ,public void addSessionInitTask(java.lang.Object) ,public void addWaitingScheduler(com.lealone.db.scheduler.Scheduler) ,public SchedulerListener<R> createSchedulerListener() ,public void executeNextStatement() ,public com.lealone.db.session.Session getCurrentSession() ,public com.lealone.db.DataBufferFactory getDataBufferFactory() ,public com.lealone.storage.fs.FileStorage getFsyncingFileStorage() ,public int getId() ,public long getLoad() ,public java.lang.String getName() ,public java.lang.Object getNetEventLoop() ,public com.lealone.transaction.PendingTransaction getPendingTransaction() ,public com.lealone.db.scheduler.SchedulerFactory getSchedulerFactory() ,public java.nio.channels.Selector getSelector() ,public com.lealone.db.scheduler.SchedulerThread getThread() ,public void handlePageOperation(com.lealone.storage.page.PageOperation) ,public boolean isFsyncDisabled() ,public boolean isStarted() ,public boolean isStopped() ,public void registerAccepter(com.lealone.server.ProtocolServer, java.nio.channels.ServerSocketChannel) ,public void removePeriodicTask(com.lealone.db.async.AsyncPeriodicTask) ,public void removeSession(com.lealone.db.session.Session) ,public void removeSessionInfo(java.lang.Object) ,public void setCurrentSession(com.lealone.db.session.Session) ,public void setFsyncDisabled(boolean) ,public void setFsyncingFileStorage(com.lealone.storage.fs.FileStorage) ,public void setSchedulerFactory(com.lealone.db.scheduler.SchedulerFactory) ,public synchronized void start() ,public synchronized void stop() ,public java.lang.String toString() ,public void validateSession(boolean) ,public void wakeUpWaitingSchedulers() ,public void wakeUpWaitingSchedulers(boolean) ,public boolean yieldIfNeeded(com.lealone.sql.PreparedSQLStatement) <variables>protected com.lealone.db.session.Session currentSession,protected boolean fsyncDisabled,protected com.lealone.storage.fs.FileStorage fsyncingFileStorage,protected final java.util.concurrent.atomic.AtomicBoolean hasWaitingSchedulers,protected final non-sealed int id,protected final non-sealed long loopInterval,protected final non-sealed java.lang.String name,protected final LinkableList<com.lealone.transaction.PendingTransaction> pendingTransactions,protected final LinkableList<com.lealone.db.async.AsyncPeriodicTask> periodicTasks,protected com.lealone.db.scheduler.SchedulerFactory schedulerFactory,protected boolean started,protected boolean stopped,protected com.lealone.db.scheduler.SchedulerThread thread,protected final non-sealed AtomicReferenceArray<com.lealone.db.scheduler.Scheduler> waitingSchedulers |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerFactoryBase.java | LoadBalanceFactory | createSchedulerFactory | class LoadBalanceFactory extends SchedulerFactoryBase {
protected LoadBalanceFactory(Map<String, String> config, Scheduler[] schedulers) {
super(config, schedulers);
}
@Override
public Scheduler getScheduler() {
long minLoad = Long.MAX_VALUE;
int index = 0;
for (int i = 0, size = schedulers.length; i < size; i++) {
long load = schedulers[i].getLoad();
if (load < minLoad) {
index = i;
minLoad = load;
}
}
return schedulers[index];
}
}
// 变成负数时从0开始
public static int getAndIncrementIndex(AtomicInteger index) {
int i = index.getAndIncrement();
if (i < 0) {
if (index.compareAndSet(i, 1)) {
i = 0;
} else {
i = index.getAndIncrement();
}
}
return i;
}
private static SchedulerFactory defaultSchedulerFactory;
public static void setDefaultSchedulerFactory(SchedulerFactory defaultSchedulerFactory) {
SchedulerFactoryBase.defaultSchedulerFactory = defaultSchedulerFactory;
}
public static SchedulerFactory getDefaultSchedulerFactory() {
return defaultSchedulerFactory;
}
public static SchedulerFactory getDefaultSchedulerFactory(String schedulerClassName,
Map<String, String> config) {
if (SchedulerFactoryBase.getDefaultSchedulerFactory() == null)
initDefaultSchedulerFactory(schedulerClassName, config);
return SchedulerFactoryBase.getDefaultSchedulerFactory();
}
public static synchronized SchedulerFactory initDefaultSchedulerFactory(String schedulerClassName,
Map<String, String> config) {
SchedulerFactory schedulerFactory = SchedulerFactoryBase.getDefaultSchedulerFactory();
if (schedulerFactory == null) {
schedulerFactory = createSchedulerFactory(schedulerClassName, config);
SchedulerFactoryBase.setDefaultSchedulerFactory(schedulerFactory);
}
return schedulerFactory;
}
public static SchedulerFactory createSchedulerFactory(String schedulerClassName,
Map<String, String> config) {<FILL_FUNCTION_BODY> |
SchedulerFactory schedulerFactory;
String sf = MapUtils.getString(config, "scheduler_factory", null);
if (sf != null) {
schedulerFactory = PluginManager.getPlugin(SchedulerFactory.class, sf);
} else {
Scheduler[] schedulers = createSchedulers(schedulerClassName, config);
schedulerFactory = SchedulerFactory.create(config, schedulers);
}
if (!schedulerFactory.isInited())
schedulerFactory.init(config);
return schedulerFactory;
| 599 | 144 | 743 | <methods>public void <init>() ,public void <init>(java.lang.String) ,public synchronized void close() ,public Map<java.lang.String,java.lang.String> getConfig() ,public java.lang.String getName() ,public Class<? extends com.lealone.db.Plugin> getPluginClass() ,public com.lealone.db.Plugin.State getState() ,public synchronized void init(Map<java.lang.String,java.lang.String>) ,public boolean isInited() ,public boolean isStarted() ,public boolean isStopped() ,public void setName(java.lang.String) ,public void start() ,public void stop() <variables>protected Map<java.lang.String,java.lang.String> config,protected java.lang.String name,protected com.lealone.db.Plugin.State state |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerListener.java | SchedulerListener | createSchedulerListener | class SchedulerListener<R> implements AsyncHandler<AsyncResult<R>> {
protected volatile R result;
protected volatile DbException exception;
protected boolean needWakeUp = true;
public void setNeedWakeUp(boolean needWakeUp) {
this.needWakeUp = needWakeUp;
}
public void setResult(R r) {
handle(new AsyncResult<>(r));
}
public void setException(Throwable t) {
handle(new AsyncResult<>(t));
}
@Override
public void handle(AsyncResult<R> ar) {
if (ar.isSucceeded()) {
result = ar.getResult();
} else {
exception = DbException.convert(ar.getCause());
}
if (needWakeUp)
wakeUp();
}
public abstract R await();
public abstract void wakeUp();
public static interface Factory {
<R> SchedulerListener<R> createSchedulerListener();
}
public static <R> SchedulerListener<R> createSchedulerListener() {<FILL_FUNCTION_BODY>}
} |
Object object = SchedulerThread.currentObject();
if (object instanceof SchedulerListener.Factory) {
return ((SchedulerListener.Factory) object).createSchedulerListener();
} else {
// 创建一个同步阻塞监听器
return new SchedulerListener<R>() {
private final CountDownLatch latch = new CountDownLatch(1);
@Override
public R await() {
try {
latch.await();
} catch (InterruptedException e) {
exception = DbException.convert(e);
}
if (exception != null)
throw exception;
return result;
}
@Override
public void wakeUp() {
latch.countDown();
}
};
}
| 299 | 200 | 499 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerLock.java | SchedulerLock | unlock | class SchedulerLock {
private static final AtomicReferenceFieldUpdater<SchedulerLock, Scheduler> //
lockUpdater = AtomicReferenceFieldUpdater.newUpdater(SchedulerLock.class, //
Scheduler.class, "lockOwner");
private volatile Scheduler lockOwner;
public boolean tryLock(Scheduler newLockOwner) {
return tryLock(newLockOwner, true);
}
public boolean tryLock(Scheduler newLockOwner, boolean waitingIfLocked) {
// 前面的操作被锁住了就算lockOwner相同后续的也不能再继续
if (newLockOwner == lockOwner)
return false;
while (true) {
if (lockUpdater.compareAndSet(this, null, newLockOwner))
return true;
Scheduler owner = lockOwner;
if (waitingIfLocked && owner != null) {
owner.addWaitingScheduler(newLockOwner);
}
// 解锁了,或者又被其他线程锁住了
if (lockOwner == null || (waitingIfLocked && lockOwner != owner))
continue;
else
return false;
}
}
public void unlock() {<FILL_FUNCTION_BODY>}
public boolean isLocked() {
return lockOwner != null;
}
public Scheduler getLockOwner() {
return lockOwner;
}
} |
if (lockOwner != null) {
Scheduler owner = lockOwner;
lockOwner = null;
owner.wakeUpWaitingSchedulers();
}
| 366 | 47 | 413 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/scheduler/SchedulerThread.java | SchedulerThread | currentScheduler | class SchedulerThread extends Thread {
private final static ThreadLocal<Scheduler> threadLocal = new ThreadLocal<>();
private final Scheduler scheduler;
public SchedulerThread(Scheduler scheduler) {
super(scheduler);
this.scheduler = scheduler;
}
public Scheduler getScheduler() {
return scheduler;
}
public static Session currentSession() {
Object t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler().getCurrentSession();
} else {
return null;
}
}
public static Object currentObject() {
Object t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler();
} else {
return t;
}
}
public static Scheduler currentScheduler() {<FILL_FUNCTION_BODY>}
public static Scheduler currentScheduler(SchedulerFactory sf) {
Thread t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler();
} else {
Scheduler scheduler = threadLocal.get();
if (scheduler == null) {
scheduler = sf.bindScheduler(t);
if (scheduler == null) {
return null;
}
threadLocal.set(scheduler);
}
return scheduler;
}
}
public static void bindScheduler(Scheduler scheduler) {
if (isScheduler())
return;
if (threadLocal.get() != scheduler)
threadLocal.set(scheduler);
}
public static boolean isScheduler() {
return Thread.currentThread() instanceof SchedulerThread;
}
} |
Thread t = Thread.currentThread();
if (t instanceof SchedulerThread) {
return ((SchedulerThread) t).getScheduler();
} else {
return null;
}
| 474 | 52 | 526 | <methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/session/SessionBase.java | SessionBase | closeTraceSystem | class SessionBase implements Session {
protected boolean autoCommit = true;
protected boolean closed;
protected boolean invalid;
protected String targetNodes;
protected RunMode runMode;
protected String newTargetNodes;
protected int consistencyLevel;
protected TraceSystem traceSystem;
@Override
public boolean isAutoCommit() {
return autoCommit;
}
@Override
public void setAutoCommit(boolean autoCommit) {
this.autoCommit = autoCommit;
}
@Override
public void close() {
closed = true;
}
@Override
public boolean isClosed() {
return closed;
}
/**
* Check if this session is closed and throws an exception if so.
*
* @throws DbException if the session is closed
*/
@Override
public void checkClosed() {
if (isClosed()) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "session closed");
}
}
@Override
public void setInvalid(boolean v) {
invalid = v;
}
@Override
public boolean isInvalid() {
return invalid;
}
@Override
public boolean isValid() {
return !invalid;
}
@Override
public void setTargetNodes(String targetNodes) {
this.targetNodes = targetNodes;
}
@Override
public String getTargetNodes() {
return targetNodes;
}
public void setConsistencyLevel(int consistencyLevel) {
this.consistencyLevel = consistencyLevel;
}
public int getConsistencyLevel() {
return consistencyLevel;
}
@Override
public void setRunMode(RunMode runMode) {
this.runMode = runMode;
}
@Override
public RunMode getRunMode() {
return runMode;
}
@Override
public boolean isRunModeChanged() {
return newTargetNodes != null;
}
@Override
public void runModeChanged(String newTargetNodes) {
this.newTargetNodes = newTargetNodes;
}
public String getNewTargetNodes() {
String nodes = newTargetNodes;
newTargetNodes = null;
return nodes;
}
public Trace getTrace(TraceModuleType traceModuleType) {
if (traceSystem != null)
return traceSystem.getTrace(traceModuleType);
else
return Trace.NO_TRACE;
}
@Override
public Trace getTrace(TraceModuleType traceModuleType, TraceObjectType traceObjectType) {
if (traceSystem != null)
return traceSystem.getTrace(traceModuleType, traceObjectType,
TraceObject.getNextTraceId(traceObjectType));
else
return Trace.NO_TRACE;
}
@Override
public Trace getTrace(TraceModuleType traceModuleType, TraceObjectType traceObjectType,
int traceObjectId) {
if (traceSystem != null)
return traceSystem.getTrace(traceModuleType, traceObjectType, traceObjectId);
else
return Trace.NO_TRACE;
}
protected void initTraceSystem(ConnectionInfo ci) {
String filePrefix = getFilePrefix(SysProperties.CLIENT_TRACE_DIRECTORY, ci.getDatabaseName());
initTraceSystem(ci, filePrefix);
}
protected void initTraceSystem(ConnectionInfo ci, String filePrefix) {
if (traceSystem != null || ci.isTraceDisabled())
return;
traceSystem = new TraceSystem();
String traceLevelFile = ci.getProperty(DbSetting.TRACE_LEVEL_FILE.getName(), null);
if (traceLevelFile != null) {
int level = Integer.parseInt(traceLevelFile);
try {
traceSystem.setLevelFile(level);
if (level > 0) {
String file = FileUtils.createTempFile(filePrefix, Constants.SUFFIX_TRACE_FILE,
false, false);
traceSystem.setFileName(file);
}
} catch (IOException e) {
throw DbException.convertIOException(e, filePrefix);
}
}
String traceLevelSystemOut = ci.getProperty(DbSetting.TRACE_LEVEL_SYSTEM_OUT.getName(), null);
if (traceLevelSystemOut != null) {
int level = Integer.parseInt(traceLevelSystemOut);
traceSystem.setLevelSystemOut(level);
}
}
protected void closeTraceSystem() {<FILL_FUNCTION_BODY>}
private static String getFilePrefix(String dir, String dbName) {
StringBuilder buff = new StringBuilder(dir);
if (!(dir.charAt(dir.length() - 1) == File.separatorChar))
buff.append(File.separatorChar);
for (int i = 0, length = dbName.length(); i < length; i++) {
char ch = dbName.charAt(i);
if (Character.isLetterOrDigit(ch)) {
buff.append(ch);
} else {
buff.append('_');
}
}
return buff.toString();
}
protected Scheduler scheduler;
@Override
public Scheduler getScheduler() {
return scheduler;
}
@Override
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
protected YieldableCommand yieldableCommand;
@Override
public void setYieldableCommand(YieldableCommand yieldableCommand) {
this.yieldableCommand = yieldableCommand;
}
@Override
public YieldableCommand getYieldableCommand() {
return yieldableCommand;
}
@Override
public YieldableCommand getYieldableCommand(boolean checkTimeout, TimeoutListener timeoutListener) {
return yieldableCommand;
}
@Override
public void init() {
}
} |
if (traceSystem != null) {
traceSystem.close();
traceSystem = null;
}
| 1,544 | 31 | 1,575 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/BlobBase.java | BlobBase | getBytes | class BlobBase extends TraceObject implements Blob {
protected Value value;
public Value getValue() {
return value;
}
/**
* Returns the length.
*
* @return the length
* @throws SQLException
*/
@Override
public long length() throws SQLException {
try {
debugCodeCall("length");
checkClosed();
if (value.getType() == Value.BLOB) {
long precision = value.getPrecision();
if (precision > 0) {
return precision;
}
}
return IOUtils.copyAndCloseInput(value.getInputStream(), null);
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* [Not supported] Truncates the object.
*
* @param len the new length
* @throws SQLException
*/
@Override
public void truncate(long len) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns some bytes of the object.
*
* @param pos the index, the first byte is at position 1
* @param length the number of bytes
* @return the bytes, at most length bytes
* @throws SQLException
*/
@Override
public byte[] getBytes(long pos, int length) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* Fills the Blob. This is only supported for new, empty Blob objects that
* were created with Connection.createBlob(). The position
* must be 1, meaning the whole Blob data is set.
*
* @param pos where to start writing (the first byte is at position 1)
* @param bytes the bytes to set
* @return the length of the added data
*/
@Override
public abstract int setBytes(long pos, byte[] bytes) throws SQLException;
/**
* [Not supported] Sets some bytes of the object.
*
* @param pos the write position
* @param bytes the bytes to set
* @param offset the bytes offset
* @param len the number of bytes to write
* @return how many bytes have been written
* @throws SQLException
*/
@Override
public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns the input stream.
*
* @return the input stream
* @throws SQLException
*/
@Override
public InputStream getBinaryStream() throws SQLException {
try {
debugCodeCall("getBinaryStream");
checkClosed();
return value.getInputStream();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Get a writer to update the Blob. This is only supported for new, empty
* Blob objects that were created with Connection.createBlob(). The Blob is
* created in a separate thread, and the object is only updated when
* OutputStream.close() is called. The position must be 1, meaning the whole
* Blob data is set.
*
* @param pos where to start writing (the first byte is at position 1)
* @return an output stream
*/
@Override
public abstract OutputStream setBinaryStream(long pos) throws SQLException;
/**
* [Not supported] Searches a pattern and return the position.
*
* @param pattern the pattern to search
* @param start the index, the first byte is at position 1
* @return the position (first byte is at position 1), or -1 for not found
* @throws SQLException
*/
@Override
public long position(byte[] pattern, long start) throws SQLException {
if (isDebugEnabled()) {
debugCode("position(" + quoteBytes(pattern) + ", " + start + ");");
}
if (Constants.BLOB_SEARCH) {
try {
checkClosed();
if (pattern == null) {
return -1;
}
if (pattern.length == 0) {
return 1;
}
// TODO performance: blob pattern search is slow
BufferedInputStream in = new BufferedInputStream(value.getInputStream());
IOUtils.skipFully(in, start - 1);
int pos = 0;
int patternPos = 0;
while (true) {
int x = in.read();
if (x < 0) {
break;
}
if (x == (pattern[patternPos] & 0xff)) {
if (patternPos == 0) {
in.mark(pattern.length);
}
if (patternPos == pattern.length) {
return pos - patternPos;
}
patternPos++;
} else {
if (patternPos > 0) {
in.reset();
pos -= patternPos;
}
}
pos++;
}
return -1;
} catch (Exception e) {
throw logAndConvert(e);
}
}
throw unsupported("LOB search");
}
/**
* [Not supported] Searches a pattern and return the position.
*
* @param blobPattern the pattern to search
* @param start the index, the first byte is at position 1
* @return the position (first byte is at position 1), or -1 for not found
* @throws SQLException
*/
@Override
public long position(Blob blobPattern, long start) throws SQLException {
if (isDebugEnabled()) {
debugCode("position(blobPattern, " + start + ");");
}
if (Constants.BLOB_SEARCH) {
try {
checkClosed();
if (blobPattern == null) {
return -1;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = blobPattern.getBinaryStream();
while (true) {
int x = in.read();
if (x < 0) {
break;
}
out.write(x);
}
return position(out.toByteArray(), start);
} catch (Exception e) {
throw logAndConvert(e);
}
}
throw unsupported("LOB subset");
}
/**
* Release all resources of this object.
*/
@Override
public void free() {
debugCodeCall("free");
value = null;
}
/**
* [Not supported] Returns the input stream, starting from an offset.
*
* @param pos where to start reading
* @param length the number of bytes that will be read
* @return the input stream to read
* @throws SQLException
*/
@Override
public InputStream getBinaryStream(long pos, long length) throws SQLException {
throw unsupported("LOB update");
}
protected void checkClosed() {
if (value == null) {
throw DbException.get(ErrorCode.OBJECT_CLOSED);
}
}
/**
* INTERNAL
*/
@Override
public String toString() {
return getTraceObjectName() + ": " + (value == null ? "null" : value.getTraceSQL());
}
} |
try {
if (isDebugEnabled()) {
debugCode("getBytes(" + pos + ", " + length + ");");
}
checkClosed();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = value.getInputStream();
try {
IOUtils.skipFully(in, pos - 1);
IOUtils.copy(in, out, length);
} finally {
in.close();
}
return out.toByteArray();
} catch (Exception e) {
throw logAndConvert(e);
}
| 1,846 | 143 | 1,989 | <methods>public non-sealed void <init>() ,public static int getNextTraceId(com.lealone.common.trace.TraceObjectType) ,public int getTraceId() ,public java.lang.String getTraceObjectName() <variables>private static final non-sealed java.util.concurrent.atomic.AtomicInteger[] ID,protected com.lealone.common.trace.Trace trace |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ClobBase.java | ClobBase | length | class ClobBase extends TraceObject implements Clob, NClob {
protected Value value;
public Value getValue() {
return value;
}
/**
* Returns the length.
*
* @return the length
*/
@Override
public long length() throws SQLException {<FILL_FUNCTION_BODY>}
/**
* [Not supported] Truncates the object.
*/
@Override
public void truncate(long len) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns the input stream.
*
* @return the input stream
*/
@Override
public InputStream getAsciiStream() throws SQLException {
try {
debugCodeCall("getAsciiStream");
checkClosed();
String s = value.getString();
return IOUtils.getInputStreamFromString(s);
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* [Not supported] Returns an output stream.
*/
@Override
public OutputStream setAsciiStream(long pos) throws SQLException {
throw unsupported("LOB update");
}
/**
* Returns the reader.
*
* @return the reader
*/
@Override
public Reader getCharacterStream() throws SQLException {
try {
debugCodeCall("getCharacterStream");
checkClosed();
return value.getReader();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Get a writer to update the Clob. This is only supported for new, empty
* Clob objects that were created with Connection.createClob() or
* createNClob(). The Clob is created in a separate thread, and the object
* is only updated when Writer.close() is called. The position must be 1,
* meaning the whole Clob data is set.
*
* @param pos where to start writing (the first character is at position 1)
* @return a writer
*/
@Override
public abstract Writer setCharacterStream(long pos) throws SQLException;
/**
* Returns a substring.
*
* @param pos the position (the first character is at position 1)
* @param length the number of characters
* @return the string
*/
@Override
public String getSubString(long pos, int length) throws SQLException {
try {
if (isDebugEnabled()) {
debugCode("getSubString(" + pos + ", " + length + ");");
}
checkClosed();
if (pos < 1) {
throw DbException.getInvalidValueException("pos", pos);
}
if (length < 0) {
throw DbException.getInvalidValueException("length", length);
}
StringWriter writer = new StringWriter(Math.min(Constants.IO_BUFFER_SIZE, length));
Reader reader = value.getReader();
try {
IOUtils.skipFully(reader, pos - 1);
IOUtils.copyAndCloseInput(reader, writer, length);
} finally {
reader.close();
}
return writer.toString();
} catch (Exception e) {
throw logAndConvert(e);
}
}
/**
* Fills the Clob. This is only supported for new, empty Clob objects that
* were created with Connection.createClob() or createNClob(). The position
* must be 1, meaning the whole Clob data is set.
*
* @param pos where to start writing (the first character is at position 1)
* @param str the string to add
* @return the length of the added text
*/
@Override
public abstract int setString(long pos, String str) throws SQLException;
/**
* [Not supported] Sets a substring.
*/
@Override
public int setString(long pos, String str, int offset, int len) throws SQLException {
throw unsupported("LOB update");
}
/**
* [Not supported] Searches a pattern and return the position.
*/
@Override
public long position(String pattern, long start) throws SQLException {
throw unsupported("LOB search");
}
/**
* [Not supported] Searches a pattern and return the position.
*/
@Override
public long position(Clob clobPattern, long start) throws SQLException {
throw unsupported("LOB search");
}
/**
* Release all resources of this object.
*/
@Override
public void free() {
debugCodeCall("free");
value = null;
}
/**
* [Not supported] Returns the reader, starting from an offset.
*/
@Override
public Reader getCharacterStream(long pos, long length) throws SQLException {
throw unsupported("LOB subset");
}
protected void checkClosed() {
if (value == null) {
throw DbException.get(ErrorCode.OBJECT_CLOSED);
}
}
/**
* INTERNAL
*/
@Override
public String toString() {
return getTraceObjectName() + ": " + (value == null ? "null" : value.getTraceSQL());
}
} |
try {
debugCodeCall("length");
checkClosed();
if (value.getType() == Value.CLOB) {
long precision = value.getPrecision();
if (precision > 0) {
return precision;
}
}
return IOUtils.copyAndCloseInput(value.getReader(), null, Long.MAX_VALUE);
} catch (Exception e) {
throw logAndConvert(e);
}
| 1,346 | 114 | 1,460 | <methods>public non-sealed void <init>() ,public static int getNextTraceId(com.lealone.common.trace.TraceObjectType) ,public int getTraceId() ,public java.lang.String getTraceObjectName() <variables>private static final non-sealed java.util.concurrent.atomic.AtomicInteger[] ID,protected com.lealone.common.trace.Trace trace |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/CompareMode.java | CompareMode | getCollator | 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 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 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
* @param binaryUnsigned whether to compare binaries as unsigned
* @return the compare mode
*/
public static synchronized CompareMode getInstance(String name, int strength,
boolean binaryUnsigned) {
if (lastUsed != null) {
if (StringUtils.equals(lastUsed.name, name) && lastUsed.strength == strength
&& lastUsed.binaryUnsigned == binaryUnsigned) {
return lastUsed;
}
}
if (name == null || name.equals(OFF)) {
lastUsed = 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) {
lastUsed = new CompareModeIcu4J(name, strength, binaryUnsigned);
} else {
lastUsed = new CompareModeDefault(name, strength, binaryUnsigned);
}
}
return lastUsed;
}
/**
* 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) {<FILL_FUNCTION_BODY>}
public String getName() {
return name == null ? OFF : name;
}
public int getStrength() {
return strength;
}
public boolean isBinaryUnsigned() {
return binaryUnsigned;
}
} |
Collator result = null;
if (name.startsWith(ICU4J)) {
name = name.substring(ICU4J.length());
} else if (name.startsWith(DEFAULT)) {
name = name.substring(DEFAULT.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;
| 1,589 | 332 | 1,921 | <no_super_class> |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/CompareModeDefault.java | CompareModeDefault | compareString | 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.getInternalError(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) {<FILL_FUNCTION_BODY>}
@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;
}
}
} |
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;
| 385 | 125 | 510 | <methods>public int compareString(java.lang.String, java.lang.String, boolean) ,public boolean equalsChars(java.lang.String, int, java.lang.String, int, boolean) ,public static java.text.Collator getCollator(java.lang.String) ,public static synchronized com.lealone.db.value.CompareMode getInstance(java.lang.String, int, boolean) ,public static java.lang.String getName(java.util.Locale) ,public java.lang.String getName() ,public int getStrength() ,public boolean isBinaryUnsigned() <variables>private static final non-sealed boolean CAN_USE_ICU4J,public static final java.lang.String DEFAULT,public static final java.lang.String ICU4J,public static final java.lang.String OFF,public static final java.lang.String SIGNED,public static final java.lang.String UNSIGNED,private final non-sealed boolean binaryUnsigned,private static com.lealone.db.value.CompareMode lastUsed,private final non-sealed java.lang.String name,private final non-sealed int strength |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/CompareModeIcu4J.java | CompareModeIcu4J | equalsChars | 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) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
private static Comparator<String> getIcu4jCollator(String name, int strength) {
try {
Comparator<String> result = null;
Class<?> collatorClass = Utils.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);
}
}
} |
return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1), ignoreCase) == 0;
| 689 | 38 | 727 | <methods>public int compareString(java.lang.String, java.lang.String, boolean) ,public boolean equalsChars(java.lang.String, int, java.lang.String, int, boolean) ,public static java.text.Collator getCollator(java.lang.String) ,public static synchronized com.lealone.db.value.CompareMode getInstance(java.lang.String, int, boolean) ,public static java.lang.String getName(java.util.Locale) ,public java.lang.String getName() ,public int getStrength() ,public boolean isBinaryUnsigned() <variables>private static final non-sealed boolean CAN_USE_ICU4J,public static final java.lang.String DEFAULT,public static final java.lang.String ICU4J,public static final java.lang.String OFF,public static final java.lang.String SIGNED,public static final java.lang.String UNSIGNED,private final non-sealed boolean binaryUnsigned,private static com.lealone.db.value.CompareMode lastUsed,private final non-sealed java.lang.String name,private final non-sealed int strength |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ReadonlyArray.java | ReadonlyArray | toString | class ReadonlyArray extends ArrayBase {
{
this.trace = Trace.NO_TRACE;
}
public ReadonlyArray(Value value) {
this.value = value;
}
public ReadonlyArray(String value) {
setValue(value);
}
public ReadonlyArray(Object value) {
if (value instanceof List) {
setValue((List<?>) value);
} else {
setValue(value.toString());
}
}
public ReadonlyArray(Object... values) {
setValue(values);
}
public ReadonlyArray(List<String> list) {
setValue(list);
}
private void setValue(List<?> list) {
setValue(list.toArray());
}
private void setValue(Object... values) {
value = DataType.convertToValue(values, Value.ARRAY);
}
private void setValue(String value) {
this.value = ValueString.get(value);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
if (value instanceof ValueArray) {
ValueArray va = (ValueArray) value;
StatementBuilder buff = new StatementBuilder("[");
for (Value v : va.getList()) {
buff.appendExceptFirst(", ");
buff.append(v.getString());
}
return buff.append(']').toString();
}
return value.toString();
| 292 | 97 | 389 | <methods>public non-sealed void <init>() ,public void free() ,public java.lang.Object getArray() throws java.sql.SQLException,public java.lang.Object getArray(Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public java.lang.Object getArray(long, int) throws java.sql.SQLException,public java.lang.Object getArray(long, int, Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public int getBaseType() throws java.sql.SQLException,public java.lang.String getBaseTypeName() throws java.sql.SQLException,public java.sql.ResultSet getResultSet() throws java.sql.SQLException,public java.sql.ResultSet getResultSet(Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public java.sql.ResultSet getResultSet(long, int) throws java.sql.SQLException,public java.sql.ResultSet getResultSet(long, int, Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public java.lang.String toString() <variables>protected com.lealone.db.value.Value value |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueArray.java | ValueArray | get | 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);
}
public static ValueArray get(java.sql.Array array) {<FILL_FUNCTION_BODY>}
/**
* 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 l > ol ? 1 : l == ol ? 0 : -1;
}
@Override
public Object getObject() {
int len = values.length;
Object[] list = (Object[]) Array.newInstance(componentType, len);
for (int i = 0; i < len; i++) {
list[i] = values[i].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.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;
}
int length = values.length;
Value[] newValues = new Value[length];
int i = 0;
boolean modified = false;
for (; i < length; i++) {
Value old = values[i];
Value v = old.convertPrecision(precision, true);
if (v != old) {
modified = 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;
}
newValues[i] = v;
}
if (i < length) {
return get(componentType, Arrays.copyOf(newValues, i));
}
return modified ? get(componentType, newValues) : this;
}
public Value getValue(int i) {
return values[i];
}
@Override
public Value add(Value v) {
ValueArray va = (ValueArray) v;
List<Value> newValues = new ArrayList<>(values.length + va.values.length);
newValues.addAll(Arrays.asList(values));
newValues.addAll(Arrays.asList(va.values));
return ValueArray.get(componentType, newValues.toArray(new Value[0]));
}
@Override
public Value subtract(Value v) {
ValueArray va = (ValueArray) v;
List<Value> newValues = new ArrayList<>(Math.abs(values.length - va.values.length));
newValues.addAll(Arrays.asList(values));
newValues.removeAll(Arrays.asList(va.values));
return ValueArray.get(componentType, newValues.toArray(new Value[0]));
}
} |
Object[] objArray;
try {
objArray = (Object[]) array.getArray();
int size = objArray.length;
Value[] values = new Value[size];
for (int i = 0; i < size; i++) {
values[i] = ValueString.get(objArray[i].toString());
}
return new ValueArray(values);
} catch (SQLException e) {
throw DbException.convert(e);
}
| 1,825 | 121 | 1,946 | <methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueBoolean.java | ValueBoolean | compareSecure | 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;
/**
* Of type Object so that Tomcat doesn't set it to null.
*/
public static final ValueBoolean TRUE = new ValueBoolean(true);
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) {<FILL_FUNCTION_BODY>}
@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;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return TYPE_BOOLEAN;
}
@Override
public int compare(Object aObj, Object bObj) {
Boolean a = (Boolean) aObj;
Boolean b = (Boolean) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
write0(buff, ((Boolean) obj).booleanValue());
}
@Override
public void writeValue(DataBuffer buff, Value v) {
write0(buff, v.getBoolean());
}
private void write0(DataBuffer buff, boolean v) {
buff.put((byte) (v ? TAG_BOOLEAN_TRUE : TYPE_BOOLEAN));
}
@Override
public Value readValue(ByteBuffer buff, int tag) {
if (tag == TYPE_BOOLEAN)
return ValueBoolean.get(false);
else
return ValueBoolean.get(true);
}
};
} |
boolean v2 = ((ValueBoolean) o).value;
boolean v = value;
return (v == v2) ? 0 : (v ? 1 : -1);
| 865 | 46 | 911 | <methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueByte.java | ValueByte | divide | 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) {<FILL_FUNCTION_BODY>}
@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
protected int compareSecure(Value o, CompareMode mode) {
ValueByte v = (ValueByte) o;
return MathUtils.compareInt(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 Byte.valueOf(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;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return BYTE;
}
@Override
public int compare(Object aObj, Object bObj) {
Byte a = (Byte) aObj;
Byte b = (Byte) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 16;
}
@Override
public void write(DataBuffer buff, Object obj) {
buff.put((byte) Value.BYTE).put(((Byte) obj).byteValue());
}
@Override
public void writeValue(DataBuffer buff, Value v) {
buff.put((byte) Value.BYTE).put(v.getByte());
}
@Override
public Value readValue(ByteBuffer buff) {
return ValueByte.get(buff.get());
}
};
} |
ValueByte other = (ValueByte) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueByte.get((byte) (value / other.value));
| 1,126 | 74 | 1,200 | <methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueBytes.java | ValueBytes | getNoCopy | 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) {<FILL_FUNCTION_BODY>}
@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 Utils.compareNotNullUnsigned(value, v2);
}
return Utils.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 = new byte[len];
System.arraycopy(value, 0, buff, 0, len);
return get(buff);
}
} |
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);
| 853 | 86 | 939 | <methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueDate.java | ValueDate | appendDate | class ValueDate extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 8;
/**
* The display size of the textual representation of a date.
* Example: 2000-01-02
*/
public static final int DISPLAY_SIZE = 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()));
}
/**
* 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(DISPLAY_SIZE);
appendDate(buff, dateValue);
return buff.toString();
}
@Override
public String getSQL() {
return "DATE '" + getString() + "'";
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
return MathUtils.compareLong(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());
}
/**
* Append a date to the string builder.
*
* @param buff the target string builder
* @param dateValue the date value
*/
static void appendDate(StringBuilder buff, long dateValue) {<FILL_FUNCTION_BODY>}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return DATE;
}
@Override
public int compare(Object aObj, Object bObj) {
Date a = (Date) aObj;
Date b = (Date) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 24;
}
@Override
public void write(DataBuffer buff, Object obj) {
Date d = (Date) obj;
write0(buff, d.getTime());
}
@Override
public void writeValue(DataBuffer buff, Value v) {
long d = ((ValueDate) v).getDateValue();
write0(buff, d);
}
private void write0(DataBuffer buff, long v) {
buff.put((byte) Value.DATE).putVarLong(v);
}
@Override
public Value readValue(ByteBuffer buff) {
return ValueDate.fromDateValue(DataUtils.readVarLong(buff));
}
};
} |
int y = DateTimeUtils.yearFromDateValue(dateValue);
int m = DateTimeUtils.monthFromDateValue(dateValue);
int d = DateTimeUtils.dayFromDateValue(dateValue);
if (y > 0 && y < 10000) {
StringUtils.appendZeroPadded(buff, 4, y);
} else {
buff.append(y);
}
buff.append('-');
StringUtils.appendZeroPadded(buff, 2, m);
buff.append('-');
StringUtils.appendZeroPadded(buff, 2, d);
| 1,167 | 151 | 1,318 | <methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache |
lealone_Lealone | Lealone/lealone-common/src/main/java/com/lealone/db/value/ValueDouble.java | ValueDouble | get | class ValueDouble extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 17;
/**
* The maximum display size of a double.
* Example: -3.3333333333333334E-100
*/
public static final int DISPLAY_SIZE = 24;
/**
* Double.doubleToLongBits(0.0)
*/
public static final long ZERO_BITS = Double.doubleToLongBits(0.0);
private static final ValueDouble ZERO = new ValueDouble(0.0);
private static final ValueDouble ONE = new ValueDouble(1.0);
private static final ValueDouble NAN = new ValueDouble(Double.NaN);
private final double value;
private ValueDouble(double value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value + v2.value);
}
@Override
public Value subtract(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value - v2.value);
}
@Override
public Value negate() {
return ValueDouble.get(-value);
}
@Override
public Value multiply(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value * v2.value);
}
@Override
public Value divide(Value v) {
ValueDouble v2 = (ValueDouble) v;
if (v2.value == 0.0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueDouble.get(value / v2.value);
}
@Override
public ValueDouble modulus(Value v) {
ValueDouble other = (ValueDouble) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueDouble.get(value % other.value);
}
@Override
public String getSQL() {
if (value == Double.POSITIVE_INFINITY) {
return "POWER(0, -1)";
} else if (value == Double.NEGATIVE_INFINITY) {
return "(-POWER(0, -1))";
} else if (Double.isNaN(value)) {
return "SQRT(-1)";
}
String s = getString();
if (s.equals("-0.0")) {
return "-CAST(0 AS DOUBLE)";
}
return s;
}
@Override
public int getType() {
return Value.DOUBLE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueDouble v = (ValueDouble) o;
return Double.compare(value, v.value);
}
@Override
public int getSignum() {
return value == 0 ? 0 : (value < 0 ? -1 : 1);
}
@Override
public double getDouble() {
return value;
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getScale() {
return 0;
}
@Override
public int hashCode() {
long hash = Double.doubleToLongBits(value);
return (int) (hash ^ (hash >> 32));
}
@Override
public Object getObject() {
return Double.valueOf(value);
}
@Override
public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setDouble(parameterIndex, value);
}
/**
* Get or create double value for the given double.
*
* @param d the double
* @return the value
*/
public static ValueDouble get(double d) {<FILL_FUNCTION_BODY>}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueDouble)) {
return false;
}
return compareSecure((ValueDouble) other, null) == 0;
}
public static final StorageDataTypeBase type = new StorageDataTypeBase() {
@Override
public int getType() {
return DOUBLE;
}
@Override
public int compare(Object aObj, Object bObj) {
Double a = (Double) aObj;
Double b = (Double) bObj;
return a.compareTo(b);
}
@Override
public int getMemory(Object obj) {
return 24;
}
@Override
public void write(DataBuffer buff, Object obj) {
double x = (Double) obj;
write0(buff, x);
}
@Override
public void writeValue(DataBuffer buff, Value v) {
double x = v.getDouble();
write0(buff, x);
}
private void write0(DataBuffer buff, double x) {
long d = Double.doubleToLongBits(x);
if (d == DOUBLE_ZERO_BITS) {
buff.put((byte) TAG_DOUBLE_0);
} else if (d == DOUBLE_ONE_BITS) {
buff.put((byte) TAG_DOUBLE_1);
} else {
long value = Long.reverse(d);
if (value >= 0 && value <= DataUtils.COMPRESSED_VAR_LONG_MAX) {
buff.put((byte) DOUBLE);
buff.putVarLong(value);
} else {
buff.put((byte) TAG_DOUBLE_FIXED);
buff.putDouble(x);
}
}
}
@Override
public Value readValue(ByteBuffer buff, int tag) {
switch (tag) {
case TAG_DOUBLE_0:
return ValueDouble.get(0d);
case TAG_DOUBLE_1:
return ValueDouble.get(1d);
case TAG_DOUBLE_FIXED:
return ValueDouble.get(buff.getDouble());
}
return ValueDouble.get(Double.longBitsToDouble(Long.reverse(DataUtils.readVarLong(buff))));
}
};
} |
if (d == 1.0) {
return ONE;
} else if (d == 0.0) {
// unfortunately, -0.0 == 0.0, but we don't want to return
// 0.0 in this case
if (Double.doubleToLongBits(d) == ZERO_BITS) {
return ZERO;
}
} else if (Double.isNaN(d)) {
return NAN;
}
return (ValueDouble) Value.cache(new ValueDouble(d));
| 1,751 | 139 | 1,890 | <methods>public non-sealed void <init>() ,public com.lealone.db.value.Value add(com.lealone.db.value.Value) ,public boolean checkPrecision(long) ,public static void clearCache() ,public void close() ,public int compareTo(com.lealone.db.value.Value) ,public final int compareTo(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public final int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.CompareMode) ,public com.lealone.db.value.Value convertPrecision(long, boolean) ,public com.lealone.db.value.Value convertScale(boolean, int) ,public com.lealone.db.value.Value convertTo(int) ,public com.lealone.db.value.Value divide(com.lealone.db.value.Value) ,public abstract boolean equals(java.lang.Object) ,public java.sql.Array getArray() ,public java.math.BigDecimal getBigDecimal() ,public java.sql.Blob getBlob() ,public boolean getBoolean() ,public byte getByte() ,public byte[] getBytes() ,public byte[] getBytesNoCopy() ,public java.sql.Clob getClob() ,public T getCollection() ,public java.sql.Date getDate() ,public abstract int getDisplaySize() ,public double getDouble() ,public float getFloat() ,public static int getHigherOrder(int, int) ,public java.io.InputStream getInputStream() ,public int getInt() ,public long getLong() ,public int getMemory() ,public abstract java.lang.Object getObject() ,public abstract long getPrecision() ,public java.io.Reader getReader() ,public java.sql.ResultSet getResultSet() ,public abstract java.lang.String getSQL() ,public int getScale() ,public short getShort() ,public int getSignum() ,public abstract java.lang.String getString() ,public java.sql.Time getTime() ,public java.sql.Timestamp getTimestamp() ,public java.lang.String getTraceSQL() ,public abstract int getType() ,public java.util.UUID getUuid() ,public abstract int hashCode() ,public final boolean isFalse() ,public com.lealone.db.value.Value modulus(com.lealone.db.value.Value) ,public com.lealone.db.value.Value multiply(com.lealone.db.value.Value) ,public com.lealone.db.value.Value negate() ,public abstract void set(java.sql.PreparedStatement, int) throws java.sql.SQLException,public com.lealone.db.value.Value subtract(com.lealone.db.value.Value) ,public java.lang.String toString() <variables>public static final int ARRAY,public static final int BLOB,public static final int BOOLEAN,public static final int BYTE,public static final int BYTES,public static final int CLOB,private static final com.lealone.db.value.CompareMode COMPARE_MODE,public static final int DATE,public static final int DECIMAL,public static final int DOUBLE,public static final int ENUM,public static final int FLOAT,public static final int INT,public static final int JAVA_OBJECT,public static final int LIST,public static final int LONG,public static final int MAP,private static final java.math.BigDecimal MAX_LONG_DECIMAL,private static final java.math.BigDecimal MIN_LONG_DECIMAL,public static final int NULL,public static final int RESULT_SET,public static final int SET,public static final int SHORT,public static final int STRING,public static final int STRING_FIXED,public static final int STRING_IGNORECASE,public static final int TIME,public static final int TIMESTAMP,public static final int TYPE_COUNT,public static final int UNKNOWN,public static final int UUID,private static SoftReference<com.lealone.db.value.Value[]> softCache |