List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getJavaProject
IJavaProject getJavaProject();
null
if this element is not contained in any Java project (for instance, the IJavaModel
is not contained in any Java project). From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java
License:Open Source License
/** * A hook method that gets called when the package field has changed. The method * validates the package name and returns the status of the validation. The validation * also updates the package fragment model. * <p>//from ww w. ja v a 2 s. c om * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus packageChanged() { StatusInfo status = new StatusInfo(); IPackageFragmentRoot root = getPackageFragmentRoot(); fPackageDialogField.enableButton(root != null); IJavaProject project = root != null ? root.getJavaProject() : null; String packName = getPackageText(); if (packName.length() > 0) { IStatus val = validatePackageName(packName, project); if (val.getSeverity() == IStatus.ERROR) { status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidPackageName, val.getMessage())); return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(Messages.format( NewWizardMessages.NewTypeWizardPage_warning_DiscouragedPackageName, val.getMessage())); // continue } } else { status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_DefaultPackageDiscouraged); } if (project != null) { if (project.exists() && packName.length() > 0) { try { IPath rootPath = root.getPath(); IPath outputPath = project.getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, don't allow to name a package // like the bin folder IPath packagePath = rootPath.append(packName.replace('.', '/')); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation); return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass } } fCurrPackage = root.getPackageFragment(packName); } else { status.setError(""); //$NON-NLS-1$ } return status; }
From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java
License:Open Source License
/** * Hook method that gets called when the enclosing type name has changed. The method * validates the enclosing type and returns the status of the validation. It also updates the * enclosing type model./*from ww w.java 2 s .c o m*/ * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus enclosingTypeChanged() { StatusInfo status = new StatusInfo(); fCurrEnclosingType = null; IPackageFragmentRoot root = getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName = getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeEnterName); return status; } try { IType type = findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeNotExists); return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingNotInCU); return status; } if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingNotEditable); return status; } fCurrEnclosingType = type; IPackageFragmentRoot enclosingRoot = JavaModelUtil.getPackageFragmentRoot(type); if (!enclosingRoot.equals(root)) { status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_EnclosingNotInSourceFolder); } return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeNotExists); JavaPlugin.log(e); return status; } }
From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java
License:Open Source License
/** * Hook method that gets called when the superclass name has changed. The method * validates the superclass name and returns the status of the validation. * <p>//from www . ja va 2 s . c o m * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superClassChanged() { StatusInfo status = new StatusInfo(); IPackageFragmentRoot root = getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClassStubTypeContext = null; String sclassName = getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } if (root != null) { Type type = TypeContextChecker.parseSuperClass(sclassName); if (type == null) { status.setError(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperClassName); return status; } if (type instanceof ParameterizedType && !JavaModelUtil.is50OrHigher(root.getJavaProject())) { status.setError(NewWizardMessages.NewTypeWizardPage_error_SuperClassNotParameterized); return status; } } else { status.setError(""); //$NON-NLS-1$ } return status; }
From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java
License:Open Source License
/** * Hook method that gets called when the list of super interface has changed. The method * validates the super interfaces and returns the status of the validation. * <p>/*w ww .j av a 2s. com*/ * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superInterfacesChanged() { StatusInfo status = new StatusInfo(); IPackageFragmentRoot root = getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements = fSuperInterfacesDialogField.getElements(); int nElements = elements.size(); for (int i = 0; i < nElements; i++) { String intfname = ((InterfaceWrapper) elements.get(i)).interfaceName; Type type = TypeContextChecker.parseSuperInterface(intfname); if (type == null) { status.setError( Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperInterfaceName, BasicElementLabels.getJavaElementName(intfname))); return status; } if (type instanceof ParameterizedType && !JavaModelUtil.is50OrHigher(root.getJavaProject())) { status.setError(Messages.format( NewWizardMessages.NewTypeWizardPage_error_SuperInterfaceNotParameterized, BasicElementLabels.getJavaElementName(intfname))); return status; } } } return status; }
From source file:org.eclipse.andmore.android.model.BuildingBlockModel.java
License:Apache License
/** * Configure source folder and package from workbench selection * //from w ww. j a v a 2s . co m * @param selection */ public void configure(IStructuredSelection selection) { try { IPackageFragmentRoot srcFolder = extractPackageFragmentRoot(selection); setPackageFragmentRoot(srcFolder); IJavaProject javaProject = srcFolder == null ? null : srcFolder.getJavaProject(); setPackageFragment(extractPackageFragment(selection, javaProject)); if (javaProject != null) { apiVersion = AndroidUtils.getApiVersionNumberForProject(javaProject.getProject()); } } catch (Exception e) { AndmoreLogger.error(BuildingBlockModel.class, "Error configuring building block from selection.", e); } }
From source file:org.eclipse.andmore.wizards.buildingblocks.NewBuildingBlocksWizardPage.java
License:Apache License
private void updatePackage(IPackageFragmentRoot packageFragmentRoot) { if (packageFragmentRoot != null) { IJavaProject project = null;//from ww w . j a va 2 s .c o m IPackageFragment pack = null; project = packageFragmentRoot.getJavaProject(); try { pack = EclipseUtils.getDefaultPackageFragment(project); getBuildBlock().setPackageFragment(pack); } catch (JavaModelException e) { AndmoreLogger.error(NewBuildingBlocksWizardPage.class, "Error getting default package fragment.", //$NON-NLS-1$ e); // do nothing } setPackageFragment(pack, true); handleFieldChanged(NewTypeWizardPage.PACKAGE); } }
From source file:org.eclipse.che.jdt.internal.core.SourceMapper.java
License:Open Source License
private synchronized void computeAllRootPaths(IType type) { if (this.areRootPathsComputed) { return;//w w w.j a va 2s.c o m } IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent(); IPath pkgFragmentRootPath = root.getPath(); final HashSet tempRoots = new HashSet(); long time = 0; if (VERBOSE) { System.out.println("compute all root paths for " + root.getElementName()); //$NON-NLS-1$ time = System.currentTimeMillis(); } final HashSet firstLevelPackageNames = new HashSet(); boolean containsADefaultPackage = false; boolean containsJavaSource = !pkgFragmentRootPath.equals(this.sourcePath); // used to optimize zip file reading only if source path and root path are equals, otherwise // assume that attachment contains Java source String sourceLevel = null; String complianceLevel = null; if (root.isArchive()) { // org.eclipse.jdt.internal.core.JavaModelManager manager = org.eclipse.jdt.internal.core.JavaModelManager.getJavaModelManager(); ZipFile zip = null; try { zip = manager.getZipFile(pkgFragmentRootPath); for (Enumeration entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); String entryName = entry.getName(); if (!entry.isDirectory()) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entryName)) { int index = entryName.indexOf('/'); if (index != -1) { String firstLevelPackageName = entryName.substring(0, index); if (!firstLevelPackageNames.contains(firstLevelPackageName)) { if (sourceLevel == null) { IJavaProject project = root.getJavaProject(); sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true); complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true); } IStatus status = Status.OK_STATUS;// JavaConventions // .validatePackageName(firstLevelPackageName, sourceLevel, complianceLevel); if (status.isOK() || status.getSeverity() == IStatus.WARNING) { firstLevelPackageNames.add(firstLevelPackageName); } } } else { containsADefaultPackage = true; } } else if (!containsJavaSource && org.eclipse.che.jdt.internal.core.util.Util.isJavaLikeFileName(entryName)) { containsJavaSource = true; } } } } catch (CoreException e) { // ignore } finally { manager.closeZipFile(zip); // handle null case } } /*else { Object target = JavaModel.getTarget(root.getPath(), true); if (target instanceof IResource) { IResource resource = (IResource) target; if (resource instanceof IContainer) { try { IResource[] members = ((IContainer) resource).members(); for (int i = 0, max = members.length; i < max; i++) { IResource member = members[i]; String resourceName = member.getName(); if (member.getType() == IResource.FOLDER) { if (sourceLevel == null) { IJavaProject project = root.getJavaProject(); sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true); complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true); } IStatus status = JavaConventions.validatePackageName(resourceName, sourceLevel, complianceLevel); if (status.isOK() || status.getSeverity() == IStatus.WARNING) { firstLevelPackageNames.add(resourceName); } } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resourceName)) { containsADefaultPackage = true; } else if (!containsJavaSource && Util.isJavaLikeFileName(resourceName)) { containsJavaSource = true; } } } catch (CoreException e) { // ignore } } } }*/ if (containsJavaSource) { // no need to read source attachment if it contains no Java source (see https://bugs.eclipse // .org/bugs/show_bug.cgi?id=190840 ) // Object target = JavaModel.getTarget(this.sourcePath, true); // if (target instanceof IContainer) { // IContainer folder = (IContainer)target; // computeRootPath(folder, firstLevelPackageNames, containsADefaultPackage, tempRoots, folder.getFullPath().segmentCount() // /*if external folder, this is the linked folder path*/); // } else { // JavaModelManager // manager = JavaModelManager.getJavaModelManager(); ZipFile zip = null; try { zip = manager.getZipFile(this.sourcePath); for (Enumeration entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); String entryName; if (!entry.isDirectory() && Util.isJavaLikeFileName(entryName = entry.getName())) { IPath path = new Path(entryName); int segmentCount = path.segmentCount(); if (segmentCount > 1) { for (int i = 0, max = path.segmentCount() - 1; i < max; i++) { if (firstLevelPackageNames.contains(path.segment(i))) { tempRoots.add(path.uptoSegment(i)); // don't break here as this path could contain other first level package names (see https://bugs // .eclipse.org/bugs/show_bug.cgi?id=74014) } if (i == max - 1 && containsADefaultPackage) { tempRoots.add(path.uptoSegment(max)); } } } else if (containsADefaultPackage) { tempRoots.add(new Path("")); //$NON-NLS-1$ } } } } catch (CoreException e) { // ignore } finally { manager.closeZipFile(zip); // handle null case } // } } int size = tempRoots.size(); if (this.rootPaths != null) { for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) { tempRoots.add(new Path((String) iterator.next())); } this.rootPaths.clear(); } else { this.rootPaths = new ArrayList(size); } size = tempRoots.size(); if (size > 0) { ArrayList sortedRoots = new ArrayList(tempRoots); if (size > 1) { Collections.sort(sortedRoots, new Comparator() { public int compare(Object o1, Object o2) { IPath path1 = (IPath) o1; IPath path2 = (IPath) o2; return path1.segmentCount() - path2.segmentCount(); } }); } for (Iterator iter = sortedRoots.iterator(); iter.hasNext();) { IPath path = (IPath) iter.next(); this.rootPaths.add(path.toString()); } } this.areRootPathsComputed = true; if (VERBOSE) { System.out.println("Spent " + (System.currentTimeMillis() - time) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ System.out.println("Found " + size + " root paths"); //$NON-NLS-1$ //$NON-NLS-2$ int i = 0; for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) { System.out.println("root[" + i + "]=" + ((String) iterator.next()));//$NON-NLS-1$ //$NON-NLS-2$ i++; } } }
From source file:org.eclipse.che.jdt.refactoring.ccp.MoveTest.java
License:Open Source License
@Test public void testDestination_yes_cuToOtherPackageWithMultiRoot() throws Exception { ParticipantTesting.reset();// w w w .j av a 2s. c o m //regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47788 IPackageFragment otherPackage = getRoot().createPackageFragment("otherPackage", true, new NullProgressMonitor()); String oldA = "package p;public class A{}"; String newA = "package otherPackage;public class A{}"; ICompilationUnit cuA = getPackageP().createCompilationUnit("A.java", oldA, false, new NullProgressMonitor()); IPackageFragmentRoot testSrc = JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "testSrc"); ResourceChangedEvent event = new ResourceChangedEvent( new File(BaseTest.class.getResource("/projects").getFile()), new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.CREATED, "projects", testSrc.getJavaProject().getProject().getName(), testSrc.getResource().getFullPath().toOSString(), false)); JavaModelManager.getJavaModelManager().deltaState.resourceChanged(event); IPackageFragment testP = testSrc.createPackageFragment("p", true, new NullProgressMonitor()); String oldRef = "package p;\npublic class Ref { A t = new A(); }"; String newRef = "package p;\n\nimport otherPackage.A;\n\npublic class Ref { A t = new A(); }"; ICompilationUnit cuRef = testP.createCompilationUnit("Ref.java", oldRef, false, new NullProgressMonitor()); event = new ResourceChangedEvent(new File(BaseTest.class.getResource("/projects").getFile()), new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.CREATED, "projects", cuRef.getJavaProject().getProject().getName(), cuRef.getResource().getFullPath().toOSString(), false)); JavaModelManager.getJavaModelManager().deltaState.resourceChanged(event); IJavaElement[] javaElements = { cuA }; IResource[] resources = {}; String[] handles = ParticipantTesting .createHandles(new Object[] { cuA, cuA.getTypes()[0], cuA.getResource() }); JavaMoveProcessor processor = verifyEnabled(resources, javaElements, createReorgQueries()); Object destination = otherPackage; verifyValidDestination(processor, destination); assertTrue("source file does not exist before moving", cuA.exists()); RefactoringStatus status = performRefactoring(processor, true); assertEquals(null, status); assertTrue("source file exists after moving", !cuA.exists()); ICompilationUnit newCu = otherPackage.getCompilationUnit(cuA.getElementName()); assertTrue("new file does not exist after moving", newCu.exists()); assertEqualLines("source differs", newA, newCu.getSource()); assertEqualLines("Ref differs", newRef, cuRef.getSource()); ParticipantTesting.testMove(handles, new MoveArguments[] { new MoveArguments(otherPackage, processor.getUpdateReferences()), new MoveArguments(otherPackage, processor.getUpdateReferences()), new MoveArguments(otherPackage.getResource(), processor.getUpdateReferences()) }); }
From source file:org.eclipse.che.plugin.java.server.JavaNavigation.java
License:Open Source License
private List<PackageFragmentRoot> toPackageRoots(IJavaProject javaProject, boolean includePackages) throws JavaModelException { IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); List<PackageFragmentRoot> result = new ArrayList<>(); for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) { if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { PackageFragmentRoot root = DtoFactory.newDto(PackageFragmentRoot.class); root.setPath(packageFragmentRoot.getPath().toOSString()); root.setProjectPath(packageFragmentRoot.getJavaProject().getPath().toOSString()); if (includePackages) { root.setPackageFragments(toPackageFragments(packageFragmentRoot)); }//ww w .ja va 2 s. c o m result.add(root); } } return result; }
From source file:org.eclipse.che.plugin.maven.server.core.classpath.ClasspathManager.java
License:Open Source License
private boolean downloadSources(IPackageFragmentRoot fragmentRoot) throws JavaModelException { fragmentRoot.getAdapter(MavenArtifactKey.class); IClasspathEntry classpathEntry = fragmentRoot.getResolvedClasspathEntry(); MavenArtifactKey artifactKey = getArtifactKey(classpathEntry); if (artifactKey != null) { MavenServerWrapper mavenServer = wrapperManager.getMavenServer(MavenWrapperManager.ServerType.DOWNLOAD); try {//ww w . j ava 2s . co m mavenServer.customize(projectManager.copyWorkspaceCache(), terminal, notifier, false, false); MavenArtifactKey sourceKey = new MavenArtifactKey(artifactKey.getGroupId(), artifactKey.getArtifactId(), artifactKey.getVersion(), artifactKey.getPackaging(), SOURCES); MavenArtifact mavenArtifact = mavenServer.resolveArtifact(sourceKey, Collections.emptyList()); if (mavenArtifact.isResolved()) { updateClasspath(projectManager.findMavenProject(fragmentRoot.getJavaProject().getProject())); } return mavenArtifact.isResolved(); } finally { wrapperManager.release(mavenServer); } } return false; }