FEST JUnit-Swing testing noobQ: how to test a main class? - swing

Despite reading the tutorial here, I cant seem to understand how to make FEST work with my application.
I have a Swing application in a big class witht a main method, and a couple of SwingWorker classes. I want to test my application as if I'm running it via the main method. The tutorial only seemed to give instructions on how to test a single component.
Miniature version of my ApplicationWindow.class that contains the main method:
private JFrame frmArtisol;
private JButton btnBrowseDB;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ApplicationWindow window = new ApplicationWindow();
window.frmArtisol.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ApplicationWindow() {
initialize();
}
And my testclass throwing an error.
public class ApplicationWindowTest {
private FrameFixture window;
#Before
public void setup() throws InitializationError{
ApplicationWindow applicationWindow = new ApplicationWindow();
JFrame frame = applicationWindow.getFrmArtisol();
frame = GuiActionRunner.execute(new GuiQuery<JFrame>() {
#Override
protected JFrame executeInEDT() throws Throwable {
return new JFrame();
}
});
window = new FrameFixture(frame);
window.show();
}
#Test
public void test(){
window.button("btnBrowseDB").click();
}
#After
public void after(){
window.cleanUp();
}
}
The error thrown when running this test:
org.fest.swing.exception.ComponentLookupException: Unable to find component using matcher org.fest.swing.core.NameMatcher[name='btnBrowseDB', type=javax.swing.JButton, requireShowing=true].
Component hierarchy:
javax.swing.JFrame[name='frame0', title='', enabled=true, visible=true, showing=true]
javax.swing.JRootPane[]
javax.swing.JPanel[name='null.glassPane']
javax.swing.JLayeredPane[]
javax.swing.JPanel[name='null.contentPane']
at org.fest.swing.core.BasicComponentFinder.componentNotFound(BasicComponentFinder.java:271)
at org.fest.swing.core.BasicComponentFinder.find(BasicComponentFinder.java:260)
at org.fest.swing.core.BasicComponentFinder.find(BasicComponentFinder.java:254)
at org.fest.swing.core.BasicComponentFinder.findByName(BasicComponentFinder.java:191)
at org.fest.swing.fixture.ContainerFixture.findByName(ContainerFixture.java:527)
at org.fest.swing.fixture.ContainerFixture.button(ContainerFixture.java:124)
at ApplicationWindowTest.test(ApplicationWindowTest.java:34)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
It seems as if the runner doesn't find my component, and this leads me to believe that I have misunderstood how to test this kind of thing. Any help pointing me in the right direction is greatly appreciated.

You may have already solved this, but I just came across your question while looking for help with a related problem.
The problem is that your setup() method creates an ApplicationWindow but then overwrites the variable frame with a reference to a completely new and unrelated JFrame object. What you want to do is create the ApplicationWindow in the executeInEDT() method like this:
#Before
public void setup() throws InitializationError{
JFrame frame = GuiActionRunner.execute(new GuiQuery<JFrame>() {
#Override
protected JFrame executeInEDT() throws Throwable {
return new ApplicationWindow().getFrmArtisol();
}
});
window = new FrameFixture(frame);
window.show();
}

Related

When use Spy and PowerMock together throws RuntimeException

When I use Spy annotation together with the PowerMock in my JUnit test case, it throws RuntimeException, but when I use Mock annotation together with the PowerMock, the test case is working fine.
Anybody able to advise about my issue?
This is my code
#RunWith(PowerMockRunner.class)
#PrepareForTest({DBConnectionPool.class})
#PowerMockIgnore("javax.management.*")
public class TestAbcController {
private static final Logger logger = Logger.getLogger(TestAbcController .class.getName());
public TestAbcController () {
}
#Spy
private SampleDao mockDao;
#InjectMocks
private AbcController ctr;
private BasicDataSource ds = null;
private MockMvc mockMvc;
#BeforeClass
public static void setUpClass() {
logger.setLevel(Level.INFO);
PowerMockito.mockStatic(DBConnectionPool.class);
PowerMockito.when(DBConnectionPool.getDataSource()).thenReturn(UnitTestDbConnection.getDataSource());
}
#Test
public void testMain() {
when(mockDao.getMap()).thenReturn(new HashMap());
}
Below is the detail of the exception
java.lang.RuntimeException: Invoking the beforeTestMethod method on
PowerMock test listener
org.powermock.api.extension.listener.AnnotationEnabler#d86a6f failed.
at
org.powermock.api.mockito.internal.configuration.PowerMockitoSpyAnnotationEngine.process(PowerMockitoSpyAnnotationEngine.java:53)
at
org.powermock.api.mockito.internal.configuration.PowerMockitoInjectingAnnotationEngine.process(PowerMockitoInjectingAnnotationEngine.java:32)
at
org.powermock.api.extension.listener.AnnotationEnabler.injectSpiesAndInjectToSetters(AnnotationEnabler.java:60)
at
org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:55)
at
org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:90)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:292)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at
org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at
org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at
org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at
org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at
org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at
org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
I fixed this issue after I upgrade my mockito-core to 2.8.9 and powermock to 1.7.4

