JavaFX : 'About' MenuItem is missing from the 'Application Menu' in OSX - java

I created a hello World Application in JavaFX and I will be using both QuitHandler and AboutHandler, I've noticed that 'About' and 'Preferences' menu Items are not shown in the menu :
How can I make it look like :
Also , QuitHandler is not executing the check save behaviour , here is the code of the javaFX Hello World.
package helloworld;
import com.apple.eawt.AppEvent;
import com.apple.eawt.QuitResponse;
import java.security.AccessControlException;
import java.util.Optional;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Sample application.
* #author me
*/
public class HelloWorldApplication extends Application {
// constants --------------------------------------------------------------------------------
private static final Logger LOG = LogManager.getLogger();
/**
* Running on Mac platform.
*/
public static final boolean MAC;
static {
boolean mac = false;
try {
final String osName = System.getProperty("os.name");
LOG.debug("OS: {}", osName);
mac = osName != null && osName.toLowerCase().contains("mac");
} catch (AccessControlException ex) {
LOG.debug("Cannot determine OS");
}
MAC = mac;
}
// member variables -------------------------------------------------------------------------
private final Alert mAlert = new Alert(Alert.AlertType.CONFIRMATION);
// methods ----------------------------------------------------------------------------------
#Override
public void start(Stage pStage) {
final BorderPane root = new BorderPane();
final MenuBar menuBar = new MenuBar();
final Menu fileMenu = new Menu("_File");
menuBar.getMenus().add(fileMenu);
// Exit
boolean macQuitMenuItem = false;
if (MAC) {
final com.apple.eawt.Application application = com.apple.eawt.Application.getApplication();
try {
application.setQuitHandler(
(AppEvent.QuitEvent pEvt, QuitResponse pQuitResponse) -> Platform.runLater(
() -> exit(pQuitResponse::cancelQuit)
)
);
macQuitMenuItem = true;
// occurs when running as untrusted applet
} catch (AccessControlException ex) {
LOG.debug("Cannot listen for application quit");
}
}
if (!macQuitMenuItem) {
fileMenu.getItems().add(new SeparatorMenuItem());
final MenuItem exitMenuItem = new MenuItem("E_xit");
exitMenuItem.setOnAction(pEvt -> exit(() -> {}));
fileMenu.getItems().add(exitMenuItem);
}
root.setTop(menuBar);
root.setCenter(new TextArea("Hello, world!"));
final Scene scene = new Scene(root, 300, 250);
pStage.setTitle("Hello World!");
pStage.setScene(scene);
mAlert.initOwner(pStage);
mAlert.setTitle("Confirm Exit");
mAlert.setHeaderText("Look, a Confirmation Dialog");
mAlert.setContentText("Are you sure you want to exit?");
pStage.show();
}
public static void main(String[] pArgs) {launch(pArgs);}
public void exit() {exit(() -> {});}
public void exit(Runnable pAbortExitRunnable) {
LOG.info("Exit");
if (checkUnsavedChanges()) {
Platform.exit();
} else {
pAbortExitRunnable.run();
}
}
private boolean checkUnsavedChanges() {
final Optional<ButtonType> result = mAlert.showAndWait();
return result.isPresent() && result.get() == ButtonType.OK;
}
}
I want to know what is wrong with this code ?
Edit 1 : pom.xml to compile and test this code.
<?xml version="1.0" encoding="UTF-8"?>
<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>app</groupId>
<artifactId>helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.yuvimasory</groupId>
<artifactId>orange-extensions</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>initialize</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>helloworld.HelloWorldApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

Getting the OSX menu to work with a JavaFX application is tricky business. I can recommend you to have a look at https://github.com/codecentric/NSMenuFX

Related

Package Twitter4j does not exist after packaging Jar

