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.
Related
I am creating a Rhapsody JavaAPI plugin that will clean the current project files and copy in a fresh model. This is to have a fresh working copy for developers so they do not have to close rhapsody and copy in the clean models manually.
My dilemma is when i close the active project, it removes it from the rhapsody view as expected. When I try reloading the new rpy file, the view does not change nor is the model reload.
How would I go about reloading the project?
Here is my plugin (note the class call works fine. Its in the method clean that I am having issues).
public class CMMCleaner {
private Path rootDir;
private Path rpyFile;
private IRPApplication rpyApp;
public CMMCleaner(final Path rootDir, final IRPApplication rpyApp) {
this.rootDir = rootDir;
if (!Files.exists(rootDir)) throw new IllegalArgumentException(rootDir + " does not exist");
this.rpyApp = rpyApp;
this.rpyFile = Paths.get(this.rpyApp.activeProject().getCurrentDirectory()).resolve(this.rpyApp.activeProject().getFilename());
}
public void clean() {
try {
rpyApp.activeProject.close();
Path cleanDir = this.rootDir.resolve("CMM_starting_model");
Path oldDir = this.rootDir.resolve("CMM_model");
Files.walk(oldDir)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
Files.walk(cleanDir)
.filter(p -> Files.isRegularFile(p))
.forEach(cleanFile -> {
Path path = oldDir.resolve(cleanDir.relativize(cleanFile));
try {
Files.createDirectories(path.getParent());
Files.copy(cleanFile, path, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception ex) {
ex.printStackTrace();
}
});
rpyApp.openProject(this.rpyFile.toAbsolutePath().toString());
rpyApp.insertProject(this.rpyFile.toAbsolutePath().toString());
rpyApp.activeProject();
rpyApp.refreshAllViews();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
No Exceptions are thrown, but as stated the project does close and I can visually see the files being deleted and copied in, but nothing happens in rhapsody after that.
I was able to solve the problem by removing the following lines:
rpyApp.activeProject.close(); and rpyApp.insertProject(this.rpyFile.toAbsolutePath().toString());
I am trying to publish an artifact to Artifactory using Java.
Here is the code.
public static void publishToArtifactoryPro(String groupId,
String artifactId,
String version,
Collection artifacts) throws JarMigrationServiceException{
// create an ivy instance
IvySettings ivySettings = new IvySettings();
ivySettings.setDefaultCache(new File("ivy/cache"));
// use the biblio resolver, if you consider resolving
// POM declared dependencies
IBiblioResolver br = new IBiblioResolver();
br.setM2compatible(true);
br.setUsepoms(true);
br.setName("ibiblio");
br.setRoot(Constants.ARTIFACTORY_PRO_RELEASE_LOCAL);
ivySettings.addResolver(br);
ivySettings.setDefaultResolver(br.getName());
Ivy ivy = Ivy.newInstance(ivySettings);
//you always need to resolve before you can retrieve
ResolveOptions ro = new ResolveOptions();
// this seems to have no impact, if you resolve by module descriptor (in contrast to resolve by ModuleRevisionId)
ro.setTransitive(true);
// if set to false, nothing will be downloaded
ro.setDownload(true);
// 1st create an ivy module (this always(!) has a "default" configuration already)
DefaultModuleDescriptor md = DefaultModuleDescriptor.newDefaultInstance(
// give it some related name (so it can be cached)
ModuleRevisionId.newInstance(
groupId,
artifactId+"-envelope",
version
)
);
// 2. add dependencies for what we are really looking for
ModuleRevisionId ri = ModuleRevisionId.newInstance(
groupId,
artifactId,
version
);
// don't go transitive here, if you want the single artifact
DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, ri, false, false, false);
// map to master to just get the code jar. See generated ivy module xmls from maven repo
// on how configurations are mapped into ivy. Or check
// e.g. http://lightguard-jp.blogspot.de/2009/04/ivy-configurations-when-pulling-from.html
dd.addDependencyConfiguration("default", "master");
md.addDependency(dd);
// now resolve
ResolveReport rr = null;
try {
rr = ivy.resolve(md,ro);
if (rr.hasError()) {
throw new RuntimeException(rr.getAllProblemMessages().toString());
}
}
catch (ParseException e) {
throw new JarMigrationServiceException(e.getMessage(), e);
}
catch (IOException e) {
throw new JarMigrationServiceException(e.getMessage(), e);
}
try {
ivy.publish(
ModuleRevisionId.newInstance(groupId, artifactId, version),
artifacts,
"artifactory-publish",
new PublishOptions()
// this is from the envelop module
.setConfs(new String[]{"default"})
);
}
catch (IOException e) {
throw new JarMigrationServiceException(e.getMessage(), e);
}
}
Here is the error:
Exception in thread "main" java.lang.IllegalStateException: ivy file not found in cache for com.mycompany#MAO;1.1.2: please resolve dependencies before publishing (ivy/cache/resolved-com.mycompany-MAO-1.1.2.xml)
at org.apache.ivy.core.publish.PublishEngine.publish(PublishEngine.java:105)
at org.apache.ivy.Ivy.publish(Ivy.java:600)
at com.mycompany.is.dt.Utilities.JarMigrationUtility.publishToArtifactoryPro(JarMigrationUtility.java:96)
at com.mycompany.is.dt.controllers.JarMigrationService.main(JarMigrationService.java:29)
So I am confused because it says ivy file not found in cache but you can see that I am setting the cache here ivySettings.setDefaultCache(new File("ivy/cache")); And when I go to ivy/cache/com/mycompany/MAO I see the jar there... Any ideas?
I have a program that changes an input Java project loaded in Eclipse. After changes I use the below code to refresh the project and extract compilation unit.
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
//projectName is the name of project loaded in eclipse
IProject project = root.getProject(projectName);
try {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
e.printStackTrace();
}
IJavaProject iJavaproject = JavaCore.create(project);
/** Extract ICompilationUnit. "classFullName" is the name of class contains new changes.*/
ICompilationUnit iCompilationUnit = getICompilationUnit(javaProject, classFullName);
/** Extract compilation unit.*/
CompilationUnit compilationUnit = getCompilationUnit(iCompilationUnit);
I have these two functions to extract iCompilationUnit and compilationUnit.
private ICompilationUnit getICompilationUnit(IJavaProject javaProject, String classFullName) {
ICompilationUnit iUnit = null;
try {
IType iType = javaProject.findType(classFullName);
iUnit = iType.getCompilationUnit();
/** Create working copy. It is safer to work with a copy.*/
WorkingCopyOwner owner = iUnit.getOwner();
iUnit = (owner == null ? iUnit.getWorkingCopy(null) : iUnit.getWorkingCopy(owner, null));
} catch (JavaModelException e) {
e.printStackTrace();
}
return iUnit;
}
CompilationUnit getCompilationUnit(ICompilationUnit iCompilationUnit) {
#SuppressWarnings("deprecation")
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(iCompilationUnit);
/** we need bindings later on.*/
parser.setResolveBindings(true);
return (CompilationUnit) parser.createAST(null);
}
However, the problem I am facing is that first call to this method (first time that any changes is applied to the project), the above code cannot detect changes and return original version. However, after that the project is refreshed correctly and final compilationUnit contains applied changes.
I am not sure the problem is for refreshLocal and maybe it is for other two functions: getCompilationUnit and getICompilationUnit.
Please let me know if any one has any idea.
I think the JDT is probably running background jobs to recompile and rebuild indices. So you need to wait for those jobs to finish. Try
IJobManager jobManager = Job.getJobManager();
jobManager.join(ResourcesPlugin.FAMILY_MANUAL_BUILD, monitor);
jobManager.join(ResourcesPlugin.FAMILY_AUTO_BUILD, monitor);
do this after the refreshLocal but before you do anything else.
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"));
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);