Find all classes in a given package [duplicate] - java

This question already has answers here:
Can you find all classes in a package using reflection?
(30 answers)
Closed 10 years ago.
Given a package, is it possible to find all the classes in it?
For instance, how do you find out what classes are contained within java.lang?
Thanks

This should get you started (look at the console output, it will make sense):
import com.google.common.collect.Multimap;
import org.reflections.Reflections;
import java.util.Map;
public class PackageWalker {
public PackageWalker() {}
public void walk() {
Reflections reflections = new Reflections("org.reflections");
for (String mmapName : reflections.getStore().getStoreMap().keySet()) {
System.out.println("KEY["+mmapName+"]");
Multimap<String,String> mmap = reflections.getStore().getStoreMap().get(mmapName);
for (Map.Entry<String,String> entry: mmap.entries()) {
System.out.println(" PAIR[ "+entry.getKey()+"="+entry.getValue()+" ]");
}
}
}
public static void main(String[] args) {
new PackageWalker().walk();
}
}
Following jars and their dependencies are required (using Ivy format):
<dependency org="org.reflections" name="reflections" rev="0.9.8"/>
Here is my project folder:
http://www.filedropper.com/laboratorytar
You just need to make sure Ivy is installed with ant (essentially put ivy.jar into your ANT_HOME/lib (or ~/.ant/lib/ on *nix) and it will just work).

Related

The type java.io.FilterOutputStream cannot be resolved. It is indirectly referenced from required .class files [duplicate]

This question already has answers here:
the type java.io.FilterOutputstream cannot be resolved. error
(2 answers)
Closed 21 hours ago.
File Structure
MathNumber.java file
package com.code_for_numbers.number;
import java.util.ArrayList;
public class MathNumber {
public ArrayList<Integer> primeNums(){
ArrayList<Integer> arrList =new ArrayList<Integer>();
arrList.add(1);
arrList.add(2);
arrList.add(3);
arrList.add(5);
arrList.add(7);
arrList.add(11);
return arrList;
}
}
PerformTask.java file
package com.code_for_numbers.number;
public class PerformTask {
public static void main(String[] args) {
MathNumber n=new MathNumber();
System.out.println(n.primeNums());
}
}
While running my code I get error in PerformTask.java file The type java.io.FilterOutputStream cannot be resolved. It is indirectly referenced from required .class files
The outcome of result I am expecting [1,2,3,5,7,11]
I think this is the same: the type java.io.FilterOutputstream cannot be resolved. error
It looks like there is no JVM configured for your project in your IDE.

Soap Webservice Client for JAVAFX Application