Swing/JavaFx Hybrid Application with crashing TextField

I have a problem which is affecting an application that for various reasons had to be written using Swing JFrames containing JavaFx panels. I can reduce the code to a simple example, based on code from https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/swing-fx-interoperability.htm.
My example opens an application containing a button that can open a simple dialog which has a textfield. If I type into the dialog's textfield, everything is fine, but if I start typing then click on anything outside the dialog (e.g. a text editor), when i go back to the textfield and type some more if behaves oddly and starts throwing exceptions. This appears to be where something is not happening on the EDT or Application thread, and I'm quite sure it's down the the dialog's show() method, though I can't see what is wrong. As far as i can tell, i've followed the correct pattern.
I'm using JDK 1.8.0_171 and IntelliJ Idea on Windows 10.
The code is as follows:
Application:
public class HybridApplication
{
private static JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> initAndShowGUI());
}
private static void initAndShowGUI() {
frame = new JFrame("Swing and JavaFX");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Platform.runLater(() -> initFX(fxPanel));
}
private static void initFX(JFXPanel fxPanel) {
Scene scene = createScene();
fxPanel.setScene(scene);
}
private static Scene createScene() {
HBox hBox = new HBox();
hBox.setSpacing(20);
Scene scene = new Scene(hBox);
TextField text = new TextField();
text.setPrefWidth(200);
text.setPrefHeight(40);
HybridDialog dialog = new HybridDialog();
Button button = new Button("Test");
button.setOnAction(event -> dialog.show());
hBox.getChildren().add(button);
hBox.getChildren().add(text);
return scene;
}
}
Dialog:
public class HybridDialog
{
private JFrame frame;
public HybridDialog()
{
SwingUtilities.invokeLater(() -> initAndShowGUI());
}
private void initAndShowGUI()
{
frame = new JFrame("Dialog");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setSize(300, 200);
frame.setVisible(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Platform.runLater(() -> initFX(fxPanel));
}
private void initFX(JFXPanel fxPanel) {
Scene scene = createScene();
fxPanel.setScene(scene);
}
private static Scene createScene() {
TextField text = new TextField();
text.setPrefWidth(200);
text.setPrefHeight(40);
HBox hBox = new HBox();
hBox.getChildren().add(text);
Scene scene = new Scene(hBox);
return scene;
}
public void show() {
SwingUtilities.invokeLater(() -> frame.setVisible(true));
}
}
The odd behaviour is that when i resume typing, say to edit what i'd typed, the textfield starts adding chunks of the text after the cursor and I soon get the following exception:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1273)
at com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
at com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
at javafx.scene.text.Text.getLogicalBounds(Text.java:358)
at javafx.scene.text.Text.getYRendering(Text.java:1069)
at javafx.scene.text.Text.access$4400(Text.java:95)
at javafx.scene.text.Text$TextAttribute$11.computeValue(Text.java:1785)
at javafx.scene.text.Text$TextAttribute$11.computeValue(Text.java:1777)
at javafx.beans.binding.ObjectBinding.get(ObjectBinding.java:153)
at javafx.beans.binding.ObjectExpression.getValue(ObjectExpression.java:50)
at javafx.beans.property.ObjectPropertyBase.get(ObjectPropertyBase.java:132)
at com.sun.javafx.scene.control.skin.TextFieldSkin.lambda$new$198(TextFieldSkin.java:233)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:105)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.access$000(ObjectPropertyBase.java:51)
at javafx.beans.property.ObjectPropertyBase$Listener.invalidated(ObjectPropertyBase.java:233)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.binding.ObjectBinding.invalidate(ObjectBinding.java:172)
at javafx.scene.text.Text.impl_geomChanged(Text.java:769)
at javafx.scene.text.Text.needsTextLayout(Text.java:194)
at javafx.scene.text.Text.needsFullTextLayout(Text.java:189)
at javafx.scene.text.Text.access$200(Text.java:95)
at javafx.scene.text.Text$2.invalidated(Text.java:389)
at javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:109)
at javafx.beans.property.StringPropertyBase.access$000(StringPropertyBase.java:49)
at javafx.beans.property.StringPropertyBase$Listener.invalidated(StringPropertyBase.java:230)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.binding.StringBinding.invalidate(StringBinding.java:171)
at com.sun.javafx.binding.BindingHelperObserver.invalidated(BindingHelperObserver.java:51)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:349)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.scene.control.TextInputControl$TextProperty.fireValueChangedEvent(TextInputControl.java:1389)
at javafx.scene.control.TextInputControl$TextProperty.markInvalid(TextInputControl.java:1393)
at javafx.scene.control.TextInputControl$TextProperty.controlContentHasChanged(TextInputControl.java:1332)
at javafx.scene.control.TextInputControl$TextProperty.access$1600(TextInputControl.java:1300)
at javafx.scene.control.TextInputControl.lambda$new$162(TextInputControl.java:139)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.scene.control.TextField$TextFieldContent.insert(TextField.java:87)
at javafx.scene.control.TextInputControl.replaceText(TextInputControl.java:1204)
at javafx.scene.control.TextInputControl.updateContent(TextInputControl.java:556)
at javafx.scene.control.TextInputControl.replaceText(TextInputControl.java:548)
at com.sun.javafx.scene.control.skin.TextFieldSkin.replaceText(TextFieldSkin.java:576)
at com.sun.javafx.scene.control.behavior.TextFieldBehavior.replaceText(TextFieldBehavior.java:202)
at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.defaultKeyTyped(TextInputControlBehavior.java:238)
at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callAction(TextInputControlBehavior.java:139)
at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(BehaviorBase.java:218)
at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callActionForEvent(TextInputControlBehavior.java:127)
at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda$new$74(BehaviorBase.java:135)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$null$299(EmbeddedScene.java:310)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$keyEvent$300(EmbeddedScene.java:296)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
If i keep typing, the following line appears in the IDE as if locked in a loop:
Exception in thread "JavaFX Application Thread" java.lang.ArrayIndexOutOfBoundsException
Thanks, in advance, for any help anyone can give.

