I am completely new to jbehave and even automated testing.
I read a tutorial online and tried following the steps.
I am trying to run this application in eclipse IDE.
I made a Math.story file which contains the tests:
Scenario: 2 squared
Given a variable x with value 2
When I multiply x by 2
Then x should equal 4
In a .java file called ExampleSteps.java, the steps are written:
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.jbehave.core.steps.Steps;
public class ExampleSteps extends Steps {
int x;
#Given("a variable x with value $value")
public void givenXValue(#Named("value") int value) {
x = value;
}
#When("I multiply x by $value")
public void whenImultiplyXBy(#Named("value") int value) {
x = x * value;
}
#Then("x should equal $value")
public void thenXshouldBe(#Named("value") int value) {
if (value != x)
throw new RuntimeException("x is " + x + ", but should be " + value);
}
}
I created another class SimpleJbehave which has the main method:
import java.util.Arrays;
import java.util.List;
import org.jbehave.core.embedder.Embedder;
public class SimpleJBehave {
private static Embedder embedder = new Embedder();
private static List<String> storyPaths = Arrays
.asList("Math.story");
public static void main(String[] args) {
embedder.candidateSteps().add(new ExampleSteps());
embedder.runStoriesAsPaths(storyPaths);
}
}
When I run this code, I get the following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/Transformer
at org.jbehave.core.configuration.Configuration.<init>(Configuration.java:112)
at org.jbehave.core.configuration.MostUsefulConfiguration.<init>(MostUsefulConfiguration.java:49)
at org.jbehave.core.embedder.Embedder.<init>(Embedder.java:30)
at org.jbehave.core.embedder.Embedder.<init>(Embedder.java:37)
at SimpleJBehave.<clinit>(SimpleJBehave.java:8)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.Transformer
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more
As I am a novice, I have not been able to understand what exactly the problem is.
It will be really nice if someone could tell me what I should do to get this code working.
Is my approach wrong?
Thank you very much in advance.
It looks like you don't have org.apache.commons.collections.Transformer on your classpath. It looks like this class is available in the apache-commons-transformer library here: http://commons.apache.org/collections/api-release/org/apache/commons/collections/Transformer.html
Download the jar and add it to your classpath. It might work.
Related
I am adding the custom object(Account) into Cache and then trying to access the object in the Function.execute() method.
But it throws org.apache.geode.pdx.internal.PdxInstanceImpl cannot be cast to com.sas.cpm.model.Account.
Custom object Account.java
public class Account implements PdxSerializable, Declarable{
public Account() {
super();
// TODO Auto-generated constructor
}
#Override
public void fromData(PdxReader pr) {…..}
#Override
public void toData(PdxWriter pw) {… }
}
Client code:
ClientCache cache = new ClientCacheFactory()
.addPoolLocator("localhost", 10334).set("log-level", "INFO").create();
// create a local region that matches the server region
// Account is the domain object
Region<String, Account> region =
cache.<String, Account>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
.create("testRegion");
feedData(region); //add Account object to region
Execution execution = FunctionService.onRegion(region);
ResultCollector<Integer, List> rc = execution.execute("UpdateCost");//.ID);//com.sas.cpm.geode
Function class : UpdateCost.java
public class UpdateCost implements Function{
#Override
public void execute(FunctionContext context) {
RegionFunctionContext regionContext = (RegionFunctionContext) context;
Region<String, Account> region = regionContext.getDataSet();
for ( Map.Entry<String, Account> entry : region.entrySet() ) {
Account account = entry.getValue(); /// THIS LINE GIVES THE ERROR
}
}
}
Error:
Exception in thread "main" org.apache.geode.cache.execute.FunctionException: org.apache.geode.cache.client.ServerOperationException: remote server on dsinsbb01ina4(46560:loner):59343:2f7e3885: While performing a remote executeRegionFunction
at org.apache.geode.internal.cache.execute.ServerRegionFunctionExecutor.executeOnServer(ServerRegionFunctionExecutor.java:229)
at org.apache.geode.internal.cache.execute.ServerRegionFunctionExecutor.executeFunction(ServerRegionFunctionExecutor.java:178)
at org.apache.geode.internal.cache.execute.ServerRegionFunctionExecutor.execute(ServerRegionFunctionExecutor.java:379)
at geodeproject1.Example.funcUpdateExec(Example.java:186)
at geodeproject1.Example.main(Example.java:68)
Caused by: org.apache.geode.cache.client.ServerOperationException: remote server on dsinsbb01ina4(46560:loner):59343:2f7e3885: While performing a remote executeRegionFunction
at org.apache.geode.cache.client.internal.ExecuteRegionFunctionOp$ExecuteRegionFunctionOpImpl.processResponse(ExecuteRegionFunctionOp.java:606)
at org.apache.geode.cache.client.internal.AbstractOp.processResponse(AbstractOp.java:225)
at org.apache.geode.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:198)
at org.apache.geode.cache.client.internal.AbstractOp.attempt(AbstractOp.java:386)
at org.apache.geode.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:269)
at org.apache.geode.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:325)
at org.apache.geode.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:892)
at org.apache.geode.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:171)
at org.apache.geode.cache.client.internal.PoolImpl.execute(PoolImpl.java:772)
at org.apache.geode.cache.client.internal.ExecuteRegionFunctionOp.execute(ExecuteRegionFunctionOp.java:162)
at org.apache.geode.cache.client.internal.ServerRegionProxy.executeFunction(ServerRegionProxy.java:732)
at org.apache.geode.internal.cache.execute.ServerRegionFunctionExecutor.executeOnServer(ServerRegionFunctionExecutor.java:220)
... 4 more
Caused by: org.apache.geode.cache.execute.FunctionException: java.lang.ClassCastException: org.apache.geode.pdx.internal.PdxInstanceImpl cannot be cast to com.sas.cpm.model.Account
at org.apache.geode.cache.client.internal.ExecuteRegionFunctionOp$ExecuteRegionFunctionOpImpl.processResponse(ExecuteRegionFunctionOp.java:583)
... 15 more
Caused by: java.lang.ClassCastException: org.apache.geode.pdx.internal.PdxInstanceImpl cannot be cast to com.sas.cpm.model.Account
at com.sas.cpm.geode.UpdateCost.execute(UpdateCost.java:49)
at org.apache.geode.internal.cache.execute.AbstractExecution.executeFunctionLocally(AbstractExecution.java:331)
at org.apache.geode.internal.cache.execute.AbstractExecution$2.run(AbstractExecution.java:300)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.geode.distributed.internal.ClusterDistributionManager.runUntilShutdown(ClusterDistributionManager.java:949)
at org.apache.geode.distributed.internal.ClusterDistributionManager.doFunctionExecutionThread(ClusterDistributionManager.java:803)
at org.apache.geode.internal.logging.LoggingThreadFactory.lambda$newThread$0(LoggingThreadFactory.java:121)
at java.lang.Thread.run(Unknown Source)
The ClassCastException is thrown because you're receiving a PdxInstance from the cache instead of an Account, this happens when you implement the PdxSerializable interface in your domain object and configure PDX Serialization with read-serialized=true.
Please have a look at Implementing PdxSerializable in Your Domain Object and Programming Your Application to Use PdxInstances for further details.
Cheers.
My Java-Code looks like this:
Person.java
public class Person {
private int age;
public Person(int age) {
this.age = age;
}
public boolean isAdult() {
return age >= 18;
}
#Override
public String toString() {
return "Person of age: " + age;
}
}
PersonTest.java
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
#RunWith(JUnitParamsRunner.class)
public class PersonTest {
#Test
#Parameters({
"17, false",
"22, true" })
public void personIsAdult(int age, boolean valid) throws Exception {
assertThat(new Person(age).isAdult(), is(valid));
}
}
And if I press "Run As" => "JUnit Test Case" I get the "java.lang.TypeNotPresentException: Type [unknown] not present".
Here the full Stack Trace:
java.lang.TypeNotPresentException: Type [unknown] not present
at sun.reflect.annotation.TypeNotPresentExceptionProxy.generateException(TypeNotPresentExceptionProxy.java:46)
at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHandler.java:84)
at com.sun.proxy.$Proxy2.value(Unknown Source)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NoClassDefFoundError: org/junit/runners/BlockJUnit4ClassRunner
at java.lang.ClassLoader.findBootstrapClass(Native Method)
at java.lang.ClassLoader.findBootstrapClassOrNull(ClassLoader.java:1015)
at java.lang.ClassLoader.loadClass(ClassLoader.java:413)
at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:439)
at sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:420)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:349)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.Class.createAnnotationData(Class.java:3521)
at java.lang.Class.annotationData(Class.java:3510)
at java.lang.Class.getAnnotation(Class.java:3415)
at org.junit.internal.builders.IgnoredBuilder.runnerForClass(IgnoredBuilder.java:10)
... 11 more
JUnit-Version is 4.12
Hamcrest-all Version is 1.3
Hamcrest-core Version is 1.3
Does anyone has an advice how to fix this Problem? Thanks in advance.
I now was able to solve my own problem using this forum here: https://jira.spring.io/browse/SPR-9450
I used the libraries as User Libraries, but obviously this was the mistake. When I use it as external jars in my classpath everything works.
I have followed every step in this (https://blogs.oracle.com/jmxetc/entry/connecting_scenebuilder_edited_fxml_to) tutorial, and yet keep getting an error about this section in the controller class:
myButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("That was easy, wasn't it?");
}
});
The only difference I can think of is that it was written for FX 2.0 and not 8.0?
Exception in Application start method
java.lang.reflect.InvocationTargetException
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:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
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:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.Error: Unresolved compilation problems:
The method setOnAction(EventHandler<ActionEvent>) in the type ButtonBase is not applicable for the arguments (new EventHandler<ActionEvent>(){})
EventHandler cannot be resolved to a type
The method handle(ActionEvent) of type new EventHandler<ActionEvent>(){} must override or implement a supertype method
at simple.SimpleController.initialize(SimpleController.java:24)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at simple.Main.start(Main.java:26)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Exception running application simple.Main
Let me know if you need to see the classes and FXML files (dw, they're very short)
Thank you!
PS- Please bear with me if I need clarification about your answer because as a Java newbie I often get confused!
EDIT 1:
package simple;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleController
implements Initializable {
#FXML // fx:id="myButton"
private Button myButton; // Value injected by FXMLLoader
#Override // This method is called by the FXMLLoader when initialization is complete
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
assert myButton != null : "fx:id=\"myButton\" was not injected: check your FXML file 'simple.fxml'.";
// initialize your logic here: all #FXML variables will have been injected
myButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("That was easy, wasn't it?");
}
});
}
}
You are missing the import for EventHandler, and you have the wrong import for ActionEvent. (Also you have imported ActionListener for some reason, though you never use it.)
Your imports should be
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
Looking at This Eclipse Bug it seems the Java Verifier (since 1.6) has had issues with ApsectJ.
The bug says AspectJ 1.8.1 will fix the problem. But using that with Java8u11 I still get the verify error.
I'm running JUnit4 under STS 3.6.0 (Eclipse 4.4). I believe this configuration is the very latest available of all packages.
Completely replaced the remainder of text with requested example. This seems to be limited to #Around advice. #Before works fine.
JUnit:
package com.test.aspectjdemo.junit;
import static org.junit.Assert.*;
import org.junit.Test;
import com.test.aspectjdemo.domain.AspectTarget;
public class AspectTargetTest {
#Test
public void testFirstMethod() throws Throwable {
AspectTarget aspectTarget = new AspectTarget();
aspectTarget.firstMethod();
}
}
Vmarg: -javaagent:C:....m2\repository\org\aspectj\aspectjweaver\1.8.1\aspectjweaver-1.8.1.jar
Class under test (I had some problems because proceed apparently declares it throws Throwable, which makes sense, but this simple test didn't throw anything. So I added a faux exception make it compile :
package com.test.aspectjdemo.domain;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class AspectTarget {
final Logger logger = LogManager.getLogger();
int x = 1;
public void firstMethod() throws Throwable {
logger.info("Start First Method");
x = secondMethod(x);
logger.info("Exit X is {}", x);
}
private int secondMethod(int x) throws Throwable {
logger.info("input is {}", x++);
if (x==100)
throw new RuntimeException();
return new Integer(x);
}
}
The Aspect:
package com.test.aspectjdemo.aspects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
public aspect LoggingAspect {
static final Logger logger = LogManager.getLogger();
/**
* Exclude JUnit methods
*/
#Pointcut("!within(com.test.aspectjdemo.junit..*Test)")
public void noJunit() {}
#Pointcut("execution(* com.test.aspectjdemo.domain.*.*(..)) && noJunit()")
public void allMethods() { }
#Around("allMethods()")
public Object allmethods(ProceedingJoinPoint joinPoint) throws Throwable {
return joinPoint.proceed();
}
Finally once again the Error, which is actually thrown when the JUnit attempts to instantiate the AspectTarget (first line of testFirstMethod method).
java.lang.VerifyError: Bad type on operand stack
Exception Details:
Location:
com/test/aspectjdemo/domain/AspectTarget.secondMethod(I)I #23: invokestatic
Reason:
Type 'org/aspectj/lang/JoinPoint' (current frame, stack[2]) is not assignable to integer
Current Frame:
bci: #23
flags: { }
locals: { 'com/test/aspectjdemo/domain/AspectTarget', integer, integer, 'org/aspectj/lang/JoinPoint' }
stack: { 'com/test/aspectjdemo/domain/AspectTarget', integer, 'org/aspectj/lang/JoinPoint', 'com/test/aspectjdemo/aspects/LoggingAspect', null, 'org/aspectj/lang/JoinPoint' }
Bytecode:
0000000: 1b3d b200 4b2a 2a1c b800 51b8 0057 4e2a
0000010: 1c2d b800 6601 2db8 006a b800 6dac
at com.test.aspectjdemo.junit.AspectTargetTest.testFirstMethod(AspectTargetTest.java:13)
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:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The problem is that you mix native AspectJ syntax (public aspect LoggingAspect) with annotation-style #AspectJ syntax. I can reproduce the problem this way.
Correct #AspectJ syntax:
package com.test.aspectjdemo.aspects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class LoggingAspect {
#Pointcut("!within(com.test.aspectjdemo.junit..*Test)")
public void excludeJUnit() {}
#Pointcut("execution(* com.test.aspectjdemo.domain.*.*(..)) && excludeJUnit()")
public void allMethods() {}
#Around("allMethods()")
public Object allmethods(ProceedingJoinPoint thisJoinPoint) throws Throwable {
System.out.println(thisJoinPoint);
return thisJoinPoint.proceed();
}
}
Correct native AspectJ syntax:
package com.test.aspectjdemo.aspects;
public aspect LoggingAspect {
pointcut excludeJUnit() :
!within(com.test.aspectjdemo.junit..*Test);
pointcut allMethods() :
execution(* com.test.aspectjdemo.domain.*.*(..)) && excludeJUnit();
Object around() : allMethods() {
System.out.println(thisJoinPoint);
return proceed();
}
}
I read on http://eclipse.geekyramblings.net/2010/12/14/preventing-multiple-instances/ on how to prevent multiple instances of your RCP from being launched. But when I made my RCP(It's a simple RCP based on the "Hello RCP" Template) executable and tried launching it, it throws me this error
java.io.IOException: The location has not been set.
at org.eclipse.core.runtime.internal.adaptor.BasicLocation.lock(BasicLocation.java:174)
at testrcp.Application.start(Application.java:43)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
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 org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
at org.eclipse.equinox.launcher.Main.run(Main.java:1407)
I am using
Eclipse Java EE IDE for Web Developers.
Version: Helios Service Release 1
Build id: 20100917-0705
Here is the code which is in my Application.java file
package testrcp;
import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.service.datalocation.Location;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
/**
* This class controls all aspects of the application's execution
*/
public class Application implements IApplication {
/* (non-Javadoc)
* #see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
*/
public Object start(IApplicationContext context) throws Exception {
Display display = PlatformUI.createDisplay();
int exitCode = IApplication.EXIT_OK;
Location instanceLocation = Platform.getInstanceLocation();
if (!instanceLocation.lock()) {
MessageDialog.openError(new Shell(display), "App Title",
"Another instance of the Application is currently running.");
} else {
int returnCode = PlatformUI.createAndRunWorkbench(display,
new ApplicationWorkbenchAdvisor());
switch (returnCode) {
case PlatformUI.RETURN_RESTART :
exitCode = IApplication.EXIT_RESTART;
break;
default :
exitCode = IApplication.EXIT_OK;
}
}
instanceLocation.release();
display.dispose();
return exitCode;
}
/* (non-Javadoc)
* #see org.eclipse.equinox.app.IApplication#stop()
*/
public void stop() {
if (!PlatformUI.isWorkbenchRunning())
return;
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed())
workbench.close();
}
});
}
}
Any help on resolving this issue or any suggestion, would be really appreciated.
Thanks,
Abbas
I was able to make it work by adding this line
instanceLocation.getURL();
after
Location instanceLocation = Platform.getInstanceLocation();
But be aware, this will however not prevent it from being launched from a different folder where the RCP executable exists... Is there any way to keep a check on that ?
You can also open a server socket when you launch your application. If you open another instance, communicate with the server. If you can communicate, that running instance can be opened leaving one instance of the application.
More in detail here