How to print imported java libraries? - java

Is there a way to print within a Java Code the libraries that has been imported, and available during the execution?
For example :
import javax.swing.JFrame;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//some code
}
}
I need to print javax.swing.JFrame.

If you need the actual imports used in your source code (rather than using the information in the bytecode), you can use a library called QDox which will parse your source code and can get a list of the imports you use:
Main.java
import com.thoughtworks.qdox.JavaDocBuilder;
import javax.swing.JFrame;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JavaDocBuilder java = new JavaDocBuilder();
java.addSourceTree(new java.io.File("."));
for (String i : java.getClassByName("Main").getSource().getImports()) {
System.out.println(i);
}
}
}
Compile and run with:
# If you don't have wget, just download the QDox jar by hand
wget -U "" http://repo1.maven.org/maven2/com/thoughtworks/qdox/qdox/1.12/qdox-1.12.jar
javac -classpath qdox-1.12.jar Main.java
java -classpath qdox-1.12.jar:. Main
The output is:
com.thoughtworks.qdox.JavaDocBuilder
javax.swing.JFrame

I don't think that there is a way to do that. Imports are only a syntactic aid for the programmer and are not reflected in the compiled class files. Anyway, what do you need such a feature for?

Related

Getting error while executing java programs of packages from command line

I'm executing the programs from command line and using packages in them.
my program file names are TestA.java and TestB.java.
I've executed below initially
javac TestA.java
No issues for the above and it generated the class file as well
for the following i'm observing the issue
javac TestB.java
output :
TestB.java:2: error: '.' expected
import TestA;
^
TestB.java:2: error: ';' expected
import TestA;
^
2 errors
and the TestA.java file is
package a.b;
class TestA {
public static void methodPublic(){
methodPrivate();
}
protected static void methodProtected(){
methodPrivate();
}
static void methodDefault(){
methodPrivate();
}
private static void methodPrivate(){}
}
TestB.java content is :
package a.b;
import TestA;
public class TestB {
public static void main(String args[]) {
TestA.methodPublic();
TestA.methodProtected();
TestA.methodDefault();
}
public static void methodPublic() {
}
protected static void methodProtected() {
}
static void methodDefault() {
}
private static void methodPrivate() {
}
}
I'm executing the javac by navigating to b folder where these two files exist.
I'm executing the javac by navigating to b folder where these two files exist.
You don't want to do that; the fully qualified class name of every class includes the package. They form a tree. Much like your filesystem. From the b folder move up two directories (to the folder containing a - e.g. cd ../.. or cd ..\.. on Windows). Then
javac -cp . a/b/TestA.java a/b/TestB.java
Also, you would normally want that to be written to a "binary" output folder. So
javac -cp . -d bin a/b/TestA.java a/b/TestB.java
Finally, you don't need to import TestA because it is in the same package as TestB. But, if you want to you need
import a.b.TestA;

Running Cucumber project using Main.run from another main method