404 NullPointerException with AngularJs Java and Jersey

I've been asked to make an App with AngularJs, Bootstrap, Java and Tomcat as a server. I'm new with java ee so maybe my error is quite simple, but I can't find a solution.
So when I start the project I see my angular app, but when i press a button and it calls http://localhost:8080/MissingDogPoc/res/dog I get this error:
Http Status 500:
java.lang.NullPointerException
com.gabriel.missingdogpoc.service.AbstractFacade.findAll(AbstractFacade.java:42)
com.gabriel.missingdogpoc.service.DogFacadeREST.findAll(DogFacadeREST.java:69)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
SOLUTION
First if you have a web.xml in your WEB-INF you don't need it as long as you have an "ApplicatiationConfig.java" (This is auto-generated if you follow the netbeans tutorials that are out there)
The code will be like this:
package com.gabriel.missingdogpoc.service;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("api")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(com.gabriel.missingdogpoc.service.DogFacadeREST.class);
}
}
Then since Tomcat its a "Web-Server" and not an "Application Server" we need to manage the entities ourselves! So we have to make our Entity manager:
LocalEntityManagerFactory.java
package com.gabriel.missingdogpoc.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
#WebListener
public class LocalEntityManagerFactory implements ServletContextListener{
private static EntityManagerFactory emf;
#Override
public void contextInitialized(ServletContextEvent event) {
emf = Persistence.createEntityManagerFactory("com.gabriel_MissingDogPoc_war_1.0-SNAPSHOTPU");
}
#Override
public void contextDestroyed(ServletContextEvent event) {
emf.close();
}
public static EntityManager createEntityManager() {
if (emf == null) {
throw new IllegalStateException("Context is not initialized yet.");
}
return emf.createEntityManager();
}
}
And now since we have our own entity manager we need to use it in our rest service. You will probably have "Abrstract Facade" if you generated it with netbeans, and you will have to replace:
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().getTransaction().begin();
getEntityManager().persist(entity);
getEntityManager().getTransaction().commit();
}
public List<T> findAll() {
getEntityManager().getTransaction().begin();
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
List<T> res= getEntityManager().createQuery(cq).getResultList();
getEntityManager().getTransaction().commit();
return res;
}
If you have any problems with the backend you can check my code in github /Gaabooo/MissingDogPoc/
Your problem is that you're using Tomcat, which is an implementation of the Servlet and JSP specifications.
You've tried to turn it into a JavaEE 7 web container by adding Jersey and EclipseLink to it. Unfortunately it will still be missing the integration between the components. In your case, Jersey has no idea that it needs to inject an EntityManager into your DogFacadeREST object, so you get a NullPointerException as soon as you try to call it. Additionally, the #Stateless annotation will be completely ignored because you need to include EJB support as well for this.
It's way easier to use something like WildFly, TomEE or GlassFish and then you can throw away all those dependencies (except for the javaee-web-api).

