programmatically load repository workspace components into local workspace - java

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();
}
}

Related

eclipse plugin project plugin dependency hell

I have this code:
ThreadPoolExecutor t;
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
final IWorkspace workspace = ResourcesPlugin.getWorkspace();
System.out.println("root" + root.getLocation().toOSString());
Runnable runnable = new Runnable() {
public void run() {
try {
IPath projectDotProjectFile = new Path("C:\\Users\\rezbi\\eclipse-workspace\\AutoRefactor-master\\AutoRefactor-master" + "/.project");
IProjectDescription projectDescription = workspace.loadProjectDescription(projectDotProjectFile);
IProject project = workspace.getRoot().getProject(projectDescription.getName());
JavaCapabilityConfigurationPage.createProject(project, projectDescription.getLocationURI(), null);
//project.create(null);
} catch (CoreException e) {
e.printStackTrace();
}
}
};
// and now get the workbench to do the work
final IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getDisplay().syncExec(runnable);
IProject[] projects = root.getProjects();
for(IProject project: projects){
System.out.println(project.getName());
}
I followed the instructions as mentioned in the link below:
http://techdc.blogspot.com/2015/01/eclipse-workbench-has-not-been-created.html
I added the following dependencies only:
org.apache.felix.gogo.command
org.apache.felix.gogo.runtime
org.apache.felix.gogo.shell
org.eclipse.equinox.console
org.eclipse.osgi
Unfortunately it is giving plugin dependency hello - I run the app, I get unresolved dependencies, I add the dependencies and there are more unresolved dependencies. And if I select "add required bundles" from run configuration, then I get "Workbench has not been created yet. Error while creating OSGi modules"
So is there an easier way to get around this?
Update:
How I am creating the project is here:
http://codeandme.blogspot.com/2012/02/creating-headless-application.html
So this is a plugin project.
And to run I right click on the manifest file. Select run as and then osgi framework. Note: I also tried including the plugin dependencies from run configuration. Then I tried to run > Eclipse Application. Either way I get the same result : workbench not created yet.
In the same java class the following code works:
public Object start(IApplicationContext context) throws Exception {
// TODO Auto-generated method stub
//String PACKAGE_NAME = "cucumber";
//final IPackageFragment packageFragment = JavaCoreHelper.getPackageFragment(PACKAGE_NAME);
//System.out.println(packageFragment);
//final ICompilationUnit cu = packageFragment.createCompilationUnit("Application5.java", "", true, null);
//IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
//IProject m_project = root.getProject("cucumber");
//System.out.println("m_project "+m_project);
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
System.out.println("HELLO ");
IProject[] projects = root.getProjects();
for (IProject project : projects) {
try {
printProjectInfo(project);
} catch (CoreException e) {
e.printStackTrace();
}
}
// createAProject();
//System.out.println("test "+root.getProject(name));
return null;
}
But as soon as I try accessing workbench things break.

Convert IFile to XtextResource

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);

How to get full file path present in eclipse project explorer?

