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>
Related
following this example and this guide I created a program that works in Eclipse development environment, however if I try to package it via maven (mvn clean package) and run it standalone I get this error:
Error: A JNI error has occurred, please check your installation and
try again Exception in thread "main" java.lang.SecurityException:
Invalid signature file digest for Manifest main attributes
I tried several ways (including using other maven plugin, like maven-assembly-plugin with jar-with-dependencies descriptorRef), without success getting different error.
this is my main (and only) class:
package it.factory.pub;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.TopicName;
public class PublishWithErrorHandler {
//
private static final Logger log = LogManager.getLogger(PublishWithErrorHandler.class);
//
public static void main(String... args) throws Exception {
String projectId = args[0];
String topicId = args[1];
String[] messages = Arrays.copyOfRange(args, 2, args.length);
log.info("projectId: " + projectId);
log.info("projectId: " + topicId);
log.info("messages: " + Arrays.toString(messages));
publishWithErrorHandlerExample(projectId, topicId, messages);
}
private static void publishWithErrorHandlerExample(String projectId, String topicId, String[] messages) throws IOException, InterruptedException {
TopicName topicName = TopicName.of(projectId, topicId);
Publisher publisher = null;
try {
// Create a publisher instance with default settings bound to the topic
publisher = Publisher.newBuilder(topicName).build();
// List<String> messages = Arrays.asList("first message", "second message");
for (final String message : messages) {
log.info("Publishing message: '" + message + "'");
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Once published, returns a server-assigned message id (unique within the topic)
ApiFuture<String> future = publisher.publish(pubsubMessage);
// Add an asynchronous callback to handle success / failure
ApiFutures.addCallback(future, new ApiFutureCallback<String>(){
#Override
public void onFailure(Throwable throwable) {
if (throwable instanceof ApiException) {
ApiException apiException = ((ApiException) throwable);
// details on the API exception
log.info(apiException.getStatusCode().getCode());
log.info(apiException.isRetryable());
}
log.error("Error publishing message : " + message);
}
#Override
public void onSuccess(String messageId) {
// Once published, returns server-assigned message ids (unique within the topic)
log.info("Published message ID: " + messageId);
}
}, MoreExecutors.directExecutor());
}
} finally {
if (publisher != null) {
// When finished with the publisher, shutdown to free up resources.
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
}
}
}
and this is my pom.xml 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>it.factory</groupId>
<artifactId>poc-pubsub</artifactId>
<version>0.0.2-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<customer>a2a</customer>
<log4j2.version>2.12.1</log4j2.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ApacheNoticeResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>it.factory.pub.PublishWithErrorHandler</Main-Class>
</manifestEntries>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<!-- pub-sub google -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>19.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
I am guessing you already figured this out, but there is a typo in pom.xml, it should be mainClass instead of Main-Class.
Aside from that, what resolved the issue for me was to exclude additional types:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>it.factory.pub.PublishWithErrorHandler</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
Since there were some additional SF and RSA files which were triggering the error
I am trying to do a POST to an API and I keep getting this error.
StandardWrapperValve[com.mycompany.timeedit.JAXRSConfiguration]: Servlet.service() for servlet com.mycompany.timeedit.JAXRSConfiguration threw exception
java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
at org.glassfish.jersey.internal.config.SystemPropertiesConfigurationModel.getProperties(SystemPropertiesConfigurationModel.java:106)
at org.glassfish.jersey.internal.config.SystemPropertiesConfigurationProvider.getProperties(SystemPropertiesConfigurationProvider.java:29)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFactory.readExternalPropertiesMap(ExternalPropertiesConfigurationFactory.java:55)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFactory.configure(ExternalPropertiesConfigurationFactory.java:72)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFeature.configure(ExternalPropertiesConfigurationFeature.java:26)
at org.glassfish.jersey.model.internal.CommonConfig.configureFeatures(CommonConfig.java:677)
at org.glassfish.jersey.model.internal.CommonConfig.configureMetaProviders(CommonConfig.java:611)
at org.glassfish.jersey.client.ClientConfig$State.configureMetaProviders(ClientConfig.java:387)
at org.glassfish.jersey.client.ClientConfig$State.initRuntime(ClientConfig.java:432)
at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:317)
at org.glassfish.jersey.client.ClientConfig.getRuntime(ClientConfig.java:802)
at org.glassfish.jersey.client.ClientRequest.getConfiguration(ClientRequest.java:261)
at org.glassfish.jersey.client.JerseyInvocation.validateHttpMethodAndEntity(JerseyInvocation.java:119)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:88)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:84)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:75)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:421)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:327)
at TestAPI.Http_Connection.addToCanvas(Http_Connection.java:80)
at TestAPI.CanvasResource.getJson(CanvasResource.java:69)
at TestAPI.CanvasResource$Proxy$_$$_WeldClientProxy.getJson(Unknown Source)
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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
at org.glassfish.jersey.internal.Errors.process(Errors.java:244)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:232)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:679)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:392)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:365)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:318)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1540)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:119)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:611)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:550)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:75)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:114)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:199)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.lang.Thread.run(Thread.java:748)
Below is my webservice.
This service is accepting a string from a jquery-ajax method that I have made aswell. But that one seems to work fine so I am not going to paste it here.
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.POST;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("canvas")
#RequestScoped
public class CanvasResource {
#Context
private UriInfo context;
public CanvasResource() {
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response getJson(String schema ){
Gson g = new Gson();
Type userListType = new TypeToken<ArrayList<TimeEdit2>>(){}.getType();
ArrayList<TimeEdit2> userArray = g.fromJson(schema, userListType);
Http_Connection hc = new Http_Connection();//Http_Connection is the name of my class
try {
hc.addToCanvas(userArray);
}
catch (ProtocolException ex) {
System.out.println("1 !!"+ex);
Logger.getLogger(CanvasResource.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
System.out.println("2 !! "+ex);
Logger.getLogger(CanvasResource.class.getName()).log(Level.SEVERE, null, ex);
}
return Response
.ok("ping")
.build();
}
This is my class that I want to post to API.
I have tried to run the class just being a main-method and that works fine, but when I make it a method and send from my webservice to my class, that's when it breaks....
The program breaks on the "Response r = invocationB...."
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.oauth2.OAuth2ClientSupport;
public class Http_Connection {
//public static void main(String[] args) throws MalformedURLException, ProtocolException, IOException
public void addToCanvas(ArrayList <TimeEdit2> timeEdit) throws MalformedURLException,
ProtocolException, IOException
{
String canvas_url = "https://ltu.instructure.com/api/v1/calendar_events.json";
String bearerToken = "<myToken>";
String context_code= "<myUser>";
URL url = new URL(canvas_url);
Form form = new Form();
form.param("calendar_event[context_code]", <myUser> );
form.param("calendar_event[title]", "testing");
form.param("calendar_event[start_at]", "2020-01-20T17:00:00Z");
form.param("calendar_event[end_at]", "2020-01-20T20:00:00Z");
form.param("calendar_event[description]","beskrivning");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
Client client = ClientBuilder.newClient().register(OAuth2ClientSupport.feature(bearerToken));
WebTarget target = client.target(canvas_url);
Invocation.Builder invocationB = target.request(MediaType.APPLICATION_JSON_TYPE);
Response r = invocationB.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
This is my pom.
<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.mycompany</groupId>
<artifactId>TimeEdit</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>TimeEdit-1.0-SNAPSHOT</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<jakartaee>8.0</jakartaee>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.security</groupId>
<artifactId>oauth2-client</artifactId>
<version>2.29.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${jakartaee}</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
My IDE is Apache Netbeans IDE 11.2
At the moment, Im using Glassfish 5.1 with Java EE 8 and JDK 1.8.
I have tried other version of glassfish, Java EE and JDK but nothing is working... Have had this error for a couple of weeks now...
This is my second try using Webservices and the first time that Im sending to API, so I really need help
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
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>
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");