I am learning the MVP architecture that google uses in their android codelabs. I have set up a simple example. Two input fields and a "+" button to show the addition result. The view is the main activity and I have a presenter that calls a service to add the two input values. The view passes itself to the presenter in the onCreate method and keeps a reference of the presenter as well.
View Interface:
public interface MainView {
String getFirstInput();
void showFirstInputError(int resId);
String getSecondInput();
void showSecondInputError(int resId);
void setResultText(int result);
}
Presenter method that is called when the button is pressed:
public void onResultClicked(){
String firstInput = view.getFirstInput();
String secondInput = view.getSecondInput();
if(firstInput.isEmpty()) {
view.showFirstInputError(R.string.num_input_error);
return;
}
if(secondInput.isEmpty()) {
view.showSecondInputError(R.string.num_input_error);
return;
}
Service service = new Service();
int result = service.add(Integer.getInteger(firstInput),
Integer.getInteger(secondInput));
view.setResultText(result);
}
Test:
#Test
public void shouldPopulateResultWhenButtonIsClicked() throws Exception {
when(view.getFirstInput()).thenReturn("3");
when(view.getSecondInput()).thenReturn("3");
when(service.add(3,3)).thenReturn(6);
presenter.onResultClicked();
verify(service).add(3,3);
verify(view).setResultText(6);
}
I get an error on the line the service is trying to add the two inputs.
presenter.onResultClicked();
int result = service.add(Integer.getInteger(firstInput),
Integer.getInteger(secondInput));
Can somebody please help. Thanks.
java.lang.NullPointerException
at com.example.ulidder.tdd_mvp_simple.MainPresenter.onResultClicked(MainPresenter.java:29)
at com.example.ulidder.tdd_mvp_simple.MainPresenterTest.shouldPopulateResultWhenButtonIsClicked(MainPresenterTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
It doesn't have anything to do with Android, Mockito or MVP, you're running a jUnit test, it's pure Java.
It's just a NullPointerException, nothing else. Go to line 29 of MainPresenter.java, add a breakpoint and launch the test in debug mode to see which method call is made on a null reference. Extract variables from chained calls if necessary.
I suspect that service.add(...) returns an java.lang.Integer and you're assigning it to an int. If it returns null, the unboxing will get you a NullPointerException at this line. Try assigning the return value to an Integer and debug the value. It may be null.
See this post for more information about unboxing of null values.
Hope this helps.
Related
I am trying to learn how to code with JavaFx but every time I try to create an object (ex.: WebView webview = new Webview();) I get this error:
ERROR-START{
Exception in Application start method
java.lang.reflect.InvocationTargetException at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567) at
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567) at
java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start
method at
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at
javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:830) Caused by:
java.lang.IllegalAccessError: superclass access check failed: class
com.sun.javafx.sg.prism.web.NGWebView (in unnamed module #0x7dab7530)
cannot access class com.sun.javafx.sg.prism.NGGroup (in module
javafx.graphics) because module javafx.graphics does not export
com.sun.javafx.sg.prism to unnamed module #0x7dab7530 at
java.base/java.lang.ClassLoader.defineClass1(Native Method) at
java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) at
java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
at
java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:821)
at
java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:719)
at
java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:642)
at
java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:600)
at
java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at AppL.start(AppL.java:8) at
javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at
java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at
javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at
javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native
Method) at
javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more Exception running application AppL
}ERROR-ENDING
I've tried to add: (I also added the PATH_TO_FX Path-variable)
--module-path ${PATH_TO_FX} --add-modules javafx.controls,javafx.fxml
to the run configurations VM-options but it only changed the error I had before this error. I tried to do this on Windows AND on Linux, neither works.
Intellj shows me that every thing works, but it doesn't.
I wanted to use netbeans or eclipse but I don't know how to add libraries to them.
That would helb me to.
Example code:
import javafx.application.Application;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class AppL extends Application {
#Override
public void start(Stage stage) throws Exception {
WebView v = new WebView();
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Thanks to anyone who wants to help me, and who doesn't lauph on my english-scills😊
I would appreciate any hints on the following problem I've encountered. While unit testing multipart file upload service method in Spring Reactive WebFlux app, I am getting NPE for reactor.core.publisher.MonoWhen$WhenCoordinator as follows
java.lang.NullPointerException
at reactor.core.publisher.MonoWhen$WhenCoordinator.subscribe(MonoWhen.java:149)
Complete log is listed below as well.
Test :
#RunWith(SpringRunner.class)
#SpringBootTest
public class FileServiceTest2 {
#MockBean
private UploadedImageRepository uploadedImageRepository;
...
#Test
public void assembleImageTest() {
UploadedImage ui1 = new UploadedImage("1", "ui1.png");
UploadedImage ui2 = new UploadedImage("2", "ui2.png");
FilePart filePart1 = mock(FilePart.class);
FilePart filePart2 = mock(FilePart.class);
given(this.uploadedImageRepository.save(ui1))
.willReturn(Mono.just(ui1));
given(this.uploadedImageRepository.save(ui2))
.willReturn(Mono.just(ui2));
given(this.uploadedImageRepository.findAll())
.willReturn(Flux.just(ui1, ui2));
given(filePart1.filename())
.willReturn(ui1.getImageName());
given(filePart1.transferTo(any()))
.willReturn(Mono.empty());
given(filePart2.filename())
.willReturn(ui2.getImageName());
given(filePart2.transferTo(any()))
.willReturn(Mono.empty());
Flux<FilePart> files = Flux.just(filePart1, filePart2);
StepVerifier.create(this.uploadService.createFile(files))
.verifyComplete();
}
Under test :
#Service
public class UploadService {
Mono<Void> createFile(Flux<FilePart> fileParts) {
return fileParts.flatMap(part -> {
Mono<UploadedImage> savedToDBImage = this.uploadedImageRepository.save(
new UploadedImage(UUID.randomUUID().toString(), part.filename()))
.log("createFile-fileSavedToDB"); // NPE!
Mono<Void> copiedFile = Mono.just(Paths.get(UPLOAD_URL, part.filename()).toFile())
.log("createFile-pathAssembled")
.doOnNext(destinationFile -> {
try {
destinationFile.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.log("createFile-fileAssembled")
.flatMap(part::transferTo)
.log("createFile-fileCopied");
return Mono.when(savedToDBImage, copiedFile)
.log("createFile-monoWhen");
})
.log("createFile-flatMap")
.then()
.log("createFile-done");
}
UploadedImage class (w Lombok) :
#Data
#RequiredArgsConstructor
#NoArgsConstructor
public class UploadedImage {
#NonNull private String id;
#NonNull private String imageName;
}
SpringData Reactive Repository:
#Repository
public interface UploadedImageRepository extends ReactiveCrudRepository<UploadedImage, String> {
}
Logs are as follows:
java.lang.NullPointerException
at reactor.core.publisher.MonoWhen$WhenCoordinator.subscribe(MonoWhen.java:149)
at reactor.core.publisher.MonoWhen.subscribe(MonoWhen.java:99)
at reactor.core.publisher.MonoOnAssembly.subscribe(MonoOnAssembly.java:76)
at reactor.core.publisher.MonoLogFuseable.subscribe(MonoLogFuseable.java:53)
at reactor.core.publisher.Mono.subscribe(Mono.java:3080)
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:372)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onNext(FluxPeekFuseable.java:198)
at reactor.core.publisher.FluxArray$ArraySubscription.slowPath(FluxArray.java:118)
at reactor.core.publisher.FluxArray$ArraySubscription.request(FluxArray.java:91)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.request(FluxPeekFuseable.java:138)
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onSubscribe(FluxFlatMap.java:332)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:172)
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53)
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59)
at reactor.core.publisher.FluxLogFuseable.subscribe(FluxLogFuseable.java:53)
at reactor.core.publisher.FluxFlatMap.subscribe(FluxFlatMap.java:97)
at reactor.core.publisher.FluxLog.subscribe(FluxLog.java:50)
at reactor.core.publisher.MonoIgnoreElements.subscribe(MonoIgnoreElements.java:37)
at reactor.core.publisher.MonoLog.subscribe(MonoLog.java:51)
at reactor.core.publisher.Mono.subscribe(Mono.java:3080)
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:728)
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:700)
at reactor.test.DefaultStepVerifierBuilder.verifyComplete(DefaultStepVerifierBuilder.java:566)
at pb.sl.UploadService.createFile(FileServiceTest2.java:112)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Looking more closely, I think you're not mocking your repository as expected, and in your test the repository call returns null.
You're not using a Mockito argument matcher but a concrete instance for the argument. Later in your service implementation, this method is called, but with a different instance. My guess is Mockito is using equals to check if the given matches that mock call - maybe your UploadedImage could be improved in that regard?
given(this.uploadedImageRepository.save(ui1)) should be:
given(this.uploadedImageRepository.save(any()))
.willAnswer(invocation -> Mono.just(invocation.getArgument(0)))
My Kotlin class compiles and runs on an emulator without a problem. But when I test it, Android Studio says the class is not found.
Here's the Kotlin class and an example of using it:
// Product.kt
data class Product(
val id: Int,
val name: String,
val manufacturer: String)
// MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Product product = new Product(0, "foo", "bar");
TextView textView = findViewById(R.id.textView);
textView.setText(product.getName());
}
}
However when I write a JUnit test for the Kotlin class:
// ProductTest.java
public class ProductTest {
#Test
public void getName() throws Exception {
Product p = new Product(0, "foo", "bar");
assertThat(p.getName(), equalTo("foo"));
}
}
Android Studio compiles the code, but refuses to run the test:
java.lang.NoClassDefFoundError: com/example/Product
at com.example.ProductTest.getName(ProductTest.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: java.lang.ClassNotFoundException: com.example.Product
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 28 more
Here comes the dependencies section in the module-level build.gradle:
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
testCompile 'junit:junit:4.12'
}
What did I do wrong?
The solution is to create a new task in the module build.gradle file.
android {
task copyTestClasses(type: Copy) {
from "build/tmp/kotlin-classes/debugUnitTest"
into "build/intermediates/classes/debug"
}
Then add that task to the "Before launch" section of the test run configuration.
This currently doesn't work with the latest tools. There is an open issue for this in the Jetbrains tracker.
This is an open issue, I guess it will be fixed soon:
https://youtrack.jetbrains.com/issue/KT-17951
https://issuetracker.google.com/issues/38454212
Meanwhile, you can use the following workaround:
task copyTestClasses(type: Copy) {
from "build/tmp/kotlin-classes/debugUnitTest"
into "build/intermediates/classes/debug"
}
task copySdkClasses(type: Copy) {
from "build/tmp/kotlin-classes/debug"
into "build/intermediates/classes/debug"
}
Add it to your Gradle file (after android {...} section)
After that, open your tests configuration and add new "before launch" step which will execute those tasks:
Someone confirmed this bug has been fixed in Android Studio 3 Canary 3: https://issuetracker.google.com/issues/38454212
I try to evaluate math expression in string form using scriptengine, but it throws me NullPointerException
java.lang.NullPointerException
at Math.main(Math.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Here is the code:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Math{
public static void main(String[] args){
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
System.out.println("scriptEngine result: "+jsEngine.eval("{2+4*3*[1+(1+2+4)]}"));
} catch (ScriptException ex) {
Logger.getLogger(Math.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
i tried the same code in netbeans and it works, but i also need it to work in DrJava development environment.
Is it possible to resolve this or is there any other library that can evaluate string like this with combination of all parenthesis "{[()]}"?
I am trying out gridgain for the first time and facing some issues with serialization. While trying to use GridClosure to project jobs on different nodes I get marshaling exception . On debugging, It seems the failure is always for Apache log4j Logger object. Its difficult for me to avoid loggers and wanted to understand if this is a known issue or someway I can remedy this. I have requireSerializable set to false for my grid config.
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.gridgain.grid.marshaller.optimized.GridOptimizedObjectOutputStream.writeSerializable(GridOptimizedObjectOutputStream.java:292)
... 45 more
Caused by: java.io.IOException: java.lang.reflect.InvocationTargetException
at org.gridgain.grid.marshaller.optimized.GridOptimizedObjectOutputStream.writeSerializable(GridOptimizedObjectOutputStream.java:295)
at org.gridgain.grid.marshaller.optimized.GridOptimizedClassDescriptor.write(GridOptimizedClassDescriptor.java:849)
at org.gridgain.grid.marshaller.optimized.GridOptimizedObjectOutputStream.writeObject0(GridOptimizedObjectOutputStream.java:198)
at org.gridgain.grid.marshaller.optimized.GridOptimizedObjectOutputStream.writeObjectOverride(GridOptimizedObjectOutputStream.java:129)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:342)
at java.util.Hashtable.writeObject(Hashtable.java:988)
... 50 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.gridgain.grid.marshaller.optimized.GridOptimizedObjectOutputStream.writeSerializable(GridOptimizedObjectOutputStream.java:292)
... 55 more
Caused by: java.lang.NullPointerException
at org.gridgain.grid.marshaller.optimized.GridOptimizedObjectOutputStream$PutFieldImpl.value(GridOptimizedObjectOutputStream.java:1003)
at org.gridgain.grid.marshaller.optimized.GridOptimizedObjectOutputStream$PutFieldImpl.put(GridOptimizedObjectOutputStream.java:965)
at java.util.Vector.writeObject(Vector.java:1068)
... 60 more
Can you make Log4J object static so it does not affect serialization? If not, GridGain allows you to inject logger resource into pretty much anything, including closures. You can configure GridLogger as GridLog4jLogger in GridConfiguration.
Here is an example:
GridRunnable run = new GridRunnable() {
// Can be any logger, including GridLog4jLogger.
#GridLoggerResource
GridLogger log;
#Override public void run() {
log.info("Hello");
// Do some logic.
}
}
or
// Can be any logger, including GridLog4jLogger
final GridLogger log = grid.log();
GridRunnable run = new GridRunnable() {
#Override public void run() {
log.info("Hello");
// Do some logic.
}
}
For more information, refer to Resource Injection page in GridGain documentation.