I have just started learning java, and know only a small amount of code, however this is still a simple program. It is more of a prank program, but mostly just to test if I can make a jar file.
Here is the code:
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.util.Random;
public class randommouse {
public static void main(String[] args) {
for (int i=1; i<1000; i++) {
Random rand = new Random();
int w = rand.nextInt(1024) + 1;
int h = rand.nextInt(768) + 1;
int t = rand.nextInt(2000) + 1;
try {
Robot r = new Robot();
r.mouseMove(w,h);
Thread.sleep(t);
} catch (AWTException e) {}
catch (InterruptedException e) {}
catch (NullPointerException e) {}
}
}
}
I save this to file called randommouse.java,
then compile it using
javac randommouse.java
This works and when I run it using
java randommouse
it works fine also.
So then I try to create a jar file. I use the command
jar cvf randommouse.jar randommouse.class
and it works. Afterwards I double click the jar file and it comes up with an error Java Exception.
So then I run it in the cmd with
java -jar randommouse.jar
and get this error
F:\Java>java -jar randommouse.jar
Exception in thread "main" java.lang.NullPointerException
at sun.launcher.LauncherHelper.getMainClassFromJar(LauncherHelper.java:3
99)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:463)
F:\Java>
Do I need to put in an argument, and if so where do I put that in and how?
Thank you in advance
Sam
From the JDK doc:
In order for this option to work, the manifest of the JAR file must
contain a line of the form
Main-Class: classname
Here, classname
identifies the class having the public static void main(String[] args)
method that serves as your application's starting point. See the Jar
tool reference page and the Jar trail of the Java Tutorial for
information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user
classes, and other user class path settings are ignored.
You have to set the entry point
$> echo "Main-Class: randommouse" > Manifest
$> jar cfm randommouse.jar Manifest randommouse.class
Did you specify the entry point in the manifest?
http://download.oracle.com/javase/tutorial/deployment/jar/appman.html
A couple of issues with your code that are not related to your actual problem, but are important nevertheless.
1) This statement is unnecessary:
import java.lang.*;
By default, every class in java.lang is implicitly imported. You don't need to do it explicitly.
2) This is dangerously bad code:
try {
// ...
} catch (AWTException e) {
} catch (InterruptedException e) {
} catch (NullPointerException e) {
}
You are catching exceptions that are most likely due to programming errors, and throwing away all evidence that they ever happened. At the very least, you should print out some kind of error message ... and the exception stacktrace to that you can diagnose it.
In this particular context (in a main method), the following is a better approach:
try {
// ...
} catch (Throwable e) {
System.err.println("An unexpected error has occurred:");
e.printStacktrace(System.err);
System.exit(1);
}
I took a look at the source code of the class and it seems to try to get the main class attribute from a list of attributes, which are Strings, and is then invoking the trim() method on the found main class attribute. When the main class is not being specified, there is no main class attribute, which causes the searching method to return null to indicate so, and when trim() is being invoked on it, it is causing the NullPointerException since the searching method has returned null. To avoid this, be sure that the main class is specified in the jar manifest:
[directory of class files]>jar -cvmf [name of manifest] MyApp.jar
And be sure that you have written the manifest right (with the line break at the end):
Main-Class: [name of main class]
Related
I'm working on macOS with JDK8.
In catch, I have to give the entire name of exception like
in this case (ArithmeticException e) instead of (Exception e)
to run the code.
If I use (Exception e) it gives an error that I'm not getting on windows os.
why is that??
and how should I solve this??
The code works perfectly on windows OS with JDK8.
On macOS work perfectly if the proper name of the exception (ArithmeticException e) is given.
import java.util.*;
public class ExceptionDemo
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("enter first number:");
a=sc.nextInt();
System.out.println("enter second number:");
b=sc.nextInt();
try
{
c=a/b;
System.out.println("Result is:"+c);
}
catch(Exception e)
{
System.out.println("second number cannot be zero/0 "+e);
}
System.out.println("still running");
}
}
This is the error I'm getting as below:
incompatible types: Exception cannot be converted to Throwable
catch(Exception e)
catch(java.lang.Exception e) {
// handle e
}
Use fully-qualified names if you aren't sure what is imported, and what class will be used under the name Exception.
The name Exception looks too broad for your application. [YourApplicationName]Exception would be a cleaner and conflictless root of your exception hierarchy (if you want to have one).
I was having the same problem, but later I noticed that my class name was Exception because of my class name which is(Exception ) I was getting that error .when I changed my class name (filename ) then it work.
If there is any file named "Exception.java" then rename that file and delete that class file then it will work fine.
The problem is your file name is Exception.java and the class you are trying to implement is the same, but from a different package (java.lang.Exception), so either you change your file name, or you can import that package, or you can write the full package at the catch param block.
you should import first
import java.lang.Exception;
I have a Gherkin executor where I execute my feature files. What I would like to do would be to add a StepDefinition file from an other jar. The user would be able to use my project with the step def that I have already wrote but he would also be able to add custom definitions from his own jar file.
Currently I have a JavaClassLoader where I load my class from my jar and I use it in my main
public class JavaClassLoader<C> extends ClassLoader {
public C LoadClass(String directory, String classpath, Class<C> parentClass) throws ClassNotFoundException {
File pluginsDir = new File(System.getProperty("user.dir") + directory);
for (File jar : pluginsDir.listFiles()) {
try {
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { jar.toURL() },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName(classpath, true, loader);
Class<? extends C> newClass = clazz.asSubclass(parentClass);
// Apparently its bad to use Class.newInstance, so we use
// newClass.getConstructor() instead
Constructor<? extends C> constructor = newClass.getConstructor();
return constructor.newInstance();
} catch (ClassNotFoundException e) {
// There might be multiple JARs in the directory,
// so keep looking
continue;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
throw new ClassNotFoundException("Class " + classpath
+ " wasn't found in directory " + System.getProperty("user.dir") + directory);
}
}
JavaClassLoader<AbstractStepDefs> loader = new JavaClassLoader<AbstractStepDefs>();
loader.LoadClass("/", "stepDef.dynamicClass", AbstractStepDefs.class);
The problem is that Cucumber isn't able to read the methods that I wrote in my other jar. Is there a way to use a step def file that isn't in the project?
Is there a way to use a step def file that isn't in the project?
Yes, and no. The yes part is closer to "sort of". git supports a couple of ways of referencing subprojects within other projects. The common "subprojects" are maintained in their own project and then pulled into using projects. Look here for a discussion. I looked into doing submodules once. I even had it working. But I couldn't convince the TeamCity owners to support it. It works but you have to be careful about how you use it. There are haters.
What I ended up doing was to create a shared "global" project that contained page files for the common login and navigation pages. This global project also contained all the startup and shutdown support for different browsers and for remote execution on SauceLabs.
The step definitions had to be repeated (yuck; I prefer DRY) but these are small as they mostly just call the page file methods. All of these web pages are defined in the global project in their own class files. The common housekeeping code is defined in class WebDriverManager.
#Given("^I navigate to the public ACME WebPage and select Login$")
public void iNavigateToTheAcmePublicWebPage() {
pageFactory.AcmePublicWebPage().navigateTo(
WebDriverManager.instance().getAcmeUrl());
pageFactory.AcmePublicWebPage().closeNotificationPopUp(); //If there is one
pageFactory.AcmePublicWebPage().selectLoginLink();
}
#When("^I close the browser$")
public void iCloseTheBrowser() {
WebDriverManager.instance().closeBrowser();
}
I have reduced most, but not all duplication. Most junior test automation engineers don't have to worry about the heavy lifting as long as I maintain the global git project and notify them when they need to download a new global jar from TeamCity.
I'm using Jcolibri Studio and everytime I try to rung my CBR application it gives me the error
Error: Does not contain a main type
May currently Main Method(Jcolibri Studio creates this main):
public static void main(String[] args) {
CBRApplication cbrApp = new CBRApplication();
try {
cbrApp.configure();
CBRCaseBase caseBase = cbrApp.preCycle();
for(CBRCase c: caseBase.getCases())
System.out.println(c);
} catch (ExecutionException e) {
e.printStackTrace();
}
}
If I try to Run As > Java Application
It gives me a list of classes and ask me to pick one, but I have no idea which one. Tried almost everything and I keep getting receiving this error.
Not really sure how important it is, but if you go to Project's Properties you can see this little red X (Pretty sure this JRE is installed).
I've been working on a project that I described in this question that I asked previously. I'm trying to invoke a method from a class who's name is dynamically generated (and the class compiled while the program runs). I call Class watchFace = Class.forName("pebbleos.PebbleOS_" + fileName); followed by currentWatchFace = watchFace.newInstance(); in the method loadWatchFace(), and then in the method runWatchFace() I try to invoke the method using this:
Method method = null;
try {
method = currentWatchFace.getClass().getMethod("initializeFace");
} catch (SecurityException | NoSuchMethodException e) {
System.out.println("Error");
}
method.invoke(currentWatchFace);
My watch face's code is being taken from a text file, which looks like this:
package pebbleos;
public class PebbleOS_Default {
public PebbleOS_Default () {
}
public void initializeFace() {
System.out.println(“Hello World”);
}
}
Just a quick note, the above is supposedly the "cause" of this error: java.lang.reflect.InvocationTargetException
From the code you posted, seems that you're using the wrong character “ that looks a lot like " but they're not the same. Fix it, recompile the code and try again.
Here's the background of the underlying problem, I am collaborating with a group on a project which uses Swt libraries and I am trying to package the software for deployment. As it turns out SWT is very platform/architecture dependent. I would like to be able to package all six jars (linux, mac, win and 32/64-bit) into the same package and use the appropriate library depending on the system. I realize that it is a tough challenge however, switching to Swing (or anything else) isn't really an option right now.
I have found a number of relevant threads (#Aaron Digulla's thread and #mchr's thread) which provided me valuable insights regarding the problem at hand. I have tried to implement the solution proposed by #Alexey Romanov here. With one difference, as the loadSwtJar() method he proposes is not static, I instantiate the object, and immediately following that, run the method before anything else is done to the object.
It appears as the loading procedure doesn't work properly. My reasoning for this statement is as follows:
If all Swt jars are removed from the classpath of the executable jar file, then Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/swt/events/MouseListener is thrown which is caused by: java.lang.ClassNotFoundException: org.eclipse.swt.events.MouseListener
to me this means that the libraries are not found on classpath, am I mistaken?
If swt jars are left on the classpath then the first jar file is used by the system during execution. Meaning if gtk-linux-x86_64 happens to be the first swt jar on the list of jars then the system tries to use that, regardless if the system is win32 or Mac OSX.
I have tried to add some output to see if the loadSwtJar() method is choosing the right jar, and the output seems right on all platforms I have tried, as in the right package is selected (and the files do exist in the runnable jar). But nevertheless the right library is not loaded hence execution errors occur:
Exception in thread "main" java.lang.reflect.InvocationTargetException caused by for ex: Caused by: java.lang.UnsatisfiedLinkError: Cannot load 32-bit SWT libraries on 64-bit JVM
(Note that this is the error I get on my Linux machine if I change the order of appearance of 64-bit and 32 bit swt libraries on the build.xml file)
So, what seems to be the problem here? Am I missing out on some detail, or is it simply not possible to check system properties and load an appropriate library accordingly?
Finally below is an excerpt of my build file, figured it might help finding the source of the problem.
Thanks in advance,
EDIT: After a long debug session with a colleague, the problem is resolved (except an annoying bug regarding Thread management on MacOS as I mentioned here). It involved tweaking with the ANT build as well as the way the main class was written. (The main class, as it turns out, was extending & implementing references from the SWT library which meant that the code wouldn't compile at all, wrapped the main class with another class and loaded the SWT jars from there which seemed to be enough to tackle the problem)
Thanks and regards to everyone who contributed, especially #Aaron. Really appreciated!
Here is a copy of the latest version of my Main class. Let me know if that works for you. I tested it on Linux (32/64bit) and Windows (32bit).
package de.pdark.epen.editor;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;
import de.pdark.epen.exceptions.WikiException;
public class Main
{
public final static String VERSION = "V0.9 (13.05.2010)"; //$NON-NLS-1$
private final static Logger log = LoggerFactory.getLogger (Main.class);
private static final String ORG_ECLIPSE_SWT_WIDGETS_SHELL = "org.eclipse.swt.widgets.Shell"; //$NON-NLS-1$
/**
* #param args
*/
#SuppressWarnings({"nls", "PMD.SystemPrintln"})
public static void main (String[] args)
{
String msg = "Starting ePen "+VERSION;
System.out.println (msg);
log.info (msg);
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory ();
StatusPrinter.print (lc);
int rc = 1;
try
{
Main main = new Main ();
main.run (args);
rc = 0;
}
catch (Throwable t) //NOPMD
{
ExceptionUtils.printRootCauseStackTrace (t);
}
finally
{
System.out.println ("Done.");
log.info ("Exit {}", rc);
System.exit (rc); //NOPMD
}
}
#SuppressWarnings({"nls", "PMD.SystemPrintln", "PMD.SignatureDeclareThrowsException"})
private void run (String[] args) throws Exception
{
if (!SystemUtils.isJavaVersionAtLeast (150))
{
System.out.println ("Version="+SystemUtils.JAVA_VERSION_INT);
throw new WikiException ("Need at least Java 5 but this Java is only "+SystemUtils.JAVA_VERSION);
}
loadSwtJar ();
URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); //NOPMD
Class<?> c = cl.loadClass ("de.pdark.epen.editor.EPenEditor");
Class<?> shellClass = cl.loadClass (ORG_ECLIPSE_SWT_WIDGETS_SHELL);
Constructor<?> ctor = c.getConstructor (shellClass);
Object obj = ctor.newInstance (new Object[] { null });
Method run = c.getMethod ("run", args.getClass ()); //$NON-NLS-1$
run.invoke (obj, new Object[] { args });
}
#SuppressWarnings({"nls", "PMD"})
private void loadSwtJar ()
{
try {
Class.forName (ORG_ECLIPSE_SWT_WIDGETS_SHELL);
// Already on classpath
return;
} catch (ClassNotFoundException e) {
// Add the JAR
}
String osName = SystemUtils.OS_NAME.toLowerCase ();
String osArch = SystemUtils.OS_ARCH.toLowerCase ();
String swtFileNameOsPart =
osName.contains("win") ? "win32" :
osName.contains("mac") ? "macosx" :
osName.contains("linux") || osName.contains("nix") ? "linux" :
null;
String swtFileNameUiPart =
osName.contains("win") ? "win32" :
osName.contains("mac") ? "cocoa" :
osName.contains("linux") || osName.contains("nix") ? "gtk" :
null;
if (null == swtFileNameOsPart)
{
throw new RuntimeException ("Can't determine name of SWT Jar from os.name=[" + osName + "] and os.arch=["
+ osArch + "]");
}
String swtFileNameArchPart = osArch.contains ("64") ? ".x86_64" : ".x86";
if(".x86".equals(swtFileNameArchPart) && "macosx".equals(swtFileNameOsPart)) {
swtFileNameArchPart = "";
}
String swtFileName = "org.eclipse.swt." + swtFileNameUiPart + "." + swtFileNameOsPart + swtFileNameArchPart + "-3.6.0.jar";
File file = new File ("swt", swtFileName);
if (!file.exists ())
{
throw new RuntimeException ("Can't locate SWT Jar " + file.getAbsolutePath ());
}
try
{
URLClassLoader classLoader = (URLClassLoader) getClass ().getClassLoader ();
Method addUrlMethod = URLClassLoader.class.getDeclaredMethod ("addURL", URL.class);
addUrlMethod.setAccessible (true);
URL swtFileUrl = file.toURI ().toURL ();
log.info ("Adding {} to the classpath", swtFileUrl);
addUrlMethod.invoke (classLoader, swtFileUrl);
}
catch (Exception e)
{
throw new RuntimeException ("Unable to add the swt jar to the class path: " + file.getAbsoluteFile (), e);
}
}
}
You could use Java Web Start as a bootstrap mechanism for your multi platform SWT application. See a corresponding entry in SWT FAQ.
Alternatively, you could put SWT native libraries for each platform into a separate folders and specify them -Djava.library.path in your platform-specific startup script.