Rename linked resource programmatically - java

I an new to Eclipse Plugin Development and I am trying to rename my linked file.
I have created a linked file in Eclipse as below:
IFile myLinkedFile = folder.getFile(originalFileName);
myLinkedFile.createLink(myabsolutePath, IResource.NONE, null);
This works like a charm.
However, now I would like to rename myLinkedFile without changing the name of the original File. Just like the behavior of pressing F2 or by the Rename from the context menu that appears on right clicking the liked file.
I am trying to achieve renaming using move()
originalFile.move(newPath, IResource.FORCE, null);
However it always throws
org.eclipse.core.internal.resources.ResourceException
...and complains about my newPath. Can someone tell me what is wrong in my approach and how do I do it right?
My original file is a text file located at C:/Temp/originalFile.txt. I would like to rename the file to newFile.txt in my workspace. The exception says invalid path. For the newPath I have specified as C:/Temp/newFile.txt
In the below example the original files is located in the resources folder of my project
Here I am creating a new folder called myTextFiles. This folder will contain the linked files.
After creating the linked files I am trying to rename the linked files.
IFolder folder = myCurrentProject.getFolder("myTextFiles");
folder.create(IResource.REPLACE, true, null);
IFile file = folder.getFile(absoluteLocation); //absolute location of folder containing images
file.createLink(absoluteLocation, IResource.REPLACE, null);
folder.refreshLocal(IResource.DEPTH_INFINITE, null);
String myNewFileName = "newFile.txt";
IFile myLinkedFile = folder.getFile(myNewFileName);
IPath newPath = new Path(myNewFileName);
IFile movedFile = folder.getFile(newFileName);
movedFile.createLink(newPath, IResource.NONE, null);
folder.refreshLocal(IResource.DEPTH_INFINITE, null);

You can only use move to move the resource to a new location in the Eclipse workspace.
The path you specify for move must be a path relative to the root of the Eclipse workspace or relative to the current resource location - often just a file name.
So
IPath newPath = new Path("/project/folder/newFile.txt");
or
IPath newPath = new Path("newFile.txt");
Paths starting with '/' are relative to the workspace root (known as a 'absolute' path), anything else is relative to the current resource folder.
Paths in the Eclipse workspace never use "C:/"

Related

Eclipse IFolder from absolute path

I have the need to create an IFolder in an absolute location.
I usually have a class that does a "build" (or at least what I call a "build") for me in the workspace. The IFolder for the build-target-folder is returned by a method like this:
public IFolder getTargetFolder(IProject project){
return project.getFolder("build");
}
Now I created a subclass of this for the "deployment" (into a directory with absolute identifier). This subclass contains the same functionality but the getTargetfolder routine should be like this:
#Override
public IFolder getTargetFolder(IProject project){
IPath path = new Path("M:\\Path\\To\\My\\Deployment\\Directory\\");
IFolder target = project.getFolder(path);
return target;
}
However, I run into problems and I seem to not get a handle on the folder and an exception that says the folder (<ProjectRoot>/Path/To/My/Deployment/Directory) does not exist. How can I specify that this should not be a relative path?
The name given to project.getFolder() must be the name of a member folder (see the JavaDoc).
You cannot access a file or folder with the Resources API that lies outside of the workspace. If however the M:\\... path lies within a projects that is part of the workspace then you can resolve the folder through IWorkspaceRoot#getContainerForLocation()
For example:
IContainer container = project.getWorkspace().getRoot().getContainerForLocation( "M:\\..." );
The returned container can be either an IProject or an IFolder. But note that the returned container does not necessarily lies within the project.
Some more information can be found in Resources and the file system

Unable to check if file exists or not in web project

I have a pdf file in my web project at the below location :
"static/Downloadables/20/Home_insurance_booklet.pdf "
"static" is present in the WebContent. The context root of the project is "pas".
In one of the jsp, I need to check if the file Home_insurance_booklet.pdf exists or not. I tried in many ways but unable to succeed. Below is the code I have used.
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
Through the file exists, the condition is returning false. How to check if the file exists or not w.r.t to certain location in the root of the web project ?
Edit:
File path displayed is
/pas/static/Downloadables/20/Home_insurance_booklet.pdf
Try the following:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
And here is the API-Doc of getRealPath():
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Use
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
The ServletContext#getRealPath() converts a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root.
After that append in this way :
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
Then use
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
check whether file is loaded in the project or not. and then try for absolute path first of the file in your code then try for relative path.
You have to use a file system based URL instead of relative web based URL.