I am trying to call the webservice for my application. If I call it in a sample project it is working perfectly fine. But when I merge it with My Java FX it is giving me so many errors. Web Service Client is auto generated using the Eclipse. I am trying to call the Methods only. Can Anyone help me?
Error: **Correction** I have edited it and I am using now JAVASE-15 and JVAFX-SDK 11.0.2
The package javax.xml.namespace is accessible from more than one module: java.xml, jaxrpc
Correction Update 2: I have removed Java.xml dependencies and module-info file as well.
but the new error is this
**Error: Could not find or load main class gload.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application**
and IF I keep the module info file it shows:
**Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.graphics not found, required by gload**
Model:
package gload.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JOptionPane;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data.CustomerItem;
import org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data.Result;
import org.tempuri.IService;
import org.tempuri.ServiceLocator;
public class PdmData
{
public String scode;
public boolean state = false;
public static String CdfFile;
public static String pdflocation;
public static String Custom_Ci;
public static String Generic_Ci;
public static String Mp_ref;
public static String Interface;
public static String Comments;
public static String PersoAppli;
public static String Code;
public static String Revision;
public static String Customer_Name;
public static String Customer_reference;
public static String getCode() {
return Code;
}
public static void setCode(String code) {
Code = code;
}
public static String getRevision() {
return Revision;
}
public static void setRevision(String revision) {
Revision = revision;
}
public static String getCustomer_Name() {
return Customer_Name;
}
public static void setCustomer_Name(String customer_Name) {
Customer_Name = customer_Name;
}
public static String getCustomer_reference() {
return Customer_reference;
}
public static void setCustomer_reference(String customer_reference) {
Customer_reference = customer_reference;
}
public static String getPersoAppli() {
return PersoAppli;
}
public static void setPersoAppli(String persoAppli) {
PersoAppli = persoAppli;
}
public static String getGeneric_Ci() {
return Generic_Ci;
}
public static void setGeneric_Ci(String generic_Ci) {
Generic_Ci = generic_Ci;
}
public static String getCdfFile() {
return CdfFile;
}
public static void setCdfFile(String cdfFile) {
CdfFile = cdfFile;
}
public static String getPdflocation() {
return pdflocation;
}
public static void setPdflocation(String pdflocation) {
PdmData.pdflocation = pdflocation;
}
public String Cdffile(String reference) {
ServiceLocator locator = new ServiceLocator(); -------->Web Service Locator and call
try {
IService basicHttpBinding_IService = locator.getBasicHttpBinding_IService();
Result result = basicHttpBinding_IService.getFilebyDcode(reference);
//To download the files
String link = result.getLocation();
System.out.println(link);
File out = new File("C:\\TempDownload\\" + reference +".zip"); //Creating a zip file to store the contents of download file
new Thread(new Download(link,out)).start();
//To Unzip the file
Path source = Paths.get("C:\\TempDownload\\" + reference +".zip");
Path target = Paths.get("C:\\TempDownload\\Unzip");
try {
unzipFolder(source, target);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
//Creating a File object for directory
File directoryPath = new File("C:\\TempDownload\\Unzip\\Pre Ppc" + reference + "A_Released");
//List of all files and directories
String[] contents = directoryPath.list();
System.out.println("List of files and directories in the specified directory:");
FilenameFilter pdffilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".pdf")) {
return true;
} else {
return false;
}
}
};
String[] contents1 = directoryPath.list(pdffilter);
for(String fileName : contents1) {
System.out.println(fileName);
setCdfFile(fileName);
setPdflocation(directoryPath.toString());
}
//To extract the Data From PDF
File file = new File(getPdflocation() + "\\" + getCdfFile());
//FileInputStream fis = new FileInputStream(file);
PDDocument document = PDDocument.load(file);
PDFTextStripper pdfReader = new PDFTextStripper();
String docText = pdfReader.getText(document);
System.out.println(docText);
document.close();
//To extract details from document
String CI_Ref = "CI Ref";
int pos ;
pos = docText.indexOf(CI_Ref);
setGeneric_Ci(docText.substring(pos+7 , pos+15));
System.out.println("Generic CI: " + getGeneric_Ci());
//To get Details of CI
CustomerItem customerItem = basicHttpBinding_IService.getCiDetails(getGeneric_Ci());
setPersoAppli(customerItem.getPersoAppli());
setCode(customerItem.getCode());
setRevision(customerItem.getRevision());
setCustomer_Name(customerItem.getCustomerName());
setCustomer_reference(customerItem.getCustomerReference());
}catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Unable to reach Service : " + e.getMessage());
}
return getPersoAppli();
}
Module info file
module gload {
requires javafx.controls;
requires javafx.fxml;
requires java.desktop;
requires java.rmi;
requires java.base;
requires axis;
requires jaxrpc;
requires org.apache.pdfbox;
opens gload;
opens gload.views.main;
opens gload.utils;
opens gload.model;
opens gload.controllers;
opens org.tempuri;
opens org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data;
}
and IF I keep Jaxrpc in classpath instead of module path I get error like this Description
The type javax.xml.rpc.ServiceException cannot be resolved. It is indirectly referenced from required .class files
OK, this won't really be an answer, more pointers to related issues and potential approaches to come up with solutions. But I'll post it as an answer as it is likely better to do that than lots of comments.
Unfortunately, you have multiple errors and issues, so I'll try to deal with some of them seperately.
According to:
Java FX Modular Application, Module not found (Java 11, Intellij)
The error:
Error occurred during initialization of boot layer
java.lang.module.FindException:
Module X not found, required by Y
can occur when --module-path is wrong and the module can't be found. Probably, that is at least one of your issues. The linked answer is for Idea and I don't use Eclipse, so I don't know how to resolve the issue in Eclipse, but perhaps you could do some research to find out.
Regarding:
The package javax.xml.namespace is accessible from more than one module
there is some info on what is going on here:
Eclipse is confused by imports ("accessible from more than one module").
This fix appears tricky to me. Please review the linked questions and solutions. It looks like either you need to either
Forego Java 9+ modularity OR
Manage your dependencies to not include the violating transitive dependency OR
Change to a library that doesn't rely on the broken library (probably the preferred solution in this case).
The broken library causing this issue is likely the version of jaxrpc you are using. My guess is that some of the relevant XML libraries were only added to standard Java in Java 9, but the jaxrpc library you are using was developed prior to that. So, jaxrpc either includes the XML libraries in its classes or makes use of a transitive library that does the same. This causes a conflict because the XML libraries can only be included once in the project.
Further info on your issues is in this answer:
Eclipse can't find XML related classes after switching build path to JDK 10
The info is so ugly . . . you could read the answer, it may either help or discourage you.
Some things you could do to help resolve the situation
What should be done about this is kind of tricky and will depend on your skill level and how or if you can solve it. I'll offer up some advice on some things you could do, but there are other options. You know your application better than I so you may be able to come up with better solutions for your application.
I'd advise separating these things out, just as a way of troubleshooting, get a project which works with all of the JavaFX components and one which works with all of the SOAP components and make sure they build and do what you want. Then try to combine the two projects either by integrating them into one project or running them in separate VMs with communication between the two (e.g. via an added REST API, though that is a much more complicated solution, so think hard about that before attempting it).
Also, upgrade to the latest version of JavaFX. I don't think it will fix your issue, but it can't hurt and it is possible some refinements in recent JavaFX versions may have done some things which might help ease some of your issues (though not all of them, as some of your issues stem from jaxrpc usage in a modular project, which is unrelated to JavaFX).
Also, and probably more importantly, consider using a different SOAP client framework that interacts better with modular Java 9+ than the broken implementation that jaxrpc appears to have.
In terms of whether you should make your application modular or not (include a module-info or not), I don't really know the best approach for you. Certainly, whichever way you choose you will run into issues. But, the issues and how to resolve them will be different depending on the chosen solution path (as I guess you have already discovered during the course of your investigation for the question).
If necessary, isolate the issues down to single separate issues. If you need help in resolving each separate issue post new questions that feature minimal reproducible example code to replicate the issue. Mind if you do so, that the code is absolutely minimal and also complete so that it replicates and asks about only one issue, not a combination of more than one and that the questions are appropriate tagged - e.g. if the question is about jaxrpc and modularity it should include jaxrpc and modular tags and no JavaFX code or tags (and vice versa) and certainly on pdf code or dependencies anywhere if that isn't part of the problem.