Exception while runnig a javafx application jar file

I have a problem here with my javafx application jar, generated by Eclipse mars. Actually everything is running pretty well if I am running inside eclipse. However when I use the command line and try to run the jar of my application which was previously created by eclipse, using the command:
java -jar TalanTestingWithXPathFX.jar
I got a lot of errors in my terminal. The error are the following:
Exception in Application start method
java.lang.reflect.InvocationTargetException
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 com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
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 sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Location is not set.
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at talan.test.webApp.MainApp.initRootLayout(Unknown Source)
at talan.test.webApp.MainApp.start(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162 (Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
... 1 more
Exception running application talan.test.webApp.MainApp
This is some code from the main class
public class MainApp extends Application {
#FXML
private static Stage primaryStage;
#FXML
private AnchorPane rootLayout;
public Project mainProject;
public static rootLayOutController rootController;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setResizable(true);
this.primaryStage.setTitle("AutoGenDriver");
initRootLayout();
//showSubWindow();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("./view/rootLayOut.fxml"));
rootLayout = loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
//
primaryStage.setScene(scene);
rootController=loader.getController();
// Give the controller access to the main app.
rootLayOutController controller = loader.getController();
controller.setMainApp(this);
primaryStage.show();
} catch (IOException e) {
System.out.println("Loading error");
}
}
public void setProject(Project p){
this.mainProject = p;
}
/**
* Called when the user clicks New Project.
*/
#FXML
public static Project showNewProjectDialog() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/newProjectDialog.fxml"));
AnchorPane page = loader.load();
// Create the dialog Stage.
Stage dialogStage = new Stage();
dialogStage.setTitle("Add new Test Project");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
// Set the project into the controller.
newProjectDialogController controller = loader.getController();
controller.setDialogStage(dialogStage);
// controller.setProject(project);
// Show the dialog and wait until the user closes it
dialogStage.showAndWait();
return controller.getProject();
} catch (IOException e) {
System.out.println("Loading error");
return null;
}
}
public static void setPrimaryStage(Stage primaryStage) {
MainApp.primaryStage = primaryStage;
}
/**
* Returns the main stage.
* #return
*/
public static Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
this is some code from the rootLayOutController class
public void setRootTreeView(String nameProject) {
Image image=new Image(new File("C:\\Users\\DELL 3521\\workspaceMars\\TalanTestingFX\\Images\\dossier.png").toURI().toString(),20,20,true,true);
ImageView imv= new ImageView();
imv.setImage(image);
TreeItem<String> rootNode = new TreeItem<String>(tempProject.getName(),imv);
rootNode.setExpanded(true);
testProject.add(rootNode);
t.setRoot(rootNode);
}
/**
* add sub Elements to the TreeView
*
* #param mainApp
*/
public void addItemToTreeView(String item) {
testProject.get(0).getChildren().add(new TreeItem<String>(item));
}
public static Template getTemplate() {
return template;
}
public static void setTemplate(Template template) {
rootLayOutController.template = template;
}
public AnchorPane getContent() {
return content;
}
public void setContent(AnchorPane content) {
this.content = content;
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
#FXML
private void initialize() {
handleTreeViewSelectElement();
newSuiteItem.setDisable(true);
openPageItem.setDisable(true);
cnxItem.setDisable(true);
openPageItem.setDisable(true);
scItem.setDisable(true);
acItem.setDisable(true);
dactItem.setDisable(true);
}

Java swing JPanel example, GLCanvas error

public class Activator implements BundleActivator {
TestFrame testFrame = new TestFrame();
public static JPanel graphPanel;
public void start(BundleContext context) throws Exception {
graphPanel = cartesianGraphs.getGraphPanel();
testFrame.getPanel1().add(graphPanel);
testFrame.setVisible(true);
}
}
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private library kutuphane = null;
private JPanel contentPane;
private JTabbedPane tabbedPane;
private JPanel panel1;
private JButton btn;
public TestFrame() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
contentPane.add(getTabbedPane(), BorderLayout.CENTER);
contentPane.add(getBtn(), BorderLayout.NORTH);
}
public JPanel getPanel1() {
if (panel1 == null) {
panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
}
return panel1;
}
private JButton getBtn() {
if (btn == null) {
btn = new JButton("Remove All and Add");
btnTabSil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
TestFrame.this.getPanel1().removeAll();
Activator.graphPanel.revalidate();
// where it throws the exception is below
TestFrame.this.getPanel1().add(Activator.graphPanel);
TestFrame.this.revalidate();
TestFrame.this.repaint();
TestFrame.this.setVisible(true);
}
});
}
return btn;
}
}
In the activator class above I add (JPanel )graphpanel into (JPannel) testFrame.getPanel1() Then with a button in the testFrame class I used removeAll() method and add the static graphPannel again but I got the error below.
When I debug it I see that GLcanvas looses the peer. I couldnt find a solution.
Exception in thread "Thread-3" java.lang.RuntimeException:
javax.media.opengl.GLException: Unable to create temp OpenGL context
for device context 0xffffffffde01148b at
jogamp.common.awt.AWTEDTExecutor.invoke(AWTEDTExecutor.java:58) at
jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:103)
at
jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:205)
at
javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:172)
at javax.media.opengl.Threading.invoke(Threading.java:191) at
javax.media.opengl.awt.GLCanvas.display(GLCanvas.java:449) at
grafik.view.grafik.Gcontroller.draw(Gcontroller.java:169) at
grafik.model.data.Dcontroller.drawAll(Dcontroller.java:272) at
grafik.view.Wcontroller.GdataClean(Wcontroller.java:261) at
grafik.view.WThread.run(WThread.java:57) Caused by:
javax.media.opengl.GLException: Unable to create temp OpenGL context
for device context 0xffffffffde01148b at
jogamp.opengl.windows.wgl.WindowsWGLContext.createImpl(WindowsWGLContext.java:306)
at
jogamp.opengl.GLContextImpl.makeCurrentWithinLock(GLContextImpl.java:572)
at jogamp.opengl.GLContextImpl.makeCurrent(GLContextImpl.java:485)
at
jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:645)
at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:594)
at javax.media.opengl.awt.GLCanvas$8.run(GLCanvas.java:996) at
java.awt.event.InvocationEvent.dispatch(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$300(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source)
Please switch to JOGL 2.3.1. Then, replace "javax.media" by "com.jogamp" to avoid any compile error.
When you remove the AWT GLCanvas from its parent container, it loses its peer and its OpenGL context is destroyed. This is something that you can't avoid when using this kind of canvas. Switch to NEWT if this isn't the desired behavior.
The creation of another context might fail in some particular cases on some hardware. If you still get the same stack trace with the latest version of JOGL, please fill a bug report: http://jogamp.org/wiki/index.php/Jogl_FAQ#Bugreports_.26_Testing