List of usage examples for org.eclipse.jdt.core IJavaProject getProject
IProject getProject();
IProject
on which this IJavaProject
was created. From source file:at.bestsolution.javafx.ide.jdt.internal.NewJavaProjectService.java
License:Open Source License
public static void flush(List<CPListElement> classPathEntries, IPath outputLocation, IJavaProject javaProject, String newProjectCompliance, IProgressMonitor monitor) throws CoreException, OperationCanceledException { IProject project = javaProject.getProject(); IPath projPath = project.getFullPath(); IPath oldOutputLocation;//from w w w. j ava 2 s . c o m try { oldOutputLocation = javaProject.getOutputLocation(); } catch (CoreException e) { oldOutputLocation = projPath.append( "bin"/*PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME)*/); } if (oldOutputLocation.equals(projPath) && !outputLocation.equals(projPath)) { if (BuildPathsBlock.hasClassfiles(project)) { // if (BuildPathsBlock.getRemoveOldBinariesQuery(JavaPlugin.getActiveWorkbenchShell()).doQuery(false, projPath)) { BuildPathsBlock.removeOldClassfiles(project); // } } } else if (!outputLocation.equals(oldOutputLocation)) { IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(oldOutputLocation); if (folder.exists()) { if (folder.members().length == 0) { BuildPathsBlock.removeOldClassfiles(folder); } else { // if (BuildPathsBlock.getRemoveOldBinariesQuery(JavaPlugin.getActiveWorkbenchShell()).doQuery(folder.isDerived(), oldOutputLocation)) { BuildPathsBlock.removeOldClassfiles(folder); // } } } } monitor.worked(1); IWorkspaceRoot fWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); //create and set the output path first if (!fWorkspaceRoot.exists(outputLocation)) { IFolder folder = fWorkspaceRoot.getFolder(outputLocation); CoreUtility.createDerivedFolder(folder, true, true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } int nEntries = classPathEntries.size(); IClasspathEntry[] classpath = new IClasspathEntry[nEntries]; int i = 0; for (Iterator<CPListElement> iter = classPathEntries.iterator(); iter.hasNext();) { CPListElement entry = iter.next(); classpath[i] = entry.getClasspathEntry(); i++; IResource res = entry.getResource(); //1 tick if (res instanceof IFolder && entry.getLinkTarget() == null && !res.exists()) { CoreUtility.createFolder((IFolder) res, true, true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } //3 ticks if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IPath folderOutput = (IPath) entry.getAttribute(CPListElement.OUTPUT); if (folderOutput != null && folderOutput.segmentCount() > 1) { IFolder folder = fWorkspaceRoot.getFolder(folderOutput); CoreUtility.createDerivedFolder(folder, true, true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } IPath path = entry.getPath(); if (projPath.equals(path)) { monitor.worked(2); continue; } if (projPath.isPrefixOf(path)) { path = path.removeFirstSegments(projPath.segmentCount()); } IFolder folder = project.getFolder(path); IPath orginalPath = entry.getOrginalPath(); if (orginalPath == null) { if (!folder.exists()) { //New source folder needs to be created if (entry.getLinkTarget() == null) { CoreUtility.createFolder(folder, true, true, new SubProgressMonitor(monitor, 2)); } else { folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 2)); } } } else { if (projPath.isPrefixOf(orginalPath)) { orginalPath = orginalPath.removeFirstSegments(projPath.segmentCount()); } IFolder orginalFolder = project.getFolder(orginalPath); if (entry.getLinkTarget() == null) { if (!folder.exists()) { //Source folder was edited, move to new location IPath parentPath = entry.getPath().removeLastSegments(1); if (projPath.isPrefixOf(parentPath)) { parentPath = parentPath.removeFirstSegments(projPath.segmentCount()); } if (parentPath.segmentCount() > 0) { IFolder parentFolder = project.getFolder(parentPath); if (!parentFolder.exists()) { CoreUtility.createFolder(parentFolder, true, true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } } else { monitor.worked(1); } orginalFolder.move(entry.getPath(), true, true, new SubProgressMonitor(monitor, 1)); } } else { if (!folder.exists() || !entry.getLinkTarget().equals(entry.getOrginalLinkTarget())) { orginalFolder.delete(true, new SubProgressMonitor(monitor, 1)); folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 1)); } } } } else { if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IPath path = entry.getPath(); if (!path.equals(entry.getOrginalPath())) { String eeID = JavaRuntime.getExecutionEnvironmentId(path); if (eeID != null) { BuildPathSupport.setEEComplianceOptions(javaProject, eeID, newProjectCompliance); newProjectCompliance = null; // don't set it again below } } if (newProjectCompliance != null) { Map<String, String> options = javaProject.getOptions(false); JavaModelUtil.setComplianceOptions(options, newProjectCompliance); JavaModelUtil.setDefaultClassfileOptions(options, newProjectCompliance); // complete compliance options javaProject.setOptions(options); } } monitor.worked(3); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } } javaProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 2)); }
From source file:at.component.newcomponentwizard.generator.NewProjectCreationOperation.java
License:Open Source License
protected IClasspathEntry[] getInternalClassPathEntries(IJavaProject project, IFieldData data) { if (data.getSourceFolderName() == null) { return new IClasspathEntry[0]; }/* ww w. jav a2 s .co m*/ IClasspathEntry[] entries = new IClasspathEntry[1]; IPath path = project.getProject().getFullPath().append(data.getSourceFolderName()); entries[0] = JavaCore.newSourceEntry(path); return entries; }
From source file:bndtools.editor.components.ComponentNameProposalProvider.java
License:Open Source License
@Override protected List<IContentProposal> doGenerateProposals(String contents, int position) { final String prefix = contents.substring(0, position); IJavaProject javaProject = searchContext.getJavaProject(); final List<IContentProposal> result = new ArrayList<IContentProposal>(100); // Resource matches IProject project = javaProject.getProject(); try {//from www . j a v a 2 s.c o m project.accept(new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.FILE) { if (proxy.getName().toLowerCase().startsWith(prefix) && proxy.getName().toLowerCase().endsWith(XML_SUFFIX)) { result.add(new ResourceProposal(proxy.requestResource())); } return false; } // Recurse into everything else return true; } }, 0); } catch (CoreException e) { Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for resources.", e)); } // Class matches final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject }); final TypeNameRequestor requestor = new TypeNameRequestor() { @Override public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) { if (!Flags.isAbstract(modifiers) && (Flags.isPublic(modifiers) || Flags.isProtected(modifiers))) { result.add(new JavaContentProposal(new String(packageName), new String(simpleTypeName), false)); } }; }; final IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { new SearchEngine().searchAllTypeNames(null, 0, prefix.toCharArray(), SearchPattern.R_PREFIX_MATCH, IJavaSearchConstants.CLASS, scope, requestor, IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, monitor); } catch (JavaModelException e) { throw new InvocationTargetException(e); } } }; IRunnableContext runContext = searchContext.getRunContext(); try { if (runContext != null) { runContext.run(false, false, runnable); } else { runnable.run(new NullProgressMonitor()); } } catch (InvocationTargetException e) { Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for classes.", e.getTargetException())); } catch (InterruptedException e) { // Reset the interruption status and continue Thread.currentThread().interrupt(); } return result; }
From source file:bndtools.nature.ToggleNatureAction.java
License:Open Source License
/** * Toggles sample nature on a project/*from w ww. ja v a2 s . c o m*/ * * @param project to have sample nature added or removed */ private static IStatus toggleNature(IJavaProject project) { try { /* Version control ignores */ VersionControlIgnoresManager versionControlIgnoresManager = Plugin.getDefault() .getVersionControlIgnoresManager(); Set<String> enabledIgnorePlugins = new BndPreferences() .getVersionControlIgnoresPluginsEnabled(versionControlIgnoresManager, project, null); /* Headless build files */ HeadlessBuildManager headlessBuildManager = Plugin.getDefault().getHeadlessBuildManager(); Set<String> enabledPlugins = new BndPreferences().getHeadlessBuildPluginsEnabled(headlessBuildManager, null); IProject iProject = project.getProject(); IProjectDescription description = iProject.getDescription(); String[] natures = description.getNatureIds(); List<String> headlessBuildWarnings = new LinkedList<>(); for (int i = 0; i < natures.length; ++i) { if (BndtoolsConstants.NATURE_ID.equals(natures[i])) { // Remove the nature String[] newNatures = new String[natures.length - 1]; System.arraycopy(natures, 0, newNatures, 0, i); System.arraycopy(natures, i + 1, newNatures, i, natures.length - i - 1); description.setNatureIds(newNatures); iProject.setDescription(description, null); /* Remove the headless build files */ headlessBuildManager.setup(enabledPlugins, false, iProject.getLocation().toFile(), false, enabledIgnorePlugins, headlessBuildWarnings); /* refresh the project; files were created outside of Eclipse API */ iProject.refreshLocal(IResource.DEPTH_INFINITE, null); return createStatus( "Obsolete build files may remain in the project. Please review the messages below.", Collections.<String>emptyList(), headlessBuildWarnings); } } /* Add the headless build files */ headlessBuildManager.setup(enabledPlugins, false, iProject.getLocation().toFile(), true, enabledIgnorePlugins, headlessBuildWarnings); // Add the nature ensureBndBndExists(iProject); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = BndtoolsConstants.NATURE_ID; description.setNatureIds(newNatures); iProject.setDescription(description, null); /* refresh the project; files were created outside of Eclipse API */ iProject.refreshLocal(IResource.DEPTH_INFINITE, null); return createStatus("Some build files could not be generated. Please review the messages below.", Collections.<String>emptyList(), headlessBuildWarnings); } catch (CoreException e) { return new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error occurred while toggling Bnd project nature", e); } }
From source file:bndtools.wizards.project.AbstractNewBndProjectWizard.java
License:Open Source License
/** * Modify the newly generated Java project; this method is executed from within a workspace operation so is free to * make workspace resource modifications. * * @throws CoreException/*from www .jav a 2s . com*/ */ protected void processGeneratedProject(ProjectPaths projectPaths, BndEditModel bndModel, IJavaProject project, IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 3); Document document = new Document(""); bndModel.saveChangesTo(document); progress.worked(1); ByteArrayInputStream bndInput; try { bndInput = new ByteArrayInputStream(document.get().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return; } IFile bndBndFile = project.getProject().getFile(Project.BNDFILE); if (bndBndFile.exists()) { bndBndFile.setContents(bndInput, false, false, progress.newChild(1)); } BndProject proj = generateBndProject(project.getProject(), progress.newChild(1)); progress.setWorkRemaining(proj.getResources().size()); for (Map.Entry<String, BndProjectResource> resource : proj.getResources().entrySet()) { importResource(project.getProject(), resource.getKey(), resource.getValue(), progress.newChild(1)); } if (!bndBndFile.exists()) { bndBndFile.create(bndInput, false, progress.newChild(1)); } /* Version control ignores */ VersionControlIgnoresManager versionControlIgnoresManager = Plugin.getDefault() .getVersionControlIgnoresManager(); Set<String> enabledIgnorePlugins = new BndPreferences() .getVersionControlIgnoresPluginsEnabled(versionControlIgnoresManager, project, null); Map<String, String> sourceOutputLocations = JavaProjectUtils.getSourceOutputLocations(project); versionControlIgnoresManager.createProjectIgnores(enabledIgnorePlugins, project.getProject().getLocation().toFile(), sourceOutputLocations, projectPaths.getTargetDir()); /* Headless build files */ HeadlessBuildManager headlessBuildManager = Plugin.getDefault().getHeadlessBuildManager(); Set<String> enabledPlugins = new BndPreferences().getHeadlessBuildPluginsEnabled(headlessBuildManager, null); headlessBuildManager.setup(enabledPlugins, false, project.getProject().getLocation().toFile(), true, enabledIgnorePlugins, new LinkedList<String>()); /* refresh the project; files were created outside of Eclipse API */ project.getProject().refreshLocal(IResource.DEPTH_INFINITE, progress); project.getProject().build(IncrementalProjectBuilder.CLEAN_BUILD, progress); }
From source file:bndtools.wizards.project.AbstractNewBndProjectWizard.java
License:Open Source License
@Override public boolean performFinish() { boolean result = super.performFinish(); if (result) { final IJavaProject javaProj = (IJavaProject) getCreatedElement(); final IProject project = javaProj.getProject(); final Map<String, String> templateParams = getProjectTemplateParams(); try {//from www. j a v a2 s . co m // Run using the progress bar from the wizard dialog getContainer().run(false, false, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { // Make changes to the project final IWorkspaceRunnable op = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { try { generateProjectContent(project, monitor, templateParams); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating project content from template", e)); } } }; javaProj.getProject().getWorkspace().run(op, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); result = true; } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); final IStatus status; if (targetException instanceof CoreException) { status = ((CoreException) targetException).getStatus(); } else { status = new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error creating bnd project contents", targetException); } logger.logStatus(status); ErrorDialog.openError(getShell(), "Error", "Error creating bnd project", status); result = false; } catch (InterruptedException e) { // Shouldn't happen } // get bnd.bnd file IFile bndFile = javaProj.getProject().getFile(Project.BNDFILE); // check to see if we need to add marker about missing workspace try { if (!Central.hasWorkspaceDirectory()) { IResource markerTarget = bndFile; if (markerTarget == null || markerTarget.getType() != IResource.FILE || !markerTarget.exists()) markerTarget = project; IMarker marker = markerTarget.createMarker(BndtoolsConstants.MARKER_BND_MISSING_WORKSPACE); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.MESSAGE, "Missing Bnd Workspace. Create a new workspace with the 'New Bnd OSGi Workspace' wizard."); marker.setAttribute(BuildErrorDetailsHandler.PROP_HAS_RESOLUTIONS, true); marker.setAttribute("$bndType", BndtoolsConstants.MARKER_BND_MISSING_WORKSPACE); } } catch (Exception e1) { // ignore exceptions, this is best effort to help new users } // Open the bnd.bnd file in the editor try { if (bndFile.exists()) IDE.openEditor(getWorkbench().getActiveWorkbenchWindow().getActivePage(), bndFile); } catch (PartInitException e) { ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, MessageFormat.format("Failed to open project descriptor file {0} in the editor.", bndFile.getFullPath().toString()), e)); } } return result; }
From source file:bndtools.wizards.project.NewBndProjectWizard.java
License:Open Source License
@Override protected Map<String, String> getProjectTemplateParams() { // Project Name Map<ProjectTemplateParam, String> params = new HashMap<>(); params.put(ProjectTemplateParam.PROJECT_NAME, pageOne.getProjectName()); // Package Name String packageName = pageOne.getPackageName(); params.put(ProjectTemplateParam.BASE_PACKAGE_NAME, packageName); // Package Dir String packageDir = packageName.replace('.', '/'); params.put(ProjectTemplateParam.BASE_PACKAGE_DIR, packageDir); // Version/* w ww .j av a 2 s .c o m*/ params.put(ProjectTemplateParam.VERSION, DEFAULT_BUNDLE_VERSION); // Source Folders IJavaProject javaProject = pageTwo.getJavaProject(); Map<String, String> sourceOutputLocations = JavaProjectUtils.getSourceOutputLocations(javaProject); int nr = 1; for (Map.Entry<String, String> entry : sourceOutputLocations.entrySet()) { String src = entry.getKey(); String bin = entry.getValue(); if (nr == 1) { params.put(ProjectTemplateParam.SRC_DIR, src); params.put(ProjectTemplateParam.BIN_DIR, bin); nr = 2; } else if (nr == 2) { params.put(ProjectTemplateParam.TEST_SRC_DIR, src); params.put(ProjectTemplateParam.TEST_BIN_DIR, bin); nr = 2; } else { // if for some crazy reason we end up with more than 2 paths, we log them in // extension properties (we cannot write comments) but this should never happen // anyway since the second page will not complete if there are not exactly 2 paths // so this could only happen if someone adds another page (that changes them again) // TODO // model.genericSet("X-WARN-" + nr, "Ignoring source path " + src + " -> " + bin); nr++; } } try { String javaLevel = JavaProjectUtils.getJavaLevel(javaProject); if (javaLevel != null) params.put(ProjectTemplateParam.JAVA_LEVEL, javaLevel); } catch (Exception e) { Plugin.getDefault().getLog().log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, String.format("Unable to get Java level for project %s", javaProject.getProject().getName()), e)); } Map<String, String> params_ = new HashMap<>(); for (Entry<ProjectTemplateParam, String> entry : params.entrySet()) params_.put(entry.getKey().getString(), entry.getValue()); Map<String, String> editedParams = paramsPage.getValues(); for (Entry<String, String> editedEntry : editedParams.entrySet()) { params_.put(editedEntry.getKey(), editedEntry.getValue()); } return params_; }
From source file:byke.tests.workspaceutils.JavaProject.java
License:Open Source License
public JavaProject(IJavaProject javaProject) throws CoreException { super(javaProject.getProject(), null); _javaProject = javaProject; }
From source file:bz.davide.dmeclipsesavehookplugin.builder.DMEclipseSaveHookPluginBuilder.java
License:Open Source License
static void findTransitiveDepProjects(IJavaProject current, ArrayList<IProject> projects, ArrayList<String> fullClasspath) throws CoreException { if (!projects.contains(current.getProject())) { projects.add(current.getProject()); }/*from w w w. j a v a 2 s .c o m*/ fullClasspath.add(ResourcesPlugin.getWorkspace().getRoot().findMember(current.getOutputLocation()) .getLocation().toOSString() + "/"); ArrayList<IClasspathEntry> classPaths = new ArrayList<IClasspathEntry>(); classPaths.addAll(Arrays.asList(current.getRawClasspath())); for (int x = 0; x < classPaths.size(); x++) { IClasspathEntry cp = classPaths.get(x); if (cp.getEntryKind() == IClasspathEntry.CPE_PROJECT) { String prjName = cp.getPath().lastSegment(); IProject prj = ResourcesPlugin.getWorkspace().getRoot().getProject(prjName); if (prj.hasNature(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(prj); findTransitiveDepProjects(javaProject, projects, fullClasspath); } continue; } if (cp.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { String fullContainerName = cp.getPath().toString(); if (!fullContainerName.startsWith("org.eclipse.jdt.launching.JRE_CONTAINER/")) { System.out.println("CP C: " + fullContainerName); IClasspathContainer container = JavaCore.getClasspathContainer(cp.getPath(), current); classPaths.addAll(Arrays.asList(container.getClasspathEntries())); } } if (cp.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { IPath path = cp.getPath(); // Check first if this path is relative to workspace IResource workspaceMember = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (workspaceMember != null) { String fullPath = workspaceMember.getLocation().toOSString(); fullClasspath.add(fullPath); } else { fullClasspath.add(path.toOSString()); } } } }
From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java
License:Open Source License
@Override public boolean isActive(IJavaProject project) { boolean enabled = Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, Activator.PREF_ENABLED, true, new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE }); if (!enabled) return false; if (!PDE.hasPluginNature(project.getProject())) return false; try {/*from w w w . j a va 2s. com*/ IType annotationType = project.findType(COMPONENT_ANNOTATION); return annotationType != null && annotationType.isAnnotation(); } catch (JavaModelException e) { Activator.getDefault().getLog().log(e.getStatus()); } return false; }