I have an eclipse project with Xtext files.I need to find get all the files in the eclipse project to be XtextResource in order to find metrics about them. so far,I tried the following things :
1.Iterate all over the list of files in the project and got them as IFile .but I cant convert IFile to XtextResource.
2.I success get XtextResource from only active page in IWorkBenchPage,so if I can find all the Pages in the project and not only the active (in IworkBenchPage)or maybe set all pages in the project as active I think it can work.
this is an example code to what I have done if I have private static void setResource()
{
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart activeEditor = page.getActiveEditor();
if (activeEditor instanceof XtextEditor) {
XtextEditor xtextEditor = (XtextEditor) activeEditor;
xtextEditor.getDocument().readOnly((XtextResource resource) -> {
ResourceHandler.resource = resource;
return null;
});
}
}
I am not an expert with all those relations in eclipse and hope somecan can save me here.
thanks!
The following should work (assuming you create the place where this is used via guice aware extension factory...
#Inject
IResourceSetProvider resourceSetProvider;
...
IProject project = file.getProject();
URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
ResourceSet rs = resourceSetProvider.get(project);
Resource r = rs.getResource(uri, true);
r.load(null)
if you dont have guice at your place use
ResourceSet rs = IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(uri).get(IResourceSetProvider.class).get(project);
Related
I'm using the following code to set the content of an IFile:
public static IFile updateFile(IFile file, String content) {
if (file.exists()) {
InputStream source = new ByteArrayInputStream(content.getBytes());
try {
file.setContents(source, IResource.FORCE, new NullProgressMonitor());
source.close();
} catch (CoreException | IOException e) {
e.printStackTrace();
}
}
return file;
}
This works fine when the file is not opened in the editor, but if the file is opened I get the following warning as if the file was modified outside of Eclipse:
I tried to refresh the file (by calling refreshLocal() method) before and after calling setContents() but that didn't help.
Is there a way to avoid this warning?
Wrap your method in a WorkspaceModifyOperation.
The editor reaction looks correct, because there is a modification outside of org.eclipse.jface.text.IDocument that bound to the editor instance.
The right approach will be to modify not the file content, but an instance of "model" that represents the file content, something like IJavaElement for JDT.
Also you can try to manipulate the document content directly (needs polishing for production):
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (IWorkbenchWindow window : windows) {
IWorkbenchPage[] pages = window.getPages();
for (IWorkbenchPage page : pages) {
IEditorReference[] editorReferences = page.getEditorReferences();
for (IEditorReference editorReference : editorReferences) {
IEditorPart editorPart = editorReference.getEditor(false/*do not restore*/);
IEditorInput editorInput = editorPart.getEditorInput();
//skip editors that are not related
if (inputAffected(editorInput)) {
continue;
}
if (editorPart instanceof AbstractTextEditor) {
AbstractTextEditor textEditor = (AbstractTextEditor) editorPart;
IDocument document = textEditor.getDocumentProvider().getDocument(editorInput);
document.set(content);
}
}
}
}
Honestly, I do not understand the scenario you are trying to cover, probably there are better ways to do this.
I am trying to load a properties file from WEb-INF folder in my web application , which is running on Websphere 8.5 . I am using below code to load the file from the location
public class Init {
private final String WEB_INF_DIR_NAME="WEB-INF";
private String web_inf_path;
private final Properties APP_PROPERTIES =null;
InputStream inputStream = null;
public String getWebInfPath() throws IOException {
if (web_inf_path == null) {
web_inf_path = URLDecoder.decode(Init.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF8");
web_inf_path=web_inf_path.substring(0,web_inf_path.lastIndexOf(WEB_INF_DIR_NAME)+WEB_INF_DIR_NAME.length()).substring(1);
}
inputStream = Init.class.getResourceAsStream("/config/localhost/accountservice.properties");
// inputStream = this.getClass().getClassLoader().getResourceAsStream("/config/localhost/accountservice.properties");
if (inputStream != null) {
APP_PROPERTIES.load(inputStream);
}
System.out.println(APP_PROPERTIES.getProperty(AccountServiceDataAccessConstants.INET_LIBRARY_NAME)); // Here i am getting NULL
return web_inf_path;
}
}
I have also tried using servlet context , but its also giving me NULL. I have tried all possible ways to solve it but unfortunately i am not able to do it. I am also giving my folder structure.
Please excuse me if this is a silly question , but i am not really getting any idea about it.
Usually, everything in WebContent is placed in the root of your WAR file. So instead of
inputStream = Init.class.getResourceAsStream("/config/localhost/accountservice.properties");
It would be
inputStream = Init.class.getResourceAsStream("/WEB-INF/config/localhost/accountservice.properties");
The root of the WAR has WEB-INF in it, and then you can descend into your folder structure as normal.
I want to get the file name and its package path in eclipse when right click menu is clicked.
Action class is implemented IObjectActionDelegate
Run method is as follows,
public void run(IAction action)
{
ISelection sel = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
if (!(sel instanceof IStructuredSelection))
return null;
}
IStructuredSelection selection = (IStructuredSelection) sel ;
Object obj = selection.getFirstElement();
IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj, IFile.class);
But the "sel" variable is not a instance of IStructuredSelection. Therefore it return null.
I have gone through following link,
How to get the active package path in eclipse workspace
But no result.
The code you show should work for a selection in a view, but if you are dealing with an editor you need to do things a different way.
Something like:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart editor = page.getActiveEditor();
IEditorInput input = editor.getEditorInput();
IFile file = (IFile)Platform.getAdapterManager().getAdapter(input, IFile.class);
I'm trying to unmarshal my xml file:
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
But I get this errors:
java.io.FileNotFoundException: null (No such file or directory)
Here is my structure:
Why I can't get files from resources folder? Thanks.
Update.
After refactoring,
URL url = this.getClass().getResource("/xmlToParse/companies.xml");
File file = new File(url.getPath());
I can see an error more clearly:
java.io.FileNotFoundException: /content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml (No such file or directory)
It tries to find WEB-INF/classes/
I have added folder there, but still get this error :(
I had the same problem trying to load some XML files into my test classes. If you use Spring, as one can suggest from your question, the easiest way is to use org.springframework.core.io.Resource - the one Raphael Roth already mentioned.
The code is really straight forward. Just declare a field of the type org.springframework.core.io.Resource and annotate it with org.springframework.beans.factory.annotation.Value - like that:
#Value(value = "classpath:xmlToParse/companies.xml")
private Resource companiesXml;
To obtain the needed InputStream, just call
companiesXml.getInputStream()
and you should be okay :)
But forgive me, I have to ask one thing: Why do you want to implement a XML parser with the help of Spring? There are plenty build in :) E.g. for web services there are very good solutions that marshall your XMLs into Java Objects and back...
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
you are suppose to give an absolute path (so add a loading ´/´, where resource-folder is the root-folder):
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("/xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
i'm retriving my repository workspace programatically with this snippet:
IWorkspaceManager workspaceManager = SCMPlatform.getWorkspaceManager(teamRepository);
IWorkspaceSearchCriteria wsSearchCriteria = WorkspaceSearchCriteria.FACTORY.newInstance();
wsSearchCriteria.setKind(IWorkspaceSearchCriteria.WORKSPACES);
wsSearchCriteria.setExactOwnerName("ownerName"); //replaced with real parameter
List<IWorkspaceHandle> workspaceHandles = workspaceManager.findWorkspaces(wsSearchCriteria,Integer.MAX_VALUE, monitor);
//so, here i got my repWorkSpace:
IRepositoryWorkspace myDesiredRepositoryWorkspace = workspaceHandles.get(0);
how can i programatically fetch/load components from the repository workspace into my eclipse workspace?
you can get your components by this snippet:
List<IComponent> componentList = new ArrayList<IComponent>();
for(Object componentHandle: myDesiredRepositoryWorkspace.getComponents() ){
IItemHandle handle = (IItemHandle) componentHandle;
IItemManager itemManager = teamRepository.itemManager();
IComponent component = (IComponent) itemManager.fetchCompleteItem(handle, IItemManager.DEFAULT, monitor );
componentList.add(component);
}
after that i have my repository workspace, i have all components from each workspace but i'm not able to load the repository workspace into a local workspace.
i'm developint a eclipse plugin, so you'll need the following plugins (or imports from the plain-java-api directly):
com.ibm.team.rtc.common
com.ibm.team.repository.client
com.ibm.team.scm.client
com.ibm.team.scm.common
com.ibm.team.process.common
ok, loading works with ILoadRule2, i found a way, but sadly it involves a bypass via xml-files. It requires access to the sandbox, but it's all described below ^_^
let's assume we have our workspace and our components (as mentioned in the question), we can load the workspace with this snippet:
ISharingManager sharingManager = FileSystemCore.getSharingManager();
File workspaceRoot = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile();
PathLocation pathlocation = new PathLocation(workspaceRoot.getAbsolutePath());
ILocation sandBoxLocation = pathlocation.getCanonicalForm();
ISandbox sandbox = sharingManager.getSandbox(sandBoxLocation, false);
LoadDilemmaHandler p = LoadDilemmaHandler.getDefault();
monitor.subTask("searching for load rules file");
File f = LoadRuleUtility.createLoadRules(componentList);
InputStream ins = new FileInputStream(f);
Reader xmlReader = new InputStreamReader(ins);
ILoadRule2 rule = ILoadRuleFactory.loadRuleFactory.getLoadRule(con, xmlReader, monitor);
ILoadOperation loadoperator = rule.getLoadOp(sandbox, p, monitor);
monitor.subTask("loading files from RTC server...");
loadoperator.run(monitor);
ok, the magic of LoadRuleUtility.createLoadRules() is that it creates a xml file that describes the workspaces's components. (i'm using a DOM).
it has to look like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<scm:sourceControlLoadRule eclipseProjectOptions="import" version="1" xmlns:scm="http://com.ibm.team.scm">
<!-- for each component in your repository workspace -->
<parentLoadRule>
<component name="component_name"/>
<parentFolder repositoryPath="/"/>
</parentLoadRule>
</scm:sourceControlLoadRule>
to unload the components you simply have to delete them:
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for(IProject project: projects){
try {
project.delete(true, true, monitor);
} catch (CoreException e) {
e.printStackTrace();
}
}