proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
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-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/utils/AnnotatedBeanDefinitionUtils.java
|
AnnotatedBeanDefinitionUtils
|
getFactoryMethodMetadata
|
class AnnotatedBeanDefinitionUtils {
public static MethodMetadata getFactoryMethodMetadata(AnnotatedBeanDefinition beanDefinition) {<FILL_FUNCTION_BODY>}
public static boolean containValueAnnotation(Annotation[][] annotations) {
for (int i = 0; i < annotations.length; i++) {
Annotation[] annotationArray = annotations[i];
for (Annotation annotation : annotationArray) {
if (annotation.annotationType().getName().equals("org.springframework.beans.factory.annotation.Value")) {
return true;
}
}
}
return false;
}
}
|
Object target = ReflectionHelper.invokeNoException(beanDefinition, beanDefinition.getClass().getName(), beanDefinition.getClass().getClassLoader(), "getFactoryMethodMetadata", new Class<?>[]{});
if (target != null) {
return (MethodMetadata) target;
}
/** earlier than spring 4.1 */
if (beanDefinition.getSource() != null && beanDefinition.getSource() instanceof StandardMethodMetadata) {
StandardMethodMetadata standardMethodMetadata = (StandardMethodMetadata) beanDefinition.getSource();
return standardMethodMetadata;
}
return null;
| 153
| 144
| 297
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/utils/RegistryUtils.java
|
RegistryUtils
|
maybeRegistryToBeanFactory
|
class RegistryUtils {
public static DefaultListableBeanFactory maybeRegistryToBeanFactory(BeanDefinitionRegistry registry) {<FILL_FUNCTION_BODY>}
}
|
if (registry instanceof DefaultListableBeanFactory) {
return (DefaultListableBeanFactory) registry;
} else if (registry instanceof GenericApplicationContext) {
return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();
}
return null;
| 41
| 69
| 110
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/utils/ResourceUtils.java
|
ResourceUtils
|
convertToClasspathURL
|
class ResourceUtils {
private static final AgentLogger LOGGER = AgentLogger.getLogger(XmlBeanDefinitionScannerAgent.class);
public static String getPath(Resource resource) {
if (resource == null) {
return null;
}
String path;
if (resource instanceof ClassPathResource) {
path = ((ClassPathResource) resource).getPath();
} else if (resource instanceof ByteArrayResource) {
LOGGER.debug("Cannot get path from ByteArrayResource: {}", new String(((ByteArrayResource) resource).getByteArray()));
return null;
} else {
try {
path = convertToClasspathURL(resource.getURL().getPath());
} catch (IOException e) {
LOGGER.error("Cannot get url from resource: {}", e, resource);
return null;
}
}
return path;
}
/**
* convert src/main/resources/xxx.xml and classes/xxx.xml to xxx.xml
*
* @param filePath the file path to convert
* @return if convert succeed, return classpath path, or else return file path
*/
public static String convertToClasspathURL(String filePath) {
String[] paths = filePath.split("src/main/resources/");
if (paths.length == 2) {
return paths[1];
}
paths = filePath.split("WEB-INF/classes/");
if (paths.length == 2) {
return paths[1];
}
paths = filePath.split("WEB-INF/");
if (paths.length == 2) {
return paths[1];
}
paths = filePath.split("target/classes/");
if (paths.length == 2) {
return paths[1];
}
paths = filePath.split("target/test-classes/");
if (paths.length == 2) {
return paths[1];
}
LOGGER.error("failed to convert filePath {} to classPath path", filePath);
return filePath;
}
/**
* convert src/main/resources/xxx.xml and classes/xxx.xml to xxx.xml
*
* @param extraClassPaths the extra class paths
* @param filePath the file path to convert
* @return if convert succeed, return classpath path, or else return file path
*/
public static String convertToClasspathURL(URL[] extraClassPaths, String filePath) {<FILL_FUNCTION_BODY>}
}
|
String path = convertToClasspathURL(filePath);
if (!StringUtils.isEmpty(path)) {
return path;
}
if (extraClassPaths != null && extraClassPaths.length != 0) {
for (URL extraClassPath : extraClassPaths) {
String extraClassPathStr = extraClassPath.getPath();
String[] paths = filePath.split(extraClassPathStr);
if (paths.length == 2) {
return paths[1];
}
}
}
LOGGER.error("failed to convert filePath {} to classPath path", filePath);
return filePath;
| 631
| 161
| 792
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-thymeleaf-plugin/src/main/java/org/hotswap/agent/plugin/thymeleaf/ThymeleafPlugin.java
|
ThymeleafPlugin
|
patchParseAndProcess
|
class ThymeleafPlugin {
private static final AgentLogger LOGGER = AgentLogger.getLogger(ThymeleafPlugin.class);
@OnClassLoadEvent(classNameRegexp = "org.thymeleaf.engine.TemplateManager")
public static void patchParseAndProcess(ClassPool classPool, final CtClass ctClass) {<FILL_FUNCTION_BODY>}
}
|
try {
CtMethod method = ctClass.getDeclaredMethod("parseAndProcess", new CtClass[]{
classPool.get("org.thymeleaf.TemplateSpec"), classPool.get("org.thymeleaf.context.IContext"),
classPool.get("java.io.Writer")});
method.insertBefore("clearCachesFor($1.getTemplate());");
} catch (NotFoundException | CannotCompileException e) {
LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e);
}
| 97
| 142
| 239
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-undertow-plugin/src/main/java/org/hotswap/agent/plugin/undertow/PrefixingResourceManager.java
|
PrefixingResourceManager
|
removeResourceChangeListener
|
class PrefixingResourceManager implements ResourceManager {
private static AgentLogger LOGGER = AgentLogger.getLogger(PrefixingResourceManager.class);
private List<ResourceManager> delegates;
public PrefixingResourceManager(ResourceManager delegate) {
this.delegates = new ArrayList<>();
this.delegates.add(delegate);
}
public void setExtraResources(List extraResources) {
List<ResourceManager> delegates = new ArrayList<>();
for (Object o: extraResources) {
File resource = File.class.cast(o);
try {
delegates.add(new FileResourceManager(resource.getCanonicalFile(), 1024, true, false, "/"));
} catch (IOException e) {
LOGGER.warning("Unable to create cannonical file from {}. File skipped.", resource.getName(), e);
}
}
delegates.addAll(this.delegates);
this.delegates = delegates;
}
@Override
public Resource getResource(String path) throws IOException {
for(ResourceManager d : delegates) {
Resource res = d.getResource(path);
if(res != null) {
return res;
}
}
return null;
}
@Override
public boolean isResourceChangeListenerSupported() {
return true;
}
@Override
public void registerResourceChangeListener(ResourceChangeListener listener) {
for(ResourceManager del : delegates) {
if(del.isResourceChangeListenerSupported()) {
del.registerResourceChangeListener(listener);
}
}
}
@Override
public void removeResourceChangeListener(ResourceChangeListener listener) {<FILL_FUNCTION_BODY>}
@Override
public void close() throws IOException {
for(ResourceManager del : delegates) {
IoUtils.safeClose(del);
}
}
}
|
for(ResourceManager del : delegates) {
if(del.isResourceChangeListenerSupported()) {
del.removeResourceChangeListener(listener);
}
}
| 487
| 47
| 534
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-undertow-plugin/src/main/java/org/hotswap/agent/plugin/undertow/UndertowPlugin.java
|
UndertowPlugin
|
init
|
class UndertowPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(UndertowPlugin.class);
// Undertow resource manager object to a application classloader
static Map<Object, ClassLoader> registeredResourceManagersMap = new HashMap<>();
// For each app classloader map of undertow repository name to associated watch resource classloader
private static Map<ClassLoader, Map<String, ClassLoader>> extraRepositories = new HashMap<>();
String undertowVersion = "";
/**
* Init the plugin during DeploymentManagerImpl.deploy lifecycle. This method is invoked before the plugin is initialized.
* @param appClassLoader main web deplyment classloader.
* @param resourceManager undertow resource manager associated to deployment
*/
public static void init(ClassLoader appClassLoader, Object resourceManager) {<FILL_FUNCTION_BODY>}
private static void addExtraResources(List<File> extraResources, URL[] extraURLs) {
for (int i=0; i < extraURLs.length; i++) {
try {
File file = new File(extraURLs[i].toURI());
if (file.isDirectory()) {
extraResources.add(file);
}
} catch (URISyntaxException e) {
LOGGER.warning("Unable to convert resource URL '{}' to URI. URL is skipped.", e, extraURLs[i]);
}
}
}
/**
* Init plugin and resolve version.
*
* @param undertowVersion the undertow version
* @param appClassLoader the app class loader
*/
private void init(String undertowVersion, ClassLoader appClassLoader ) {
LOGGER.info("Undertow plugin initialized - Undertow version '{}'", undertowVersion);
this.undertowVersion = undertowVersion;
}
/**
* Close plugin
*
* @param classLoader the class loader
*/
public static void close(ClassLoader classLoader) {
Map<String, ClassLoader> registerMap = extraRepositories.remove(classLoader);
if (registerMap != null) {
for (ClassLoader loader : registerMap.values()) {
PluginManager.getInstance().getWatcher().closeClassLoader(loader);
}
}
}
/**
* Resolve the server version from Version class.
* @param appClassLoader application classloader
* @return the server version
*/
private static String resolveUndertowVersion(ClassLoader appClassLoader) {
try {
Class version = appClassLoader.loadClass("io.undertow.Version");
return (String) ReflectionHelper.invoke(null, version, "getVersionString", new Class[]{});
} catch (Exception e) {
LOGGER.debug("Unable to resolve undertow version", e);
return "unknown";
}
}
}
|
String version = resolveUndertowVersion(appClassLoader);
registeredResourceManagersMap.put(resourceManager, appClassLoader);
// create plugin configuration in advance to get extraClasspath and watchResources properties
PluginConfiguration pluginConfiguration = new PluginConfiguration(appClassLoader);
List<File> extraResources = new ArrayList<>();
addExtraResources(extraResources, pluginConfiguration.getExtraClasspath());
addExtraResources(extraResources, pluginConfiguration.getWatchResources());
addExtraResources(extraResources, pluginConfiguration.getWebappDir());
try {
ReflectionHelper.invoke(resourceManager, resourceManager.getClass(), "setExtraResources", new Class[] { List.class }, extraResources);
} catch (Exception e) {
LOGGER.error("init() exception {}.", e.getMessage());
}
Object plugin = PluginManagerInvoker.callInitializePlugin(UndertowPlugin.class, appClassLoader);
if (plugin != null) {
ReflectionHelper.invoke(plugin, plugin.getClass(), "init", new Class[]{String.class, ClassLoader.class}, version, appClassLoader);
} else {
LOGGER.debug("UndertowPlugin is disabled in {}", appClassLoader);
}
| 723
| 307
| 1,030
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-undertow-plugin/src/main/java/org/hotswap/agent/plugin/undertow/UndertowTransformer.java
|
UndertowTransformer
|
patchWebappLoader
|
class UndertowTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(UndertowTransformer.class);
@OnClassLoadEvent(classNameRegexp = "io.undertow.servlet.core.DeploymentManagerImpl")
public static void patchWebappLoader(CtClass ctClass) throws NotFoundException, CannotCompileException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
}
|
try {
ctClass.getDeclaredMethod("deploy").insertBefore( "{" +
"org.hotswap.agent.plugin.undertow.PrefixingResourceManager rm=" +
"new org.hotswap.agent.plugin.undertow.PrefixingResourceManager(originalDeployment.getResourceManager());" +
"originalDeployment.setResourceManager(rm);" +
UndertowPlugin.class.getName() + ".init(originalDeployment.getClassLoader(),rm);" +
"}"
);
} catch (NotFoundException e) {
LOGGER.error("io.undertow.servlet.core.DeploymentManagerImpl does not contain start() method.");
}
try {
ctClass.getDeclaredMethod("stop").insertBefore(
PluginManagerInvoker.buildCallCloseClassLoader("originalDeployment.getClassLoader()") +
UndertowPlugin.class.getName() + ".close(originalDeployment.getClassLoader());"
);
} catch (NotFoundException e) {
LOGGER.error("orgio.undertow.servlet.core.DeploymentManagerImpl does not contain stop() method.");
}
| 108
| 291
| 399
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-vaadin-plugin/src/main/java/org/hotswap/agent/plugin/vaadin/VaadinIntegration.java
|
VaadinIntegration
|
updateRoutes
|
class VaadinIntegration {
private static final AgentLogger LOGGER = AgentLogger
.getLogger(VaadinIntegration.class);
private VaadinServlet vaadinServlet = null;
/**
* Sets the Vaadin servlet once instantiated.
*
* @param servlet
* the Vaadin serlvet
*/
public void servletInitialized(VaadinServlet servlet) {
vaadinServlet = servlet;
LOGGER.info("{} initialized for servlet {}", getClass(), servlet);
}
/**
* Update Flow route registry and push refresh to UIs (concrete parameter
* types as {@link org.hotswap.agent.command.ReflectionCommand} determines
* the method from actual argument types).
*
* @param addedClasses
* returns classes that have been added or modified
* @param modifiedClasses
* returns classes that have been deleted
*/
public void updateRoutes(HashSet<Class<?>> addedClasses,
HashSet<Class<?>> modifiedClasses) {<FILL_FUNCTION_BODY>}
/**
* Reload UI in browser.
*/
public void reload() {
VaadinService vaadinService = vaadinServlet.getService();
Optional<BrowserLiveReload> liveReload = BrowserLiveReloadAccessor.getLiveReloadFromService(vaadinService);
if (liveReload.isPresent()) {
liveReload.get().reload();
LOGGER.info("Live reload triggered");
}
}
/**
* Updates route registry as necessary when classes have been added /
* modified / deleted.
*
* TODO: move to flow-server internal utility methods.
*
* @param registry
* route registry
* @param addedClasses
* added classes
* @param modifiedClasses
* modified classes
* @param deletedClasses
* deleted classes
*/
private static void updateRouteRegistry(RouteRegistry registry,
Set<Class<?>> addedClasses,
Set<Class<?>> modifiedClasses,
Set<Class<?>> deletedClasses) {
RouteConfiguration routeConf = RouteConfiguration.forRegistry(registry);
registry.update(() -> {
// remove deleted classes and classes that lost the annotation from registry
Stream.concat(deletedClasses.stream(),
modifiedClasses.stream().filter(
clazz -> !clazz.isAnnotationPresent(Route.class)))
.filter(Component.class::isAssignableFrom)
.forEach(clazz -> {
Class<? extends Component> componentClass = (Class<? extends Component>) clazz;
routeConf.removeRoute(componentClass);
});
// add new routes to registry
Stream.concat(addedClasses.stream(), modifiedClasses.stream())
.distinct()
.filter(Component.class::isAssignableFrom)
.filter(clazz -> clazz.isAnnotationPresent(Route.class))
.forEach(clazz -> {
Class<? extends Component> componentClass = (Class<? extends Component>) clazz;
routeConf.removeRoute(componentClass);
routeConf.setAnnotatedRoute(componentClass);
});
});
}
}
|
assert (vaadinServlet != null);
LOGGER.debug("The following classes were added:");
addedClasses.forEach(clazz -> LOGGER.debug("+ {}", clazz));
LOGGER.debug("The following classes were modified:");
modifiedClasses.forEach(clazz -> LOGGER.debug("# {}", clazz));
Method getInstanceMethod = null;
Object getInstanceMethodParam = null;
try {
// Vaadin 14.2+
getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", VaadinContext.class);
getInstanceMethodParam = vaadinServlet.getService().getContext();
} catch (NoSuchMethodException ex1) {
// In Vaadin 14.1, this method instead takes a ServletContext parameter
LOGGER.debug("ApplicationRouteRegistry::getInstance(VaadinContext) not found");
try {
getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", ServletContext.class);
getInstanceMethodParam = vaadinServlet.getServletContext();
} catch (NoSuchMethodException ex2) {
// In Vaadin 14.1, this method takes a ServletContext parameter
LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated ");
return;
}
}
try {
ApplicationRouteRegistry registry = (ApplicationRouteRegistry)
getInstanceMethod.invoke(null, getInstanceMethodParam);
updateRouteRegistry(registry, addedClasses, modifiedClasses,
Collections.emptySet());
} catch (IllegalAccessException | InvocationTargetException ex) {
LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated:", ex);
}
| 820
| 429
| 1,249
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-vaadin-plugin/src/main/java/org/hotswap/agent/plugin/vaadin/VaadinPlugin.java
|
VaadinPlugin
|
getReloadQuietTime
|
class VaadinPlugin {
@Init
Scheduler scheduler;
@Init
ClassLoader appClassLoader;
@Init
PluginConfiguration pluginConfiguration;
private UpdateRoutesCommand updateRouteRegistryCommand;
private ReflectionCommand reloadCommand;
private ReflectionCommand clearReflectionCache = new ReflectionCommand(this,
"com.vaadin.flow.internal.ReflectionCache", "clearAll");
private Set<Class<?>> addedClasses = new HashSet<>();
private Set<Class<?>> modifiedClasses = new HashSet<>();
private static final AgentLogger LOGGER = AgentLogger.getLogger(VaadinPlugin.class);
private static final String RELOAD_QUIET_TIME_PARAMETER = "vaadin.liveReloadQuietTime";
private static final int DEFAULT_RELOAD_QUIET_TIME = 1000; // ms
private int reloadQuietTime = 0;
public VaadinPlugin() {
}
@OnClassLoadEvent(classNameRegexp = "com.vaadin.flow.server.VaadinServlet")
public static void init(CtClass ctClass)
throws NotFoundException, CannotCompileException {
String src = PluginManagerInvoker
.buildInitializePlugin(VaadinPlugin.class);
src += PluginManagerInvoker.buildCallPluginMethod(VaadinPlugin.class,
"registerServlet", "this", Object.class.getName());
ctClass.getDeclaredConstructor(new CtClass[0]).insertAfter(src);
LOGGER.info("Initialized Vaadin plugin");
}
public void registerServlet(Object vaadinServlet) {
try {
Class<?> vaadinIntegrationClass = resolveClass("org.hotswap.agent.plugin.vaadin.VaadinIntegration");
Object vaadinIntegration = vaadinIntegrationClass.getConstructor()
.newInstance();
Class<?> vaadinServletClass = resolveClass("com.vaadin.flow.server.VaadinServlet");
Method m = vaadinIntegrationClass.getDeclaredMethod("servletInitialized",
vaadinServletClass);
m.invoke(vaadinIntegration, vaadinServlet);
updateRouteRegistryCommand = new UpdateRoutesCommand(vaadinIntegration);
reloadCommand = new ReflectionCommand(vaadinIntegration, "reload");
} catch (ClassNotFoundException | NoSuchMethodException
| InstantiationException | IllegalAccessException
| InvocationTargetException ex) {
LOGGER.error(null, ex);
}
}
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void invalidateReflectionCache(CtClass ctClass) throws Exception {
LOGGER.debug("Redefined class {}, clearing Vaadin reflection cache and reloading browser", ctClass.getName());
scheduler.scheduleCommand(clearReflectionCache);
scheduler.scheduleCommand(reloadCommand, getReloadQuietTime());
}
@OnClassFileEvent(classNameRegexp = ".*", events = { FileEvent.CREATE, FileEvent.MODIFY })
public void classCreated(FileEvent eventType, CtClass ctClass) throws Exception {
if (FileEvent.CREATE.equals(eventType)) {
LOGGER.debug("Create class file event for " + ctClass.getName());
addedClasses.add(resolveClass(ctClass.getName()));
} else if (FileEvent.MODIFY.equals(eventType)) {
LOGGER.debug("Modify class file event for " + ctClass.getName());
modifiedClasses.add(resolveClass(ctClass.getName()));
}
// Note that scheduling multiple calls to the same command postpones it
scheduler.scheduleCommand(updateRouteRegistryCommand);
}
private Class<?> resolveClass(String name) throws ClassNotFoundException {
return Class.forName(name, true, appClassLoader);
}
private int getReloadQuietTime() {<FILL_FUNCTION_BODY>}
private class UpdateRoutesCommand extends ReflectionCommand {
private final Object vaadinIntegration;
UpdateRoutesCommand(Object vaadinIntegration) {
super(vaadinIntegration, "updateRoutes", addedClasses, modifiedClasses);
this.vaadinIntegration = vaadinIntegration;
}
// NOTE: Identity equality semantics
@Override
public boolean equals(Object that) {
return this == that;
}
@Override
public int hashCode() {
return System.identityHashCode(vaadinIntegration);
}
@Override
public void executeCommand() {
super.executeCommand();
addedClasses.clear();
modifiedClasses.clear();
}
}
}
|
if (reloadQuietTime <= 0) {
reloadQuietTime = DEFAULT_RELOAD_QUIET_TIME;
String reloadQuietTimeValue = pluginConfiguration.getProperty(RELOAD_QUIET_TIME_PARAMETER);
if (reloadQuietTimeValue != null) {
if (reloadQuietTimeValue.matches("[1-9][0-1]+")) {
reloadQuietTime = Integer.parseInt(reloadQuietTimeValue);
LOGGER.info("Live-reload quiet time is {} ms", reloadQuietTime);
} else {
LOGGER.error("Illegal value '{}' for parameter {}, using default of {} ms",
reloadQuietTimeValue, RELOAD_QUIET_TIME_PARAMETER, DEFAULT_RELOAD_QUIET_TIME);
}
}
}
return reloadQuietTime;
| 1,227
| 222
| 1,449
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-velocity-plugin/src/main/java/org/hotswap/agent/plugin/velocity/VelocityPlugin.java
|
VelocityPlugin
|
patchSetPreferFileSystemAccess
|
class VelocityPlugin {
private static final AgentLogger LOGGER = AgentLogger.getLogger(VelocityPlugin.class);
@OnClassLoadEvent(classNameRegexp = "org.springframework.ui.velocity.VelocityEngineFactory")
public static void patchSetPreferFileSystemAccess(ClassPool classPool, final CtClass ctClass) {<FILL_FUNCTION_BODY>}
@OnClassLoadEvent(classNameRegexp = "org.springframework.ui.velocity.VelocityEngineFactory")
public static void patchSetResourceLoaderPath(ClassPool classPool, final CtClass ctClass) {
try {
CtMethod method = ctClass.getDeclaredMethod("setResourceLoaderPath", new CtClass[]{classPool.get("java.lang.String")});
method.insertAfter("this.resourceLoaderPath = \"classpath:/$$ha$velocity/,\" + this.resourceLoaderPath;");
} catch (NotFoundException | CannotCompileException e) {
LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.springframework.ui.velocity.VelocityEngineFactory")
public static void patchInitSpringResourceLoader(ClassPool classPool, final CtClass ctClass) {
try {
CtMethod method = ctClass.getDeclaredMethod("initSpringResourceLoader", new CtClass[]{classPool.get("org.apache.velocity.app.VelocityEngine"),
classPool.get("java.lang.String")});
method.insertAfter("$1.setProperty(\"spring.resource.loader.cache\", \"false\");");
} catch (NotFoundException | CannotCompileException e) {
LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e);
}
}
}
|
try {
CtMethod method = ctClass.getDeclaredMethod("setPreferFileSystemAccess", new CtClass[]{classPool.get("boolean")});
method.insertAfter("this.preferFileSystemAccess = false;");
} catch (NotFoundException | CannotCompileException e) {
LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e);
}
| 470
| 104
| 574
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weblogic-plugin/src/main/java/org/hotswap/agent/plugin/weblogic/WeblogicPlugin.java
|
WeblogicPlugin
|
transformGenericClassLoader
|
class WeblogicPlugin {
@Init
ClassLoader moduleClassLoader;
static protected AgentLogger LOGGER = AgentLogger.getLogger(WeblogicPlugin.class);
@OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.ChangeAwareClassLoader")
public static void transformChangeAwareClassLoader(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
LOGGER.info("transformChangeAwareClassLoader: {}", ctClass.getSimpleName());
String src = WeblogicPlugin.class.getName() + ".logMessage(\"ChangeAwareClassLoaderConstructor -> \" + $1.toString());";
ctClass.getDeclaredConstructor(new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder"), CtClass.booleanType, classPool.get("java.lang.ClassLoader") })
.insertBefore(src);
}
@OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.MultiClassFinder")
public static void transformMultiClassFinder(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
LOGGER.info("MultiClassFinder: {}", ctClass.getSimpleName());
String srcAddFinder = WeblogicPlugin.class.getName() + ".logMessage(\"MultiClassFinder#addFinder -> \" + $1.toString());";
ctClass.getDeclaredMethod("addFinder", new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder") }).insertBefore(srcAddFinder);
String srcAddFinderFirst = WeblogicPlugin.class.getName() + ".logMessage(\"MultiClassFinder#addFinderFirst -> \" + $1.toString());";
ctClass.getDeclaredMethod("addFinderFirst", new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder") }).insertBefore(srcAddFinderFirst);
}
@OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.CompositeWebAppFinder")
public static void transformCompositeWebAppFinder(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
LOGGER.info("CompositeWebAppFinder: {}", ctClass.getSimpleName());
String src = WeblogicPlugin.class.getName() + ".logMessage(\"CompositeWebAppFinder#addLibraryFinder -> \" + $1.toString());";
ctClass.getDeclaredMethod("addLibraryFinder", new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder") }).insertBefore(src);
}
@OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.GenericClassLoader")
public static void transformGenericClassLoader(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
public static void logMessage(String str){
LOGGER.info("logmessage: {}", str);
}
public static void logException(Exception e){
LOGGER.error("logException: {}", e);
}
}
|
LOGGER.info("transformGenericClassLoader: {}", ctClass.getSimpleName());
CtClass ctHaClassLoader = classPool.get(HotswapAgentClassLoaderExt.class.getName());
ctClass.addInterface(ctHaClassLoader);
// Implementation of HotswapAgentClassLoaderExt.setExtraClassPath(...)
//@formatter:off
ctClass.addMethod(CtNewMethod.make(
"public void $$ha$setExtraClassPath(java.net.URL[] extraClassPath) {" +
WeblogicPlugin.class.getName() + ".logMessage(\"setExtraClassPath in=\" + extraClassPath[0].toString());" +
"try {" +
"weblogic.utils.classloaders.MultiClassFinder multiClassFinder = new weblogic.utils.classloaders.MultiClassFinder();" +
"for (int i=0; i<extraClassPath.length; i++) {" +
"try {" +
"java.net.URL url = extraClassPath[i];" +
"java.io.File root = new java.io.File(url.getPath());" +
"weblogic.utils.classloaders.IndexedDirectoryClassFinder indexedDirectoryClassFinder = new weblogic.utils.classloaders.IndexedDirectoryClassFinder(root);" +
"multiClassFinder.addFinder(indexedDirectoryClassFinder);" +
"} catch (java.lang.Exception e) {" +
WeblogicPlugin.class.getName() + ".logException(e);" +
"}" +
"}" +
"this.addClassFinderFirst(multiClassFinder);" +
WeblogicPlugin.class.getName() + ".logMessage(\"setExtraClassPath result=\" + this.getClassPath());" +
"} catch (java.lang.Exception e) {" +
WeblogicPlugin.class.getName() + ".logException(e);" +
"}" +
"}", ctClass)
);
//@formatter:on
ctClass.addMethod(
CtNewMethod.make(
"public void $$ha$setWatchResourceLoader(" + WatchResourcesClassLoader.class.getName() + " watchResourceLoader) { " +
WeblogicPlugin.class.getName() + ".logMessage(\"WatchResourcesClassLoader -> \" + watchResourceLoader.toString());" +
"}",
ctClass
));
| 834
| 614
| 1,448
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-webobjects-plugin/src/main/java/org/hotswap/agent/plugin/webobjects/HotswapWebObjectsPlugin.java
|
ClearActionCache
|
executeCommand
|
class ClearActionCache implements Command {
@Override
public void executeCommand() {<FILL_FUNCTION_BODY>}
}
|
try {
nsThreadsafeMutableDictionary_removeAllObjects.invoke(actionClassesCacheDictionnary);
LOGGER.info("Resetting Action class cache");
} catch (Exception e) {
e.printStackTrace();
}
| 35
| 63
| 98
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/ArchivePathHelper.java
|
ArchivePathHelper
|
archivePathToURLViaURLClassLoader
|
class ArchivePathHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ArchivePathHelper.class);
public static String getNormalizedArchivePath(CtClass ctClass) throws NotFoundException {
String classFilePath = ctClass.getURL().getFile();
String className = ctClass.getName().replace(".", "/");
// archive path ends with '/' therefore we set end position before the '/' (-1)
return classFilePath.substring(0, classFilePath.indexOf(className) - 1);
}
/**
* Method resolves archive path from BdaId
*
* @param classLoader the class loader
* @param archiveId the archive id
* @return the normalized archive path
*/
public static String getNormalizedArchivePath(ClassLoader classLoader, String archiveId) {
URL archiveURL = archivePathToURL(classLoader, archiveId);
if (archiveURL != null) {
try {
String result = archiveURL.getFile();
// Strip trailing "/" from normalized archive path
while (result.endsWith("/")) {
result = result.substring(0, result.length() -1);
}
return result;
} catch (Exception e) {
LOGGER.error("getNormalizedArchivePath() exception {}.", e.getMessage());
}
}
return null;
}
private static URL archivePathToURL(ClassLoader classLoader, String archiveId) {
URL result = archiveFilePathToURL(archiveId);
if (result == null) {
// File doesn't exists, try to resolve it using appClassLoader
if (classLoader instanceof URLClassLoader) {
result = archivePathToURLViaURLClassLoader((URLClassLoader) classLoader, archiveId);
}
}
return result;
}
private static URL archivePathToURLViaURLClassLoader(URLClassLoader urlClassLoader, String archivePath) {<FILL_FUNCTION_BODY>}
private static URL archiveFilePathToURL(String archivePath) {
File f = new File(archivePath);
if (f.exists()) {
try {
try {
// Try to format as a URL?
return f.toURI().toURL();
} catch (MalformedURLException e) {
// try to locate a file
if (archivePath.startsWith("./"))
archivePath = archivePath.substring(2);
File file = new File(archivePath).getCanonicalFile();
return file.toURI().toURL();
}
} catch (Exception e) {
// Swallow exception
}
}
return null;
}
}
|
URL[] urls = urlClassLoader.getURLs();
if (urls != null) {
for (URL url: urls) {
String fileName = url.getFile();
String checkedArchivePath = (fileName.endsWith("/") && !archivePath.endsWith("/")) ? (archivePath + "/") : archivePath;
if (fileName.endsWith(checkedArchivePath)) {
return archiveFilePathToURL(fileName);
}
}
}
return null;
| 671
| 129
| 800
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/WeldClassSignatureHelper.java
|
WeldClassSignatureHelper
|
getSignatureForProxyClass
|
class WeldClassSignatureHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(WeldClassSignatureHelper.class);
private static final ClassSignatureElement[] SIGNATURE_ELEM_PROXY = {
ClassSignatureElement.SUPER_CLASS,
ClassSignatureElement.INTERFACES,
ClassSignatureElement.CLASS_ANNOTATION,
ClassSignatureElement.CONSTRUCTOR,
ClassSignatureElement.METHOD,
ClassSignatureElement.METHOD_ANNOTATION,
ClassSignatureElement.METHOD_PARAM_ANNOTATION,
ClassSignatureElement.METHOD_EXCEPTION,
ClassSignatureElement.FIELD,
ClassSignatureElement.FIELD_ANNOTATION
};
private static final ClassSignatureElement[] SIGNATURE_ELEM_METHOD_FIELDS = {
ClassSignatureElement.SUPER_CLASS,
ClassSignatureElement.INTERFACES,
ClassSignatureElement.CLASS_ANNOTATION,
ClassSignatureElement.CONSTRUCTOR,
ClassSignatureElement.CONSTRUCTOR_PRIVATE, // private constructors are used if CONSTRUCTOR && CONSTRUCTOR_PRIVATE are set
ClassSignatureElement.METHOD,
ClassSignatureElement.METHOD_PRIVATE, // private methods are used if METHOD && METHOD_PRIVATE are set
ClassSignatureElement.METHOD_ANNOTATION, // applies to constructors as well
ClassSignatureElement.METHOD_PARAM_ANNOTATION, // applies to constructors as well
ClassSignatureElement.FIELD,
ClassSignatureElement.FIELD_ANNOTATION
};
private static final ClassSignatureElement[] SIGNATURE_ELEM_FIELDS = {
ClassSignatureElement.FIELD,
ClassSignatureElement.FIELD_ANNOTATION
};
/**
* Gets the class signature for proxy class comparison
*
* @param clazz the clazz for which signature is calculated
* @return the java class signature
*/
public static String getSignatureForProxyClass(Class<?> clazz) {<FILL_FUNCTION_BODY>}
/**
* Gets the signature by strategy.
*
* @param strategy the strategy
* @param clazz the clazz
* @return the signature by strategy
*/
public static String getSignatureByStrategy(BeanReloadStrategy strategy, Class<?> clazz) {
if (strategy == null) {
strategy = BeanReloadStrategy.NEVER;
}
switch (strategy) {
case CLASS_CHANGE :
return null;
case METHOD_FIELD_SIGNATURE_CHANGE :
return getClassMethodFieldsSignature(clazz);
case FIELD_SIGNATURE_CHANGE :
return getClassFieldsSignature(clazz);
default:
case NEVER:
return null;
}
}
private static String getClassMethodFieldsSignature(Class<?> clazz) {
try {
return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_METHOD_FIELDS);
} catch (Exception e) {
LOGGER.error("getSignatureForProxyClass(): Error reading signature", e);
return null;
}
}
private static String getClassFieldsSignature(Class<?> clazz) {
try {
return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_FIELDS);
} catch (Exception e) {
LOGGER.error("getSignatureForProxyClass(): Error reading signature", e);
return null;
}
}
}
|
try {
return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_PROXY);
} catch (Exception e) {
LOGGER.error("getSignatureForProxyClass(): Error reading signature", e);
return null;
}
| 877
| 71
| 948
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/beans/ContextualReloadHelper.java
|
ContextualReloadHelper
|
reinitialize
|
class ContextualReloadHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ContextualReloadHelper.class);
public static void reload(WeldHotswapContext ctx) {
Set<Contextual<Object>> beans = ctx.$$ha$getBeansToReloadWeld();
if (beans != null && !beans.isEmpty()) {
LOGGER.debug("Starting re-loading Contextuals in {}, {}", ctx, beans.size());
Iterator<Contextual<Object>> it = beans.iterator();
while (it.hasNext()) {
Contextual<Object> managedBean = it.next();
destroy(ctx, managedBean);
}
beans.clear();
LOGGER.debug("Finished re-loading Contextuals in {}", ctx);
}
}
/**
* Tries to add the bean in the context so it is reloaded in the next activation of the context.
*
* @param ctx
* @param managedBean
* @return
*/
public static boolean addToReloadSet(Context ctx, Contextual<Object> managedBean) {
try {
LOGGER.debug("Adding bean in '{}' : {}", ctx.getClass(), managedBean);
Field toRedefine = ctx.getClass().getDeclaredField("$$ha$toReloadWeld");
Set toReload = Set.class.cast(toRedefine.get(ctx));
if (toReload == null) {
toReload = new HashSet();
toRedefine.set(ctx, toReload);
}
toReload.add(managedBean);
return true;
} catch(Exception e) {
LOGGER.warning("Context {} is not patched. Can not add {} to reload set", e, ctx, managedBean);
}
return false;
}
/**
* Will remove bean from context forcing a clean new instance to be created (eg calling post-construct)
*
* @param ctx
* @param managedBean
*/
public static void destroy(WeldHotswapContext ctx, Contextual<?> managedBean ) {
try {
LOGGER.debug("Removing Contextual from Context........ {},: {}", managedBean, ctx);
Object get = ctx.get(managedBean);
if (get != null) {
ctx.destroy(managedBean);
}
get = ctx.get(managedBean);
if (get != null) {
LOGGER.error("Error removing ManagedBean {}, it still exists as instance {} ", managedBean, get);
ctx.destroy(managedBean);
}
} catch (Exception e) {
LOGGER.error("Error destoying bean {},: {}", e, managedBean, ctx);
}
}
/**
* Will re-inject any managed beans in the target. Will not call any other life-cycle methods
*
* @param ctx
* @param managedBean
*/
public static void reinitialize(Context ctx, Contextual<Object> contextual) {<FILL_FUNCTION_BODY>}
}
|
try {
ManagedBean<Object> managedBean = ManagedBean.class.cast(contextual);
LOGGER.debug("Re-Initializing........ {},: {}", managedBean, ctx);
Object get = ctx.get(managedBean);
if (get != null) {
LOGGER.debug("Bean injection points are reinitialized '{}'", managedBean);
managedBean.getProducer().inject(get, managedBean.getBeanManager().createCreationalContext(managedBean));
}
} catch (Exception e) {
LOGGER.error("Error reinitializing bean {},: {}", e, contextual, ctx);
}
| 776
| 162
| 938
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/command/BdaAgentRegistry.java
|
BdaAgentRegistry
|
getArchiveByClassName
|
class BdaAgentRegistry {
// map archive path -> BeanClassRefreshAgent
private static Map<String, BeanClassRefreshAgent> INSTANCES = new ConcurrentHashMap<>();
public static Map<String, BeanClassRefreshAgent> getInstances() {
return INSTANCES;
}
public static boolean contains(String archivePath) {
return INSTANCES.containsKey(archivePath);
}
public static void put(String archivePath, BeanClassRefreshAgent bdaAgent) {
INSTANCES.put(archivePath, bdaAgent);
}
public static BeanClassRefreshAgent get(String archivePath) {
return INSTANCES.get(archivePath);
}
public static Collection<BeanClassRefreshAgent> values() {
return INSTANCES.values();
}
/**
* Iterate over agents and find the one containing the class by name
*
* @param className
* @return
*/
public static String getArchiveByClassName(String className){<FILL_FUNCTION_BODY>}
}
|
for(BeanClassRefreshAgent agent: INSTANCES.values()) {
if(agent.getDeploymentArchive().getBeanClasses().contains(className)) {
return agent.getArchivePath();
}
}
return null;
| 288
| 65
| 353
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/command/ProxyClassLoadingDelegate.java
|
ProxyClassLoadingDelegate
|
toClassWeld3
|
class ProxyClassLoadingDelegate {
private static final ThreadLocal<Boolean> MAGIC_IN_PROGRESS = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
public static final void beginProxyRegeneration() {
MAGIC_IN_PROGRESS.set(true);
}
public static final void endProxyRegeneration() {
MAGIC_IN_PROGRESS.remove();
}
public static Class<?> loadClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException {
if (MAGIC_IN_PROGRESS.get()) {
throw new ClassNotFoundException("HotswapAgent");
}
return classLoader.loadClass(className);
}
public static Class<?> toClassWeld2(ClassFile ct, ClassLoader loader, ProtectionDomain domain) throws ClassNotFoundException {
if (MAGIC_IN_PROGRESS.get()) {
try {
final Class<?> originalProxyClass = loader.loadClass(ct.getName());
try {
Map<Class<?>, byte[]> reloadMap = new HashMap<>();
reloadMap.put(originalProxyClass, ct.toBytecode());
// TODO : is this standard way how to reload class?
PluginManager.getInstance().hotswap(reloadMap);
return originalProxyClass;
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException e) {
}
}
Class<?> classFileUtilsClass = Class.forName("org.jboss.weld.util.bytecode.ClassFileUtils", true, loader);
return (Class<?>) ReflectionHelper.invoke(null, classFileUtilsClass, "toClass",
new Class[] { ClassFile.class, ClassLoader.class, ProtectionDomain.class }, ct, loader, domain);
}
public static Class<?> toClassWeld3(Object proxyFactory, ClassFile ct, Class<?> originalClass, ProxyServices proxyServices, ProtectionDomain domain) {<FILL_FUNCTION_BODY>}
}
|
if (MAGIC_IN_PROGRESS.get()) {
try {
ClassLoader loader = originalClass.getClassLoader();
if (loader == null) {
loader = Thread.currentThread().getContextClassLoader();
}
final Class<?> originalProxyClass = loader.loadClass(ct.getName());
try {
Map<Class<?>, byte[]> reloadMap = new HashMap<>();
reloadMap.put(originalProxyClass, ct.toBytecode());
// TODO : is this standard way how to reload class?
PluginManager.getInstance().hotswap(reloadMap);
return originalProxyClass;
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException e) {
}
}
return (Class<?>) ReflectionHelper.invoke(proxyFactory, proxyFactory.getClass(), "$$ha$toClass",
new Class[] { ClassFile.class, Class.class, ProxyServices.class, ProtectionDomain.class }, ct, originalClass, proxyServices, domain);
| 545
| 272
| 817
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/AbstractClassBeanTransformer.java
|
AbstractClassBeanTransformer
|
transformAbstractClassBean
|
class AbstractClassBeanTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(AbstractClassBeanTransformer.class);
/**
*
* @param ctClass
* @param classPool
* @throws NotFoundException
* @throws CannotCompileException
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.AbstractClassBean")
public static void transformAbstractClassBean(CtClass ctClass, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
}
|
if (!HaCdiCommons.isJakarta(classPool)) {
return;
}
CtMethod method = ctClass.getDeclaredMethod("cleanupAfterBoot");
method.setBody("{ }");
LOGGER.debug("AbstractClassBean.cleanupAfterBoot patched");
| 148
| 79
| 227
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/BeanDeploymentArchiveTransformer.java
|
BeanDeploymentArchiveTransformer
|
transformJbossBda
|
class BeanDeploymentArchiveTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(BeanDeploymentArchiveTransformer.class);
/**
* Basic WeldBeanDeploymentArchive transformation.
*
* @param classPool the class pool
* @param clazz the clazz
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.environment.deployment.WeldBeanDeploymentArchive")
public static void transform(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {
if (!HaCdiCommons.isJakarta(classPool)) {
return;
}
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(WeldJakartaPlugin.class));
src.append(PluginManagerInvoker.buildCallPluginMethod(WeldJakartaPlugin.class, "init"));
src.append("org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent.registerArchive(getClass().getClassLoader(), this, null);");
src.append("}");
for (CtConstructor constructor : clazz.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
LOGGER.debug("Class '{}' patched with BDA registration.", clazz.getName());
}
/**
* JbossAS (Wildfly) BeanDeploymentArchiveImpl transformation.
*
* @param clazz
* @param classPool
* @throws NotFoundException
* @throws CannotCompileException
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl")
public static void transformJbossBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
/**
* GlassFish BeanDeploymentArchiveImpl transformation.
*
* @param classPool the class pool
* @param clazz the clazz
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.glassfish.weld.BeanDeploymentArchiveImpl")
public static void transformGlassFishBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {
if (!HaCdiCommons.isJakarta(classPool)) {
return;
}
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(WeldJakartaPlugin.class, "this.moduleClassLoaderForBDA"));
src.append(PluginManagerInvoker.buildCallPluginMethod("this.moduleClassLoaderForBDA", WeldJakartaPlugin.class, "initInGlassFish"));
src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, this.moduleClassLoaderForBDA);");
src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});");
src.append(" agM.invoke(null, new Object[] { this.moduleClassLoaderForBDA, this, null});");
src.append("}");
for (CtConstructor constructor : clazz.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration.");
}
}
|
if (!HaCdiCommons.isJakarta(classPool)) {
return;
}
StringBuilder src = new StringBuilder("{");
src.append("if (beansXml!=null && beanArchiveType!=null && (\"EXPLICIT\".equals(beanArchiveType.toString()) || \"IMPLICIT\".equals(beanArchiveType.toString()))){");
src.append(PluginManagerInvoker.buildInitializePlugin(WeldJakartaPlugin.class, "module.getClassLoader()"));
src.append(PluginManagerInvoker.buildCallPluginMethod("module.getClassLoader()", WeldJakartaPlugin.class, "initInJBossAS"));
src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, module.getClassLoader());");
src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});");
src.append(" agM.invoke(null, new Object[] { module.getClassLoader(),this, beanArchiveType.toString()});");
src.append("}}");
for (CtConstructor constructor : clazz.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration.");
| 1,011
| 412
| 1,423
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/CdiContextsTransformer.java
|
CdiContextsTransformer
|
transformReloadingWeldContexts
|
class CdiContextsTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(CdiContextsTransformer.class);
public static final String BOUND_SESSION_BEAN_STORE_REGISTRY = "$$ha$boundSessionBeanStoreRegistry";
/**
* Add context reloading functionality to base contexts classes.
*
* @param classPool the class pool
* @param ctClass the class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "(org.jboss.weld.context.AbstractManagedContext)|" +
"(org.jboss.weld.context.AbstractSharedContext)|" +
"(org.jboss.weld.context.unbound.DependentContextImpl)|" +
"(org.jboss.weld.util.ForwardingContext)|" +
"(org.apache.myfaces.flow.cdi.FlowScopedContextImpl)|" +
"(org.apache.myfaces.cdi.view.ViewScopeContextImpl)"
)
public static void transformReloadingWeldContexts(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
/**
* Add custom tracker field to session context
*
* @param classPool the class pool
* @param ctClass the class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.context.AbstractContext")
public static void transformHttpSessionContext(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
if (!HaCdiCommons.isJakarta(classPool)) {
return;
}
HaCdiCommons.transformContext(classPool, ctClass);
}
}
|
if (!HaCdiCommons.isJakarta(classPool)) {
return;
}
LOGGER.debug("Adding interface {} to {}.", WeldHotswapContext.class.getName(), ctClass.getName());
ctClass.addInterface(classPool.get(WeldHotswapContext.class.getName()));
CtField toReloadFld = CtField.make("public transient java.util.Set $$ha$toReloadWeld = null;", ctClass);
ctClass.addField(toReloadFld);
CtField reloadingFld = CtField.make("public transient boolean $$ha$reloadingWeld = false;", ctClass);
ctClass.addField(reloadingFld);
CtMethod addBeanToReload = CtMethod.make(
"public void $$ha$addBeanToReloadWeld(jakarta.enterprise.context.spi.Contextual bean) {" +
"if ($$ha$toReloadWeld == null)" +
"$$ha$toReloadWeld = new java.util.HashSet();" +
"$$ha$toReloadWeld.add(bean);" +
"}",
ctClass
);
ctClass.addMethod(addBeanToReload);
CtMethod getBeansToReload = CtMethod.make("public java.util.Set $$ha$getBeansToReloadWeld(){return $$ha$toReloadWeld;}", ctClass);
ctClass.addMethod(getBeansToReload);
CtMethod reload = CtMethod.make("public void $$ha$reloadWeld() {" + ContextualReloadHelper.class.getName() +".reload(this);}", ctClass);
ctClass.addMethod(reload);
CtMethod isActive = ctClass.getDeclaredMethod("isActive");
isActive.insertAfter(
"{" +
"if($_ && !$$ha$reloadingWeld ) { " +
"$$ha$reloadingWeld = true;" +
"$$ha$reloadWeld();" +
"$$ha$reloadingWeld = false;" +
"}" +
"return $_;" +
"}"
);
LOGGER.debug("Class '{}' patched with hot-swapping support", ctClass.getName() );
| 514
| 604
| 1,118
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/ProxyFactoryTransformer.java
|
ProxyFactoryTransformer
|
edit
|
class ProxyFactoryTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyFactoryTransformer.class);
/**
* Patch ProxyFactory class.
* - add factory registration into constructor
* - changes call classLoader.loadClass(...) in getProxyClass() to ProxyClassLoadingDelegate.loadClass(classLoader, ...)
* - changes call ClassFileUtils.toClass() in createProxyClass() to ProxyClassLoadingDelegate.loadClass(...)
*
* @param classPool the class pool
* @param ctClass the ProxyFactory class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.proxy.ProxyFactory")
public static void patchProxyFactory(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
if (!HaCdiCommons.isJakarta(classPool)) {
return;
}
CtClass[] constructorParams = new CtClass[] {
classPool.get("java.lang.String"),
classPool.get("java.lang.Class"),
classPool.get("java.util.Set"),
//classPool.get("java.lang.String"),
classPool.get("jakarta.enterprise.inject.spi.Bean"),
classPool.get("boolean")
};
CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(constructorParams);
// TODO : we should find constructor without this() call and put registration only into this one
declaredConstructor.insertAfter("{" +
"java.lang.Class originalClass = (this.bean != null) ? this.bean.getBeanClass() : this.proxiedBeanType;" +
"java.lang.ClassLoader loader = originalClass.getClassLoader();" +
"if (loader==null) {"+
"loader = Thread.currentThread().getContextClassLoader();" +
"}" +
"if (" + PluginManager.class.getName() + ".getInstance().isPluginInitialized(\"" + WeldJakartaPlugin.class.getName() + "\", loader)) {" +
PluginManagerInvoker.buildCallPluginMethod("loader", WeldJakartaPlugin.class, "registerProxyFactory",
"this", "java.lang.Object",
"bean", "java.lang.Object",
"loader", "java.lang.ClassLoader",
"proxiedBeanType", "java.lang.Class"
) +
"}" +
"}");
try {
// Weld 3
CtMethod oldMethod = ctClass.getDeclaredMethod("toClass");
oldMethod.setName("$$ha$toClass"); // TODO: use another convention for renamed?
oldMethod.setModifiers(Modifier.PUBLIC);
CtMethod newMethod = CtNewMethod.make(
"protected java.lang.Class toClass(org.jboss.classfilewriter.ClassFile ct, java.lang.Class originalClass, " +
"org.jboss.weld.serialization.spi.ProxyServices proxyServices, java.security.ProtectionDomain domain) {" +
"return org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld3(this, ct, originalClass, proxyServices, domain);" +
"}", ctClass);
ctClass.addMethod(newMethod);
} catch (NotFoundException e) {
// Weld 2
CtMethod getProxyClassMethod = ctClass.getDeclaredMethod("getProxyClass");
getProxyClassMethod.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {
if (m.getClassName().equals(ClassLoader.class.getName()) && m.getMethodName().equals("loadClass"))
m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.loadClass(this.classLoader,$1); }");
}
});
CtMethod createProxyClassMethod = ctClass.getDeclaredMethod("createProxyClass");
createProxyClassMethod.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {<FILL_FUNCTION_BODY>}
}
);
}
}
}
|
// Patch Weld2
if (m.getClassName().equals("org.jboss.weld.util.bytecode.ClassFileUtils") && m.getMethodName().equals("toClass"))
try {
if (m.getMethod().getParameterTypes().length == 3) {
m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld2($$); }");
} else if (m.getMethod().getParameterTypes().length == 4) {
LOGGER.debug("Proxy factory patch for delegating method skipped.", m.getClassName(), m.getMethodName());
} else {
LOGGER.error("Method '{}.{}' patch failed. Unknown method arguments.", m.getClassName(), m.getMethodName());
}
} catch (NotFoundException e) {
LOGGER.error("Method '{}' not found in '{}'.", m.getMethodName(), m.getClassName());
}
| 1,111
| 247
| 1,358
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/ArchivePathHelper.java
|
ArchivePathHelper
|
getNormalizedArchivePath
|
class ArchivePathHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ArchivePathHelper.class);
public static String getNormalizedArchivePath(CtClass ctClass) throws NotFoundException {
String classFilePath = ctClass.getURL().getFile();
String className = ctClass.getName().replace(".", "/");
// archive path ends with '/' therefore we set end position before the '/' (-1)
return classFilePath.substring(0, classFilePath.indexOf(className) - 1);
}
/**
* Method resolves archive path from BdaId
*
* @param classLoader the class loader
* @param archiveId the archive id
* @return the normalized archive path
*/
public static String getNormalizedArchivePath(ClassLoader classLoader, String archiveId) {<FILL_FUNCTION_BODY>}
private static URL archivePathToURL(ClassLoader classLoader, String archiveId) {
URL result = archiveFilePathToURL(archiveId);
if (result == null) {
// File doesn't exists, try to resolve it using appClassLoader
if (classLoader instanceof URLClassLoader) {
result = archivePathToURLViaURLClassLoader((URLClassLoader) classLoader, archiveId);
}
}
return result;
}
private static URL archivePathToURLViaURLClassLoader(URLClassLoader urlClassLoader, String archivePath) {
URL[] urls = urlClassLoader.getURLs();
if (urls != null) {
for (URL url: urls) {
String fileName = url.getFile();
String checkedArchivePath = (fileName.endsWith("/") && !archivePath.endsWith("/")) ? (archivePath + "/") : archivePath;
if (fileName.endsWith(checkedArchivePath)) {
return archiveFilePathToURL(fileName);
}
}
}
return null;
}
private static URL archiveFilePathToURL(String archivePath) {
File f = new File(archivePath);
if (f.exists()) {
try {
try {
// Try to format as a URL?
return f.toURI().toURL();
} catch (MalformedURLException e) {
// try to locate a file
if (archivePath.startsWith("./"))
archivePath = archivePath.substring(2);
File file = new File(archivePath).getCanonicalFile();
return file.toURI().toURL();
}
} catch (Exception e) {
// Swallow exception
}
}
return null;
}
}
|
URL archiveURL = archivePathToURL(classLoader, archiveId);
if (archiveURL != null) {
try {
String result = archiveURL.getFile();
// Strip trailing "/" from normalized archive path
while (result.endsWith("/")) {
result = result.substring(0, result.length() -1);
}
return result;
} catch (Exception e) {
LOGGER.error("getNormalizedArchivePath() exception {}.", e.getMessage());
}
}
return null;
| 663
| 137
| 800
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/WeldClassSignatureHelper.java
|
WeldClassSignatureHelper
|
getSignatureByStrategy
|
class WeldClassSignatureHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(WeldClassSignatureHelper.class);
private static final ClassSignatureElement[] SIGNATURE_ELEM_PROXY = {
ClassSignatureElement.SUPER_CLASS,
ClassSignatureElement.INTERFACES,
ClassSignatureElement.CLASS_ANNOTATION,
ClassSignatureElement.CONSTRUCTOR,
ClassSignatureElement.METHOD,
ClassSignatureElement.METHOD_ANNOTATION,
ClassSignatureElement.METHOD_PARAM_ANNOTATION,
ClassSignatureElement.METHOD_EXCEPTION,
ClassSignatureElement.FIELD,
ClassSignatureElement.FIELD_ANNOTATION
};
private static final ClassSignatureElement[] SIGNATURE_ELEM_METHOD_FIELDS = {
ClassSignatureElement.SUPER_CLASS,
ClassSignatureElement.INTERFACES,
ClassSignatureElement.CLASS_ANNOTATION,
ClassSignatureElement.CONSTRUCTOR,
ClassSignatureElement.CONSTRUCTOR_PRIVATE, // private constructors are used if CONSTRUCTOR && CONSTRUCTOR_PRIVATE are set
ClassSignatureElement.METHOD,
ClassSignatureElement.METHOD_PRIVATE, // private methods are used if METHOD && METHOD_PRIVATE are set
ClassSignatureElement.METHOD_ANNOTATION, // applies to constructors as well
ClassSignatureElement.METHOD_PARAM_ANNOTATION, // applies to constructors as well
ClassSignatureElement.FIELD,
ClassSignatureElement.FIELD_ANNOTATION
};
private static final ClassSignatureElement[] SIGNATURE_ELEM_FIELDS = {
ClassSignatureElement.FIELD,
ClassSignatureElement.FIELD_ANNOTATION
};
/**
* Gets the class signature for proxy class comparison
*
* @param clazz the clazz for which signature is calculated
* @return the java class signature
*/
public static String getSignatureForProxyClass(Class<?> clazz) {
try {
return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_PROXY);
} catch (Exception e) {
LOGGER.error("getSignatureForProxyClass(): Error reading signature", e);
return null;
}
}
/**
* Gets the signature by strategy.
*
* @param strategy the strategy
* @param clazz the clazz
* @return the signature by strategy
*/
public static String getSignatureByStrategy(BeanReloadStrategy strategy, Class<?> clazz) {<FILL_FUNCTION_BODY>}
private static String getClassMethodFieldsSignature(Class<?> clazz) {
try {
return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_METHOD_FIELDS);
} catch (Exception e) {
LOGGER.error("getSignatureForProxyClass(): Error reading signature", e);
return null;
}
}
private static String getClassFieldsSignature(Class<?> clazz) {
try {
return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_FIELDS);
} catch (Exception e) {
LOGGER.error("getSignatureForProxyClass(): Error reading signature", e);
return null;
}
}
}
|
if (strategy == null) {
strategy = BeanReloadStrategy.NEVER;
}
switch (strategy) {
case CLASS_CHANGE :
return null;
case METHOD_FIELD_SIGNATURE_CHANGE :
return getClassMethodFieldsSignature(clazz);
case FIELD_SIGNATURE_CHANGE :
return getClassFieldsSignature(clazz);
default:
case NEVER:
return null;
}
| 829
| 119
| 948
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/beans/ContextualReloadHelper.java
|
ContextualReloadHelper
|
addToReloadSet
|
class ContextualReloadHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ContextualReloadHelper.class);
public static void reload(WeldHotswapContext ctx) {
Set<Contextual<Object>> beans = ctx.$$ha$getBeansToReloadWeld();
if (beans != null && !beans.isEmpty()) {
LOGGER.debug("Starting re-loading Contextuals in {}, {}", ctx, beans.size());
Iterator<Contextual<Object>> it = beans.iterator();
while (it.hasNext()) {
Contextual<Object> managedBean = it.next();
destroy(ctx, managedBean);
}
beans.clear();
LOGGER.debug("Finished re-loading Contextuals in {}", ctx);
}
}
/**
* Tries to add the bean in the context so it is reloaded in the next activation of the context.
*
* @param ctx
* @param managedBean
* @return
*/
public static boolean addToReloadSet(Context ctx, Contextual<Object> managedBean) {<FILL_FUNCTION_BODY>}
/**
* Will remove bean from context forcing a clean new instance to be created (eg calling post-construct)
*
* @param ctx
* @param managedBean
*/
public static void destroy(WeldHotswapContext ctx, Contextual<?> managedBean ) {
try {
LOGGER.debug("Removing Contextual from Context........ {},: {}", managedBean, ctx);
Object get = ctx.get(managedBean);
if (get != null) {
ctx.destroy(managedBean);
}
get = ctx.get(managedBean);
if (get != null) {
LOGGER.error("Error removing ManagedBean {}, it still exists as instance {} ", managedBean, get);
ctx.destroy(managedBean);
}
} catch (Exception e) {
LOGGER.error("Error destoying bean {},: {}", e, managedBean, ctx);
}
}
/**
* Will re-inject any managed beans in the target. Will not call any other life-cycle methods
*
* @param ctx
* @param managedBean
*/
public static void reinitialize(Context ctx, Contextual<Object> contextual) {
try {
ManagedBean<Object> managedBean = ManagedBean.class.cast(contextual);
LOGGER.debug("Re-Initializing........ {},: {}", managedBean, ctx);
Object get = ctx.get(managedBean);
if (get != null) {
LOGGER.debug("Bean injection points are reinitialized '{}'", managedBean);
managedBean.getProducer().inject(get, managedBean.getBeanManager().createCreationalContext(managedBean));
}
} catch (Exception e) {
LOGGER.error("Error reinitializing bean {},: {}", e, contextual, ctx);
}
}
}
|
try {
LOGGER.debug("Adding bean in '{}' : {}", ctx.getClass(), managedBean);
Field toRedefine = ctx.getClass().getDeclaredField("$$ha$toReloadWeld");
Set toReload = Set.class.cast(toRedefine.get(ctx));
if (toReload == null) {
toReload = new HashSet();
toRedefine.set(ctx, toReload);
}
toReload.add(managedBean);
return true;
} catch(Exception e) {
LOGGER.warning("Context {} is not patched. Can not add {} to reload set", e, ctx, managedBean);
}
return false;
| 754
| 184
| 938
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/command/BdaAgentRegistry.java
|
BdaAgentRegistry
|
getArchiveByClassName
|
class BdaAgentRegistry {
// map archive path -> BeanClassRefreshAgent
private static Map<String, BeanClassRefreshAgent> INSTANCES = new ConcurrentHashMap<>();
public static Map<String, BeanClassRefreshAgent> getInstances() {
return INSTANCES;
}
public static boolean contains(String archivePath) {
return INSTANCES.containsKey(archivePath);
}
public static void put(String archivePath, BeanClassRefreshAgent bdaAgent) {
INSTANCES.put(archivePath, bdaAgent);
}
public static BeanClassRefreshAgent get(String archivePath) {
return INSTANCES.get(archivePath);
}
public static Collection<BeanClassRefreshAgent> values() {
return INSTANCES.values();
}
/**
* Iterate over agents and find the one containing the class by name
*
* @param className
* @return
*/
public static String getArchiveByClassName(String className){<FILL_FUNCTION_BODY>}
}
|
for(BeanClassRefreshAgent agent: INSTANCES.values()) {
if(agent.getDeploymentArchive().getBeanClasses().contains(className)) {
return agent.getArchivePath();
}
}
return null;
| 288
| 65
| 353
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/command/ProxyClassLoadingDelegate.java
|
ProxyClassLoadingDelegate
|
toClassWeld2
|
class ProxyClassLoadingDelegate {
private static final ThreadLocal<Boolean> MAGIC_IN_PROGRESS = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
public static final void beginProxyRegeneration() {
MAGIC_IN_PROGRESS.set(true);
}
public static final void endProxyRegeneration() {
MAGIC_IN_PROGRESS.remove();
}
public static Class<?> loadClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException {
if (MAGIC_IN_PROGRESS.get()) {
throw new ClassNotFoundException("HotswapAgent");
}
return classLoader.loadClass(className);
}
public static Class<?> toClassWeld2(ClassFile ct, ClassLoader loader, ProtectionDomain domain) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
public static Class<?> toClassWeld3(Object proxyFactory, ClassFile ct, Class<?> originalClass, ProxyServices proxyServices, ProtectionDomain domain) {
if (MAGIC_IN_PROGRESS.get()) {
try {
ClassLoader loader = originalClass.getClassLoader();
if (loader == null) {
loader = Thread.currentThread().getContextClassLoader();
}
final Class<?> originalProxyClass = loader.loadClass(ct.getName());
try {
Map<Class<?>, byte[]> reloadMap = new HashMap<>();
reloadMap.put(originalProxyClass, ct.toBytecode());
// TODO : is this standard way how to reload class?
PluginManager.getInstance().hotswap(reloadMap);
return originalProxyClass;
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException e) {
}
}
return (Class<?>) ReflectionHelper.invoke(proxyFactory, proxyFactory.getClass(), "$$ha$toClass",
new Class[] { ClassFile.class, Class.class, ProxyServices.class, ProtectionDomain.class }, ct, originalClass, proxyServices, domain);
}
}
|
if (MAGIC_IN_PROGRESS.get()) {
try {
final Class<?> originalProxyClass = loader.loadClass(ct.getName());
try {
Map<Class<?>, byte[]> reloadMap = new HashMap<>();
reloadMap.put(originalProxyClass, ct.toBytecode());
// TODO : is this standard way how to reload class?
PluginManager.getInstance().hotswap(reloadMap);
return originalProxyClass;
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException e) {
}
}
Class<?> classFileUtilsClass = Class.forName("org.jboss.weld.util.bytecode.ClassFileUtils", true, loader);
return (Class<?>) ReflectionHelper.invoke(null, classFileUtilsClass, "toClass",
new Class[] { ClassFile.class, ClassLoader.class, ProtectionDomain.class }, ct, loader, domain);
| 561
| 256
| 817
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/AbstractClassBeanTransformer.java
|
AbstractClassBeanTransformer
|
transformAbstractClassBean
|
class AbstractClassBeanTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(AbstractClassBeanTransformer.class);
/**
*
* @param ctClass
* @param classPool
* @throws NotFoundException
* @throws CannotCompileException
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.AbstractClassBean")
public static void transformAbstractClassBean(CtClass ctClass, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
}
|
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
CtMethod method = ctClass.getDeclaredMethod("cleanupAfterBoot");
method.setBody("{ }");
LOGGER.debug("AbstractClassBean.cleanupAfterBoot patched");
| 148
| 79
| 227
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/BeanDeploymentArchiveTransformer.java
|
BeanDeploymentArchiveTransformer
|
transform
|
class BeanDeploymentArchiveTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(BeanDeploymentArchiveTransformer.class);
/**
* Basic WeldBeanDeploymentArchive transformation.
*
* @param classPool the class pool
* @param clazz the clazz
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.environment.deployment.WeldBeanDeploymentArchive")
public static void transform(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
/**
* JbossAS (Wildfly) BeanDeploymentArchiveImpl transformation.
*
* @param clazz
* @param classPool
* @throws NotFoundException
* @throws CannotCompileException
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl")
public static void transformJbossBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
StringBuilder src = new StringBuilder("{");
src.append("if (beansXml!=null && beanArchiveType!=null && (\"EXPLICIT\".equals(beanArchiveType.toString()) || \"IMPLICIT\".equals(beanArchiveType.toString()))){");
src.append(PluginManagerInvoker.buildInitializePlugin(WeldPlugin.class, "module.getClassLoader()"));
src.append(PluginManagerInvoker.buildCallPluginMethod("module.getClassLoader()", WeldPlugin.class, "initInJBossAS"));
src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, module.getClassLoader());");
src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});");
src.append(" agM.invoke(null, new Object[] { module.getClassLoader(),this, beanArchiveType.toString()});");
src.append("}}");
for (CtConstructor constructor : clazz.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration.");
}
/**
* GlassFish BeanDeploymentArchiveImpl transformation.
*
* @param classPool the class pool
* @param clazz the clazz
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.glassfish.weld.BeanDeploymentArchiveImpl")
public static void transformGlassFishBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(WeldPlugin.class, "this.moduleClassLoaderForBDA"));
src.append(PluginManagerInvoker.buildCallPluginMethod("this.moduleClassLoaderForBDA", WeldPlugin.class, "initInGlassFish"));
src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, this.moduleClassLoaderForBDA);");
src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});");
src.append(" agM.invoke(null, new Object[] { this.moduleClassLoaderForBDA, this, null});");
src.append("}");
for (CtConstructor constructor : clazz.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration.");
}
}
|
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(WeldPlugin.class));
src.append(PluginManagerInvoker.buildCallPluginMethod(WeldPlugin.class, "init"));
src.append("org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent.registerArchive(getClass().getClassLoader(), this, null);");
src.append("}");
for (CtConstructor constructor : clazz.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
LOGGER.debug("Class '{}' patched with BDA registration.", clazz.getName());
| 1,200
| 199
| 1,399
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/CdiContextsTransformer.java
|
CdiContextsTransformer
|
transformReloadingWeldContexts
|
class CdiContextsTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(CdiContextsTransformer.class);
public static final String BOUND_SESSION_BEAN_STORE_REGISTRY = "$$ha$boundSessionBeanStoreRegistry";
/**
* Add context reloading functionality to base contexts classes.
*
* @param classPool the class pool
* @param ctClass the class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "(org.jboss.weld.context.AbstractManagedContext)|" +
"(org.jboss.weld.context.AbstractSharedContext)|" +
"(org.jboss.weld.context.unbound.DependentContextImpl)|" +
"(org.jboss.weld.util.ForwardingContext)|" +
"(org.apache.myfaces.flow.cdi.FlowScopedContextImpl)|" +
"(org.apache.myfaces.cdi.view.ViewScopeContextImpl)"
)
public static void transformReloadingWeldContexts(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
/**
* Add custom tracker field to session context
*
* @param classPool the class pool
* @param ctClass the class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.context.AbstractContext")
public static void transformHttpSessionContext(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
HaCdiCommons.transformContext(classPool, ctClass);
}
}
|
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
LOGGER.debug("Adding interface {} to {}.", WeldHotswapContext.class.getName(), ctClass.getName());
ctClass.addInterface(classPool.get(WeldHotswapContext.class.getName()));
CtField toReloadFld = CtField.make("public transient java.util.Set $$ha$toReloadWeld = null;", ctClass);
ctClass.addField(toReloadFld);
CtField reloadingFld = CtField.make("public transient boolean $$ha$reloadingWeld = false;", ctClass);
ctClass.addField(reloadingFld);
CtMethod addBeanToReload = CtMethod.make(
"public void $$ha$addBeanToReloadWeld(javax.enterprise.context.spi.Contextual bean) {" +
"if ($$ha$toReloadWeld == null)" +
"$$ha$toReloadWeld = new java.util.HashSet();" +
"$$ha$toReloadWeld.add(bean);" +
"}",
ctClass
);
ctClass.addMethod(addBeanToReload);
CtMethod getBeansToReload = CtMethod.make("public java.util.Set $$ha$getBeansToReloadWeld(){return $$ha$toReloadWeld;}", ctClass);
ctClass.addMethod(getBeansToReload);
CtMethod reload = CtMethod.make("public void $$ha$reloadWeld() {" + ContextualReloadHelper.class.getName() +".reload(this);}", ctClass);
ctClass.addMethod(reload);
CtMethod isActive = ctClass.getDeclaredMethod("isActive");
isActive.insertAfter(
"{" +
"if($_ && !$$ha$reloadingWeld ) { " +
"$$ha$reloadingWeld = true;" +
"$$ha$reloadWeld();" +
"$$ha$reloadingWeld = false;" +
"}" +
"return $_;" +
"}"
);
LOGGER.debug("Class '{}' patched with hot-swapping support", ctClass.getName() );
| 514
| 602
| 1,116
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/ProxyFactoryTransformer.java
|
ProxyFactoryTransformer
|
patchProxyFactory
|
class ProxyFactoryTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyFactoryTransformer.class);
/**
* Patch ProxyFactory class.
* - add factory registration into constructor
* - changes call classLoader.loadClass(...) in getProxyClass() to ProxyClassLoadingDelegate.loadClass(classLoader, ...)
* - changes call ClassFileUtils.toClass() in createProxyClass() to ProxyClassLoadingDelegate.loadClass(...)
*
* @param classPool the class pool
* @param ctClass the ProxyFactory class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.proxy.ProxyFactory")
public static void patchProxyFactory(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
}
|
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
CtClass[] constructorParams = new CtClass[] {
classPool.get("java.lang.String"),
classPool.get("java.lang.Class"),
classPool.get("java.util.Set"),
//classPool.get("java.lang.String"),
classPool.get("javax.enterprise.inject.spi.Bean"),
classPool.get("boolean")
};
CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(constructorParams);
// TODO : we should find constructor without this() call and put registration only into this one
declaredConstructor.insertAfter("{" +
"java.lang.Class originalClass = (this.bean != null) ? this.bean.getBeanClass() : this.proxiedBeanType;" +
"java.lang.ClassLoader loader = originalClass.getClassLoader();" +
"if (loader==null) {"+
"loader = Thread.currentThread().getContextClassLoader();" +
"}" +
"if (" + PluginManager.class.getName() + ".getInstance().isPluginInitialized(\"" + WeldPlugin.class.getName() + "\", loader)) {" +
PluginManagerInvoker.buildCallPluginMethod("loader", WeldPlugin.class, "registerProxyFactory",
"this", "java.lang.Object",
"bean", "java.lang.Object",
"loader", "java.lang.ClassLoader",
"proxiedBeanType", "java.lang.Class"
) +
"}" +
"}");
try {
// Weld 3
CtMethod oldMethod = ctClass.getDeclaredMethod("toClass");
oldMethod.setName("$$ha$toClass"); // TODO: use another convention for renamed?
oldMethod.setModifiers(Modifier.PUBLIC);
CtMethod newMethod = CtNewMethod.make(
"protected java.lang.Class toClass(org.jboss.classfilewriter.ClassFile ct, java.lang.Class originalClass, " +
"org.jboss.weld.serialization.spi.ProxyServices proxyServices, java.security.ProtectionDomain domain) {" +
"return org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld3(this, ct, originalClass, proxyServices, domain);" +
"}", ctClass);
ctClass.addMethod(newMethod);
} catch (NotFoundException e) {
// Weld 2
CtMethod getProxyClassMethod = ctClass.getDeclaredMethod("getProxyClass");
getProxyClassMethod.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {
if (m.getClassName().equals(ClassLoader.class.getName()) && m.getMethodName().equals("loadClass"))
m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.loadClass(this.classLoader,$1); }");
}
});
CtMethod createProxyClassMethod = ctClass.getDeclaredMethod("createProxyClass");
createProxyClassMethod.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {
// Patch Weld2
if (m.getClassName().equals("org.jboss.weld.util.bytecode.ClassFileUtils") && m.getMethodName().equals("toClass"))
try {
if (m.getMethod().getParameterTypes().length == 3) {
m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld2($$); }");
} else if (m.getMethod().getParameterTypes().length == 4) {
LOGGER.debug("Proxy factory patch for delegating method skipped.", m.getClassName(), m.getMethodName());
} else {
LOGGER.error("Method '{}.{}' patch failed. Unknown method arguments.", m.getClassName(), m.getMethodName());
}
} catch (NotFoundException e) {
LOGGER.error("Method '{}' not found in '{}'.", m.getMethodName(), m.getClassName());
}
}
}
);
}
| 247
| 1,101
| 1,348
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-wicket-plugin/src/main/java/org/hotswap/agent/plugin/wicket/WicketPlugin.java
|
WicketPlugin
|
clearCache
|
class WicketPlugin {
private static final String WICKET_APPLICATION = "org.apache.wicket.protocol.http.WebApplication";
private static final AgentLogger LOGGER = AgentLogger.getLogger(WicketPlugin.class);
@Init
Scheduler scheduler;
@Init
ClassLoader appClassLoader;
private Object wicketApplication;
@OnClassLoadEvent(classNameRegexp = WICKET_APPLICATION)
public static void init(CtClass ctClass) throws NotFoundException, CannotCompileException {
String src = PluginManagerInvoker
.buildInitializePlugin(WicketPlugin.class);
src += PluginManagerInvoker.buildCallPluginMethod(WicketPlugin.class,
"registerApplication", "this", "java.lang.Object");
ctClass.getDeclaredConstructor(new CtClass[0]).insertAfter(src);
LOGGER.info("Wicket application has been enhanced.");
}
public void registerApplication(Object wicketApplication) {
this.wicketApplication = wicketApplication;
LOGGER.info("Plugin {} initialized for application {}", getClass(),
wicketApplication);
}
@OnResourceFileEvent(path = "/", filter = ".*.properties")
public void clearLocalizerCaches() {
scheduler.scheduleCommand(this::clearCache);
}
private void clearCache() {<FILL_FUNCTION_BODY>}
private Object getLocalizer() {
try {
final Method getResourceSettingsMethod = resolveClass("org.apache.wicket.Application")
.getDeclaredMethod("getResourceSettings");
final Method getLocalizerMethod = resolveClass("org.apache.wicket.settings.ResourceSettings")
.getDeclaredMethod("getLocalizer");
final Object resourceSettings = getResourceSettingsMethod.invoke(wicketApplication);
return getLocalizerMethod.invoke(resourceSettings);
} catch (Exception e) {
LOGGER.error("Error getting Wicket localizer", e);
return null;
}
}
private Class<?> resolveClass(String name) throws ClassNotFoundException {
return Class.forName(name, true, appClassLoader);
}
}
|
LOGGER.debug("Refreshing Wicket localizer cache.");
try {
final Object localizer = getLocalizer();
final Method clearCacheMethod = resolveClass("org.apache.wicket.Localizer")
.getDeclaredMethod("clearCache");
clearCacheMethod.invoke(localizer);
} catch (Exception e) {
LOGGER.error("Error refreshing Wicket localizer cache", e);
}
| 555
| 106
| 661
|
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-wildfly-el-plugin/src/main/java/org/hotswap/agent/plugin/wildfly/el/PurgeWildFlyBeanELResolverCacheCommand.java
|
PurgeWildFlyBeanELResolverCacheCommand
|
executeCommand
|
class PurgeWildFlyBeanELResolverCacheCommand extends MergeableCommand {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(PurgeWildFlyBeanELResolverCacheCommand.class);
/** The app class loader. */
private ClassLoader appClassLoader;
/** The class name. */
private String className;
/**
* Instantiates a new purge wild fly bean el resolver cache command.
*
* @param appClassLoader the app class loader
* @param className the class name
*/
public PurgeWildFlyBeanELResolverCacheCommand(ClassLoader appClassLoader, String className) {
this.appClassLoader = appClassLoader;
this.className = className;
}
/* (non-Javadoc)
* @see org.hotswap.agent.command.Command#executeCommand()
*/
@Override
public void executeCommand() {<FILL_FUNCTION_BODY>}
/**
* Resolve class.
*
* @param name the name
* @return the class
* @throws ClassNotFoundException the class not found exception
*/
private Class<?> resolveClass(String name) throws ClassNotFoundException {
return Class.forName(name, true, appClassLoader);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PurgeWildFlyBeanELResolverCacheCommand that = (PurgeWildFlyBeanELResolverCacheCommand) o;
if (!appClassLoader.equals(that.appClassLoader))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int result = appClassLoader.hashCode();
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "PurgeWildFlyBeanELResolverCacheCommand{" + "appClassLoader=" + appClassLoader + '}';
}
}
|
LOGGER.info("Cleaning BeanPropertiesCache {} {}.", className, appClassLoader);
if (className != null) {
try {
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(appClassLoader);
Class<?> cacheClazz = Class.forName("org.jboss.el.cache.BeanPropertiesCache", true, appClassLoader);
Method beanElResolverMethod = cacheClazz.getDeclaredMethod("getProperties", new Class<?>[] {});
Object o = beanElResolverMethod.invoke(null);
@SuppressWarnings("unchecked")
Map<Class<?>, Object> m = Map.class.cast(o);
Iterator<Map.Entry<Class<?>, Object>> it = m.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Class<?>, Object> entry = it.next();
if(entry.getKey().getClassLoader() == appClassLoader) {
if (entry.getKey().getName().equals(className) || (entry.getKey().getName()).equals(className + "$Proxy$_$$_WeldSubclass")) {
it.remove();
}
}
}
} finally {
Thread.currentThread().setContextClassLoader(oldContextClassLoader);
}
} catch (Exception e) {
LOGGER.error("Error cleaning BeanPropertiesCache. {}", e, className);
}
} else {
try {
LOGGER.info("Cleaning BeanPropertiesCache {}.", appClassLoader);
Method beanElResolverMethod = resolveClass("org.jboss.el.cache.BeanPropertiesCache").getDeclaredMethod("clear", ClassLoader.class);
beanElResolverMethod.setAccessible(true);
beanElResolverMethod.invoke(null, appClassLoader);
} catch (Exception e) {
LOGGER.error("Error cleaning BeanPropertiesCache. {}", e, appClassLoader);
}
try {
LOGGER.info("Cleaning FactoryFinderCache {}.", appClassLoader);
Method beanElResolverMethod = resolveClass("org.jboss.el.cache.FactoryFinderCache").getDeclaredMethod("clearClassLoader", ClassLoader.class);
beanElResolverMethod.setAccessible(true);
beanElResolverMethod.invoke(null, appClassLoader);
} catch (Exception e) {
LOGGER.error("Error cleaning FactoryFinderCache. {}", e, appClassLoader);
}
}
| 612
| 633
| 1,245
|
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-wildfly-el-plugin/src/main/java/org/hotswap/agent/plugin/wildfly/el/WildFlyELResolverPlugin.java
|
WildFlyELResolverPlugin
|
beanELResolverRegisterVariable
|
class WildFlyELResolverPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(WildFlyELResolverPlugin.class);
public static final String PURGE_CLASS_CACHE_METHOD_NAME = "$$ha$resetCache";
@Init
Scheduler scheduler;
@Init
ClassLoader appClassLoader;
/**
* Hook on BeanELResolver class and for each instance: - ensure plugin is
* initialized - register instances using registerBeanELResolver() method.
*
* @param ctClass
* the ct class
* @param classPool
* the class pool
* @throws CannotCompileException
* the cannot compile exception
* @throws NotFoundException
* the not found exception
*/
@OnClassLoadEvent(classNameRegexp = "javax.el.BeanELResolver")
public static void beanELResolverRegisterVariable(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>}
/**
* Hook on BeanELResolver class and for each instance: - ensure plugin is
* initialized - register instances using registerBeanELResolver() method.
*
* @param ctClass
* the ct class
* @param classPool
* the class pool
* @throws CannotCompileException
* the cannot compile exception
* @throws NotFoundException
* the not found exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.el.cache.BeanPropertiesCache")
public static void beanPropertiesCache(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter("java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();" + PluginManagerInvoker.buildInitializePlugin(WildFlyELResolverPlugin.class, "$$cl"));
}
LOGGER.info("Patched org.jboss.el.cache.BeanPropertiesCache");
}
/**
* Hook on org.jboss.el.cache.BeanPropertiesCache.SoftConcurrentHashMap
* class and for each instance: - ensure plugin is initialized - register
* instances using registerBeanELResolver() method
*
* @param ctClass
* the ct class
* @param classPool
* the class pool
* @throws CannotCompileException
* the cannot compile exception
* @throws NotFoundException
* the not found exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.el.cache.BeanPropertiesCache.SoftConcurrentHashMap")
public static void beanPropertiesCacheSoftConcurrentHashMap(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {
ctClass.addMethod(CtMethod.make("public java.util.Set entrySet() { return map.entrySet();}", ctClass));
LOGGER.info("Patched org.jboss.el.cache.BeanPropertiesCache$SoftConcurrentHashMap");
}
/**
* Hook on BeanELResolver class and for each instance: - ensure plugin is
* initialized - register instances using registerBeanELResolver() method.
*
* @param ctClass
* the ct class
* @param classPool
* the class pool
* @throws CannotCompileException
* the cannot compile exception
* @throws NotFoundException
* the not found exception
*/
@OnClassLoadEvent(classNameRegexp = "org.jboss.el.cache.FactoryFinderCache")
public static void factoryFinderCache(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter("java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();" + //
PluginManagerInvoker.buildInitializePlugin(WildFlyELResolverPlugin.class, "$$cl"));
}
LOGGER.info("Patched org.jboss.el.cache.FactoryFinderCache");
}
/**
* Invalidate class cache.
*
* @param original
* the original
* @throws Exception
* the exception
*/
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void invalidateClassCache(Class<?> original) throws Exception {
LOGGER.trace("Running invalidateClassCache {}", appClassLoader);
PurgeWildFlyBeanELResolverCacheCommand cmd = new PurgeWildFlyBeanELResolverCacheCommand(appClassLoader, original.getName());
scheduler.scheduleCommand(cmd, 250, DuplicateSheduleBehaviour.SKIP);
}
/**
* Initialize instance.
*
* @param pluginConfiguration
* the plugin configuration
*/
@Init
public void initializeInstance(PluginConfiguration pluginConfiguration) {
LOGGER.info("WildFlyELResolver plugin initialized");
}
}
|
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter("java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();" + PluginManagerInvoker.buildInitializePlugin(WildFlyELResolverPlugin.class, "$$cl"));
}
LOGGER.info("Patched JbossELResolver");
| 1,304
| 94
| 1,398
|
<no_super_class>
|
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>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.