Eclipse how to reference file in a different src under the same project - eclipse

My current setup in eclipse is like this:
trunk
--working/src
--resources
I have a java file inside a package under working/src and I am trying to retrieve a file in the resources. The path I am using is "../resources/file.txt". However I am getting an error saying that the file does not exist.
Any help would be appreciated thanks!

Considering your structure
I have package like
trunk
working/src/FileRead.java
resources/name list.txt
Following Code might solve your problem
package working.src;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class FileRead {
public FileRead() {
URL url = getClass().getResource("/resources/name list.txt");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String nameList;
while ((nameList = in.readLine()) != null) {
System.out.println(nameList);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileRead();
}
}

Files will be referenced relative to your project path, so use "resources/file.txt" to reference the file.
However, if you want the file to be accessible when you export the program as a JAR, the path "resources/file.txt" must exist relative to your JAR.

It depends on how you have specified your Java Build Path inside eclipse. I have tested two setups with different results:
Define the directory working/src only as build path. You can get the information what is in your build path through: Select project > Properties > Java Build Path > Tab Source. There are all source folders listed. You see there that there is a default output folder defined. All resources that are contained in a build path are copied to the default output folder, and are then available for the eclipse classes there. You can check that in the resource perspective in your bin folder if the resource is copied there. In this setup, only the classes are generated, resources are not copied (and therefore not found).
Define the directory working/src and resources as build path. Then the resource is copied and may then found by the path "file.txt"
So eclipse has a simple build process included and hides that from the developer, but it is a build process nonetheless.

Related

Could not find main method from given launch configuration

I've a simple Java project that works when I execute it at Eclipse environment. But when I try to export it to a Runnable Jar, I get the following error:
JAR export finished with warnings. See details for additional information.
Exported with compile warnings: JavaSwing/src.main.java/com/cansoft/GUIProgram.java
Exported with compile warnings: JavaSwing/src.main.java/com/util/Util.java
Jar export finished with problems. See details for additional information.
Could not find main method from given launch configuration.
I read other posts which suggest to create a MANIFEST.MF file specifying the main-class which I did. It is placed at MyProjectFolder/META-INF/MANIFEST.MF and it contains the following information:
Manifest-Version: 1.0
Class-Path: resources
main-class: com.cansoft.GUIProgram
My main class is as follows:
public class GUIProgram {
private JFrame folderCreationSubappFrame;
private Color color;
private String home;
private final static Logger LOG_MONITOR = Logger.getLogger("com.cansoft");
public static void main(String[] args) {
try {
new GUIProgram();
} catch (Exception e) {
LOG_MONITOR.log(Level.INFO,e.getMessage());
}
}
public GUIProgram() throws InterruptedException, SecurityException, IOException {
home = System.getProperty("user.home") + File.separator + "Documents";
startLogSystem();
if(isFirstRun()) {
showWelcomeFrame();
} else {
initialize();
}
} .... More and more code
Does anybody know what am I missing? Any help much appreciated.
Thank you.
It is not enough to create the manifest file, you need to explicitly choose it in the Eclipse jar export dialog.
Answer to Comment
If you use "runnable jar", make sure that you chose the correct launch configuration and that the launch configuration successfully runs when chosing "Run As" -> "Run Configurations" -> "Java Application" -> Your Configuration -> "Run"
I finally find out where the problem was, it was quite simple btw. I had created my GUIProgram within a src.main.java package, but that package was created (my bad) as resources instead of folders, so Eclipse was smart enought to run it but when trying to generate the JAR which expected a correct java project structure, it was failing because truly there were not GUIProgram java class at src path (src was not folder type but resources).
Hope I succeed explaining.

Launch External Tools from Eclipse Plug-in View

I'm building a simple Eclipse plug-in out of preexisting Java application project that relays on 2 external files, one x-executable/application and one .sh script.
The call is implemented in application like this, (which wouldn't work in plug-in):
Process p = new ProcessBuilder("external/application_name", "-d", path).start();
I used External Tool Configuration to define how I want this external files to be launch (when user clicks button on View) and I've exported configuration (example of one):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramLaunchConfigurationType">
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/softwareevolution/external/application_name}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-d ${project_loc}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${project_loc}"/>
</launchConfiguration>
How can I have this application install along with Eclipse plug in,
or a as a part of it? (see #howlger answer billow) - I set plugin to install as directory /
Connected plugin to Feature project- checked unpack after
installation - and exported Feature project. Select application's
folder on Build/Binary build.
Can I then make use out of this exported .launch files, and if so
under which extension point should I include them in plugin.xml? -
No. (see #greg-449)
The application is supposed to produce 2 files on the path where it
is executed from. I am facing permission denied when trying to
launch it in terminal from plug-in's install directory but not when
launching in workspace. (see #howlger answer billow) - Upon exporting the plugin, initial
permissions of application had changed. Used instructions in p2.inf
to chmod them back.
The newly generated files (from runing .sh script) are missing write permission.
ProcessBuilder
After finally setting up plugin correctly and adding ProcessBuilder I was getting exception message : Cannot run program "rfind_20" (in
directory
"home/adminuser/.p2/pool/plugins/rFindTest3_1.0.0.201809030453/external"
error=2:, No such file or directory
File rfind_20 did exist and permission were 777. The targeted project also existed.
Although the working directory was set to applications folder, the application name was not enough, the absolute path was required as
command argument.
pb = new ProcessBuilder(url.getPath(), "-d", project.getProject().getLocation().toString());
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IProject project= sampleGetSelectedProject();
ProcessBuilder pb;
Process rfind, ajust, copy;
Bundle bundle = FrameworkUtil.getBundle(getClass());//Bundle bundle = Platform.getBundle("rFindTest3");
URL url = FileLocator.find(bundle, new Path("external/rfind_20"), null);
URL dirurl = FileLocator.find(bundle, new Path("external/"), null);
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
try {
MessageDialog.openInformation(
window.getShell(),
"Test",
project.getProject().getLocation().toString());
url = FileLocator.toFileURL(url);
dirurl = FileLocator.toFileURL(dirurl);
pb = new ProcessBuilder(url.getPath(), "-d", project.getProject().getLocation().toString());
//no matter the working directory the absolute path was required!! sending "rfind_20" as command did not work as command
pb.directory(new File(dirurl.getFile()));
rfind = pb.start();
rfind.waitFor();
rfind.destroy();
}catch(Exception e) {
MessageDialog.openInformation(
window.getShell(),
"Test",
e.getMessage());
}
return null;
}
The only remaining mystery is why my sampleGetProject() method wouldn't work in Plug-in Perspective. So just keep in mind to switch to other Perspectives when testing your plug-in.
There are two ways to ship an application as part of a plugin and run it via ProcessBuilder (the *.launch file cannot be used inside a plugin for that):
Extract the executable files from the plugin JAR to a (temp) directory and change their file permissions before running them
Install the plugin as a directory:
In META-INF/MANIFEST.MF add the line Eclipse-BundleShape: dir (see "The Eclipse-BundleShape Header" in Eclipse help - Platform Plug-in Developer Guide - OSGi Bundle Manifest Headers)
Create a Feature Project and connect your plug-in in Included Plug-in, check "Unpack the plug-in archive after the installation"
Create a META-INF/p2.inf file that contains the following (see Eclipse help - Platform Plug-in Developer Guide: "Touchpoint Instruction Advice" in Customizing p2 metadata and "chmod" in Provisioning Actions and Touchpoints):
instructions.install = \
chmod(targetDir:${artifact.location},targetFile:path/to/executable1,permissions:755);\
chmod(targetDir:${artifact.location},targetFile:path/to-executale_which_generates_files/executable2,permissions:733);\
chmod(targetDir:${artifact.location},targetFile:path/to-executale_which_generates_files/,permissions:766);
instructions.install.import = org.eclipse.equinox.p2.touchpoint.eclipse.chmod
If you have a xxx.launch file in the workspace you can launch it using
IFile file = ... get IFile for workspace file
ILaunchConfiguration config = DebugPlugin.getDefault().getLaunchManager().getLaunchConfiguration(file);
DebugUITools.launch(config, ILaunchManager.RUN_MODE, false);
If you have an executable as part of a plug-in then you can't use a .launch file. Instead use FileLocator to get the location of the executable and run it with ProcessBuilder
Bundle bundle = FrameworkUtil.getBundle(getClass());
URL url = FileLocator.find(bundle, new Path("relative path to executable"));
url = FileLocator.toFileURL(url);

How to get resources path from an Eclipse plugin

I am developing an Eclipse plugin using Eclipse Plugin-in-project where it will add a menu item in the toolbar.
My plugin project is depending on one file which is located in the same plugin project I want the path of that file.
Below is the sample code I have used to get the path:
Bundle bundle = Platform.getBundle("com.feat.eclipse.plugin");
URL fileURL = bundle.getEntry("webspy/lib/file.txt");
File file = null;
String path=null;
try {
file = new File(FileLocator.resolve(fileURL).toURI());
path = file.getAbsolutePath();
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
While running from Eclipse Run as > Eclipse Application it is giving me the correct path. But when I export my plugin as jar and add it in my Eclipse plugins folder its not giving me the correct path.
Please help me to resolve this!
Use:
URL url = FileLocator.find(bundle, new Path("webspy/lib/file.txt"), null);
url = FileLocator.toFileURL(url);
File file = URIUtil.toFile(URIUtil.toURI(url));
When your files are packed in a jar FileLocator.toFileURL will copy them to a temporary location so that you can access them using File.
Files in jars have no java.io.File as they are in the JAR file.
You probably want FileLocator.openStream(...) to read the file contents.
If you really want a java.io.File, then you can consider using Eclipse EFS and its IFileStore.toLocalFile(...) to extract the file for you to a temporary directory. Something like EFS.getStore(fileURL).toLocalFile(EFS.CACHE, null) should do what you want, but remember that will put the file in the temp directory and delete it on Eclipse exit.

Intellij IDEA - Output path ...\project\target\idea-classes intersects with a source root. Only files that were created by build will be cleaned

Using Intellij IDEA with Scala plugin.
When doing a Build -> Rebuild Project I get the following make warnings:
Output path ProjectRootFolder\project\target\idea-test-classes intersects with a source root. Only files that were created by build will be cleaned.
Output path ProjectRootFolder\project\target\idea-classes intersects with a source root. Only files that were created by build will be cleaned.
The project was generated with SBT gen-idea plugin.
The two output paths mentioned in the warnings are set as output path and test output path for the build module of the project under Project Structure -> Modules -> ProjectName-build -> Paths -> Use module compile output path.
Looking at the Sources tab for both the ProjectName module and ProjectName-build modules I saw that there is no place where ProjectRootFolder\project\target was marked as Source.
It seems the warnings were caused by the fact that the project and . folders were marked as Sources in the ProjectName-build module.
Since the SBT build module is not needed when using IDEA to build the project, one solution would be to generate the IDEA project without that module:
sbt gen-idea no-sbt-build-module
More details here: https://github.com/mpeltonen/sbt-idea/issues/180
UPDATE
Removing the build module is actually problematic since the build.scala file will show a lot of warnings because the required libraries would be missing.
A solution would be to unmark . and project from being Sources of the build module, which is also troublesome since it would need to be done after each gen-idea.
A better solution would be to use sbt to build the project instead of make. To achieve that remove the make before launch step in the IDEA run configuration and add a SBT products step instead.
I get the same warning and it didn't cause any problems so far.
Judging by this code it seems that they simply delete only files generated by IDE, otherwise they would want to delete everything in target directory. They are playing safe by checking if there could be any source files there:
// check that output and source roots are not overlapping
final List<File> filesToDelete = new ArrayList<File>();
for (Map.Entry<File, Collection<BuildTarget<?>>> entry : rootsToDelete.entrySet()) {
context.checkCanceled();
boolean okToDelete = true;
final File outputRoot = entry.getKey();
if (JpsPathUtil.isUnder(allSourceRoots, outputRoot)) {
okToDelete = false;
}
else {
final Set<File> _outRoot = Collections.singleton(outputRoot);
for (File srcRoot : allSourceRoots) {
if (JpsPathUtil.isUnder(_outRoot, srcRoot)) {
okToDelete = false;
break;
}
}
}
if (okToDelete) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = outputRoot.listFiles();
if (children != null) {
filesToDelete.addAll(Arrays.asList(children));
}
else if (outputRoot.isFile()) {
filesToDelete.add(outputRoot);
}
}
else {
context.processMessage(new CompilerMessage(
"", BuildMessage.Kind.WARNING, "Output path " + outputRoot.getPath() + " intersects with a source root. Only files that were created by build will be cleaned.")
);
// clean only those files we are aware of
for (BuildTarget<?> target : entry.getValue()) {
clearOutputFiles(context, target);
}
}
}

Use webapp classpath using JavaCompiler in Tomcat within Eclipse with Maven

I have an existing "Example Webapp" that references "Example Library" using Maven. I'm running Tomcat 7 inside Eclipse 4.3RC3 with the m2e plugin. When I launch Example Webapp on Tomcat inside Eclipse, I have verified that the example-library.jar is probably getting deployed in the Tomcat instance's WEB-INF/lib folder.
The Example Webapp has code that compiles certain classes on the fly using JavaCompiler.CompilationTask. These dynamically generated classes reference classes in example-library.jar. Unfortunately the compile task is failing because the referenced classes cannot be found.
I understand that I can set the JavaCompiler classpath, but System.getProperty("java.class.path") only returns me the Tomcat classpath, not the webapp classpath:
C:\bin\tomcat\bin\bootstrap.jar;C:\bin\tomcat\bin\tomcat-juli.jar;C:\bin\jdk6\lib\tools.jar
Other have said that I need to get the real path of WEB-INF/lib from the servlet context, but the class generation code doesn't know anything about a servlet context --- it is written to be agnostic of whether it is used on the client or on the server.
In another question, one answer indicated I could enumerate the classloader URLs, and sure enough this provides me with the jars in WEB-INF/lib, but when I provide this as a -classpath option to compiler.getTask(), the task still fails because it can't find the referenced classes.
How can I simply provide the classpath of the currently executing code to the JavaCompiler instance so that it will find the classes from the libraries in WEB-INF/lib? (A similar question was raised but never answered regarding referencing jars within ear files using JavaCompiler.)
Example: In an attempt to get things working at any cost, I even tried to hard-code the classpath. For example, I have foobar.lib in my webapp lib directory, so I used the following code, modified from the answers I indicated above:
List<String> options = new ArrayList<String>();
options.add("-classpath");
options.add("C:\\work\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\FooBar\\WEB-INF\\lib\\foobar.jar");
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
boolean success = task.call();
In the end success is false, and my diaognostics indicates package com.example.foo.bar does not exist..., even though that package is in foobar.jar.
Put example-library.jar somewhere in your file system and pass that location to the code that runs JavaCompiler (the -classpath option). If you use an exploded WAR file to deploy, you can of course point it to the physical location within the WEB-INF/lib folder. The point is that you only need one configurable parameter in your webapp to do this, which can be a properties file entry, -D system property, database row or something else entirely.
Sample code (tested in Tomcat 7 and OpenJDK 1.7 on Fedora 18 x64):
private File compile(File javaFile, String classpath) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjects(javaFile);
List<String> options = classpath != null ? Arrays.asList("-classpath", classpath) : null;
StringWriter output = new StringWriter();
try {
boolean successful = compiler.getTask(output, fileManager, null, options, null, compilationUnit).call();
if (!successful) {
throw new CompilationException("Failed to compile: " + javaFile, output.toString());
}
return firstClassFileFrom(javaFile.getParentFile());
} finally {
fileManager.close();
}
}
private File firstClassFileFrom(File directory) {
return directory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".class");
}
})[0];
}
See https://github.com/jpalomaki/compiler for a runnable sample webapp.
i met the same question. The reason is not "-classpath" .
my code :
String classpath ="xx/WEB-INF/clases ";
List<String> options = classpath != null ? Arrays.asList("-d", classpath,"-cp",classpath) : null;
CompilationTask task = compiler.getTask(null, javaDinamicoManager, diagnostics,
options, null, Arrays.asList(sourceObj));
boolean result = task.call();
the “result” will return true .
You could follow the answer provided for the even more specific question of how to load dependencies of compiled code from within a web app running directly from an unexpanded WAR file (there are no JAR files to reference - only the container's class loder knows how to access the classes): https://stackoverflow.com/a/45038007/2546679