How to read the file entry with same name in multiple library jars with spring boot?

I have a spring application with multiple dependent libraries that have the inner properties/xml that I want to read.
test-app.jar
dep1.jar
dep2.jar
dep3.jar
...
Each of the dep1/2/3 jars have the file called META-INF/config.properties which contains the files to further read within that dependent jars.
I tried the ResourceUtils.getURL("classpath:/META-INF/config.properties"), but it always reads from the first dependent file.
How can I read from each jars that contains the same name?
I found this solution after searching:
final Enumeration<URL> resEnum =
MyClass.class.getClassLoader()
.getResources("META-INF/config.properties");
final List<URL> resources =
Collections.list(resEnum);
//Copied from riptutorial.com
Refs:
https://riptutorial.com/java/example/19290/loading-same-name-resource-from-multiple-jars
https://stackoverflow.com/a/6730897
Updated solution:
package abc;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
public class MultipleClasspathEntries {
public static void main(String[] args) throws IOException {
final Enumeration<URL> resEnum =
MultipleClasspathEntries.class.getClassLoader()
.getResources("META-INF/MANIFEST.MF");
while (resEnum.hasMoreElements()) {
System.out.println(resEnum.nextElement());
}
}
}
//Copied from riptutorial.com
$JAVA_HOME/bin/javac abc/*.java
$JAVA_HOME/bin/java -cp /c/so-67847004/commons-lang-2.4.jar:/c/so-67847004/commons-collections-3.2.1.jar:. abc.MultipleClasspathEntries
Output:
jar:file:/C:/so-67847004/commons-lang-2.4.jar!/META-INF/MANIFEST.MF
jar:file:/C:/so-67847004/commons-collections-3.2.1.jar!/META-INF/MANIFEST.MF

Issue with Py4j tutorial

Please note I do not have any previous experience with Java. I am having issues with the following tutorial for Py4j: https://www.py4j.org/getting_started.html
I installed Py4j in an Anaconda environment. I am working in Ubuntu. I set my classpath to include the .jar file for Py4j. When I try to compile the sample code on the above web-page I received an error saying the Stack symbol didn't exist. I tried to add a line of code to import it, but that did not help either (see images).
Error and Directory Structure (image)
Source code:
Stack.java
package py4j.examples;
import java.util.LinkedList;
import java.util.List;
public class Stack {
private List<String> internalList = new LinkedList<String>();
public void push(String element) {
internalList.add(0, element);
}
public String pop() {
return internalList.remove(0);
}
public List<String> getInternalList() {
return internalList;
}
public void pushAll(List<String> elements) {
for (String element : elements) {
this.push(element);
}
}
}
StackEntryPoint.java
package py4j.examples;
import py4j.GatewayServer;
import py4j.examples.Stack; // <-- I added this line but it does not solve the issue
public class StackEntryPoint {
private Stack stack;
public StackEntryPoint() {
stack = new Stack();
stack.push("Initial Item");
}
public Stack getStack() {
return stack;
}
public static void main(String[] args) {
GatewayServer gatewayServer = new GatewayServer(new StackEntryPoint());
gatewayServer.start();
System.out.println("Gateway Server Started");
}
}
I haven't used Java before, so I'm confused about how to link classes during compilation. I've tried looking extensively at Java documentation/resources online and questions related, but can't seem to solve this problem. Could someone point out what I'm doing incorrectly?
Thank you.
You are compiling class StackEntryPoint, but you have not compiled the Stack class yet. Do so first, otherwise it cannot use it to compile StackEntryPoint.
Normally your IDE would solve this for you, but you've got a special setup going here (with the Python integration) so I'm not sure how you'd integrate it.
Ideally, you'll build your Java library as a separate JAR using conventional Java tooling (e.g. Maven and IntelliJ IDEA), but it's not a bad exercise to learn to do it bare-bones first.

org.openide.util.Lookup Cannot Find Any Classes Implementing

SQLUtils.java:
import org.openide.util.Lookup;
import java.util.ServiceLoader; // This doesn't work either
public class SQLUtils {
public static DBDriver getDriver(String prefix) {
for(DBDriver e : Lookup.getDefault().lookupAll(DBDriver.class)) {
System.out.println(e.getPrefix());
if(e.getPrefix().equalsIgnoreCase(prefix)) {
return e;
}
}
return null;
}
}
MySQLDriver.java:
public class MySQLDriver implements DBDriver {
#Override
public String getPrefix() {
return "mysql";
}
}
DBDriver.java:
import java.io.Serializable;
public interface DBDriver extends Serializable {
public String getPrefix();
}
Main.java:
public class Main {
public static void main(String[] args) {
DBDriver d = SQLUtils.getDriver("mysql");
}
}
This does nothing when running it, it cannot find any classes implementing.
What the program is trying to do is get the driver that is entered as a parameter for SQLUtils.getDriver(String prefix) (in Main.java).
For some reason I cannot get this to work.
I'm not familiar with OpenIDE Lookup mechanism, but I am familiar with the Java ServiceLoader mechanism.
You need to provide a file in the META-INF/services/ folder describing what classes implement specific interfaces. From the Java Docs describing the ServiceLoader class is this example:
If com.example.impl.StandardCodecs is an implementation of the
com.example.CodecSet service then its jar file also contains a file
named
META-INF/services/com.example.CodecSet
This file contains the single line:
com.example.impl.StandardCodecs # Standard codecs implementing com.example.CodecSet
What you are missing is a similar file that needs to be included on your classpath or within your JAR file.
You don't include you package names so I cannot provide a more direct example to help solve your problem.
I dropped the NetBeans API and switched to Reflections. I implemented Maven and ran it with IntelliJ. Works well for me.

Categories