I am working on eclipse plugin. In this i have a file name present in a project hierarchy. i need the full path of file abc.java present in project Test.
The file presented in path F:/Test/src/main/java/com/sung/Pre/abc.java
IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot();
IProject project = rootWorkspace.getProject("/Test");
file1 = project.getFile("/abc.java");
FileEditorInput fileEditorInput = new FileEditorInput(file1);
IWorkbench workbench = PlatformUI.getWorkbench();
IEditorDescriptor desc = workbench.getEditorRegistry().getDefaultEditor(file1.getName());
IWorkbenchPage page11 = workbench.getActiveWorkbenchWindow().getActivePage();
try {
page11.openEditor(fileEditorInput, desc.getId(),true);
} catch (PartInitException e1) {
e1.printStackTrace();
}
This is searching file in /Test folder. If the file presented in the root Test folder it's able to open this file but if it's inside some folder like F:/Test/src/main/java/com/sung/Pre/abc.java than it's can not find the file.
I also tried below code but facing the same issue
try {
//IDE.openEditor(page11, uri, "org.eclipse.ui.ide.IDE", true);
IDE.openEditor(page11, file1, true);
} catch (PartInitException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
so my question is if we have a file name presented in project hierarchy so how can we get the absolute or full path of that.
Please remember that i am doing this task in eclipse plugin project
You can specify a path on project.getFile:
project.getFile(new Path("src/main/java/com/sung/Pre/abc.java"));
or get the IFolder for the folder containing the file and use
folder.getFile(new Path("abc.java"));

Export war from headless Eclipse

How do I export a WAR file from an Eclipse .web project programmatically with Java?
I have big problems with war ant task due to complex project structure(
ProjectX.web has a dependency from ProjectX.java) and i'm very confused by the
WebComponentExportWizard implementation.
Is there any WTP API to use? (like this old version http://www.eclipse.org/webtools/jst/components/j2ee/api/j2ee_operationsAPI.html )
After some heavy fight i manage to obtain the war file trough this method:
#SuppressWarnings("restriction")
public static void exportWar(IProject webProject) throws CoreException {
WebComponentExportDataModelProvider modelProvider = new WebComponentExportDataModelProvider();
IDataModel dataModel = DataModelFactory.createDataModel(modelProvider);
dataModel.setBooleanProperty(IJ2EEComponentExportDataModelProperties.EXPORT_SOURCE_FILES, false);
dataModel.setBooleanProperty(IJ2EEComponentExportDataModelProperties.OVERWRITE_EXISTING, true);
dataModel.setStringProperty(IJ2EEComponentExportDataModelProperties.PROJECT_NAME, webProject.getName());
dataModel.setStringProperty(IJ2EEComponentExportDataModelProperties.ARCHIVE_DESTINATION, webProject
.getLocation().append(webProject.getName()).addFileExtension("war").toOSString());
dataModel.setProperty(
IJ2EEComponentExportDataModelProperties.COMPONENT,
ComponentCore.createComponent(webProject));
IDataModelOperation modelOperation = dataModel.getDefaultOperation();
try {
log.debug("Start the export war operation");
modelOperation.execute(null, null);
}
catch (ExecutionException e) {
log.error("Error when exporting .war project", e);
}
}
I used org.eclipse.wst.server.core.util.PublishHelper.publishZip() like below, and it works for me.
IPath war = workDirectory.append("app.war");
PublishHelper publishHelper = new PublishHelper(null);
J2EEFlexProjDeployable deployable =
new J2EEFlexProjDeployable(project, ComponentCore.createComponent(project));
publishHelper.publishZip(deployable.members(), war, null);

eclipse plugin > how to include a jar file programmaticaly

So..., I've made a plugin for Eclipse that generates a new java project and ads files from templates, etc... However the code in the /src directory is then uncompilable because I need to add a jar file I have to the libraries tab.
The project is already a Java project via:
org.eclipse.jdt.core.IJavaProject javaProject = org.eclipse.jdt.core.JavaCore.create(proj);
org.eclipse.jdt.core.IClasspathEntry src = JavaCore.newSourceEntry(folder.getFullPath());
IClasspathEntry jre = JavaCore.newContainerEntry(new Path(
org.eclipse.jdt.launching.JavaRuntime.JRE_CONTAINER), new IAccessRule[0],
new IClasspathAttribute[] {
JavaCore.newClasspathAttribute("owner.project.facets", "java")
}, false);
IClasspathEntry[] entries = new IClasspathEntry[] {
src, jre
};
javaProject.setRawClasspath(entries, proj.getFullPath().append("bin"), new NullProgressMonitor());
And now, basically, I need to do programmaticaly, what the button "Add Jars..." does.
Been struggling with this for a while...
Any code tips or a link to a tutorial that DOES EXACTLY THIS would be helpful. Please no links to generic Eclipse plugin tutorials :) as I've probably seen them all by now...
Thnx a lot
Here's how I did it, not sure if your reqs are exaclty the same, but hope it helps in some way...
IFile file = addJar(project, "/resources/myJar.jar", MY_JAR_TARGET_PATH, monitor); //$NON-NLS-1$
newcpEntries.add(JavaCore.newLibraryEntry(file.getFullPath(), null, null, false));
// .....
where addJar() looks something like this:
private static IFile addJar(IProject project, String srcPath, String targetPath, IProgressMonitor monitor) {
URL srcURL = MyPlugin.getDefault().getBundle().getEntry(srcPath);
IFile file = project.getFile(targetPath);
InputStream is = null;
try {
is = srcURL.openStream();
file.create(is, true, monitor);
} catch (CoreException e) {//...
} catch (IOException e) {//...
}
finally {
try {
if (is != null)
is.close();
} catch (IOException ignored) {}
}
return file;
}
Not sure how you would do it through the eclipse API's, but all that jar config window does is write to your project-name/.classpath file which looks something like:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="lib" path="x-jars/lucene-fast-vector-highlighter-3.0.3-patch1822.jar"/>
<classpathentry kind="lib" path="x-jars/lucene-highlighter-3.0.3.jar"/>
So one option would be to have your setup code edit this file once the project has been created, but this is probably too much of hack for what you want though.

Categories