Use Relative path in place of absolute path

First of all i request people do not consider it as a duplicate question, please look into query.
I am copying the xml files from one folder to other folder, in the source folder, i have some files which have some content like "backingFile="$IDP_ROOT/metadata/iPAU-SP-metadata.xml" but while writing to the destination folder.
i am replacing the "$IDP_ROOT" with my current working directory. The entire copying of files is for deploying into tomcat
server. The copying is done only when server starts for the first time.
Problem: If i change the folder name from my root path in my machine after i run the server,
the entire process will be stopped because the destination folder files already contains the content which is with
existed files names or folder names.
So i want to change it to relative path instead absolute path. What is the best way to do it?
Please look at code below:
// Getting the current working directory
String currentdir = new File(".").getAbsoluteFile().getParent() + File.separator;
if(currentdir.indexOf("ControlPanel")!=-1){
rootPath=currentdir.substring(0, currentdir.indexOf("ControlPanel"));
}else{
rootPath=currentdir;
}
rootPath = rootPath.replace("\\", "/");
// target file in source folder is having "backingFile="$IDP_ROOT/metadata/iPAU-SP-metadata.xml"
String content = FileReaderUtil.readFile(targetFile,
rootPath + "Idp/conf");
content = updatePath(content, Install.rootPath
+ "IdP/IdPserver/metadata","$IDP_ROOT");
FileWriterUtil.writeToFile(Install.rootPath
+ "IdP/IdPserver/idp/conf", content,
targetFile);
// update method
public String updatePath(String content, String replaceString,String replaceKey) {
replaceKey = replaceKey!=null ? replaceKey : "$IDP_SERVER_ROOT";
replaceString= replaceString.replace("\\","/");
String updateContent = content.replace(replaceKey,
replaceString);
return updateContent;
}

Moving a Directory to a higher Directory in Java?

I have a folder called "data". It's in a subdirectory of my system, lets say in "big folder." I want to move the data folder out to my home folder, or "user." So the data folder's path is user/big folder/data. How do I move it out?
You should play around with the following snippet (not tested):
File src = new File("user/big folder/data");
File dest = new File("user");
boolean success = src.renameTo(new File(dest, src.getName()));
if (!success) {
// Directory was not successfully moved
}

Get the absolute path of the currently edited file in Eclipse

I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path.
This is what I do now:
IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput().
getAdapter(IFile.class);
Now I have an IFile object, and I can retrieve it's path:
file.getFullPath().toOSString();
However this still only gives me the path relative to the workspace. How can I get the absolute path from that?
Looks like you want IResource.getRawLocation(). That returns an IPath, which also has a makeAbsolute() method if you want to be doubly sure you've got an absolute path.
I think a more Java friendly solution would be to do use the following:
IResource.getLocation().toFile()
This takes advantage of the IPath API (the getLocation() part) and will return a java.io.File instance. Of course the other answers will probably get you to where you want to be too.
On a tangential note, I find the IDE class (org.eclipse.ui.ide.IDE) a useful utility resource when it comes to editors.
The answer that worked for me (and I tested it!) was:
// Get the currently selected file from the editor
IWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
if (file == null) throw new FileNotFoundException();
String path = file.getRawLocation().toOSString();
System.out.println("path: " + path);
I usually call IFile.getLocation() which returns an IPath and then call IPath.toOSString().
file.getLocation().toOSString()
IWorkspace ws = ResourcesPlugin.getWorkspace();
IProject project = ws.getRoot().getProject("*project_name*");
IPath location = new Path(editor.getTitleToolTip());
IFile file = project.getFile(location.lastSegment());
into file.getLocationURI() it's the absolute path
For me, this run ok.
IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();
File file = workSpaceRoot.getRawLocation().makeAbsolute().toFile();
file list from this location:
File[] files = file.listFiles();

Categories