How to use AWS SDK for java with maven? - java

I want to fetch the messages in the SQS queue. I am using the maven for the first time. Here are the steps I have did so far.
1. Created maven project using this command:
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=aws-try -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
The above command created a aws-try directory with src folder and pom.xml.
2. Added AWS-SDK dependency in pom.xml:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.78</version>
</dependency>
3. Added the SQSTry.java file under src > main > java > com > mycompany > app > SQSTry.java
package com.mycompany.app;
import java.util.List;
import java.util.Map.Entry;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;
public class SQSTry {
public static void main (String args[]) {
System.out.println("SQSTry");
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
AmazonSQS sqs = new AmazonSQSClient(credentials);
Region apNortheast1 = Region.getRegion(Regions.AP_NORTHEAST_1);
sqs.setRegion(apNortheast1);
System.out.println("===========================================");
System.out.println("Getting Started with Amazon SQS");
System.out.println("===========================================\n");
}
}
4. Now package command
mvn package
The above command was run against the pom.xml in the root of aws-try directory.
This gives the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/amazonaws/AmazonClientException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2625)
at java.lang.Class.getMethod0(Class.java:2866)
at java.lang.Class.getMethod(Class.java:1676)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: com.amazonaws.AmazonClientException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more
I have added the dependency correctly. If you have noticed the above SQSTry.java file, the AWSCredentials was also a package from amazon, but id does not give any error.
What am I missing ?

You need to add maven-shade-plugin to the pom.xml which packages all AWS sdk jars to a standalone jar file.
Adding the following worked for me:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
I found this solution from here.

Can you try mvn clean install. Also verify if you are using the right version for the SDK
Try adding
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-core -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>1.11.78</version>
</dependency>

Related

Could not find or load main class when running JAR on Ubuntu [duplicate]

