List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPath
IPath getPath();
From source file:org.eclipse.jdt.internal.core.search.matching.MatchLocator.java
License:Open Source License
public static ClassFileReader classFileReader(IType type) { IClassFile classFile = type.getClassFile(); JavaModelManager manager = JavaModelManager.getJavaModelManager(); if (classFile.isOpen()) return (ClassFileReader) manager.getInfo(type); PackageFragment pkg = (PackageFragment) type.getPackageFragment(); IPackageFragmentRoot root = (IPackageFragmentRoot) pkg.getParent(); try {/*from w ww .ja v a 2 s. c o m*/ if (!root.isArchive()) return Util.newClassFileReader(((JavaElement) type).resource()); ZipFile zipFile = null; try { IPath zipPath = root.getPath(); if (JavaModelManager.ZIP_ACCESS_VERBOSE) System.out.println("(" + Thread.currentThread() //$NON-NLS-1$ + ") [MatchLocator.classFileReader()] Creating ZipFile on " + zipPath); //$NON-NLS-1$ zipFile = manager.getZipFile(zipPath); String classFileName = classFile.getElementName(); String path = Util.concatWith(pkg.names, classFileName, '/'); return ClassFileReader.read(zipFile, path); } finally { manager.closeZipFile(zipFile); } } catch (ClassFormatException e) { // invalid class file: return null } catch (CoreException e) { // cannot read class file: return null } catch (IOException e) { // cannot read class file: return null } return null; }
From source file:org.eclipse.jdt.internal.core.SourceMapper.java
License:Open Source License
private synchronized void computeAllRootPaths(IType type) { if (this.areRootPathsComputed) { return;/*from w w w. j a va 2s . c om*/ } 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()) { JavaModelManager manager = 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 (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 = JavaConventions.validatePackageName(firstLevelPackageName, sourceLevel, complianceLevel); if (status.isOK() || status.getSeverity() == IStatus.WARNING) { firstLevelPackageNames.add(firstLevelPackageName); } } } else { containsADefaultPackage = true; } } else if (!containsJavaSource && org.eclipse.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 (Util.isClassFileName(resourceName)) { containsADefaultPackage = true; } else if (!containsJavaSource && org.eclipse.jdt.internal.core.util.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() && org.eclipse.jdt.internal.core.util.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.jem.internal.beaninfo.core.BeanInfoCacheController.java
License:Open Source License
private synchronized RootIndex getRootIndex(IPackageFragmentRoot root, IProject project) { Index index = project != null ? getProjectIndex(project) : getMainIndex(); IPath rootPath = root.getPath(); RootIndex rootIndex = (RootIndex) index.rootToRootIndex.get(rootPath); if (rootIndex == null) { // Need to do a new root path. String rootName = ROOT_PREFIX + (++index.highRootNumber); rootIndex = root.isArchive() ? createArchiveRootIndex(root, rootName, index) : new FolderRootIndex(rootName, index); index.rootToRootIndex.put(rootPath, rootIndex); // Don't set index dirty until we actually save a class cache file. Until then it only needs to be in memory. }//w w w . j a va 2s .c o m rootIndex.setupIndex(project); // Set it up, or may already be set, so it will do nothing in that case. return rootIndex; }
From source file:org.eclipse.jem.internal.beaninfo.core.BeanInfoCacheController.java
License:Open Source License
private RootIndex createArchiveRootIndex(IPackageFragmentRoot rootArchive, String rootName, Index index) { long modStamp = IResource.NULL_STAMP; if (rootArchive.isExternal()) { modStamp = rootArchive.getPath().toFile().lastModified(); } else {/* ww w . java2 s. com*/ try { modStamp = rootArchive.getUnderlyingResource().getModificationStamp(); } catch (JavaModelException e) { BeaninfoPlugin.getPlugin().getLogger().log(e); } } return new ArchiveRootIndex(rootName, modStamp, index); }
From source file:org.eclipse.jpt.jpa.ui.internal.wizards.gen.DefaultTableGenerationWizardPage.java
License:Open Source License
private IPackageFragmentRoot getSourceFolder(String srcFolder) { IPackageFragmentRoot packageFragmentRoot = null; srcFolder = '/' + srcFolder; IJavaProject javaProject = this.jpaProject.getJavaProject(); for (IPackageFragmentRoot root : JavaProjectTools.getSourceFolders(javaProject)) { //Save the first source root in case we don't find one that matches the saved value if (packageFragmentRoot == null) { packageFragmentRoot = root;/*from w w w . j ava 2s. c o m*/ } //check for alternative source root that matches the saved value if (root.getPath().toString().equals(srcFolder)) { packageFragmentRoot = root; break; } } return packageFragmentRoot; }
From source file:org.eclipse.jpt.jpa.ui.internal.wizards.gen.GenerateEntitiesFromSchemaWizard.java
License:Open Source License
/** * Create the ORMGenCustomizer when user selects a new connection profile and schema * /*from ww w. j a v a 2s.c o m*/ * JpaPlatform implementor can provide a custom ORMGenCustomizer specific to a platform * with AdapterFactory through Eclipse org.eclipse.core.runtime.adapters extension point: * <pre> * *<extension * point="org.eclipse.core.runtime.adapters"> * <factory * adaptableType="org.eclipse.jpt.jpa.eclipselink.core.internal.EclipseLinkPlatform" * class="oracle.eclipse.tools.orm.internal.EclipseLinkORMGenCustomizerAdapterFactory"> * <adapter * type="oracle.eclipse.tools.orm.internal.ORMGenCustomizer"> * </adapter> * </factory> *</extension> *</pre> * * @param schema */ public ORMGenCustomizer createORMGenCustomizer(Schema schema) { JpaPlatform jpaPlatform = this.jpaProject.getJpaPlatform(); ORMGenCustomizer obj = PlatformTools.getAdapter(jpaPlatform, ORMGenCustomizer.class); if (obj != null) { this.customizer = (ORMGenCustomizer) obj; this.customizer.init(this.getCustomizationFile(), schema); } else { this.customizer = new BaseEntityGenCustomizer(); this.customizer.init(this.getCustomizationFile(), schema); } ORMGenTable newDefaultTable = this.getCustomizer().createGenTable(null); if (this.selection != null && this.selection.getFirstElement() instanceof IPackageFragment) { IPackageFragment packageFrag = (IPackageFragment) this.selection.getFirstElement(); newDefaultTable.setPackage(packageFrag.getElementName()); for (IPackageFragmentRoot root : JavaProjectTools.getSourceFolders(this.jpaProject.getJavaProject())) { String srcFolder = root.getPath().toPortableString(); if (packageFrag.getPath().toPortableString().startsWith(srcFolder + '/')) { newDefaultTable.setSourceFolder(srcFolder.substring(1)); } } } else if (newDefaultTable.getPackage().equals(StringTools.EMPTY_STRING)) { newDefaultTable.setPackage(JpaPreferences.getEntityGenDefaultPackageName(this.jpaProject.getProject())); } return this.customizer; }
From source file:org.eclipse.jst.j2ee.classpathdep.ClasspathDependencyUtil.java
License:Open Source License
/** * Returns all resolved classpath entries for the specified Java project that * have one of the special WTP classpath component dependency attributes. * /* www . ja va 2 s. c o m*/ * @param javaProject Java project whose component classpath dependencies are being retrieved. * @param isWebApp True if the target project is associated with a web project. * @param onlyValid If true, only valid dependencies will be returned. If false, the raw entry must be valid but the * resolved can be invalid. * @return Map from IClasspathEntry to IClasspathAttribute for classpath component dependencies. * @throws CoreException Thrown if an error is encountered accessing the unresolved classpath. */ public static Map<IClasspathEntry, IClasspathAttribute> getComponentClasspathDependencies( final IJavaProjectLite javaProjectLite, final boolean isLegacyJ2EE, final boolean onlyValid) throws CoreException { final ClasspathDependencyValidatorData data = new ClasspathDependencyValidatorData( javaProjectLite.getProject()); final boolean isWebApp = JavaEEProjectUtilities.isDynamicWebProject(javaProjectLite.getProject()); // get the raw entries final Map<IClasspathEntry, IClasspathAttribute> referencedRawEntries = getRawComponentClasspathDependencies( javaProjectLite, DependencyAttributeType.CLASSPATH_COMPONENT_DEPENDENCY, isLegacyJ2EE); final Map<IClasspathEntry, IClasspathAttribute> validRawEntries = new HashMap<IClasspathEntry, IClasspathAttribute>(); final Map<IClasspathEntry, IClasspathAttribute> validRawClassPathContainerEntries = new HashMap<IClasspathEntry, IClasspathAttribute>(); // filter out non-valid referenced raw entries final Iterator<IClasspathEntry> i = referencedRawEntries.keySet().iterator(); while (i.hasNext()) { final IClasspathEntry entry = i.next(); final IClasspathAttribute attrib = referencedRawEntries.get(entry); if (isValid(entry, attrib, isWebApp, javaProjectLite.getProject(), data)) { if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { //Put in a separate map the classpath container entries, since they will be handled differently validRawClassPathContainerEntries.put(entry, attrib); } else { validRawEntries.put(entry, attrib); } } } // if we have no valid raw entries, return empty map if (validRawEntries.isEmpty() && validRawClassPathContainerEntries.isEmpty()) { return Collections.emptyMap(); } // XXX Would like to replace the code below with use of a public JDT API that returns // the raw IClasspathEntry for a given resolved IClasspathEntry (see see https://bugs.eclipse.org/bugs/show_bug.cgi?id=183995) // The code must currently leverage IPackageFragmentRoot to determine this // mapping and, because IPackageFragmentRoots do not maintain IClasspathEntry data, a prior // call is needed to getResolvedClasspath() and the resolved IClasspathEntries have to be stored in a Map from IPath-to-IClasspathEntry to // support retrieval using the resolved IPackageFragmentRoot // retrieve the resolved classpath //TODO this call to javaProject needs to be removed. Need to figure out what exactly this is attempting to do. IJavaProject javaProject = JavaCore.create(javaProjectLite.getProject()); //TODO this call to javaProject needs to be removed. Need to figure out what exactly this is attempting to do. final IClasspathEntry[] entries = javaProject.getResolvedClasspath(true); final Map<IPath, IClasspathEntry> pathToResolvedEntry = new HashMap<IPath, IClasspathEntry>(); // store in a map from path to entry for (int j = 0; j < entries.length; j++) { pathToResolvedEntry.put(entries[j].getPath(), entries[j]); } //Gather all resolved entries from the package roots and the classpath containers final Map<IClasspathEntry, IClasspathAttribute> resolvedEntries = new LinkedHashMap<IClasspathEntry, IClasspathAttribute>(); // grab all IPackageFragmentRoots // TODO this ignores project cp entries; can easily add in the raw project cp entries, however, do not have a good way to // map project cp entries resolved from cp containers back to the corresponding raw entry (and thereby determine if the // entry has the publish/export attribute) //TODO this call to javaProject needs to be removed. Need to figure out what exactly this is attempting to do. final IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots(); for (IPackageFragmentRoot root : roots) { final IClasspathEntry rawEntry = root.getRawClasspathEntry(); // is the raw entry valid? IClasspathAttribute attrib = validRawEntries.get(rawEntry); if (attrib == null) { continue; } final IPath pkgFragPath = root.getPath(); final IClasspathEntry resolvedEntry = pathToResolvedEntry.get(pkgFragPath); resolvedEntries.put(resolvedEntry, attrib); } // Add entries coming from classpath containers to the list of resolved entries for (Map.Entry<IClasspathEntry, IClasspathAttribute> entry : validRawClassPathContainerEntries.entrySet()) { IClasspathContainer classpathContainer = JavaCore.getClasspathContainer(entry.getKey().getPath(), javaProject); if (classpathContainer != null) { IClasspathEntry[] classpathContainerEntries = classpathContainer.getClasspathEntries(); if (classpathContainerEntries != null) { for (int j = 0; j < classpathContainerEntries.length; j++) { resolvedEntries.put(classpathContainerEntries[j], entry.getValue()); } } } } //Setup the final result final Map<IClasspathEntry, IClasspathAttribute> referencedEntries = new LinkedHashMap<IClasspathEntry, IClasspathAttribute>(); for (Map.Entry<IClasspathEntry, IClasspathAttribute> mapEntry : resolvedEntries.entrySet()) { final IClasspathEntry resolvedEntry = mapEntry.getKey(); IClasspathAttribute attrib = mapEntry.getValue(); final IClasspathAttribute resolvedAttrib = checkForComponentDependencyAttribute(resolvedEntry, DependencyAttributeType.DEPENDENCY_OR_NONDEPENDENCY, isLegacyJ2EE); // attribute for the resolved entry must either be unspecified or it must be the // dependency attribute for it to be included if (resolvedAttrib == null || resolvedAttrib.getName().equals(CLASSPATH_COMPONENT_DEPENDENCY)) { // filter out resolved entry if it doesn't pass the validation rules if (!onlyValid || isValid(resolvedEntry, resolvedAttrib != null ? resolvedAttrib : attrib, isWebApp, javaProjectLite.getProject(), data)) { if (resolvedAttrib != null) { // if there is an attribute on the sub-entry, use that attrib = resolvedAttrib; } referencedEntries.put(resolvedEntry, attrib); } } } return referencedEntries; }
From source file:org.eclipse.jst.j2ee.internal.dialogs.TypeJavaSearchScope.java
License:Open Source License
public void add(IJavaElement element) throws JavaModelException { IPackageFragmentRoot root = null; switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: // a workspace sope should be used break;/*www.j a v a 2s . co m*/ case IJavaElement.JAVA_PROJECT: this.add((IJavaProject) element, true, new HashSet(2)); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: root = (IPackageFragmentRoot) element; this.add(root.getPath(), true); break; case IJavaElement.PACKAGE_FRAGMENT: root = (IPackageFragmentRoot) element.getParent(); if (root.isArchive()) { this.add(root.getPath().append(new Path(element.getElementName().replace('.', '/'))), false); } else { IResource resource = element.getUnderlyingResource(); if (resource != null && resource.isAccessible()) { this.add(resource.getFullPath(), false); } } break; default: // remember sub-cu (or sub-class file) java elements if (element instanceof IMember) { if (this.elements == null) { this.elements = new ArrayList(); } this.elements.add(element); } this.add(this.fullPath(element), true); // find package fragment root including this java element IJavaElement parent = element.getParent(); while (parent != null && !(parent instanceof IPackageFragmentRoot)) { parent = parent.getParent(); } if (parent instanceof IPackageFragmentRoot) { root = (IPackageFragmentRoot) parent; } } if (root != null) { if (root.getKind() == IPackageFragmentRoot.K_BINARY) { this.addEnclosingProjectOrJar(root.getPath()); } else { this.addEnclosingProjectOrJar(root.getJavaProject().getProject().getFullPath()); } } }
From source file:org.eclipse.jst.j2ee.internal.wizard.NewJavaClassWizardPage.java
License:Open Source License
/** * Add folder group to composite/* w w w. jav a2 s . com*/ */ private void addFolderGroup(Composite composite) { // folder Label folderLabel = new Label(composite, SWT.LEFT); folderLabel.setText(J2EEUIMessages.FOLDER_LABEL); folderLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); folderText = new Text(composite, SWT.SINGLE | SWT.BORDER); folderText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); synchHelper.synchText(folderText, INewJavaClassDataModelProperties.SOURCE_FOLDER, null); IPackageFragmentRoot root = getSelectedPackageFragmentRoot(); String projectName = model.getStringProperty(IArtifactEditOperationDataModelProperties.PROJECT_NAME); if (projectName != null && projectName.length() > 0) { IProject targetProject = ProjectUtilities.getProject(projectName); if (root == null || !root.getJavaProject().getProject().equals(targetProject) || root.isArchive()) { IFolder folder = getDefaultJavaSourceFolder(targetProject); if (folder != null) folderText.setText(folder.getFullPath().toOSString()); } else { folderText.setText(root.getPath().toString()); } } folderButton = new Button(composite, SWT.PUSH); folderButton.setText(J2EEUIMessages.BROWSE_BUTTON_LABEL_O); folderButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); folderButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { handleFolderButtonPressed(); } public void widgetDefaultSelected(SelectionEvent e) { // Do nothing } }); }
From source file:org.eclipse.jst.j2ee.internal.wizard.NewJavaClassWizardPage.java
License:Open Source License
/** * Add package group to composite/*from w ww.ja v a2 s. c o m*/ */ private void addPackageGroup(Composite composite) { // package packageLabel = new Label(composite, SWT.LEFT); packageLabel.setText(J2EEUIMessages.JAVA_PACKAGE_LABEL); packageLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); packageText = new Text(composite, SWT.SINGLE | SWT.BORDER); packageText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); synchHelper.synchText(packageText, INewJavaClassDataModelProperties.JAVA_PACKAGE, null); IPackageFragment packageFragment = getSelectedPackageFragment(); String targetProject = model.getStringProperty(IArtifactEditOperationDataModelProperties.PROJECT_NAME); if (packageFragment != null && packageFragment.exists() && packageFragment.getJavaProject().getElementName().equals(targetProject)) { IPackageFragmentRoot root = getPackageFragmentRoot(packageFragment); if (root != null) folderText.setText(root.getPath().toString()); model.setProperty(INewJavaClassDataModelProperties.JAVA_PACKAGE, packageFragment.getElementName()); } packageButton = new Button(composite, SWT.PUSH); packageButton.setText(J2EEUIMessages.BROWSE_BUTTON_LABEL_W); packageButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); packageButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { handlePackageButtonPressed(); } public void widgetDefaultSelected(SelectionEvent e) { // Do nothing } }); }