Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jarek/7015: overwrite java classes #7125

Merged
merged 4 commits into from
Apr 10, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
#7015: enable to overwrite java classes
  • Loading branch information
jaroslawmalekcodete committed Apr 5, 2018
commit 7ab92f38c1ade3148febec4b29a76ed1d12385e8
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ protected void doReloadEvaluator() {

public abstract ClassLoader getClassLoader();

public ClassLoader getClassLoaderForImport() {
return getClassLoader();
}

@Override
public List<Path> addJarsToClasspath(List<PathToJar> paths) {
LinkedList<Path> addedPaths = Lists.newLinkedList();
Expand All @@ -117,7 +121,7 @@ private boolean addJarToClasspath(PathToJar path) {

@Override
public AddImportStatus addImport(ImportPath anImport) {
AddImportStatus add = imports.add(anImport, getClassLoader());
AddImportStatus add = imports.add(anImport, getClassLoaderForImport());
if (AddImportStatus.ADDED.equals(add)) {
addImportToClassLoader(anImport);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright 2018 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twosigma.beakerx.javash;

import com.twosigma.beakerx.jvm.classloader.BeakerxUrlClassLoader;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beakerx => BeakerX

import com.twosigma.beakerx.kernel.PathToJar;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.Collections.singletonList;

public class JavaBeakerxUrlClassLoader extends URLClassLoader {

private BeakerxUrlClassLoader beakerxUrlClassLoader;
private JavaInternalUrlClassLoader javaURLClassLoader;

public JavaBeakerxUrlClassLoader(ClassLoader systemClassLoader, PathToJar pathToJar) {
super(new URL[0]);
beakerxUrlClassLoader = new BeakerxUrlClassLoader(this.getURLs(), systemClassLoader);
javaURLClassLoader = new JavaInternalUrlClassLoader(beakerxUrlClassLoader, new URL[0]);
javaURLClassLoader.addJar(pathToJar);
}

public void addJar(PathToJar pathToJar) {
javaURLClassLoader.addJar(pathToJar);
}

public void addInitJar(PathToJar pathToJar) {
beakerxUrlClassLoader.addJar(pathToJar);
}

public void addInitPathToJars(List<PathToJar> paths) {
for (PathToJar dir : paths) {
addInitJar(dir);
}
}

public Class<?> loadClass(String name) throws ClassNotFoundException {
Class<?> aClass = null;
try {
aClass = javaURLClassLoader.loadClass(name);
} catch (Exception e) {
}
if (aClass != null) {
return aClass;
}
return beakerxUrlClassLoader.loadClass(name);
}

public void resetClassloader() {
javaURLClassLoader = new JavaInternalUrlClassLoader(beakerxUrlClassLoader, javaURLClassLoader.getURLs());
}


public JavaInternalUrlClassLoader getJavaURLClassLoader() {
return javaURLClassLoader;
}

static class JavaInternalUrlClassLoader extends BeakerxUrlClassLoader {

private static final List<String> excludedClasses = singletonList("slf4j");

private BeakerxUrlClassLoader external;

public JavaInternalUrlClassLoader(BeakerxUrlClassLoader external, URL[] urls) {
super(urls, null);
this.external = external;
}

public Class<?> loadClass(String name) throws ClassNotFoundException {
if (isNotInExcludedClasses(name)) {
Class<?> aClass = null;
try {
aClass = super.loadClass(name);
} catch (Exception e) {
}
if (aClass != null) {
return aClass;
}
}
return external.loadClass(name);
}

private boolean isNotInExcludedClasses(String name) {
return excludedClasses.stream()
.filter(name::contains)
.collect(Collectors.toList())
.isEmpty();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ private boolean compile(Codev codev, String classId, String ret) {
codev.javaSourceCode.append("}\n");

compilationUnit.addJavaSource(codev.getPname() + "." + JavaEvaluator.WRAPPER_CLASS_NAME + classId, codev.javaSourceCode.toString());
boolean compile = javaSourceCompiler.compile(compilationUnit);
boolean compile = javaSourceCompiler.compile(javaEvaluator.getClassLoader(), compilationUnit);
if (compile) {
javaSourceCompiler.persistCompiledClasses(compilationUnit);
return true;
Expand All @@ -168,6 +168,7 @@ private TryResult compileNewDefinitionClass(JobDescriptor j, Matcher m, Codev co
try {
javaSourceCompiler.compile(compilationUnit);
javaSourceCompiler.persistCompiledClasses(compilationUnit);
javaEvaluator.getJavaClassLoader().resetClassloader();
either = TryResult.createResult(codev.getPname() + "." + cname);
} catch (CompilationException e) {
either = TryResult.createError(buildErrorMessage(e, codev.lineNumbersMapping));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@

import com.twosigma.beakerx.TryResult;
import com.twosigma.beakerx.autocomplete.AutocompleteResult;
import com.twosigma.beakerx.autocomplete.ClasspathScanner;
import com.twosigma.beakerx.evaluator.BaseEvaluator;
import com.twosigma.beakerx.evaluator.JobDescriptor;
import com.twosigma.beakerx.evaluator.TempFolderFactory;
import com.twosigma.beakerx.evaluator.TempFolderFactoryImpl;
import com.twosigma.beakerx.javash.JavaBeakerxUrlClassLoader;
import com.twosigma.beakerx.javash.autocomplete.JavaAutocomplete;
import com.twosigma.beakerx.javash.autocomplete.JavaClasspathScanner;
import com.twosigma.beakerx.jvm.classloader.BeakerxUrlClassLoader;
import com.twosigma.beakerx.jvm.object.SimpleEvaluationObject;
import com.twosigma.beakerx.jvm.threads.BeakerCellExecutor;
import com.twosigma.beakerx.jvm.threads.CellExecutor;
Expand All @@ -43,7 +42,7 @@ public class JavaEvaluator extends BaseEvaluator {
private final String packageId;
private JavaClasspathScanner cps;
private JavaAutocomplete jac;
private BeakerxUrlClassLoader loader = null;
private JavaBeakerxUrlClassLoader loader = null;

public JavaEvaluator(String id, String sId, EvaluatorParameters evaluatorParameters) {
this(id, sId, new BeakerCellExecutor("javash"), new TempFolderFactoryImpl(), evaluatorParameters);
Expand All @@ -57,6 +56,11 @@ public JavaEvaluator(String id, String sId, CellExecutor cellExecutor, TempFolde
loader = newClassLoader();
}

@Override
public ClassLoader getClassLoaderForImport() {
return getJavaClassLoader().getJavaURLClassLoader();
}

@Override
protected void doResetEnvironment() {
String cpp = createClasspath(classPath, outDir);
Expand Down Expand Up @@ -126,13 +130,13 @@ public String getPackageId() {
return packageId;
}

private BeakerxUrlClassLoader newClassLoader() {
BeakerxUrlClassLoader loader = new BeakerxUrlClassLoader(ClassLoader.getSystemClassLoader());
loader.addPathToJars(getClasspath().getPaths());
private JavaBeakerxUrlClassLoader newClassLoader() {
JavaBeakerxUrlClassLoader loader = new JavaBeakerxUrlClassLoader(ClassLoader.getSystemClassLoader(),new PathToJar(outDir));
loader.addInitPathToJars(getClasspath().getPaths());
return loader;
}

public BeakerxUrlClassLoader getJavaClassLoader() {
public JavaBeakerxUrlClassLoader getJavaClassLoader() {
return loader;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,40 @@ public void evaluateIfStatement() throws Exception {
//then
assertThat((String) evaluate.result()).isEqualTo("AAA");
}

@Test
public void overwriteClass() throws Exception {
//given
runCode("" +
"package hello;\n" +
"public class Main {\n" +
" public static String doSth (){\n" +
" return \"hello\";\n" +
" }\n" +
"}");

runCode("" +
"package hello;\n" +
"return Main.doSth();");
//when
runCode("" +
"package hello;\n" +
"public class Main {\n" +
" public static String doSth (){\n" +
" return \"hello2\";\n" +
" }\n" +
"}");

TryResult result = runCode("" +
"package hello;\n" +
"return Main.doSth();");
//then
assertThat((String) result.result()).contains("hello2");
}

private TryResult runCode(String s) {
SimpleEvaluationObject seo = new SimpleEvaluationObject(s);
return javaEvaluator.evaluate(seo, s);
}

}
76 changes: 76 additions & 0 deletions test/ipynb/java/overwriteJavaClass.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"package hello;\n",
"public class Main {\n",
" public static void main(String args[]){\n",
" System.out.println(\"Hello\");\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"package hello;\n",
"Main.main(null);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"package hello;\n",
"public class Main {\n",
" public static void main(String args[]){\n",
" System.out.println(\"Hello world\");\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"package hello;\n",
"Main.main(null);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Java",
"language": "java",
"name": "java"
},
"language_info": {
"codemirror_mode": "text/x-java",
"file_extension": ".java",
"mimetype": "",
"name": "Java",
"nbconverter_exporter": "",
"version": "1.8.0_121"
}
},
"nbformat": 4,
"nbformat_minor": 2
}