eclipse plugin > how to include a jar file programmaticaly - java

So..., I've made a plugin for Eclipse that generates a new java project and ads files from templates, etc... However the code in the /src directory is then uncompilable because I need to add a jar file I have to the libraries tab.
The project is already a Java project via:
org.eclipse.jdt.core.IJavaProject javaProject = org.eclipse.jdt.core.JavaCore.create(proj);
org.eclipse.jdt.core.IClasspathEntry src = JavaCore.newSourceEntry(folder.getFullPath());
IClasspathEntry jre = JavaCore.newContainerEntry(new Path(
org.eclipse.jdt.launching.JavaRuntime.JRE_CONTAINER), new IAccessRule[0],
new IClasspathAttribute[] {
JavaCore.newClasspathAttribute("owner.project.facets", "java")
}, false);
IClasspathEntry[] entries = new IClasspathEntry[] {
src, jre
};
javaProject.setRawClasspath(entries, proj.getFullPath().append("bin"), new NullProgressMonitor());
And now, basically, I need to do programmaticaly, what the button "Add Jars..." does.
Been struggling with this for a while...
Any code tips or a link to a tutorial that DOES EXACTLY THIS would be helpful. Please no links to generic Eclipse plugin tutorials :) as I've probably seen them all by now...
Thnx a lot

Here's how I did it, not sure if your reqs are exaclty the same, but hope it helps in some way...
IFile file = addJar(project, "/resources/myJar.jar", MY_JAR_TARGET_PATH, monitor); //$NON-NLS-1$
newcpEntries.add(JavaCore.newLibraryEntry(file.getFullPath(), null, null, false));
// .....
where addJar() looks something like this:
private static IFile addJar(IProject project, String srcPath, String targetPath, IProgressMonitor monitor) {
URL srcURL = MyPlugin.getDefault().getBundle().getEntry(srcPath);
IFile file = project.getFile(targetPath);
InputStream is = null;
try {
is = srcURL.openStream();
file.create(is, true, monitor);
} catch (CoreException e) {//...
} catch (IOException e) {//...
}
finally {
try {
if (is != null)
is.close();
} catch (IOException ignored) {}
}
return file;
}

Not sure how you would do it through the eclipse API's, but all that jar config window does is write to your project-name/.classpath file which looks something like:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="lib" path="x-jars/lucene-fast-vector-highlighter-3.0.3-patch1822.jar"/>
<classpathentry kind="lib" path="x-jars/lucene-highlighter-3.0.3.jar"/>
So one option would be to have your setup code edit this file once the project has been created, but this is probably too much of hack for what you want though.

Related

Java- Load file from same package in NB platform application

I have the following piece of code,
public void vbsCalled() {
try {
String file = "src\\com\\first\\hello\\hello.vbs";
Runtime.getRuntime().exec("wscript " + file + " ");
} catch (IOException ex) {
Logger.getLogger(RunVBS.class.getName()).log(Level.SEVERE, null, ex);
}
}
I am using netbeans IDE,
Scenario 1:
I create a new java project (New Project -> Java -> Java Application)
The project Structure looks like below,
--Java Application1
-Source Packages
-com.first.hello //Package
-ClassWhichHaveVbsCalledMethod.java
-hello.vbs
with this am able to call the hello.vbs from same package and no error.
Scenario 2:
I create a netbeans platform application (New project - > Netbeans Modules ->NetBeans platform Application)
The project Structure looks like below,
RunVBS.java has the vbsCalled() Method and with the hello.vbs in same package as scenario 1,
Now, it looks for the file in
"C:\application1\src\com\first\hello\hello.vbs"
and shows no such file found error.
How can i load the file in netbeans platform application as like scenario1.
Create a folder in your project's root directory called release
Move hello.vbs to the release/ folder
Use the InstalledFileLocator class to get the runtime path of your file.
Here is what your vbsCalled() method would then look like.
public void vbsCalled() {
try {
File file = InstalledFileLocator.getDefault().locate(
"hello.vbs", // filename relative to the release/ directory
"com.first.hello", // Your module's code name base __not package!__
false);
Runtime.getRuntime().exec("wscript " + file.getAbsolutePath() + " ");
} catch (IOException ex) {
Logger.getLogger(RunVBS.class.getName()).log(Level.SEVERE, null, ex);
}
}
See DevFaqInstalledFileLocator for more details

Exporting image in runnable jar doesn't work

I'm having a weird problem in java. I want to create a runnable jar:
This is my only class:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)
As soon as I export the project to a runnable jar and launch it, it returns false.
I don't know why. Somebody has an idea?
Thanks in advance
edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images
If you would like to load resources from your .jar file use getClass().getResource(). That returns a URL with correct path.
Image icon = ImageIO.read(getClass().getResource("imageĀ“s path"));
To access images in a jar, use Class.getResource().
I typically do something like this:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
Still you're understand, Kindly go through this link.
Eclipse exported Runnable JAR not showing images
Because the image is not separate file but packed inside the .jar.
Use the code to create the image from stream
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
try to use this to get image
InputStream input = getClass().getResourceAsStream("/your image path in jar");
Two Simple steps:
1 - Add the folder ( where the image is ) to Build Path;
2 - Use this:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));

