"Error: Could not find or load main class” in jenkins - java

i am using jenkins in ubuntu and i need to call a java class from python script. The code:
import os
import shutil
import sys
from subprocess import call, STDOUT
param1=os.getenv(‘PARAM1’)
param2=os.getenv(‘PARAM2’)
param3=os.getenv(‘PARAM3’)
cmd1 =”cp /…/Class.class $JENKINS_HOME/jobs/$JOB_NAME/builds/$BUILD_NUMBER/Class.class ”
cmd2=”java $JENKINS_HOME/jobs/$JOB_NAME/builds/$BUILD_NUMBER/Class ” +””+param1+””+param2””+param3
print>>> sys.stder, “Launching command: “ + cmd2
call(cmd1,shell=True)
call(cmd2,shell=True)
But the console output shows “Error: Could not find or load main class”
I have checked an the file was copied, and Jenkis have installed the Java SE Development Kit 8u31 version.
I have try build the process in two step, first copy the java file and later set up the variables and do the second call but appears the same error.
Thanks,
i have changed the code to:
classpath=os.path.join(os.getenv('JENKINS_HOME'),"jobs",os.getenv(JOB_NAME'),"builds",os.getenv('BUILD_NUMBER'))
cmd2=[“java”,”-classpath”,classpath,”Class”,param1,param2,param3]
call(cmd2)
The code Works!!!
When i build with parameters the console output shows "Usage_ java [- options] class [args...]..."

Java doesn't support "run this file as a class" directly. Instead, you need to add the class to the classpath and then call it using the Java Fully Qualified name:
java -classpath $JENKINS_HOME/jobs/$JOB_NAME/builds/$BUILD_NUMBER com.foo.Class ...
would run the Java code in .../builds/$BUILD_NUMBER/com/foo/Class.class
Note: Avoid call() with a string. Instead build a list of command plus arguments. That way, you can replace variables correctly and spaces in file names won't cause unexpected/hard to find problems:
classpath = os.path.join(os.genenv("JENKINS_HOME), "jobs", ...)
cmd = [
"java",
"-classpath",
classpath,
"Class",
...
]
call(cmd)

Related

I am unable to compile and run a java program using python script

I think when I use os.system("cd java path") to change the path to java directory it's just don't change the path to that directory...
Here's the code I have written:
import os
import time
#import subprocess
os.system("cls")
os.system("cd C:\\Program Files\\Java\\jdk-13.0.1\\bin")
time.sleep(2)
os.system("javac add.java")
os.system("java add")
Error:
error: file not found: add.java
Usage: javac
use --help for a list of possible options
Error: Could not find or load main class add
Caused by: java.lang.ClassNotFoundException: add
I think the problem is that your current directory may not contains add.java after doing cd C:\\Program Files\\Java\\jdk-13.0.1\\bin:
You may try this "static solution" that works for one java instalation:
import os
import time
#import subprocess
os.system("cls")
time.sleep(2)
os.system("C:\\Program Files\\Java\\jdk-13.0.1\\bin\\javac add.java")
os.system("C:\\Program Files\\Java\\jdk-13.0.1\\bin\\java add")
You may also include your java installation path in the PATH of the operative system, and you may run javac and java without their absolute path. If you later change the java version, with only updating the java path the script will maintain operable. In this case the code will be like this:
import os
import time
#import subprocess
os.system("cls")
time.sleep(2)
os.system("javac add.java")
os.system("java add")
This code worked for me and I had to copy script into the bin folder to make it work..
import os
import time
aditya = True
while aditya:
os.system("cls")
print("Enter a program name to execute:")
name = input()
os.system(f"javac {name}.java")
os.system(f"java {name}")
key = input()

can't run .jar file /java.jar: line 1: public: command not found

I have Ubuntu 16.04.
and downloaded a JDK with a tar.gz file extension and followed This wikihow to install it.
When I try to run a .jar game (like Minecraft) It works successfully, and I have netbeans downloaded that is connected to the same JDK and compiled some programs that i can run in terminal, But When I type :
./Hello_world.jar
Which is :
package main;
public class project {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
I get this output :
./Hello_world.jar: line 1: $'PK\003\004': command not found
./Hello_world.jar: line 2: $'\b.\020oK': command not found
./Hello_world.jar: line 3: syntax error near unexpected token `)'
./Hello_world.jar: line 3:-oK�}����META-INF/MANIFEST.MFM�1
�0��#��uHh Q���X� ��N1�Ҧ$)��7�(�p�ww
�A����|��}�1���ή�n��p<�Рŗ��:CpN~�s�ν�˚�3��%
��)���goPK`
Simple: JAR files aren't executables. You can only invoke binaries/scripts by telling your shell to ./command.
They are archives that contain compiled Java classes.
Thus you use them like:
java -jar somejar.jar
This starts a java virtual machine, and tells it to open the given JAR file. The JVM will then figure the "main" class to run from the meta information that can be backed into the JAR file - to then "run" that main class.
( assuming that the corresponding JAR file has been built in a why that allows running it like this. see here for details on how you enable this "easy way" of running a JAR file )
And just in case: with some scripting magic, you actually can turn a JAR file into a "binary", see here for example.

I get an error: An unexpected error occurred while trying to open file hola.jar

i am using Linux ubuntu and i have created a java program named hola.java which is the following program code, this program works perfectly
import javax.swing.*;
import java.awt.*;
public class hola extends JFrame {
JButton b1 = new JButton("presionar");
hola(){
super("Botones");
setSize(250,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo=new FlowLayout();
setLayout(flo);
add(b1);
setVisible(true);
}
public static void main(String[] args)
{
hola bt = new hola();
}
}
This java program works perfectly when it runs
Now I created a jar file of this program using in command line:
jar cf hola.jar hola.class
This creates a Jar file named hola.jar
I even wrote Main-Class: hola in the manifest.mf file.
When I try to run this by:
java -jar hola.jar
I get an error: An unexpected error occurred while trying to open file hola.jar
Please tell me how to run jar file so that I get an output :'( , what could be the possible reason that i can not run this program as a jar file, even the program works perfectly using "java hola.java"
This error mostly indicates invalid MANIFEST.MF file. Perhaps long line, missing final line terminator, accidental empty line in the middle, ... many things can go wrong. Using -cp just goes around the problem, but does not fix the root cause.
To run a java file within a jar file, you don't need to open it. You simply need to ensure your classpath is having the given jar file
If the class is within a package then you can run using
java -cp hola.jar package.hola
If the class is not in a package then simply use
java -cp hola.jar hola
If you are not within the directory where hola.jar is located, then you can try following:
In case of within package
java -cp /locationOfJar/hola.jar package.hola
or In case of not in package
java -cp /locationOfJar/hola.jar hola
Error can also happen with > 65535 files in the .jar on some OS
I experienced same error message attempting to launch via -jar:
$ java -jar app.jar
Error: An unexpected error occurred while trying to open file: app.jar
Root cause is that my sbt-assembly output .jar file contains more than 65535 entries.
$ zipinfo app.jar |wc -l
65543
Solution: Short term solution was removal of older dependencies to lower the number of assembled .class files below the 16 bit file count limit.
Long term solution will involve testing Zip64 jvm support on the target OS. Unsure of why the zip64 auto negotiation isn't occurring automatically.
This issue is reproducible using sbt-assembly 15.0, openjdk version "11.0.8" on MacOSX 10.15.7.
Start of the code review:
package java.util.zip;
...
public
class ZipOutputStream extends DeflaterOutputStream implements ZipConstants {
/**
* Whether to use ZIP64 for zip files with more than 64k entries.
* Until ZIP64 support in zip implementations is ubiquitous, this
* system property allows the creation of zip files which can be
* read by legacy zip implementations which tolerate "incorrect"
* total entry count fields, such as the ones in jdk6, and even
* some in jdk7.
*/
private static final boolean inhibitZip64 =
Boolean.parseBoolean(
GetPropertyAction.privilegedGetProperty("jdk.util.zip.inhibitZip64"));

javac error: Class names are only accepted if annotation processing is explicitly requested

I get this error when I compile my java program:
error: Class names, 'EnumDevices', are only accepted if annotation
processing is explicitly requested
1 error
Here is the java code (I'm running this on Ubuntu).
import jcuda.CUDA;
import jcuda.driver.CUdevprop;
import jcuda.driver.types.CUdevice;
public class EnumDevices {
public static void main(String args[]) {
CUDA cuda = new CUDA(true);
int count = cuda.getDeviceCount();
System.out.println("Total number of devices: " + count);
for (int i = 0; i < count; i++) {
CUdevice dev = cuda.getDevice(i);
String name = cuda.getDeviceName(dev);
System.out.println("Name: " + name);
int version[] = cuda.getDeviceComputeCapability(dev);
System.out.println("Version: " +
String.format("%d.%d", version[0], version[1]));
CUdevprop prop = cuda.getDeviceProperties(dev);
System.out.println("Clock rate: " + prop.clockRate + " MHz");
System.out.println("Threads per block: " + prop.maxThreadsPerBlock);
}
}
}
Here is the javac command:
javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices
How do I compile this program?
You at least need to add the .java extension to the file name in this line:
javac -cp /home/manish.yadav/Desktop/JCuda-All-0.3.2-bin-linux-x86_64 EnumDevices
From the official faq:
Class names, 'HelloWorldApp', are only accepted if annotation processing is explicitly requested
If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp.
Also, in your second javac-example, (in which you actually included .java) you need to include the all required .jar-files needed for compilation.
I was stumped by this too because I was including the .Java extension ... then I noticed the capital J.
This will also cause the "annotation processing" error:
javac myclass.Java
Instead, it should be:
javac myclass.java
Using javac ClassName.java to compile the program,
then use java ClassName to execute the compiled code. You can't mix javac with the ClassName only (without the java extension).
The error "Class names are only accepted if annotation processing is explicitly requested" can be caused by one or more of the following:
Not using the .java extension for your java file when compiling.
Improper capitalization of the .java extension (i.e. .Java) when compiling.
Any other typo in the .java extension when compiling.
When compiling and running at the same time, forgetting to use '&&' to concatenate the two commands (i.e. javac Hangman.java java Hangman). It took me like 30 minutes to figure this out, which I noticed by running the compilation and the running the program separately, which of course worked perfectly fine.
This may not be the complete list of causes to this error, but these are the causes that I am aware of so far.
I learned that you also can get this error by storing the source file in a folder named Java
chandan#cmaster:~/More$ javac New.java
chandan#cmaster:~/More$ javac New
error: Class names, 'New', are only accepted if annotation processing is explicitly requested
1 error
So if you by mistake after compiling again use javac for running a program.
How you can reproduce this cryptic error on the Ubuntu terminal:
Put this in a file called Main.java:
public Main{
public static void main(String[] args){
System.out.println("ok");
}
}
Then compile it like this:
user#defiant /home/user $ javac Main
error: Class names, 'Main', are only accepted if
annotation processing is explicitly requested
1 error
It's because you didn't specify .java at the end of Main.
Do it like this, and it works:
user#defiant /home/user $ javac Main.java
user#defiant /home/user $
Slap your forehead now and grumble that the error message is so cryptic.
Perhaps you may be compiling with file name instead of method name....Check once I too made the same mistake but I corrected it quickly .....#happy Coding
first download jdk from https://www.oracle.com/technetwork/java/javase/downloads/index.html.
Then in search write Edit the System environment variables
In open window i push bottom called Environment Variables
Then in System variables enter image description here
Push bottom new
In field new variables write "Path"
In field new value Write directory in folder bin in jdk like
"C:\Program Files\Java\jdk1.8.0_191\bin"
but in my OS work only this "C:\Program Files\Java\jdk1.8.0_191\bin\javac.exe"
enter image description here
press ok 3 times
Start Cmd.
I push bottom windows + R.
Then write cmd.
In cmd write "cd (your directory with code )" looks like C:\Users\user\IdeaProjects\app\src.
Then write "javac (name of your main class for your program).java" looks like blabla.java
and javac create byte code like (name of your main class).class in your directory.
last write in cmd "java (name of your main class)" and my program start work
To avoid this error, you should use javac command with .java extension.
Javac DescendingOrder.java <- this work perfectly.
I created a jar file from a Maven project
(by write mvn package or mvn install )
after that i open the cmd , move to the jar direction and then
to run this code the
java -cp FILENAME.jar package.Java-Main-File-Name-Class
Edited : after puting in Pom file declar the main to run the code :
java -jar FILENAME.JAR
If you compile multiple files in the same line, ensure that you use javac only once and not for every class file.
Incorrect:
Correct:

Why can't I load this class file in Rhino console?

I'm prototyping a web page scraper using Rhino and Env-js. Nevermind that the documentation for both projects is atrocious... I'm trying to load up the File.java example class that is supplied with Rhino. For simplicity sake, I've got File.java, js.jar, jline.jar and env.rhino.1.2.js all in one directory. I've tried specifying the current directory using the classpath command line option, but still whenever I call defineClass("File") I get an error saying the class file isn't found. What am I doing wrong here??
$ ls -1
File.java
env.rhino.1.2.js
jline.jar
js.jar
$ java -cp .:js.jar:jline.jar jline.ConsoleRunner org.mozilla.javascript.tools.shell.Main -opt -1
Rhino 1.7 release 2 2009 03 22
js> defineClass("File")
js: "<stdin>", line 2: Class "File" not found.
at <stdin>:2
Don't you need to compile File.java before using it, as the classpath "." only makes sense if it contains some compiled class in it?

Categories

Resources