I'm getting this error
Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Ap
plication
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
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)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
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)
... 13 more
When trying to run my class file, this is the source
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.concurrent.Executor;
public class TestApplication extends Application{
#Override
public void start(Stage stage) throws Exception {
new TestApplication();
}
public TestApplication() {
try{
final Parent root = FXMLLoader.load(Executor.class.getResource("test.fxml"));
final Stage stage = new Stage(){{
setScene(new Scene(root, 300, 250));
setTitle("Test");
setResizable(false);
show();
}};
}catch(Exception e){
e.printStackTrace();
}
}
}
The fxml file contains a simple gui.
I've worked on this very same issue for the past few hours. Even though I haven't seen it written explicitly, it appears that you MUST use one of the JavaFX packaging tools, which is either an Ant task or the javafxpackager executable. (See http://docs.oracle.com/javafx/2/deployment/packaging.htm, section 5.3.1). The NetBeans IDE uses Ant to package the code. (I'm using IntelliJ)
When you use one of those packaging methods, in addition to all of your application's code and resources, it also adds the following to your output JAR file:
/com/javafx/main/Main$1.class
/com/javafx/main/Main$2.class
/com/javafx/main/Main.class
/com/javafx/main/NoJavaFXFallback.class
With these in place, you can run the app from the command line:
java -jar outjar.jar
and all works fine. If I remove the extra com.javafx.main files, the app does not run.
To double-check this, I looked at all four JAR files in the JavaFX samples (BrickBreaker, Ensemble, FXML-LoginDemo, and SwingInterop). They all have the "extra" files, too.
For my small test app, I used this command line to build an "executable" JAR file:
javafxpackager -createjar -appclass sample.Main -outfile outjar -v -nocss2bin -srcdir C:\workspaces\garoup1\out\production\javafx1
Hope this helps!
I had the same problem and below steps helped me to solve it,
Adding the vm arguments while running the application,
--module-path /home/user/Java-libraries/openjfx-11.0.2_linux-x64_bin-sdk/javafx-sdk-11.0.2/lib/ --add-modules javafx.controls,javafx.fxml
Note:
The --module-path will contain the jars of Java fx
I used open-jdk 13
Configure this in your eclipse (If you are using so) or you can just compile and run like,
Compile
javac --module-path /path/to/java-fx-libs/ --add-modules javafx.controls,javafx.fxml *.java
Run
java --module-path /path/to/java-fx-libs/ --add-modules javafx.controls,javafx.fxml MyMainClass
I believe that my example will help someone. I had not succeeded with building REALLY executable jar file, that can be run by click from any place/directory with Java 8. Moving to Java 11 and few other twicks did the business.
Move to Java 11. Specify SDK, other staff in IDE, add this to pom.xml
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
Add JavaFX dependencies
<!--JavaFX-->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>15.0.1</version>
<type>pom</type>
</dependency>
<!--JavaFX-controls-->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>15.0.1</version>
</dependency>
Build application
Create wrapper class for your Main class, which extends Application
public class Launcher {
public static void main(String[] args) {
Main.main(args);
}
}
Add the following to pom.xml
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>path-to-launcher.Launcher</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<finalName>final-jar-file-name</finalName>
<archive>
<manifest>
<mainClass>path-to-launcher.Launcher</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Run this maven command
mvn clean -Dmaven.clean.failOnError=false compile assembly:single -DskipTests=true
The jar file with specified name will appear in target directory. It will be executable independent from where you are running it.
Using java 8 shouldn't give this problem but it did for me
I created my jar initially from Eclipse Export -> Runnable Jar and it was fine. When I moved to Maven it failed with the above.
Comparing the two jars showed that nothing fx related was packaged with the jar (as I'd expect) but that the Eclipse generated manifest had Class-Path: . in it. Getting maven to package the jar with the following worked for me (with Java 8)
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.pg.fxapplication.Main</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
I know it may not be the "proper" way of launching an javafx application but i have struggled with this problem for some time and came up with a workaround that does not require to use any external packaging applications, force you to use ant or maven plugin (which conflicts with the shade plugin) etc...
The solution uses Utils4j to load jfxrt dynamically at runtime. You cannot load it in a class extending javafx.application.Application, do it in a separate class and name it for example: Launcher
import org.fuin.utils4j.Utils4J
public class Launcher {
public static void main(String[] args) {
Utils4J.addToClasspath("file:///"+System.getProperty("java.home")+ File.separator+"lib"+File.separator+"jfxrt.jar");
// CODE TO RUN YOUR CLASS THAT EXTENDS javafx.application.Application goes here.
}
}
you can include Utils4j with your project (if using maven):
<dependency>
<groupId>org.fuin</groupId>
<artifactId>utils4j</artifactId>
<version>0.7.0</version>
</dependency>
I use maven and I just run this mvn install:install-file -Dfile="/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/jfxrt.jar" -DgroupId=com.oracle.javafx -DartifactId=javafx -Dversion=2.2 -Dpackaging=jar in terminal(Maybe a little difference in Windows.). Then maven will install jfxrt.jar then you can simply reference it as
<dependency>
<groupId>com.oracle.javafx</groupId>
<artifactId>javafx</artifactId>
<version>2.2</version>
</dependency>
If you are using netbeans like me and you have two versions of JDK installed, then you should change the classpath to the appropriate java installation in the config file. This is also a bug in Netbeans:
There are two ways to do it:
Either start NetBeans with --jdkhome by executing this:
"C:\Program Files\NetBeans Dev 201402160001\bin\netbeans.exe" --jdkhome "C:\Program Files\Java\jdk1.7.0_51"
Or set the "netbeans_jdkhome" property in /etc/netbeans.conf e.g.
# Default location of JDK, can be overridden by using --jdkhome <dir>:
netbeans_jdkhome="C:\Program Files\Java\jdk1.7.0_51"
IntelliJ and maybe other IDE's do not refactor your Run/Debug configuration. You must manually change your package name preceding the name of your Main class. For instance, change 'sample.Main' to 'com.company.package.ui.Main' so it will launch correctly next time you try to run it. The IDE might have already marked the Run/Debug button with a red cross because it couldn't find the main class. It also gives a warning when you open the Run/Debug configuration.
I already answered it on "Ask ubntu".
I recommend you to go with https://openjfx.io/openjfx-docs/ .i am using Eclipse IDE but it works for all IDE
Then you can refer to this global variable when setting the VM options as:
In IDE Right-click on project->Run As -> Run Configuration ->Arguments->VM Arguments
For Windows,
--module-path "\path to javafx\lib" --add-modules javafx.controls,javafx.fxml
For Linux,
--module-path /path to javafx/lib --add-modules javafx.controls,javafx.fxml
I'm developing on Linux a simple WebApp i got the same error, but is really easy to fix it (assuming you are developing on the command line as myself).
cat compile.sh
#!/bin/bash
/usr/lib/jvm/jdk1.7.0_25/bin/javac WebViewSample.java -cp /usr/lib/jvm/jdk1.7.0_25
/jre/lib/jfxrt.jar
$ cat run.sh
#!/bin/sh
JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25/bin/
CLASSPATH=/usr/lib/jvm/jre1.7.0_25/lib/jfxrt.jar:.
$JAVA_HOME/java -cp $CLASSPATH WebViewSample $* 2>&1 /dev/null | awk -F\| '{ print $2"|"$3 ; exit $1 }'
exit $?
I had a problem of not finding the Pair class from javafx.
It seems that vanilla eclipse (without the e(fx)clipse extension) doesn't search the javaFX runtime jar included with java.
I just added to my eclipse project build path this external jar (or if you are in a debug configuration, add the external jar in the JRE tab of the debug configuration):
$JAVA_HOME/jre/lib/ext/jfxrt.jar
(replace JAVA_HOME with your jdk folder)
For me it was in /installs/jdk1.8.0_211/jre/lib/ext/jfxrt.jar
in eclipse environment: add jfxrt.jar to Bundle-ClassPath in MANIFEST.MF file.
Bundle-ClassPath: .,
jfxrt.jar

ClassNotFoundException error when trying to run java project using maven

In order to execute a java project using maven, I put on the terminal this two commands:
To build project:
mvn package
To run project:
mvn exec:java
The build always execute with success, but every time I try to run the project, I receive this error:
java.lang.ClassNotFoundException: com.pipa.api.Application
at java.net.URLClassLoader.findClass (URLClassLoader.java:471)
at java.lang.ClassLoader.loadClass (ClassLoader.java:588)
at java.lang.ClassLoader.loadClass (ClassLoader.java:521)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:281)
at java.lang.Thread.run (Thread.java:834)
Do you know what may be happening?
This is my Application.java file, with main function inside
package com.pipa.api;
import com.pipa.api.handlers.FetchUserPositionHandler;
import com.pipa.api.handlers.HighScoreHandler;
import com.pipa.api.handlers.ScoreRegisterHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
public class Application {
public static void main(String[] args) throws IOException {
int serverPort = 8000;
HttpServer server = HttpServer.create(new InetSocketAddress(serverPort), 0);
server.createContext("/", new FetchUserPositionHandler());
server.createContext("/highscorelist", new HighScoreHandler());
server.createContext("/score", new ScoreRegisterHandler());
server.setExecutor(null);
server.start();
}
}
This is my pom.xml
<groupId>com.pipa.httpserver</groupId>
<artifactId>pipa</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<mainClass>com.pipa.api.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
I finally did this works. I discover that I need to put main / java right after src, on my project folder structure, following the pattern that maven uses. I did not notice, but even that my build command was working, my .jar file was been generated empty.

Spring boot application cannot run using cmd

I try to run my compiled jar file using java -jar jarfile.jar but it returning following error.
Exception in thread "main" java.lang.ClassNotFoundException: MainApplication
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:93)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.PropertiesLauncher.main(PropertiesLauncher.java:593)
Why this is happening. When i run in the spring tool suit it run perfectly. This happen only when i try to run my application using CMD windows
SOLVED This answer is correct.
This is the error i have done when configuration of my pom.xml in the api module of my project.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.0.RELEASE</version>
<configuration>
<mainClass>com.mobios.MainApplication</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Following line create error
<mainClass>MainApplication</mainClass>
This define the main class of the application. But i have only mentioned the class name only. It must include the group id also. I think lot of people doing this kind of simple mistakes like me. As a spring boot beginner i think it is common. The above line must be like following.
<mainClass>com.mobios.MainApplication</mainClass>
Now working fine when building the jar and run it. But without group id i can run the project in eclipse or any other development tool you are using.
Did you add this type of spring boot application class?
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class FApplication {
public static void main(String[] args) {
SpringApplication.run(FApplication.class, args);
}
}
May be your application can not find java manifest on your jar file.
Open command prompt and goto your where pom.xml presents
run mvn clean install
once you get the message build successful
goto target folder by cd target
then run the command java -jar <file-name>.jar
if you are still getting the error message while running then some spring config is wrong.
create new spring boot application from https://start.spring.io/

Very simple step by step JBehave setup tutorial?

Though I have read many, but many articles on how to use JBehave, I can't get it to work. Here are the steps I went through so far:
Created new Java Project
Downloaded JBehave JAR file version 3.6.8 and added it to my build path libraries
Created a package called com.wmi.tutorials.bdd.stack.specs under the test source folder in my workspace
Added the JBehave JAR file to my Build path Library configuration
Created a JBehave story in the above-mentioned package (StackBehaviourStories.story)
Created a Java class in the above-mentioned package (StackBehaviourStory.java)
Created a Java class in the above-mentioned package (StackBehaviourSteps.java)
Imported the Given, Named, Then, When annotations in my Java class
Written two different scenarios in my JBehave story file
And still, I can't get it to work/run! =(
The story file:
Narrative:
In order to learn to with JBehave using Eclipse
As a junior Java developer though senior in .Net and in BDD
I want to define the behaviour of a custom stack
Scenario: I push an item onto the stack
Given I have an empty stack
When I push an item 'orange'
Then I should count 1
Scenario: I pop from the stack
Given I have an empty stack
When I push an item 'apple'
And I pop the stack
Then I should count 0
The story class
package com.wmi.tutorials.bdd.stack.specs
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.junit.JUnitStory;
public class StackBehaviourStory extends JUnitStory {
#Override
public Configuration configuration() { return new MostUsefulConfiguration(); }
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration()
, new StackBehaviourSteps());
}
}
The steps class
package com.wmi.tutorials.bdd.stack.specs
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.junit.Assert;
public class StackBehaviourSteps {
#Given("I have an empty stack")
public void givenIHaveAnEmptyStack() { stack = new CustomStack(); }
#When("I push an item $item")
public void whenIPushAnItem(#Named("item") String item) { stack.push(item); }
#Then("I should count $expected")
public void thenIShouldCount(#Named("expected") int expected) {
int actual = stack.count();
if (actual != expected)
throw new RuntimeException("expected:"+expected+";actual:"+actual);
}
}
I'm currently using Eclipse Kepler (4.3) JEE with everything I need to use JUnit, Google App Engine, and yes, JBehave is installed correctly following the Eclipse JBehave installation tutorial.
I can't get it to work. So how can I make it work correctly using Eclipse, JBehave and JUnit?
I know I'm late to the party here but I'm posting because this is the info I wish I had a week ago as it would've saved me a lot of pain. I'm very much into the idea of BDD, but am unfortunately finding JBehave's docs to be a bit of a nightmare, especially when it comes to Maven integration. Moreover a lot of the code I found both on their website and elsewhere didn't work. Through trial and error, and lots of tutorials, I was able to piece together the following. It runs both in Maven and Eclipse, has a single binding class that maps stories to step files, and is able to find story files located in src/test/resources.
here is a working pom file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.projectvalis.st1</groupId>
<artifactId>st1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>st1</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument></compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${failsafe.and.surefire.version}</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<version>4.0.2</version>
<executions>
<execution>
<id>run-stories-as-embeddables</id>
<phase>integration-test</phase>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
<ignoreFailureInStories>false</ignoreFailureInStories>
<ignoreFailureInView>false</ignoreFailureInView>
<systemProperties>
<property>
<name>java.awt.headless</name>
<value>true</value>
</property>
</systemProperties>
</configuration>
<goals>
<goal>run-stories-as-embeddables</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-core</artifactId>
<version>4.0.2</version>
</dependency>
</dependencies>
</project>
here is a sample story file
Narrative:
In order to work with files to compress
As a guy who wants to win a bet with cameron
I want to ensure files are ingested and processed in the manner in which the
methods in the ingest class purport to process them.
Scenario: Simple test to give JBehave a test drive
Given a file, a.log
When the caller loads the file as a byte array
Then the byte array that is returned contains the correct number of bytes.
here is a sample step file
package com.projectvalis.compUtils.tests.ingest;
import java.io.File;
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;
import org.junit.Assert;
import com.projectvalis.compUtils.util.fileIO.Ingest;
/**
* BDD tests for the ingest class
* #author funktapuss
*
*/
public class LoadByteSteps extends Steps {
private String fNameS;
private byte[] byteARR;
#Given("a file, $filename")
public void setFileName(#Named("filename") String filename) {
File file = new File(getClass().getResource("/" + filename).getFile());
fNameS = file.getPath();
}
#When("the caller loads the file as a byte array")
public void loadFile() {
byteARR = Ingest.loadFile(fNameS);
}
#Then("the byte array that is returned contains the "
+ "correct number of bytes.")
public void checkArrSize() {
File file = new File(fNameS);
Assert.assertTrue(
"loading error - "
+ "the file and the resultant byte array are different sizes!",
(long)byteARR.length == file.length());
}
}
and here is the generic runner
package com.projectvalis.compUtils.tests.runner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.core.steps.Steps;
import com.projectvalis.compUtils.tests.ingest.LoadByteSteps;
/**
* generic binder for all JBehave tests. Binds all the story files to the
* step files. works for both Eclipse and Maven command line build.
* #author funktapuss
*
*/
public class JBehaveRunner_Test extends JUnitStories {
#Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(
new LoadFromClasspath(this.getClass().getClassLoader()))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withFormats(Format.HTML, Format.CONSOLE)
.withRelativeDirectory("jbehave-report")
);
}
#Override
public InjectableStepsFactory stepsFactory() {
ArrayList<Steps> stepFileList = new ArrayList<Steps>();
stepFileList.add(new LoadByteSteps());
return new InstanceStepsFactory(configuration(), stepFileList);
}
#Override
protected List<String> storyPaths() {
return new StoryFinder().
findPaths(CodeLocations.codeLocationFromClass(
this.getClass()),
Arrays.asList("**/*.story"),
Arrays.asList(""));
}
}
the runner lives in src/test/java//tests.runner.
the ingest test lives in src/test/java//tests.ingest.
the story files live in src/test/resources/stories.
As far as I can tell, JBehave has LOTS of options, so this certainly isn't the only way of doing things. Treat this like a template that will get you up and running quickly.
full source is on github.
Following step by step closely the jbehave Getting Started tutorial, the Run story section says: [...] the ICanToggleACell.java class will allow itself to run as a JUnit test.
This means that the JUnit library is required in your Build path.
Using Eclipse:
Select your current project and right-click it, Build path, Configure Build Path...
Properties for [current project], Java Build Path, Libraries, click [Add Library...]
Add Library, select JUnit, click [Next]
JUnit Library, JUnit library version, select the version you wish to use, click [Finish]
Java Build Path, click [OK]
Project Explorer, select your ICanToggleACell.java class, right-click it, then Run As, and click on JUnit Test
So this is the same here as for the above-example code. The StackBehaviourStory.java class should let itself run as a JUnit test after you add the proper library to the Java build path.
In my case, I have extended my Steps class from Steps (from jbehave core)
i had updated the JunitStory to JunitStories and it worked
public class StackBehaviourStory extends JUnitStory ---> JunitStories

JavaFX Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Application

I'm getting this error
Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Ap
plication
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
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)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
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)
... 13 more
When trying to run my class file, this is the source
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.concurrent.Executor;
public class TestApplication extends Application{
#Override
public void start(Stage stage) throws Exception {
new TestApplication();
}
public TestApplication() {
try{
final Parent root = FXMLLoader.load(Executor.class.getResource("test.fxml"));
final Stage stage = new Stage(){{
setScene(new Scene(root, 300, 250));
setTitle("Test");
setResizable(false);
show();
}};
}catch(Exception e){
e.printStackTrace();
}
}
}
The fxml file contains a simple gui.
I've worked on this very same issue for the past few hours. Even though I haven't seen it written explicitly, it appears that you MUST use one of the JavaFX packaging tools, which is either an Ant task or the javafxpackager executable. (See http://docs.oracle.com/javafx/2/deployment/packaging.htm, section 5.3.1). The NetBeans IDE uses Ant to package the code. (I'm using IntelliJ)
When you use one of those packaging methods, in addition to all of your application's code and resources, it also adds the following to your output JAR file:
/com/javafx/main/Main$1.class
/com/javafx/main/Main$2.class
/com/javafx/main/Main.class
/com/javafx/main/NoJavaFXFallback.class
With these in place, you can run the app from the command line:
java -jar outjar.jar
and all works fine. If I remove the extra com.javafx.main files, the app does not run.
To double-check this, I looked at all four JAR files in the JavaFX samples (BrickBreaker, Ensemble, FXML-LoginDemo, and SwingInterop). They all have the "extra" files, too.
For my small test app, I used this command line to build an "executable" JAR file:
javafxpackager -createjar -appclass sample.Main -outfile outjar -v -nocss2bin -srcdir C:\workspaces\garoup1\out\production\javafx1
Hope this helps!
I had the same problem and below steps helped me to solve it,
Adding the vm arguments while running the application,
--module-path /home/user/Java-libraries/openjfx-11.0.2_linux-x64_bin-sdk/javafx-sdk-11.0.2/lib/ --add-modules javafx.controls,javafx.fxml
Note:
The --module-path will contain the jars of Java fx
I used open-jdk 13
Configure this in your eclipse (If you are using so) or you can just compile and run like,
Compile
javac --module-path /path/to/java-fx-libs/ --add-modules javafx.controls,javafx.fxml *.java
Run
java --module-path /path/to/java-fx-libs/ --add-modules javafx.controls,javafx.fxml MyMainClass
I believe that my example will help someone. I had not succeeded with building REALLY executable jar file, that can be run by click from any place/directory with Java 8. Moving to Java 11 and few other twicks did the business.
Move to Java 11. Specify SDK, other staff in IDE, add this to pom.xml
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
Add JavaFX dependencies
<!--JavaFX-->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>15.0.1</version>
<type>pom</type>
</dependency>
<!--JavaFX-controls-->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>15.0.1</version>
</dependency>
Build application
Create wrapper class for your Main class, which extends Application
public class Launcher {
public static void main(String[] args) {
Main.main(args);
}
}
Add the following to pom.xml
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>path-to-launcher.Launcher</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<finalName>final-jar-file-name</finalName>
<archive>
<manifest>
<mainClass>path-to-launcher.Launcher</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Run this maven command
mvn clean -Dmaven.clean.failOnError=false compile assembly:single -DskipTests=true
The jar file with specified name will appear in target directory. It will be executable independent from where you are running it.
Using java 8 shouldn't give this problem but it did for me
I created my jar initially from Eclipse Export -> Runnable Jar and it was fine. When I moved to Maven it failed with the above.
Comparing the two jars showed that nothing fx related was packaged with the jar (as I'd expect) but that the Eclipse generated manifest had Class-Path: . in it. Getting maven to package the jar with the following worked for me (with Java 8)
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.pg.fxapplication.Main</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
I know it may not be the "proper" way of launching an javafx application but i have struggled with this problem for some time and came up with a workaround that does not require to use any external packaging applications, force you to use ant or maven plugin (which conflicts with the shade plugin) etc...
The solution uses Utils4j to load jfxrt dynamically at runtime. You cannot load it in a class extending javafx.application.Application, do it in a separate class and name it for example: Launcher
import org.fuin.utils4j.Utils4J
public class Launcher {
public static void main(String[] args) {
Utils4J.addToClasspath("file:///"+System.getProperty("java.home")+ File.separator+"lib"+File.separator+"jfxrt.jar");
// CODE TO RUN YOUR CLASS THAT EXTENDS javafx.application.Application goes here.
}
}
you can include Utils4j with your project (if using maven):
<dependency>
<groupId>org.fuin</groupId>
<artifactId>utils4j</artifactId>
<version>0.7.0</version>
</dependency>
I use maven and I just run this mvn install:install-file -Dfile="/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/jfxrt.jar" -DgroupId=com.oracle.javafx -DartifactId=javafx -Dversion=2.2 -Dpackaging=jar in terminal(Maybe a little difference in Windows.). Then maven will install jfxrt.jar then you can simply reference it as
<dependency>
<groupId>com.oracle.javafx</groupId>
<artifactId>javafx</artifactId>
<version>2.2</version>
</dependency>
If you are using netbeans like me and you have two versions of JDK installed, then you should change the classpath to the appropriate java installation in the config file. This is also a bug in Netbeans:
There are two ways to do it:
Either start NetBeans with --jdkhome by executing this:
"C:\Program Files\NetBeans Dev 201402160001\bin\netbeans.exe" --jdkhome "C:\Program Files\Java\jdk1.7.0_51"
Or set the "netbeans_jdkhome" property in /etc/netbeans.conf e.g.
# Default location of JDK, can be overridden by using --jdkhome <dir>:
netbeans_jdkhome="C:\Program Files\Java\jdk1.7.0_51"
IntelliJ and maybe other IDE's do not refactor your Run/Debug configuration. You must manually change your package name preceding the name of your Main class. For instance, change 'sample.Main' to 'com.company.package.ui.Main' so it will launch correctly next time you try to run it. The IDE might have already marked the Run/Debug button with a red cross because it couldn't find the main class. It also gives a warning when you open the Run/Debug configuration.
I already answered it on "Ask ubntu".
I recommend you to go with https://openjfx.io/openjfx-docs/ .i am using Eclipse IDE but it works for all IDE
Then you can refer to this global variable when setting the VM options as:
In IDE Right-click on project->Run As -> Run Configuration ->Arguments->VM Arguments
For Windows,
--module-path "\path to javafx\lib" --add-modules javafx.controls,javafx.fxml
For Linux,
--module-path /path to javafx/lib --add-modules javafx.controls,javafx.fxml
I'm developing on Linux a simple WebApp i got the same error, but is really easy to fix it (assuming you are developing on the command line as myself).
cat compile.sh
#!/bin/bash
/usr/lib/jvm/jdk1.7.0_25/bin/javac WebViewSample.java -cp /usr/lib/jvm/jdk1.7.0_25
/jre/lib/jfxrt.jar
$ cat run.sh
#!/bin/sh
JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25/bin/
CLASSPATH=/usr/lib/jvm/jre1.7.0_25/lib/jfxrt.jar:.
$JAVA_HOME/java -cp $CLASSPATH WebViewSample $* 2>&1 /dev/null | awk -F\| '{ print $2"|"$3 ; exit $1 }'
exit $?
I had a problem of not finding the Pair class from javafx.
It seems that vanilla eclipse (without the e(fx)clipse extension) doesn't search the javaFX runtime jar included with java.
I just added to my eclipse project build path this external jar (or if you are in a debug configuration, add the external jar in the JRE tab of the debug configuration):
$JAVA_HOME/jre/lib/ext/jfxrt.jar
(replace JAVA_HOME with your jdk folder)
For me it was in /installs/jdk1.8.0_211/jre/lib/ext/jfxrt.jar
in eclipse environment: add jfxrt.jar to Bundle-ClassPath in MANIFEST.MF file.
Bundle-ClassPath: .,
jfxrt.jar

Categories

Resources