Write a file into Java archive (JAR)

I would like to write a file into Java archive (JAR).
What do I need to modify in my code?
private void menu_savegame(ActionEvent e) {
File config = new File("config");
try {
FileWriter fw = new FileWriter(config);
fw.append(Integer.toString(level.current));
fw.append("\n");
if (win){
fw.append(Integer.toString(ballCount));
}
else{
fw.append(Integer.toString(G));
}
fw.append("\n");
fw.append(Integer.toString(liveLeft));
fw.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
I just would like this file to be written not to the folder, but into the Game.jar file - I have there all the game resources (images).
Dont forget that JAR is a typical ZIP file. In provided link you can see how it is performed.
zip manipulation with java
eventually, use external libraries like JBoss ShrinkWrap.
here's link to api
good luck!

How to get full file path present in eclipse project explorer?

I am working on eclipse plugin. In this i have a file name present in a project hierarchy. i need the full path of file abc.java present in project Test.
The file presented in path F:/Test/src/main/java/com/sung/Pre/abc.java
IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot();
IProject project = rootWorkspace.getProject("/Test");
file1 = project.getFile("/abc.java");
FileEditorInput fileEditorInput = new FileEditorInput(file1);
IWorkbench workbench = PlatformUI.getWorkbench();
IEditorDescriptor desc = workbench.getEditorRegistry().getDefaultEditor(file1.getName());
IWorkbenchPage page11 = workbench.getActiveWorkbenchWindow().getActivePage();
try {
page11.openEditor(fileEditorInput, desc.getId(),true);
} catch (PartInitException e1) {
e1.printStackTrace();
}
This is searching file in /Test folder. If the file presented in the root Test folder it's able to open this file but if it's inside some folder like F:/Test/src/main/java/com/sung/Pre/abc.java than it's can not find the file.
I also tried below code but facing the same issue
try {
//IDE.openEditor(page11, uri, "org.eclipse.ui.ide.IDE", true);
IDE.openEditor(page11, file1, true);
} catch (PartInitException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
so my question is if we have a file name presented in project hierarchy so how can we get the absolute or full path of that.
Please remember that i am doing this task in eclipse plugin project
You can specify a path on project.getFile:
project.getFile(new Path("src/main/java/com/sung/Pre/abc.java"));
or get the IFolder for the folder containing the file and use
folder.getFile(new Path("abc.java"));

Export war from headless Eclipse

How do I export a WAR file from an Eclipse .web project programmatically with Java?
I have big problems with war ant task due to complex project structure(
ProjectX.web has a dependency from ProjectX.java) and i'm very confused by the
WebComponentExportWizard implementation.
Is there any WTP API to use? (like this old version http://www.eclipse.org/webtools/jst/components/j2ee/api/j2ee_operationsAPI.html )
After some heavy fight i manage to obtain the war file trough this method:
#SuppressWarnings("restriction")
public static void exportWar(IProject webProject) throws CoreException {
WebComponentExportDataModelProvider modelProvider = new WebComponentExportDataModelProvider();
IDataModel dataModel = DataModelFactory.createDataModel(modelProvider);
dataModel.setBooleanProperty(IJ2EEComponentExportDataModelProperties.EXPORT_SOURCE_FILES, false);
dataModel.setBooleanProperty(IJ2EEComponentExportDataModelProperties.OVERWRITE_EXISTING, true);
dataModel.setStringProperty(IJ2EEComponentExportDataModelProperties.PROJECT_NAME, webProject.getName());
dataModel.setStringProperty(IJ2EEComponentExportDataModelProperties.ARCHIVE_DESTINATION, webProject
.getLocation().append(webProject.getName()).addFileExtension("war").toOSString());
dataModel.setProperty(
IJ2EEComponentExportDataModelProperties.COMPONENT,
ComponentCore.createComponent(webProject));
IDataModelOperation modelOperation = dataModel.getDefaultOperation();
try {
log.debug("Start the export war operation");
modelOperation.execute(null, null);
}
catch (ExecutionException e) {
log.error("Error when exporting .war project", e);
}
}
I used org.eclipse.wst.server.core.util.PublishHelper.publishZip() like below, and it works for me.
IPath war = workDirectory.append("app.war");
PublishHelper publishHelper = new PublishHelper(null);
J2EEFlexProjDeployable deployable =
new J2EEFlexProjDeployable(project, ComponentCore.createComponent(project));
publishHelper.publishZip(deployable.members(), war, null);

Categories