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.
Related
I am making a GTK+3 App with GJS where users select a folder from a GtkFileChooserButton (action property set to select-folder). I want to find all image files in the given folder the user have selected, so I can display one of the images.
I tried this._fileChooserButton.get_files() and this._folderChooseButton.get_uris() but they only return one file, which is the path to the selected folder. Like this:
_init(application) {
this._folderChooseButton.connect('file-set', () => {
this._onFolderChosen();
});
}
_onFolderChosen() {
let folder = this._folderChooseButton.get_file();
// somehow get files from the folder here
this._image.set_from_file(files[1]);
}
From the API it is not really clear to me, how do I find out which image files are inside the user's selected directory (and subdirectories)?
OK, after help from patrick, georges and matthias at guadec, here is what I got.
The get_file() function I tried returns a GFile, which in this case is a folder (in UNIX, folders are also files). In order to get the files within the directory path, we need to call enumerate_children_async() on our GFile, returned by the get_file() function.
The enumate_children_async() function takes five parameters:
A comma-separated attribute list. In our case, since we want the identifiers of the children in the directory, we want to use the attribute called standard::name.
FileQueryInfoFlag: This allows to either follow or not follow symbolic links. In this case, we will use FileQueryInfoFlag.NONE which will not follow symbolic links.
io_priority: How high priority the IO operation should have (we will use GLib.PRIORITY_DEFAULT)
cancellable: A cancellable, which is a way to cancel this operation, in this case we will leave it as null.
callback: This is the function/code you want to run in response to the files having been retreived.
More info on this function is at GJS-Docs at GNOME.org
The enumerate_children_async() function returns a GFileEnumerator, which we can use to retreive a number of the files, by calling next_files_async(), which takes these arguments:
num_files: How many files you want to retreive. In your case, we use 1.
io_priority and cancellable (same as above).
callback: Where we can run a function or code to actually retreive the file.
Below, is the final code for doing this.
const { Gio, GLib, GObject, Gtk } = imports.gi; // import Gio and GLib API at top of your document.
_onFolderChosen() {
let folder = this._folderChooseButton.get_file();
let files = folder.enumerate_children_async(
'standard::name',
Gio.FileQueryInfoFlags.NONE,
GLib.PRIORITY_DEFAULT,
null,
(source, result, data) => {
this._fileEnumerator = null;
try {
this._fileEnumerator = folder.enumerate_children_finish(result);
} catch (e) {
log('(Error) Could not retreive list of files! Error:' + e);
return;
}
this._readNextFile();
});
}
_readNextFile() {
if (!this._fileEnumerator)
return;
let fileInfo = null;
this._fileEnumerator.next_files_async(
1,
GLib.PRIORITY_DEFAULT,
null,
(source, result, data) => {
try {
fileInfo = this._fileEnumerator.next_files_finish(result);
} catch (e) {
log('Could not retreive the next file! Error:' + e);
return;
}
let file = fileInfo[0].get_name();
let filePath = GLib.build_filenamev([this._folderChooseButton.get_filename(), file]);
this._carousselImage.set_from_file(filePath);
});
}
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")
Recently, I was working on a project that can print DOCX files in Netbeans. I am new in java so I'm not really familiar with it. I use Aspose.Words but I really don't know how to use it. I watch many tutorials but they are not in NetBeans so I am confused. Thanks a lot in advance for helping me.
This is my code:
String dox = path.getText();
XWPFDocument docx = null;
try {
docx = new XWPFDocument(POIXMLDocument.openPackage(dox));
XWPFWordExtractor ext = new XWPFWordExtractor(docx);
content.setText(ext.getText());
} catch (IOException ex) {
Logger.getLogger(count.class.getName()).log(Level.SEVERE, null, ex);
}
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new OutputPrinter(path.getText()));
boolean doPrint = job.printDialog();
if (doPrint)
{
try
{
job.print();
}
catch (PrinterException e)
{
// Print job did not complete.
}
}
I tried extracting it but it only gets the content. What I'm trying is to print the whole document just like in the MSWord.
First of all: Why is this a NetBeans question? I can’t see any NetBeans relations, maybe you should change it to Java (at least the tag).
Second: I think your question is a duplicate to this one
I've written some code to perform OCR on a PDF using Tesseract (Tess4J):
public void DoOCRAnalyse(String From) throws FileNotFoundException {
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
File[] files=PdfUtilities.convertPdf2Png(new File(From));
for (File f:files) {
try {
String result = instance.doOCR(f);
/*String result = instance.doOCR(take File or BufferedImage); */
SearchForSVHC(result,SvhcList);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
}
It recognizes text, which is great, but my problem is that it needs the images to be in a directory on disk. How can I pass a BufferedImage or File to the methode doOCR() without needing the files on disk?
You are passing a File object to doOCR. When you call convertPdf2Png, it invokes GhostScript to convert a PDF file to one or more PNG files. You certainly can delete them after OCR if you want, e.g., by executing f.Delete() in a finally block.
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;
}