So I am learning Kafka currently and have attempted to duplicate the examples provided from Apache here. This is example code for the consumer and I have written it in java just as shown. When I attempt to execute the file however I run into some issues. I am able to get the file to compile but it will not run properly.
I am executing the program with the following line without the quotations, "java TestConsumer localhost:2181 group1 test 4" This passes the 4 arguments necessary in the example code. I am provided with the following error though when I execute this command.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Category
at kafka.utils.VerifiableProperties.<init>(Unknown Source)
at kafka.consumer.ConsumerConfig.<init>(Unknown Source)
at TestConsumer.ConsumerProps(TestConsumer.java:69)
at TestConsumer.<init>(TestConsumer.java:31)
at TestConsumer.main(TestConsumer.java:97)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Category
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 5 more
I have tried going in an manually replacing the arguments with the necessary values and attempting to execute that way but I am given a different issue. Below is the error message along with the code I'm using just in case I screwed something up from the example provided. If anyone can help me out I would be incredibly appreciative since I am attempting to write my own consumer to test with parsing given information, etc. Thanks
log4j:WARN No appenders could be found for logger (kafka.utils.VerifiableProperties).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.NoClassDefFoundError: org/I0Itec/zkclient/IZkStateListener
at kafka.javaapi.consumer.ZookeeperConsumerConnector.<init>(Unknown Source)
at kafka.javaapi.consumer.ZookeeperConsumerConnector.<init>(Unknown Source)
at kafka.consumer.Consumer$.createJavaConsumerConnector(Unknown Source)
at kafka.consumer.Consumer.createJavaConsumerConnector(Unknown Source)
at TestConsumer.<init>(TestConsumer.java:31)
at TestConsumer.main(TestConsumer.java:97)
Caused by: java.lang.ClassNotFoundException: org.I0Itec.zkclient.IZkStateListener
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 6 more
/*
* Test Consumer to gather input from
* a Producer. Attempt to perform functions
* from the produced data
*/
// Kafka API
import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
public class TestConsumer{
private final ConsumerConnector consumer;
private final String topic;
private ExecutorService executor;
// CONSTRUCTOR
public TestConsumer(String zookeeper, String groupid, String aTopic){
consumer = kafka.consumer.Consumer.createJavaConsumerConnector(ConsumerProps(zookeeper, groupid));
this.topic = aTopic;
}
// END CONSTRUCTOR
// RUN FUNCTION
public void run(int threads){
Map<String, Integer> topicMap = new HashMap<String, Integer>();
topicMap.put(topic, new Integer(threads));
Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicMap);
List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);
executor = Executors.newFixedThreadPool(threads); // process threads
int numThread = 0; // thread counter for consumption
// consumer all messages
for(final KafkaStream stream : streams){
executor.submit(new TestConsumerRun(stream, numThread));
numThread ++;
}
}
// END RUN FUNCTION
// CREATE PROPERTIES FUNCTION
private static ConsumerConfig ConsumerProps(String zookeeper, String groupid){
Properties properties = new Properties(); // config properties file
properties.put("zookeeper.connect", zookeeper);
properties.put("group.id", groupid);
properties.put("zookeeper.session.timeout.ms", "400");
properties.put("zookeeper.sync.time.ms", "200");
properties.put("auto.commit.interval.ms", "1000");
properties.put("auto.offset.reset", "smallest");
return new ConsumerConfig(properties);
}
// END CREATE PROPERTIES FUNCTION
// SHUTDOWN FUNCTION
public void shutdown(){
if (consumer != null) consumer.shutdown();
if (executor != null) executor.shutdown();
try{
if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)){
System.out.println("Timed out waiting for consumer threads to shut down, exiting uncleanly");
}
} catch (InterruptedException e){
System.out.println("Interrupted during shutdown, exiting uncleanly");
}
}
// END SHUTDOWN FUNCTION
// MAIN FUNCTION
public static void main(String[] args){
String zookeeper = args[0];
String groupid = args[1];
String topic = args[2];
int threads = Integer.parseInt(args[3]);
TestConsumer test = new TestConsumer(zookeeper, groupid, topic); // send information to constructor
test.run(threads); // pass threads for iteration
try{
Thread.sleep(10000);
} catch (InterruptedException ie){
}
test.shutdown(); // close program
}
// END MAIN FUNCTION
}
/*
* Test Consumer to gather input from
* a Producer. Attempt to perform functions
* from the produced data
*/
// Kafka API
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
public class TestConsumerRun implements Runnable{
private KafkaStream aStream;
private int aThread;
// CONSTRUCTOR
public TestConsumerRun(KafkaStream stream, int thread){
aStream = stream; // set stream from main read
aThread = thread; // set thread from main read
}
// END CONSTRUCTOR
// RUN FUNCTION
public void run(){
ConsumerIterator<byte[], byte[]> iterator = aStream.iterator(); // used to check throughout the list continiously
while(iterator.hasNext())
System.out.println("Thread " + aThread + ": " + new String(iterator.next().message()));
System.out.println("Shutting down Thread: " + aThread);
}
// END RUN FUNCTION
}
Try adding BasicConfigurator.configure(); in the main method and it will work fine.
I had the same problem. You need to add log4j jar to your classpath. Also you might need to add slf4j and commons-logging.
java.lang.NoClassDefFoundError occurs when JVM can't find the class at runtime. (But it was there during compile.) Happens when a jar is missing during runtime and also for many other reasons. Your classpath during the compile and runtime needs to be the same. Sometimes you might have the same jar with different versions, so at runtime JVM might find the different version rather than the one used in compile.
Related
I have a program, that downloads a Git repository, builds it and launches defined Main class. It works properly with ordinary projects, but when I want to launch a JavaFX project, I get strange errors like:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at Main.main(Main.java:31)
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: app.UI_Main
at javafx.application.Application.launch(Application.java:260)
at app.UI_Main.main(UI_Main.java:31)
... 5 more
Caused by: java.lang.ClassNotFoundException: app.UI_Main
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at javafx.application.Application.launch(Application.java:248)
... 6 more
My Main class is:
public class Main {
private static final String GIT_ADDRESS = "https://github.com/lerryv/CheckCheckerDesktop";
private static final String MAIN_PATH = "app/";
private static final String MAIN_CLASS = "app.UI_Main";
public static void main(String[] args) throws GitAPIException, IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Git.cloneRepository().setURI(GIT_ADDRESS).setDirectory(Paths.get("./dir/").toFile()).call();
Collection<String> result = compile(Paths.get("./dir/src/").toFile());
String command = System.getProperty("java.home") + "/../bin/javac -d dirOut -cp \".:json-simple-1.1.jar\" " + result.join(" ");
Runtime.getRuntime().exec(command);
URLClassLoader urlClassLoader = URLClassLoader.newInstance(
new URL[]{
new File("dirOut/").toURI().toURL()
}
);
Class clazz = urlClassLoader.loadClass(MAIN_CLASS);
Method main = clazz.getDeclaredMethod("main", String[].class);
assert Modifier.isStatic(main.getModifiers());
main.invoke(null, (Object) args);
}
private static Collection<String> compile(File directory) {
assert directory.isDirectory();
Collection<String> result = new Collection<>();
boolean hasFiles = false;
for (File file: directory.listFiles()) {
if (file.isDirectory()) {
result.addAll(compile(file));
} else {
if (!hasFiles) {
String path = file.getAbsolutePath();
String extension = path.substring(path.lastIndexOf(".") + 1);
if (extension.equals("java")) hasFiles = true;
}
}
}
if (hasFiles) result.add(directory.getAbsolutePath() + "/*.java");
return result;
};
}
At first I thought it cannot find the class, but when I removed the method.invoke statement, errors disappeared. Why does it happen and are there any workarounds?
Runtime.getRuntime().exec(command)
This is starting another process, so after this line is executed compilation is not yet finished, you need to wait for this process to end, and probably you should also handle output/error stream of process to check if it succeed or not.
Process compileProc = Runtime.getRuntime().exec(command);
compileProc.waitFor();
Also I don't know what are you trying to do, but remember that not everyone might have compiler available and configured java.hame property, or configured it to different java version. (like older one and your code will not compile or newer one and you code will not run)
The program opens a new thread to start the project, but it executes the next line without monitoring its completion, so the thread can be removed if it is not necessary. If necessary, you need to write a monitoring thread to monitor and schedule all threads so that it can continue to execute after it has finished its work. Tasks of the main thread.
I am learning using a test Kafka consumer & producer however facing below error.
Kafka consumer program:
package kafka001;
import java.util.Arrays;
import java.util.Properties;
import java.util.Scanner;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.errors.WakeupException;
public class ConsumerApp {
private static Scanner in;
private static boolean stop = false;
public static void main(String[] args) throws Exception {
System.out.println(args[0] + args.length);
if (args.length != 2) {
System.err.printf("Usage: %s <topicName> <groupId>\n");
System.exit(-1);
}
in = new Scanner(System.in);
String topicName = args[0];
String groupId = args[1];
ConsumerThread consumerRunnable = new ConsumerThread(topicName, groupId);
consumerRunnable.start();
//System.out.println("Here");
String line = "";
while (!line.equals("exit")) {
line = in.next();
}
consumerRunnable.getKafkaConsumer().wakeup();
System.out.println("Stopping consumer now.....");
consumerRunnable.join();
}
private static class ConsumerThread extends Thread{
private String topicName;
private String groupId;
private KafkaConsumer<String,String> kafkaConsumer;
public ConsumerThread(String topicName, String groupId){
//System.out.println("inside ConsumerThread constructor");
this.topicName = topicName;
this.groupId = groupId;
}
public void run() {
//System.out.println("inside run");
// Setup Kafka producer properties
Properties configProperties = new Properties();
configProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "aup7727s.unix.anz:9092");
configProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
configProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
configProperties.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
configProperties.put(ConsumerConfig.CLIENT_ID_CONFIG, "simple");
// subscribe to topic
kafkaConsumer = new KafkaConsumer<String, String>(configProperties);
kafkaConsumer.subscribe(Arrays.asList(topicName));
// Get/process messages from topic and print it to console
try {while(true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(100);
for (ConsumerRecord<String, String> record : records)
System.out.println(record.value());
}
} catch(WakeupException ex) {
System.out.println("Exception caught " + ex.getMessage());
}finally {
kafkaConsumer.close();
System.out.println("After closing KafkaConsumer");
}
}
public KafkaConsumer<String,String> getKafkaConsumer(){
return this.kafkaConsumer;
}
}
}
When I compile the code, I am noticing following class files:
ConsumerApp$ConsumerThread.class and
ConsumerApp.class
I've generated jar file named ConsumerApp.jar through eclipse and when I run this in Hadoop cluster, I get noclassdeffound error as below:
java -cp ConsumerApp.jar kafka001/ConsumerApp console1 group1
or
hadoop jar ConsumerApp.jar console1 group1
Exception in thread "main" java.lang.NoClassDefFoundError: org.apache.kafka.common.errors.WakeupException
at kafka001.ConsumerApp.main(ConsumerApp.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.kafka.common.errors.WakeupException
at java.net.URLClassLoader.findClass(URLClassLoader.java:607)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:846)
at java.lang.ClassLoader.loadClass(ClassLoader.java:825)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:325)
at java.lang.ClassLoader.loadClass(ClassLoader.java:805)
... 1 more
I am using Eclipse to compile, maven build and generate jar file. Line number 24 correspond to creation of ConsumerThread instance.
I am unable to resolve if its due to ConsumerThread class name being incorrectly saved (Class file generated as ConsumerApp$ConsumerThread.class instead of ConsumerThread.class) ? or something to be taken care while generating jar file ?
Since I can't view the entire project, I would try this: Right click on the project -> go to Maven 2 tools -> click generate artifacts (check for updates). That should create any missing dependencies. Also make sure you check out other similar posts that may resolve your issue like this.
I am trying to implement a simple code to read the data from the ultrasonic and send it to a server by using Californium. The problem is that when I use debug, it doesn't have any error. However when I export the code to a runable jar file and run it on my raspberry pi, it throws the following errors:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NoClassDefFoundError: org/eclipse/californium/elements/util/NamedThreadFactory
at org.eclipse.californium.core.CoapServer.<init>(CoapServer.java:163)
at org.eclipse.californium.core.CoapServer.<init>(CoapServer.java:120)
at iot.main.device.DeviceClient.main(DeviceClient.java:34)
... 5 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.californium.elements.util.NamedThreadFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 8 more
I am not sure what caused this and how to solve it, any suggestion would be much helpful. Below is the code:
package iot.main.device;
import static org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST;
import static org.eclipse.californium.core.coap.CoAP.ResponseCode.CHANGED;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.server.resources.CoapExchange;
import com.pi4j.io.gpio.*;
public class DeviceClient {
private static GpioPinDigitalOutput sensorTriggerPin ;
private static GpioPinDigitalInput sensorEchoPin ;
final static GpioController gpio = GpioFactory.getInstance();
public static void main(String[] args) {
double ultraVal;
sensorTriggerPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04); // Trigger pin as OUTPUT
sensorEchoPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_05,PinPullResistance.PULL_DOWN); // Echo pin as INPUT
CoapClient client = new CoapClient("coap://localhost/Ultrasonic");
CoapServer server = new CoapServer();
server.add(new UltraResource());
server.start();
while(true){
try {
Thread.sleep(2000);
sensorTriggerPin.high(); // Make trigger pin HIGH
Thread.sleep((long) 0.00001);// Delay for 10 microseconds
sensorTriggerPin.low(); //Make trigger pin LOW
while(sensorEchoPin.isLow()){ //Wait until the ECHO pin gets HIGH
}
long startTime= System.nanoTime(); // Store the surrent time to calculate ECHO pin HIGH time.
while(sensorEchoPin.isHigh()){ //Wait until the ECHO pin gets LOW
}
long endTime= System.nanoTime(); // Store the echo pin HIGH end time to calculate ECHO pin HIGH time.
ultraVal = ((((endTime - startTime)/1e3)/2) / 29.1);
System.out.println("Distance : " + ultraVal + " cm"); //Printing out the distance in cm
Thread.sleep(1000);
CoapResponse response = client.put(Double.toString(ultraVal), MediaTypeRegistry.TEXT_PLAIN);
if (response!=null) {
System.out.println( response.getCode() );
System.out.println( response.getOptions() );
System.out.println( response.getResponseText() );
} else {
System.out.println("Request failed");
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class UltraResource extends CoapResource {
public String value = "Resource has not changed yet !!!";
public UltraResource() {
super("Ultrasonic");
setObservable(true);
}
#Override
public void handleGET(CoapExchange exchange) {
exchange.respond(value);
}
#Override
public void handlePUT(CoapExchange exchange) {
String payload = exchange.getRequestText();
System.out.println(payload + " cm");
try {
exchange.respond(CHANGED, payload);
value = new String(payload);
changed();
} catch (Exception e) {
e.printStackTrace();
exchange.respond(BAD_REQUEST, "Invalid String");
}
}
}
}
The error states that
Caused by: java.lang.ClassNotFoundException: org.eclipse.californium.elements.util.NamedThreadFactory
This means you are writing code that uses a dependency from Californium. That dependency is within your dev. environment but it is not within the runtime environment of your Raspberry Pi.
Have a look at this other post which may help you. Also this SO site may be better.
I have a basic Maven java app that I created and it depends on JeroMQ which is a full Java implemenetation of ZeroMQ. Since I also need to wrap this java app as a windows service, I chose to use Apache Commons Daemon and specifically, followed this excellent example: http://web.archive.org/web/20090228071059/http://blog.platinumsolutions.com/node/234 Here's what the Java code looks like:
package com.org.SubscriberACD;
import java.nio.charset.Charset;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Socket;
/**
* JeroMQ Subscriber for Apache Commons Daemon
*
*/
public class Subscriber
{
/**
* Single static instance of the service class
*/
private static Subscriber subscriber_service = new Subscriber();
/**
* Static method called by prunsrv to start/stop
* the service. Pass the argument "start"
* to start the service, and pass "stop" to
* stop the service.
*/
public static void windowsService(String args[]) {
String cmd = "start";
if(args.length > 0) {
cmd = args[0];
}
if("start".equals(cmd)) {
subscriber_service.start();
}
else {
subscriber_service.stop();
}
}
/**
* Flag to know if this service
* instance has been stopped.
*/
private boolean stopped = false;
/**
* Start this service instance
*/
public void start() {
stopped = false;
System.out.println("My Service Started "
+ new java.util.Date());
ZContext context = new ZContext();
Socket subscriber = context.createSocket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
String subscription = "MySub";
subscriber.subscribe(subscription.getBytes(Charset.forName("UTF-8")));
while(!stopped) {
System.out.println("My Service Executing "
+ new java.util.Date());
String topic = subscriber.recvStr();
if (topic == null)
break;
String data = subscriber.recvStr();
assert(topic.equals(subscription));
System.out.println(data);
synchronized(this) {
try {
this.wait(60000); // wait 1 minute
}
catch(InterruptedException ie){}
}
}
subscriber.close();
context.close();
context.destroy();
System.out.println("My Service Finished "
+ new java.util.Date());
}
/**
* Stop this service instance
*/
public void stop() {
stopped = true;
synchronized(this) {
this.notify();
}
}
}
Then I created the following folder structure just like the tutorial suggested:
E:\SubscriberACD
\bin
\subscriberACD.exe
\subscriberACDw.exe
\classes
\com\org\SubscriberACD\Subscriber.class
\logs
I then navigated to the bin directory and issued the following command to install the service:
subscriberACD.exe //IS//SubscriberACD --Install=E:\SubscriberACD\bin\subscriberACD.exe --Descriptio
n="Subscriber using Apache Commons Daemon" --Jvm=c:\glassfish4\jdk7\jre
\bin\server\jvm.dll --Classpath=E:\SubscriberACD\classes --StartMode=jvm
--StartClass=com.org.SubscriberACD.Subscriber --StartMethod=windowsSer
vice --StartParams=start --StopMode=jvm --StopClass=com.org.SubscriberA
CD.Subscriber --StopMethod=windowsService --StopParams=stop --LogPath=E:\SubscriberACD\logs --StdOutput=auto --StdError=auto
The install works fine since I can see it in Windows Services. However, when I try to start it from there, I get an error saying "Windows cannot start the SubscriberACD on Local Computer".
I checked the error logs and see the following entry:
2016-04-14 14:38:40 Commons Daemon procrun stderr initialized
Exception in thread "main" ror: org/zeromq/ZContext
at com.org.SubscriberACD.Subscriber.start(Subscriber.java:57)
at com.org.SubscriberACD.Subscriber.windowsService(Subscriber.java:33)
Caused by: java.lang.ClassNotFoundException: org.zeromq.ZContext
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 2 more
It's worth noting that JeroMQ is currently a jar under my Maven Dependencies. I configured it from my POM.xml file.
I think the problem might be that my service doesn't have access to the JeroMQ jar that is under my Maven Dependencies. My assumption is that the class file doesn't contain the dependencies. So what I tried was exporting my entire project as a jar and stuck that baby under E:\SubscriberACD\classes\
So my structure now looks like this:
E:\SubscriberACD
\bin
\subscriberACD.exe
\subscriberACDw.exe
\classes
\com\org\SubscriberACD\
\Subscriber.class
\Subscriber.jar
\logs
However, that didn't fix the issue. Can anyone shed some light on this?
Change your --Classpath argument to :
--Classpath=E:\SubscriberACD\classes\your-jar-filename.jar
You almost certainly have other jarfiles you'll need, so just append them to the end of the --Classpath using ; (semi-colon) delimiters...
--Classpath=E:\SubscriberACD\classes\your-jar-filename.jar;e:\other-dir\classes\some-other.jar;etc...
I've abandoned GlassFish 4-point-anything in favor of Payara41. Amazingly GF has unresolved JDBC and JMS Resources configuration bugs. See:
Glassfish Admin Console throws java.lang.IllegalStateException when creating JDBC Pool
Payara perfectly fixed the JMS configuration issues. So all I need are the environment properties my standalone Java Client needs to get an InitialContext(env) to lookup() those Resources.
Note: InitalContext() doesn't work in a standalone. Only in an EJB Container that can look up the {Payara Home}/glassfish/lib/jndi-properties file. That file has one property so that's what I have in my code below:
Key: "java.naming.factory.initial"
Value: "com.sun.enterprise.naming.impl.SerialInitContextFactory"
That set off a series of NoClassDerfinitionFound Exceptions that led me to add these jars with these classes to my client's buildpath, and to /glassfish/lib/. They are in the order I encountered them.
"glassfish-naming.jar" w/ "com.sun.enterprise.naming.impl.SerialInitContextFactory"
"internal-api-3.1.2.jar" w/ "org.glassfish.internal.api.Globals"
" hk2-api-2.1.46.jar " w/ "org.glassfish.hk2.api.ServiceLocator"
"appserv-rt.jar" from glassfish/lib added to client build path
But now my code throws a java.lang.NoSuchMethodError for Globals.getDefaultHabitat(). Please note, below the Exception doesn't get caught in my catch block. (And I don't see it in Payara's service.log either.)
I know my client finds Globals.class, because adding it caused the NoClassDefinitionFound for ServiceLocator. Are there two "Globals.class" out there ... one w/ and one w/o that method. Or is the "Lorg" in console output really different from "org", i.e. is there a "Lorg/glassfish/hk2/api/ServiceLocator"?
I'm stuck. And this seems such a bread and butter kind of need -- environment properties a standalone Java client needs to get Payara's InitialContext -- it would be nice to be able to add it here for everyone to use (in addition to the jars I've already located.) I'd love to see Payara soar, because I love its Admin Console compared to JBoss and MayFly's XML orientation. Any suggestions? I'm stumped.Code and console output follows:
Code
package org.america3.testclasses;
import java.util.Properties;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.america3.toolkit.U;
public class Test2 implements MessageListener {
static final Properties JNDI_PROPERTIES = new Properties() {
private static final long serialVersionUID = 1L;
{/*This property key:vlaue pair is specified in Payara41/glassfish/lib/jndi-properties*/
/*The class it calls for is in Payara41/glassfish/lib/glassfish-naming.jar*/
this.put ("java.naming.factory.initial","com.sun.enterprise.naming.impl.SerialInitContextFactory");}
};
//constructor
public Test2 () {
String iAmM = U.getIAmMShort(Thread.currentThread().getStackTrace());
System.out.println(iAmM + "beg");
try {
Context jndiContext = (Context) new InitialContext(JNDI_PROPERTIES);
} catch (Exception e) {
System.out.println(" " + iAmM + "InitialContext failed to instantiate");
System.out.println(" " + iAmM + "Exception : " + e.getClass().getName());
System.out.println(" " + iAmM + "e.getMessage(): " + e.getMessage());
System.out.println(" " + iAmM + "e.getMessage(): " + e.getCause());
e.printStackTrace();
}
System.out.println(iAmM + "end");
}
public static void main(String[] args) {
Test2 messageCenter = new Test2 ();
}
public void onMessage(Message arg0) {
// TODO Auto-generated method stub
}
}
Console
Test2.<init> () beg
Exception in thread "main" java.lang.NoSuchMethodError: org.glassfish.internal.api.Globals.getDefaultHabitat()Lorg/glassfish/hk2/api/ServiceLocator;
at com.sun.enterprise.naming.impl.SerialInitContextFactory.<init>(SerialInitContextFactory.java:126)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.<init>(Unknown Source)
at org.america3.testclasses.Test2.<init>(Test2.java:24)
at org.america3.testclasses.Test2.main(Test2.java:36)
PS: Could someone with enough points add a "Paraya" tag below. I mean with Glassfish's console throwing exceptions when used to configure any JNDI or JMS Resource I think many people will switch.
JAR internal-api-3.1.2.jar is for Glassfish v3, and its Globals class has a method getDefaultHabitat() that returns Habitat:
public static Habitat getDefaultHabitat() {
return defaultHabitat;
}
However, Glassfish v4 has changed method signatures, and you have to use new Glassfish v4 internal API whose Globals class has appropriate method getDefaultHabitat() that returns ServiceLocator:
public static ServiceLocator getDefaultHabitat() {
return defaultHabitat;
}
In other words, replace internal-api-3.1.2.jar with internal-api-4.1.jar which can be found on Maven Central here
You should add ${PAYARA-HOME}/glassfish/lib/gf-client.jar to your classpath as this references all the other required jars in it's META-INF/MANIFEST.MF. Please note, it uses relative path references so you really need to install Payara on the client machine.