I'm trying to create a new file in an eclipse plugin. It's not necessarily a Java file, it can be an HTML file for example.
Right now I'm doing this:
IProject project = ...;
IFile file = project.getFile("/somepath/somefilename"); // such as file.exists() == false
String contents = "Whatever";
InputStream source = new ByteArrayInputStream(contents.getBytes());
file.create(source, false, null);
The file gets created, but the problem is that it doesn't get recognized as any type; I can't open it in any internal editor. That's until I restart Eclipse (refresh or close then open the project doesn't help). After a restart, the file is perfectly usable and opens in the correct default editor for its type.
Is there any method I need to call to get the file outside of that "limbo" state?
That thread does mention the createFile call, but also refers to a FileEditorInput to open it:
Instead of java.io.File, you should use IFile.create(..) or IFile.createLink(..). You will need to get an IFile handle from the project using IProject.getFile(..) first, then create the file using that handle.
Once the file is created you can create FileEditorInput from it and use IWorkbenchPage.openEditor(..) to open the file in an editor.
Now, would that kind of method (from this AbstractExampleInstallerWizard) be of any help in this case?
protected void openEditor(IFile file, String editorID) throws PartInitException
{
IEditorRegistry editorRegistry = getWorkbench().getEditorRegistry();
if (editorID == null || editorRegistry.findEditor(editorID) == null)
{
editorID = getWorkbench().getEditorRegistry().getDefaultEditor(file.getFullPath().toString()).getId();
}
IWorkbenchPage page = getWorkbench().getActiveWorkbenchWindow().getActivePage();
page.openEditor(new FileEditorInput(file), editorID, true, IWorkbenchPage.MATCH_ID);
}
See also this SDOModelWizard opening an editor on a new IFile:
// Open an editor on the new file.
//
try
{
page.openEditor
(new FileEditorInput(modelFile),
workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());
}
catch (PartInitException exception)
{
MessageDialog.openError(workbenchWindow.getShell(), SDOEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
return false;
}
Related
I am creating a jar file using org.eclipse.core.resources.IProject. while creating i would like to exclude few files from the selected directory based on the file extension.
if (selectPackageCombo.getText().equals(item)) {
IProject project = availableProjects.get(i);
Package package = EclipsePackageRepository.instance().getPackage(project);
if (package != null) {
try {
project.createFilter(IResourceFilterDescription.EXCLUDE_ALL| IResourceFilterDescription.FOLDERS|IResourceFilterDescription.FILES,
new FileInfoMatcherDescription("org.eclipse.ui.ide.multiFilter", "1.0-name-matches-false-false-Test"),IResource.BACKGROUND_REFRESH, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
jarData.setSelectedProject(project);
jarData.setOutputSuffix(package.getPackageResource().getType());
}
break;
}
Please help me how to create the object of FileInfoMatcherDescription to exclude all the files with the extension ".ayt"
There isn't much informaton about this but it looks like you can work out the values by using the 'Resource Filters' page in the project properties and creating the filter you want. The id and arguments values will then be saved in the .project file in the project which you can read.
So for your requirement I get
<matcher>
<id>org.eclipse.ui.ide.multiFilter</id>
<arguments>1.0-name-matches-false-false-*.ayt</arguments>
</matcher>
so the constructor is
new FileInfoMatcherDescription("org.eclipse.ui.ide.multiFilter",
"1.0-name-matches-false-false-*.ayt")
I need to invoke eclipse importwizard from the eclipse plugin project programmatically. i follow the example from , seems not work
https://resheim.net/2010/07/invoking-eclipse-wizard.html
then in my code , it shows wizards array is empty, do i need to register importwizard ? and how?
IWizardDescriptor[] wizards= PlatformUI.getWorkbench().getImportWizardRegistry().getPrimaryWizards();
The import dialog doesn't use 'primary' wizards. You need to know the id of the wizard you want to use and call the wizard registry findWizard method.
The Import Projects wizard id is org.eclipse.ui.wizards.import.ExternalProject so the code would look like:
String id = "org.eclipse.ui.wizards.import.ExternalProject"
IWizardDescriptor descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(id);
IWizard wizard = descriptor.createWizard();
WizardDialog wd = new WizardDialog(display.getActiveShell(), wizard);
wd.setTitle(wizard.getWindowTitle());
wd.open();
private void openProject(String projectfolder) throws CoreException {
//TODO: check if project is already created and open, if yes do nothing or just refresh
IProjectDescription description = null;
IProject project = null;
description = ResourcesPlugin.getWorkspace().loadProjectDescription(
new Path(new File(projectfolder).getAbsolutePath()
+ "/.project"));
project = ResourcesPlugin.getWorkspace().getRoot()
.getProject(description.getName());
project.create(description, null);
project.open(null);
}
We can refactor the project names, but I need help regarding the filename refactoring in eclipse in a programatic way. We have a folder under this folder there lies a xxx.zzz file and we want to rename/refactor this file.
Kind regards
Try to right click the file, select refactor and enter your desired file name. You may be asked additionally to update references and similarly names variables. Check them both (recommended) and your file And all its references will be updated
If the file is a class file, you can try the code below:
RefactoringContribution contribution = RefactoringCore.getRefactoringContribution(IJavaRefactorings.RENAME_COMPILATION_UNIT);
RenameJavaElementDescriptor descriptor = (RenameJavaElementDescriptor) contribution.createDescriptor();
descriptor.setProject(cu.getResource().getProject().getName());
descriptor.setNewName(newFileName);
descriptor.setJavaElement(cu);
descriptor.setUpdateReferences(true);
RefactoringStatus status = new RefactoringStatus();
try {
RenameRefactoring refactoring = (RenameRefactoring) descriptor.createRefactoring(status);
IProgressMonitor monitor = new NullProgressMonitor();
RefactoringStatus status1 = refactoring.checkInitialConditions(monitor);
if (!status1.hasFatalError()) {
RefactoringStatus status2 = refactoring.checkFinalConditions(monitor);
if (!status2.hasFatalError()) {
Change change = refactoring.createChange(monitor);
change.perform(monitor);
}
}
} catch (CoreException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
cu is of type ICompilationUnit and you can get a compilation unit from IPackageFragment.
You can also replace IJavaRefactorings.RENAME_COMPILATION_UNIT with what your need.
I have an application that uploads a file. I need to pass this file into another program but for that I need the file name only. Is there any simple code for that, using only Java or a servlet procedure?
while (files.hasMoreElements())
{
name = (String)files.nextElement();
type = multipartRequest.getContentType(name);
filename = multipartRequest.getFilesystemName(name);
originalFilename = multipartRequest.getOriginalFileName(name);
//extract the file extension - this can be use to reject a
//undesired file extension
extension1 = filename.substring
(filename.length() - 4, filename.length());
extension2 = originalFilename.substring
(originalFilename.length() - 4, originalFilename.length());
//return a File object for the specified uploaded file
File currentFile = multipartRequest.getFile(name);
//InputStream inputStream = new BufferedInputStream
(new FileInputStream(currentFile));
if(currentFile == null) {
out.println("There is no file selected!");
return;
}
There's a method in apache commons-io to get the file's extension. There's also guava Files class, with its getFileExtension method.
I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename