How to add templates.xml using plugin? - eclipse

Editor templates in eclipse can be imported from xml file. Instead of manually importing, wanted to create a plugin. Which will import the templates.xml kept in specified folder at start of the eclipse.
How this can be achieved?

You can use the JFace org.eclipse.jface.text.templates.persistence.TemplateReaderWriter to read a template.xml. Something like:
File file = .... file to read
TemplateReaderWriter reader = new TemplateReaderWriter();
InputStream input = new BufferedInputStream(new FileInputStream(file));
TemplatePersistenceData[] datas = reader.read(input, null);
(code to deal with errors and closing the input left out)
You can then put the data in a TemplateStore:
TemplateStore fTemplateStore = ... store to use
for (TemplatePersistenceData data: datas) {
fTemplateStore.add(data);
}
fTemplateStore.save();
The template store you use depends on which templates you are updating.
For the Java Editor template store you can get the store with
JavaPlugin.getDefault().getTemplateStore();
But the JavaPlugin is not part of the official Eclipse API.
The above code is a simplified version of the import code in org.eclipse.ui.texteditor.templates.TemplatePreferencePage

Related

Extracting data from owl file using java,gwt,eclipse

I have to display content from the owl file namely the class names.. onto my browser, I am using GWT,eclipse to do so, could some one tell me the following :-
1)how do I integrate the owl file with the eclipse project?
2)How do I run queries from my java project to extract class names from the owl file?
3)Where can I get the protege api to nclude into my project?!
You could just store your .owl file anywhere inside your project or on any other location on your harddrive. You just provide a path to it, when you load/store it (see code below).
Take a look at the OWLAPI, it allows you to load an existing ontology and retrieve all classes from it. Your code could look like this:
private static void loadAndPrintEntities() {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
IRI documentIRI = IRI.create("file:///C:/folder/", "your_rontology.owl");
try {
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(documentIRI);
//Prints all axioms, not just classes
ontology.axioms().forEach(a -> System.out.println(a));
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
}
Rather than trying to integrate the Protegé API into your project, I suggest you write a plugin for Protegé. There are some great examples that should get you started. Import this project into Eclipse, modify the content, build your plugin and drop it into Protegé. That's it, you're ready to go!

How to read the source content-type from each Eclipse file?

I have an Eclipse project that contains several source files, with a bunch of different encodings: some files are UTF8, some others are ISO-8859-1, others more are windows-1252.
Moreover, there are files whose encoding is explicit (it can bee seen in each file Properties window) while that of others is Inherited from container.
I need to convert them to UTF8 - and I've already found I can use iconv for that - see my answer here for details -, but since they're more than one thousand, I can't convert them one by one: is there any programmatic way to get the encoding from the IDE or something similar?
I'm on Windows, I may do some shell scripting and / or write auxiliary software.
The charset setting of project file could be found in ${PROJECT_FOLDER}/.settings/org.eclipse.core.resources.prefs
Since there are so many files in your project. Create a simple Eclipse plugin could reduce the effort. Here are the steps:
Select Eclipse menu item New > Project... > Plug-in Project
Accept default values and goto last page, choose Hello, World template.
Open and edit plugin.xml, adding required plugin org.eclipse.core.resources in Dependencies page.
Edit SampleAction.java, refer the sample code below..
Create a Debug Configuration for execute Eclipse Application.
Start the eclipse and import your project.
Select menu item Sample Menu to invoke public void run(IAction action).
Sample code of Eclipse resource API:
//import org.eclipse.core.resources.*;
//import org.eclipse.core.runtime.*;
public void run(IAction action) {
final boolean keepHistory = true;
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("yourProjectName");
project.accept(new IResourceVisitor() {
public boolean visit(IResource resource) {
IFile file = (IFile)resource;
try {
String charset = file.getCharset(true);
if (!"UTF-8".equals(charset)) {
InputStream is = file.getContents();
//convert to UTF-8 and save it
String str = new String(IOUtils.toByteArray(is), charset);
file.setContents(new ByteArrayInputStream(str.getBytes("UTF-8")), true, keepHistory, null);
//remove charset setting
file.setCharset("UTF-8", null);
}
} catch (Throwable e) {
//log error... maybe process later via project.getFile(new Path(projectRelativePath))
Activator.getDefault().getLog().log(new Status(IStatus.INFO, Activator.PLUGIN_ID,
file.getProjectRelativePath().toString(), e));
}
return false;
}
}, IResource.DEPTH_INFINITE, IResource.FILE);
}

TypeLite generate external modules?

I am trying to generate external modules rather than a type definition file. I believe I need to do the following:
Change the extension of the file to .ts instead of .d.ts.
Generate one file per module.
Add the key word "Export" in front of each interface and enum.
I was easily able to change the extension of the file by changing the "output extension" setting in the tt file.
I cannot figure out how to split the modules into separate files.
I cannot figure out how to add the Export key word to each interface.
TypeLITE doesn't support generating multiple files. This feature has been requested by several users, but I am not aware of a simple way to generate multiple files from the single tt file.
export keyword can't be added without changing source code of the library (TsGenerator.cs). This is very specific requirement, so I probably won't add it to the library.
TypeLite is a good project but lacking in Documentation and examples, it's open source so anyone can contribute and make it better.
As for creating a file per class i solved it using the code below.
private static void GenerateTypeScriptContracts(string assemblyFile, string outputPath)
{
// Clean TS Folder
System.IO.DirectoryInfo di = new DirectoryInfo(outputPath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
// --
var assembly = Assembly.LoadFrom(assemblyFile);
// If you want a subset of classes from this assembly, filter them here
var models = assembly.GetTypes();
foreach (var model in models)
{
var generator = new TypeScriptFluent()
.WithConvertor<Guid>(c => "string")
.WithMemberFormatter((identifier) => Char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1));
generator.ModelBuilder.Add(model);
// Generate TS interface definitions
var tsClassDefinitions = generator.Generate(TsGeneratorOutput.Properties | TsGeneratorOutput.Fields);
File.WriteAllText(Path.Combine(outputPath, "I" + model.FullName.Replace("ProjectName.DtoModels.", "") + ".ts"), tsClassDefinitions);
}
}

How do I import an Eclipse project from a .zip file programmatically?

I'm trying to figure out how to import an Eclipse project from an archive file (a .zip) programmatically - I want to do the same thing the import wizard does, but automatically (re-importing the same project regularly using the wizard is starting to feel really long-winded). I've found some related questions (e.g. Programmatically importing an existing project into Eclipse), but I can't figure out how to get the same sort of thing working for the .zip import.
My current thinking is as follows: if I can get a project description from the .zip somehow, then I can programmatically create the project (as per the referenced question). From there, I'm hoping I can:
Create a ZipLeveledStructureProvider (http://javasourcecode.org/html/open-source/eclipse/eclipse-3.5.2/org/eclipse/ui/internal/wizards/datatransfer/ZipLeveledStructureProvider.java.html) for the .zip file.
Run an ImportOperation (http://javasourcecode.org/html/open-source/eclipse/eclipse-3.5.2/org/eclipse/ui/wizards/datatransfer/ImportOperation.java.html) to import the contents of the .zip into the created project.
Does this make any sense? (If not, what should I be doing please?) If so, how should I be going about getting a project description from the .zip?
For what it's worth, this seems to work (pre-tidying):
IWorkspace workspace = this.project.getWorkspace();
IProjectDescription newProjectDescription = workspace.newProjectDescription(projectName);
IProject newProject = workspace.getRoot().getProject(projectName);
newProject.create(newProjectDescription, null);
newProject.open(null);
zipFile = new ZipFile(workspace.getRoot().getLocation() + "/" + projectName + ".zip");
IOverwriteQuery overwriteQuery = new IOverwriteQuery() {
public String queryOverwrite(String file) { return ALL; }
};
ZipLeveledStructureProvider provider = new ZipLeveledStructureProvider(zipFile);
List<Object> fileSystemObjects = new ArrayList<Object>();
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
fileSystemObjects.add((Object)entries.nextElement());
}
ImportOperation importOperation = new ImportOperation(newProject.getFullPath(), new ZipEntry(projectName), provider, overwriteQuery, fileSystemObjects);
importOperation.setCreateContainerStructure(false);
importOperation.run(new NullProgressMonitor());

Open a pdf from the Help menu in a RCP application

I included a HELP_CONTENTS action from the ActionFactory in my RCP application but I would like to open a PDF file when I call it in the application and not the normal xml file. Is that possible? I didn't find any examples online.
If you use HelpContentsAction then you'll get Eclipse help. If you want to display your own file then create your own action (you can reuse the icon and text if you want to).
Use IWorkbenchPage.openEditor(IEditorInput input, String editorId) method to open PDF file:
org.eclipse.core.resources.IFile workspaceFile;
java.io.File externalFile;
//PDF in workspace
IEditorInput input = new FileEditorInput(workspaceFile);
//or external
IFileSystem fs = org.eclipse.core.filesystem.EFS.getLocalFileSystem();
IFileStore fileStore = fs.fromLocalFile(externalFile);
input = new FileStoreEditorInput(fileStore);
IWorkbenchPage page =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
page.openEditor(input, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);