I am trying to create a Twitter app with Java, running the application from Idea works and the Tweet gets sent, however after running mvn clean package and java -jat TwitterClient-1.0-SNAPSHOT.jar, then clicking the send tweet button I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: twitter4j/conf/ConfigurationBuilder
at company.fourleafclover.TwitterClient.Main$1.actionPerformed(Main.java:59)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6617)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6382)
at java.desktop/java.awt.Container.processEvent(Container.java:2264)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4993)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2322)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4934)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4563)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4504)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2308)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2773)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.ClassNotFoundException: twitter4j.conf.ConfigurationBuilder
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
... 36 more
my Main class and pom.xml:
package company.fourleafclover.TwitterClient;
import twitter4j.*;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
System.out.println("Started!");
final JFrame frame = new JFrame("Twitter Client");
JLabel lblKey = new JLabel("API Key:");
JTextField tfKey = new JTextField(20);
lblKey.setLabelFor(tfKey);
JLabel lblSecret = new JLabel("API Secret:");
JTextField tfSecret = new JTextField(20);
lblSecret.setLabelFor(tfSecret);
JLabel lblToken = new JLabel("Access Token:");
JTextField tfToken = new JTextField(20);
lblToken.setLabelFor(tfToken);
JLabel lblASecret = new JLabel("Access Secret:");
JTextField tfAsecret = new JTextField(20);
lblASecret.setLabelFor(tfAsecret);
JLabel lblmsg = new JLabel("Message:");
JTextField tfmsg = new JTextField(20);
lblmsg.setLabelFor(tfmsg);
JButton btnGet = new JButton("Send tweet");
btnGet.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String consumerKey = new String(tfKey.getText());
String consumerSecret = new String(tfSecret.getText());
String oAuthAccessToken = new String(tfToken.getText());
String oAuthAccessTokenSecret = new String(tfAsecret.getText());
String Msg = new String(tfmsg.getText());
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(oAuthAccessToken)
.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
Status status = twitter.updateStatus(Msg);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
} catch (Exception te) {
te.printStackTrace();
}
JOptionPane.showMessageDialog(frame,
"Tweet sent!");
}
});
JButton btnLogin = new JButton("button");
JPanel panel = new JPanel();
panel.setLayout(new SpringLayout());
panel.add(lblKey);//API Key
panel.add(tfKey);//Api Key
panel.add(lblSecret);//Access Secret
panel.add(tfSecret);panel.add(lblToken);//API Token
panel.add(tfToken);//API Token
panel.add(lblASecret);
panel.add(tfAsecret);
panel.add(lblmsg);
panel.add(tfmsg);
panel.add(btnLogin);
panel.add(btnGet);
jtextfielddemo.SpringUtilities.makeCompactGrid(panel,
6, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(470, 200);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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>company.fourleafclover</groupId>
<artifactId>TwitterClient</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>io.github.cdimascio</groupId>
<artifactId>dotenv-java</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>4.0.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>company.fourleafclover.TwitterClient.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
I have also tried downladoing and importing Twitter4j-core into the Module Settings, which had no effect. Module Settings
Something is wrong with your build tag.
This works fine for me. You than have to take the one with jar-with-dependencies
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>Your.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>
</build>

Annotation processor not executed

I am learning about annotation processor. I have created a following test project.
Project structure:
annotation MessageManager:
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public #interface MessageManager {
public String messageBase() default "lang/res";
}
class MessageManagerProcessor:
package processor;
import annotation.MessageManager;
import com.google.auto.service.AutoService;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import java.io.File;
import java.io.IOException;
import java.util.*;
#AutoService(MessageManagerProcessor.class)
#SupportedSourceVersion(SourceVersion.RELEASE_8)
public class MessageManagerProcessor extends AbstractProcessor {
#Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotations = new LinkedHashSet<>();
annotations.add(MessageManager.class.getCanonicalName());
System.out.println("im here");
return annotations;
}
#Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(MessageManager.class)) {
System.out.println(element);
}
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
System.out.println("IM HEEEEEEERE");
return false;
}
}
MessageManagerImpl:
package test;
import annotation.MessageManager;
#MessageManager
public class MessageManagerImpl {
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
<artifactId>SpringMessageManager</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<generatedSourcesDirectory>${project.build.directory}
/generated-sources/</generatedSourcesDirectory>
<annotationProcessors>
<annotationProcessor>
processor.MessageManagerProcessor
</annotationProcessor>
</annotationProcessors>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<compilerArgument>
-proc:none
</compilerArgument>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>1.0-rc7</version>
</dependency>
</dependencies>
</project>
I am executing the project with mvn clean install but the annotation processor is not executed. Should I run the processor some other way? Also META-INF/services/javax.annotation.processing.Processor contains path to my processor processor.MessageManagerProcessor

Getting cucumber.runtime.CucumberException: Couldn't load plugin class: prettty while running cucmber script using Testng

Hi I am trying to run a script developed using cucumber with testng but i am getting error as follows -:
cucumber.runtime.CucumberException: Couldn't load plugin class: prettty
at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:175)
at cucumber.runtime.formatter.PluginFactory.pluginClass(PluginFactory.java:165)
at cucumber.runtime.formatter.PluginFactory.getPluginClass(PluginFactory.java:226)
at cucumber.runtime.formatter.PluginFactory.isFormatterName(PluginFactory.java:195)
at cucumber.runtime.RuntimeOptionsFactory.addPlugins(RuntimeOptionsFactory.java:90)
at cucumber.runtime.RuntimeOptionsFactory.buildArgsFromOptions(RuntimeOptionsFactory.java:37)
at cucumber.runtime.RuntimeOptionsFactory.create(RuntimeOptionsFactory.java:24)
at cucumber.api.testng.TestNGCucumberRunner.<init>(TestNGCucumberRunner.java:37)
at cucumber.api.testng.AbstractTestNGCucumberTests.setUpClass(AbstractTestNGCucumberTests.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:514)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:178)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:782)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.ClassNotFoundException: prettty
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:173)
... 32 more
My Framework structure is as follows -:
framework
My pom file is as follows -:
<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.w2a</groupId>
<artifactId>CucumberPageObjects</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-core</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.9.1</version>
</dependency>
<dependency>
<groupId>com.vimalselvam</groupId>
<artifactId>cucumber-extentsreport</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<fork>true</fork>
<executable>C:\Program Files\Java\jdk1.8.0_161\bin\javac.exe</executable>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<includes>
<exclude>**/*Demo.java</exclude>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.20</version>
</plugin>
</plugins>
</build>
</project>
My Runner class is as follows -:
package runner;
import java.io.File;
import java.text.SimpleDateFormat;
impo
rt java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.BeforeClass;
import com.cucumber.listener.ExtentCucumberFormatter;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
#CucumberOptions(
plugin= {"json:target/RunCuke/cucumber.json",
"prettty","html:target/RunCuke/cucumber.html",
"com.cucumber.listener.ExtentCucumberFormatter"},
features="/src/test/resources/features",
glue="steps",
tags= {" #Search-Cars"}
)
public class RunCuke extends AbstractTestNGCucumberTests{
#BeforeClass
public static void setup() {
SimpleDateFormat sdf=new SimpleDateFormat("ddMMyyyy_hhmmss");
Date curdate=new Date();
String strDate=sdf.format(curdate);
String filename=System.getProperty("user.dir")+"\\target\\Exten_Report"+strDate +".html";
File newFile=new File(filename);
ExtentCucumberFormatter.initiateExtentCucumberFormatter(newFile,false);
ExtentCucumberFormatter.loadConfig(new File("/src/test/resources/extent-config.xml"));
ExtentCucumberFormatter.addSystemInfo("Browser Name","Chrome");
ExtentCucumberFormatter.addSystemInfo("Browser Version","v57.0");
ExtentCucumberFormatter.addSystemInfo("Selenium Version","v3.9.1");
Map systemInfo=new HashMap();
systemInfo.put("Cucumber version", "v1.2.3");
systemInfo.put("Extent Cucumber Report version", "v1.1.0");
ExtentCucumberFormatter.addSystemInfo(systemInfo);
}
}
My utility class -:
package utils;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumDriver {
private static SeleniumDriver seleniumDriver;
private static WebDriver driver;
private static WebDriverWait waitdriver;
public final static int timeout=30;
public final static int pageloadtimeout=50;
private SeleniumDriver() {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"/src/test/resources/executables/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
waitdriver=new WebDriverWait(driver, timeout);
driver.manage().timeouts().implicitlyWait(timeout , TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(pageloadtimeout, TimeUnit.SECONDS);
}
public static void setupdriver() {
if(seleniumDriver==null) {
seleniumDriver=new SeleniumDriver();
}
}
public static void tearDown() {
if(driver!=null) {
driver.close();
driver.quit();
}
seleniumDriver=null;
}
public static void openpage(String url) {
driver.get(url);
}
public static WebDriver getDriver() {
return driver;
}
}
My Step definiton class is as follows -:
package steps;
import java.util.List;
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import pages.actions.CarsGuideHomepageactions;
import pages.actions.CarsSearchpageactions;
import utils.SeleniumDriver;
public class SearchCarsSteps {
CarsGuideHomepageactions homeactions=new CarsGuideHomepageactions();
CarsSearchpageactions searchcar=new CarsSearchpageactions();
#Given("^I am on the Home Page \"([^\"]*)\" of CarsGuide Website$")
public void i_am_on_the_Home_Page_of_CarsGuide_Website(String url) throws Throwable {
SeleniumDriver.openpage(url);
}
#When("^I move to Car For Sale Menu$")
public void i_move_to_Car_For_Sale_Menu(List<String> list) throws Throwable {
String menu=list.get(1);
System.out.println("Menu selected is "+ menu);
homeactions.movetocarsforsalemenu();
}
#And("^click on \"([^\"]*)\" link$")
public void click_on_link(String searchcar) throws Throwable {
homeactions.clickonsearchcars();
}
#And("^select carbrand as \"([^\"]*)\" from AnyMake dropdown$")
public void select_carbrand_as_from_AnyMake_dropdown(String carbrand) throws Throwable {
searchcar.selectcarmake(carbrand);
}
#And("^select \"([^\"]*)\" as car model$")
public void select_as_car_model(String carmodel) throws Throwable {
searchcar.selectcarmodel(carmodel);
}
#And("^select location as \"([^\"]*)\" from SelectLocation dropdown$")
public void select_location_as_from_SelectLocation_dropdown(String loctn) throws Throwable {
searchcar.selectcarlocation(loctn);
}
#And("^select \"([^\"]*)\" as price$")
public void select_as_price(String price) throws Throwable {
searchcar.selectcarprice(price);
}
#And("^click on Find_My_Next_Car button$")
public void click_on_Find_My_Next_Car_button() throws Throwable {
searchcar.clickonfindbutton();
}
#Then("^I should see list of searched cars$")
public void i_should_see_list_of_searched_cars() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#And("^the page title should be \"([^\"]*)\"$")
public void the_page_title_should_be(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
}
And Before and after class are -:
package steps;
import cucumber.api.java.Before;
import utils.SeleniumDriver;
public class BeforeActions {
#Before
public static void setUp() {
SeleniumDriver.setupdriver();
}
}
package steps;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import utils.SeleniumDriver;
public class Afteractions {
#After
public static void teardown(Scenario sc) {
WebDriver driver =SeleniumDriver.getDriver();
if(sc.isFailed()) {
byte[] screenshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
sc.embed(screenshot, "image/png");
}
SeleniumDriver.tearDown();
}
}
Feature file is as follows -:
#Search-Cars
Feature: Acceptance testing to validate Search Cars Page is working.
In order to validate that
the Search Cars page is working
Doing the Acceptance Testing
#Search-Cars-Positive
Scenario: Validate Search Cars Page
Given I am on the Home Page "https://www.carsguide.com.au" of CarsGuide Website
When I move to Car For Sale Menu
| Menu |
| Cars For Sale |
And click on "Search Cars" link
And select carbrand as "BMW" from AnyMake dropdown
And select "1 SERIES" as car model
And select location as "Australia" from SelectLocation dropdown
And select "$1,000" as price
And click on Find_My_Next_Car button
Then I should see list of searched cars
And the page title should be "Bmw 1 Series Cars Under $1000 for Sale | CarsGuide"
My extent-config.xml file is as follows -:
<?xml version="1.0" encoding="UTF-8"?>
<extentreports>
<configuration>
<!-- report theme -->
<!-- standard, dark -->
<theme>standard</theme>
<!-- document encoding -->
<!-- defaults to UTF-8 -->
<encoding>UTF-8</encoding>
<!-- protocol for script and stylesheets -->
<!-- defaults to https -->
<protocol>https</protocol>
<!-- title of the document -->
<documentTitle>ExtentReports by vikram</documentTitle>
<!-- report name - displayed at top-nav -->
<reportName>JUnit TestRunner : Cucumber Report by vikram</reportName>
<!-- report headline - displayed at top-nav, after reportHeadline -->
<reportHeadline></reportHeadline>
<!-- global date format override -->
<!-- defaults to yyyy-MM-dd -->
<dateFormat>yyyy-MM-dd</dateFormat>
<!-- global time format override -->
<!-- defaults to HH:mm:ss -->
<timeFormat>HH:mm:ss</timeFormat>
<!-- custom javascript -->
<scripts>
<![CDATA[
$(document).ready(function() {
});
]]>
</scripts>
<!-- custom styles -->
<styles>
<![CDATA[
]]>
</styles>
</configuration>
</extentreports>
Any help to solve this issue is highly respected.
Let me know if u need other part of my code
Typo in 'prettty' in your runner class. Should be modified as below which means you will get a nice html report at the end of the test run.
plugin= {"json:target/RunCuke/cucumber.json",
"pretty","html:target/RunCuke/cucumber.html",
"com.cucumber.listener.ExtentCucumberFormatter"},

Embeded OSGi (Felix) bundle start BundleException : missing requirement

I've got an embeded OSGi framework (Felix).
I'm installing the basic bundles without problem, I can access the Felix webconsole.
But starting libra-commons-osgi-core-wsbundle-1.4.0.war gives me this error :
"org.osgi.framework.BundleException: Unable to resolve hu.libra.commnos.osgi.core.wsbundle [9](R 9.0): missing requirement [hu.libra.commnos.osgi.core.wsbundle [9](R 9.0)] osgi.wiring.package; (osgi.wiring.package=hu.libra.commnos.osgi.core.service) Unresolved requirements: [[hu.libra.commnos.osgi.core.wsbundle [9](R 9.0)] osgi.wiring.package; (osgi.wiring.package=hu.libra.commnos.osgi.core.service)]"
hu.libra.commnos.osgi.core.service bundle is installed and started (Felix webconsole shows bundle as Active and shows the registered service)
hu.libra.commnos.osgi.core.service\META-INF\MANIFEST.MF contains
Export-Package: hu.libra.commons.osgi.core.service;version="1.4.0";uses:="org.osgi.framework"
hu.libra.commnos.osgi.core.wsbundle\META-INF\MANIFEST.MF contains
Import-Package: org.osgi.framework;version="[1.8,2)",javax.servlet,jav
ax.servlet.http,hu.libra.commnos.osgi.core.service
What is the problem? Thank You!
My embeded Framework :
.java
package hu.libra.commons.osgi.core;
import static org.osgi.framework.Constants.FRAGMENT_HOST;
import static org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN;
import static org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
public class LibraOSGiCore {
//LOGGING
private static final Logger log = Logger.getLogger(LibraOSGiCore.class);
//FIELDS
private static final Framework framework;
private static final List<Bundle> bundleList = new LinkedList<>();
//CONSTRUCTORS
static {
try {
//log4j
PropertyConfigurator.configure("log4j.properties");
//config
Map<String, String> config = new HashMap<>();
config.put(FRAMEWORK_STORAGE_CLEAN, FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
setConfig(config);
//framework
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
framework = frameworkFactory.newFramework(config);
framework.start();
}
catch (RuntimeException | BundleException e) {
log.fatal(e, e);
throw new RuntimeException(e);
}
}
//MAIN
public static void main(
String[] args) {
try {
try {
installBundles();
startBundles();
}
catch (IOException | BundleException e) {
log.fatal(e, e);
throw new RuntimeException(e);
}
try {
framework.waitForStop(0);
}
catch (InterruptedException e) {
return;
}
}
finally {
System.exit(0);
}
}
//METHODS - private
private static void setConfig(
Map<String, String> config) {
//TODO use config.xml
config.put("org.osgi.service.http.port", "8181");
//config.put("felix.webconsole.username", "...");
//config.put("felix.webconsole.password", "...");
}
private static Bundle installBundle(
String name,
String postfix,
String ext)
throws IOException,
BundleException {
if (postfix != null) {
postfix = "-" + postfix;
}
else {
postfix = "";
}
String resourceName = name + postfix + "." + ext;
InputStream is;
File file = new File(resourceName);
if (file.exists()) {
is = new FileInputStream(file);
}
else {
is = LibraOSGiCore.class.getResourceAsStream(resourceName);
}
try(InputStream xis = is) {
Bundle bundle = framework.getBundleContext().installBundle("file:/" + name + "." + ext, is);
return bundle;
}
}
private static void installBundles()
throws IOException,
BundleException {
//Felix basic bundles
bundleList.add(installBundle("org.apache.felix.log", "1.0.1", "jar"));
bundleList.add(installBundle("org.apache.felix.configadmin", "1.8.12", "jar"));
bundleList.add(installBundle("org.apache.felix.eventadmin", "1.4.8", "jar"));
bundleList.add(installBundle("org.apache.felix.http.servlet-api", "1.1.2", "jar"));
bundleList.add(installBundle("org.apache.felix.http.api", "3.0.0", "jar"));
//Felix Jetty bundle
bundleList.add(installBundle("org.apache.felix.http.jetty", "3.4.0", "jar"));
//Felix Webconsole bundle
bundleList.add(installBundle("org.apache.felix.webconsole", "4.2.16-all", "jar"));
//Core bundles
bundleList.add(installBundle("libra-commons-osgi-core-service", "1.4.0", "jar"));
bundleList.add(installBundle("libra-commons-osgi-core-wsbundle", "1.4.0", "war"));
}
private static void startBundles()
throws BundleException {
for (Bundle bundle : bundleList) {
if (bundle.getHeaders().get(FRAGMENT_HOST) != null)
continue;
bundle.start();
}
}
}
pom.xml
<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">
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<modelVersion>4.0.0</modelVersion>
<groupId>hu.libra.commons</groupId>
<artifactId>libra-commons-osgi-core</artifactId>
<version>1.4.0</version>
<name>Libra Common OSGi Core</name>
<packaging>bundle</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
<configuration>
<instructions>
<Bundle-SymbolicName>hu.libra.commnos.osgi.core</Bundle-SymbolicName>
</instructions>
</configuration>
</execution>
</executions>
<configuration>
<supportedProjectTypes>
<supportedProjectType>jar</supportedProjectType>
<supportedProjectType>bundle</supportedProjectType>
</supportedProjectTypes>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
<dependencies>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- OSGi -->
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.framework</artifactId>
<version>5.6.1</version>
</dependency>
</dependencies>
</project>
hu.libra.commnos.osgi.core.service pom.xml
<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">
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<modelVersion>4.0.0</modelVersion>
<groupId>hu.libra.commons</groupId>
<artifactId>libra-commons-osgi-core-service</artifactId>
<version>1.4.0</version>
<name>Libra Common OSGi Core Service Bundle</name>
<packaging>bundle</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
<configuration>
<supportedProjectTypes>
<supportedProjectType>jar</supportedProjectType>
<supportedProjectType>bundle</supportedProjectType>
</supportedProjectTypes>
<instructions>
<Bundle-SymbolicName>hu.libra.commons.osgi.core.service</Bundle-SymbolicName>
<Bundle-Activator>hu.libra.commons.osgi.core.service.Activator</Bundle-Activator>
<Export-Package>hu.libra.commons.osgi.core.service</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- OSGi -->
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
hu.libra.commnos.osgi.core.wsbundle pom.xml
<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">
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<modelVersion>4.0.0</modelVersion>
<groupId>hu.libra.commons</groupId>
<artifactId>libra-commons-osgi-core-wsbundle</artifactId>
<version>1.4.0</version>
<name>Libra Common OSGi Core Webservice Bundle</name>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
<configuration>
<supportedProjectTypes>
<supportedProjectType>war</supportedProjectType>
</supportedProjectTypes>
<instructions>
<Bundle-SymbolicName>hu.libra.commnos.osgi.core.wsbundle</Bundle-SymbolicName>
<Bundle-Activator>hu.libra.commons.osgi.core.wsbundle.Activator</Bundle-Activator>
<Private-Package>hu.libra.commons.osgi.core.wsbundle</Private-Package>
<Import-Package>
org.osgi.framework,
javax.servlet,
javax.servlet.http,
javax.servlet.*,
javax.servlet.jsp.*,
javax.servlet.jsp.jstl.*,
hu.libra.commnos.osgi.core.service
</Import-Package>
<DynamicImport-Package>
javax.*,
org.xml.sax,
org.xml.sax.*,
org.w3c.*
</DynamicImport-Package>
<Bundle-ClassPath>.,WEB-INF/classes</Bundle-ClassPath>
<Embed-Directory>WEB-INF/lib</Embed-Directory>
<Web-ContextPath>/libraosgicore</Web-ContextPath>
<Webapp-Context>/libraosgicore</Webapp-Context>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- OSGi -->
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<!-- Libra OSGi Core Service -->
<dependency>
<groupId>hu.libra.commons</groupId>
<artifactId>libra-commons-osgi-core-service</artifactId>
<version>1.4.0</version>
<scope>provided</scope>
</dependency>
<!-- WS -->
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.2.10</version>
</dependency>
</dependencies>
</project>

FileNotFoundException when running Maven generated jar

Trying to create my first ever executable jar and am using Maven to do so.
The Java runs fine by itself but when I try and run the jar I get a FileNotFoundException for src\main\resources\sound.wav.
I think the problem is obviously in the pom.xml file and in the resources declaration, but my lack of experience with maven and jars and lack of idea means that I can't seem to fix it no matter how much fiddling I do.
My pom.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupID</groupId>
<artifactId>Main</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<finalName>MailCheck</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>sound.wav</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>package-jar-with-dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>Main</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
and my Java file looks like this:
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import javax.mail.*;
import javax.mail.search.FlagTerm;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Main {
public static void main(String[] args)
{
String password = "mypassword";
String emailAddress = "myemail";
String soundFile = "src\\main\\resources\\sound.wav";
AudioStream as = null;
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
InputStream in = new FileInputStream(soundFile);
as = new AudioStream(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
Session session = Session.getInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", emailAddress, password);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] messages = inbox.search(ft);
int unreadMail = 0;
for (Message message : messages)
{
unreadMail++;
if (unreadMail > 0)
{
AudioPlayer.player.start(as);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
After package, this file should exist in the generated JAR. Please check this. And besides, you can not get InputStream of a file in a JAR like normal file in file system. You should try to get the InputStream from resource.
InputStream in = Main.class.getClassLoader()
.getResourceAsStream("src/main/resources/sound.wav");

Categories

Resources