I am new to Cucumber and trying to solve simple issue:
I have created a Java Project and referred all the cucumber related jars to the build-path of this project (called it "CukeTest4") and below is the structure showing the java file and feature file. When I run this feature file as Cucumber feature in Eclipse, it runs fine.
Now, I would like to run this from another main method. I created another Java Project, Added a Class with main method with code below which is in default package.
import cucumber.api.cli.Main;
public class UseCukeFromMain {
public static void main(String[] args) throws Throwable
{
Main.main(new String[]{"-g", "C:/work/workspaces/neon2_wks_new1/Cuketest4/src/com/cuke", "C:/work/workspaces/neon2_wks_new1/Cuketest4/src/com/cuke/cukefeature.feature"});
}
}
I have provided implementation for the method in the java file as it works fine from Eclipse but shows the message below to implement the method
[33mU[0m
1 Scenarios ([33m1 undefined[0m)
1 Steps ([33m1 undefined[0m)
0m0.000s
You can implement missing steps with the snippets below:
#Given("^I want to write a step with precondition$")
public void i_want_to_write_a_step_with_precondition() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
I have tried a lot of combination for -g option, but the message is same.
EDIT2
From the comments below, adding the package to glue when the other project is in classpath, works fine.
Main.main(new String[]{"-g", "com.cuke", "C:/work/workspaces/neon2_wks_new1/Cuketest4/src/com/cuke/cukefeature.feature"};
But, Another issue:
I have some old projects that I need to integrate with cucumber. All the .class and .java are present in the folder(NO src or bin directory):
C:\work\RFT_WS2\Cuketest3
, I have this directory in the Classpath. I have tried following option but unable to understand the issue:
-g "" path/to/feature //(NOT WORKING)
-g "classpath:" path/to/feature //(NOT WORKING)
-g "Cuketest3" // Added "C:\work\RFT_WS2" in classpath (NOT WORKING)
Now if I add the .java file to a package say "steps" and have "C:\work\RFT_WS2\Cuketest3" in classpath, option looks like
-g "steps" path/to/feature //(WORKING)
My question is that how to get it to find the methods implementation for a default package.
Also how do add multiple glue option, for example
Not Working cases I tried
Main.main(new String[]{"-g", "com.cuke,com.cuke1", "C:/work/workspaces/neon2_wks_new1/Cuketest4/src/com/cuke/cukefeature.feature"};
Main.main(new String[]{"-g", "com.cuke", "com.cuke1", "C:/work/workspaces/neon2_wks_new1/Cuketest4/src/com/cuke/cukefeature.feature"};
Thanks.
The glue option takes a path value which reflects the package(s) of the glue classes to be included in the classpath.
Find a simplified working example below
Assume following structure
/tmp/cuke-test/features/cukefeature.feature
/tmp/cuke-test/lib
/tmp/cuke-test/project1/src/com/cuke/CukeSteps.java
/tmp/cuke-test/project2/src/UseCukeFromMain.java
cukefeature.feature
Feature: simple test
Scenario: test programatic call of Cucumber
Given we have feature file
When some glue code exists
Then those steps should not fail
lib
cucumber-core-2.1.0.jar
cucumber-html-0.2.6.jar
cucumber-java-2.1.0.jar
cucumber-jvm-deps-1.0.6.jar
cucumber-testng-2.1.0.jar
gherkin-5.0.0.jar
jcommander-1.64.jar
snakeyaml-1.17.jar
tag-expressions-1.0.1.jar
testng-6.11.jar
CukeSteps.java
package com.cuke;
import cucumber.api.PendingException;
import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.en.*;
public class CukeSteps {
#Given("^we have feature file$")
public void we_have_feature_file() throws Throwable {
System.out.println("execute Given step");
}
#When("^some glue code exists$")
public void some_glue_code_exists() throws Throwable {
System.out.println("execute Then step");
}
#Then("^those steps should not fail$")
public void those_steps_should_not_fail() throws Throwable {
throw new PendingException();
}
}
UseCukeFromMain.java
import cucumber.api.cli.Main;
public class UseCukeFromMain {
public static void main(String[] args) throws Throwable {
Main.main(new String[]{
"--glue",
"com/cuke", // the package which contains the glue classes
"/tmp/cuke-test/features/cukefeature.feature"}
);
}
}
compile the classes
javac -cp "lib/*" -d project1/bin/ project1/src/com/cuke/*.java
javac -cp "lib/*" -d project2/bin/ project2/src/*.java
run the UseCukeFromMain
The root direcotry which contains the glue classes (project1/bin) must be in the classpath.
java -cp "project2/bin:project1/bin:lib/*" UseCukeFromMain
output
execute Given step
execute Then step
1 Scenarios (1 pending)
3 Steps (1 pending, 2 passed)
0m0.104s
cucumber.api.PendingException: TODO: implement me
at com.cuke.CukeSteps.those_steps_should_not_fail(CukeSteps.java:21)
at ✽.those steps should not fail(/tmp/cuke-test/features/cukefeature.feature:6)
edit Using Step definitions in default package
Assume following structure
features/cukefeature.feature
lib/
project1/src/CukeSteps.java
project2/src/UseCukeFromMain.java
cukefeature.feature
lib/
the same as in the first example
CukeSteps.java
// note: there is no package statement
import cucumber.api.PendingException;
import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.en.*;
public class CukeSteps {
#Given("^we have feature file$")
public void we_have_feature_file() throws Throwable {
System.out.println("execute Given step");
}
#When("^some glue code exists$")
public void some_glue_code_exists() throws Throwable {
System.out.println("execute Then step");
}
#Then("^those steps should not fail$")
public void those_steps_should_not_fail() throws Throwable {
throw new PendingException();
}
}
UseCukeFromMain.java
import cucumber.api.cli.Main;
public class UseCukeFromMain {
public static void main(String[] args) throws Throwable {
Main.main(new String[]{
"--glue",
"", // to used Step definitions in default package
"features/cukefeature.feature"}
);
}
}
compile classes
The option -d . creates the class files in the current directory.
javac -cp "lib/*" -d . project1/src/*.java
javac -cp "lib/*" -d project2/bin/ project2/src/*.java
created class files
CukeSteps.class
project2/bin/UseCukeFromMain.class
run the UseCukeFromMain
The current directory is added to the classpath using the ..
java -cp "project2/bin:.:lib/*" UseCukeFromMain
output
execute Given step - default package
execute Then step - default package
1 Scenarios (1 pending)
3 Steps (1 pending, 2 passed)
0m0.096s
cucumber.api.PendingException: TODO: implement me
at CukeSteps.those_steps_should_not_fail(CukeSteps.java:19)
at ✽.those steps should not fail(features/cukefeature.feature:5)
edit Using Step definitions from different packages.
Assume following structure
features/cukefeature.feature
lib
project1/src/com/cuke1/CukeStepsB.java
project1/src/com/cuke/CukeStepsA.java
project2/src/UseCukeFromMain.java
cukefeature.feature
lib/
the same as in the first example
The Step definitions are split in two classes, in different packages
CukeStepsA.java
package com.cuke;
import cucumber.api.PendingException;
import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.en.*;
public class CukeStepsA {
#Given("^we have feature file$")
public void we_have_feature_file() throws Throwable {
System.out.println("execute Given step - package com.cuke");
}
}
CukeStepsB.java
package com.cuke1;
import cucumber.api.PendingException;
import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.en.*;
public class CukeStepsB {
#When("^some glue code exists$")
public void some_glue_code_exists() throws Throwable {
System.out.println("execute Then step - package com.cuke1");
}
#Then("^those steps should not fail$")
public void those_steps_should_not_fail() throws Throwable {
throw new PendingException();
}
}
UseCukeFromMain.java
import cucumber.api.cli.Main;
public class UseCukeFromMain {
public static void main(String[] args) throws Throwable {
Main.main(new String[]{
"--glue",
"com/cuke",
"--glue",
"com/cuke1",
"features/cukefeature.feature"}
);
}
}
compile classes
javac -cp "lib/*" -d project1/bin/ project1/src/com/cuke/*.java project1/src/com/cuke1/*.java
javac -cp "lib/*" -d project2/bin/ project2/src/*.java
created class files
project1/bin/com/cuke1/CukeStepsB.class
project1/bin/com/cuke/CukeStepsA.class
project2/bin/UseCukeFromMain.class
run the UseCukeFromMain
java -cp "project2/bin:project1/bin:lib/*" UseCukeFromMain
output
execute Given step - package com.cuke
execute Then step - package com.cuke1
1 Scenarios (1 pending)
3 Steps (1 pending, 2 passed)
0m0.114s
cucumber.api.PendingException: TODO: implement me
at com.cuke1.CukeStepsB.those_steps_should_not_fail(CukeStepsB.java:16)
at ✽.those steps should not fail(features/cukefeature.feature:5)
The absolute path is required for feature file. The step def directory requires classpath format.
public static void main(String[] args) throws Throwable {
//Your code to get feature file full path
Main.main(new String[]{"-g", "classpath to step definition file", "Full path to feature file"});
}

how to solve package does not exist error in java

I am trying to compile my java file name Test.java. Test.java calling a class com.api.APIUser.java which is available in a user.jar file. I have added user.jar in lib folder. But Test.java is unable to pick APIUser.java. While I am compiling Test.java using javac I am getting error
"package com.api does not exist".
Test.java
import com.api.APIUser;
public class Test{
APIUser ap = new APIUser();
ap .login();
public static void main(String[] args){
//to do
}
}
APIUser
package com.api
public class APIUser{
public string login(){
//to do
return string;
}
}
If any one have idea why I am getting this error.please suggest me solution.
Thanks in advance.
put a semicolon after the package com.api like as below
package com.api;
clean and build the project and run if any issue inform
You have multiple issues in your code.
You have no line termination present for the com.api import in the APIUser class;
You have a syntax error in your login method.
Below is the improved code:
import com.api.APIUser;
public class Test {
// APIUser ap = new APIUser(); // This call should be in the method body,
// there is no use to keep it at the class level
// ap.login(); // This call should be in method body
public static void main(String[] args) {
// TO DO
APIUser ap = new APIUser();
ap.login();
}
}
APIUser
package com.api; // added termination here
public class APIUser {
//access specifier should be public
public string login(){
//to do
//return string;//return some value from here, since string is not present this will lead to error
return "string";
}
}
Also be sure that the JAR file is present in the classpath. If you are not using any IDE, you must use the -cp switch along with the JAR file path, so that a class can be loaded from there.
You can use the code below to understand how to compile your class using classpath from command prompt.
javac -cp .;/lib/user.jar; -D com.api.Test.java

How to add static imports to IntelliJ IDEA live template

I need to port the following Eclipse template to IntelliJ IDEA
/**
* See method name.
*/
#${testType:newType(org.junit.Test)}
public void should${testdesc}() {
// given ${cursor}
${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')}
// when
// then
}
What I've got so far is
/**
* See method name.
*/
#org.junit.Test
public void should$EXPR$() {
// given $END$
${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')}
// when
// then
}
And then tick the Shorten FQ names flag.
What's the IDEA equivalent for the ${staticImport:importStatic()} expression?
You cannot just import the static imports in a live template. (You can for a file template, see below). But you can when using a method in the template. You just simply fully qualify the class and then select both the "Shorten FQ names" and "Use static import if possible" options. For example, the following:
org.junit.Assert.assertEquals("$END$", $EXPECTED$, $ACTUAL$);
Will result in:
import static org.junit.Assert.*;
. . .
assertEquals("my error message", myExpectedVar, myActualVar);
when invoked. (I have the $EXPECTED$ and $ACTUAL$ variables set to variableOfType("") with corresponding default values expected and actual)
If you want certain static imports to be included in all your unit tests, then I would recommend editing the "Class" File and Code Template. For example:
package ${PACKAGE_NAME};
#if ($NAME.endsWith("Test"))
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.BDDMockito.*;
#end
#parse("File Header.java")
public class ${NAME}
{
#if ($NAME.endsWith("Test"))
// Add any default test methods or such you want here.
#end
}
Keep in mind however, the static import will immediately be removed if you have the "Optimize imports on the fly" option (in IDE Settings > Editor > Auto import) turned on, unless you also include a method (or other code) that makes use of the static import.
Now its possible to add live templates with static imports:
You have to check static import in Options
#org.junit.Test
public void should$EXPR$when$CONDITION$() {
org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue()));
}

Jar Maker -- Which is the main class?

Alrighty, so I'm working on making a .jar for a client for a little game and I know how to use everything and have done this before, on windows, now i'm on a mac. This shouldn't make a difference but incase you wanted to know, there you go.
Now, I have a folder in eclipse named client, now normally the client.java is the main class but there is another named EGUI, this has the "public static void main(String[] args)", but in my client.java file, it also has a method like this:
public static final void main(String args[])
{
try
{
anInt957 = 0;
anInt958 = 0;
method52(false);//highmem
aBoolean959 = true;//members
signlink.storeid = 32;
signlink.startpriv(InetAddress.getLocalHost());
client client1 = new client();
client1.method1(503, false, 765);
setserver(args[0], "5555");
return;
}
catch(Exception exception)
{
return;
}
}
I guess my question is, does the "final" make it the main file? Or would it still be the EGUI, which looks like this:
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class EGUI
{
public static void main(String args[])
{
client.main(new String[] {
"127.0.0.1", "127.0.0.1", "127.0.0.1"
});
}
}
So, what i'm asking for is, why is it that when I'm setting the main file to EGUI, it isnt working? the applet opens up, but I keep getting an "error connecting to server" message every time, when I run it through terminal by copying the run.bat info and pasting that, it works perfectly! Any help is greatly appreciated!
public static void main(String args[]) means you can execute the class from the commandline. The final keyword means the method cannot be overridden by a sub class.
In your case this does not make it the jar's main execution class. The main class is set in META-INF/MANIFEST.MF. Normally it should have a line:
Main-Class: classname
but then with the actual class.
So open the jar with a zip program, and check MANIFEST.MF.
Your client.java has a main method, for testing purposes I suppose.

Categories