Example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment.

Prototype

IPackageFragment getPackageFragment(String packageName);

Source Link

Document

Returns the package fragment with the given package name.

Usage

From source file:org.parallelj.extensions.data.generator.wizard.dialog.PackageSelectionDialog.java

License:Open Source License

/**
 * Below method contains events when File Type selected as XML file
 * // ww w .j a  v  a 2s .  c  om
 * @param packageFragment
 *            :packageFragment contains a list of IPackageFragment
 */

private void eventsOnXMLFileSelection(java.util.List<IPackageFragment> packageFragment) {
    if (packageText.getText() == null || packageText.getText().length() == 0) {

        errorWarningLabel.setImage(Activator.getDefault().getImage(WizardConstants.ERROR_IMAGE));
        errorWarningLabel.setText(Messages.INVALID_XMLPACKAGE_ERROR.message());
        enableDisableOKButton(false);
    } else {
        errorWarningLabel.setImage(null);
        errorWarningLabel.setText(Messages.JAXBANNOTED_POJO_INFO.message());
        enableDisableOKButton(true);
        IFolder mainSourceFolder = javaProject.getProject().getFolder(WizardConstants.TARGET_PACKAGE_SOURCE);
        IPackageFragmentRoot mainPackageFragmentRoot = javaProject.getPackageFragmentRoot(mainSourceFolder);
        if (mainPackageFragmentRoot != null)
            dialogData.setPackageFragment(mainPackageFragmentRoot.getPackageFragment(packageText.getText()));
    }
}

From source file:org.sculptor.dsl.ui.resource.MavenClasspathUriResolver.java

License:Apache License

/**
 * Before forwarding to/*from www .j  a  v a2 s  . c o m*/
 * {@link JdtClasspathUriResolver#findResourceInWorkspace(IJavaProject, URI)}
 * this methods uses {@link #isMavenResourceDirectory(IPackageFragment)} to
 * check if the given classpath URI references a resource in an excluded
 * Maven resource directory.
 */
@Override
protected URI findResourceInWorkspace(IJavaProject javaProject, URI classpathUri) throws CoreException {
    if (javaProject.exists()) {
        String packagePath = classpathUri.trimSegments(1).path();
        String fileName = classpathUri.lastSegment();
        IPath filePath = new Path(fileName);
        String packageName = isEmpty(packagePath) ? "" : packagePath.substring(1).replace('/', '.');
        for (IPackageFragmentRoot packageFragmentRoot : javaProject.getAllPackageFragmentRoots()) {
            IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(packageName);
            if (isMavenResourceDirectory(packageFragment)) {
                IResource packageFragmentResource = packageFragment.getResource();
                if (packageFragmentResource instanceof IContainer) {
                    IFile file = ((IContainer) packageFragmentResource).getFile(filePath);
                    if (file.exists()) {
                        return createPlatformResourceURI(file);
                    }
                }
            }
        }
    }
    return super.findResourceInWorkspace(javaProject, classpathUri);
}

From source file:org.seasar.dbflute.emecha.eclipse.plugin.dfassist.link.SqlFileHyperlink.java

License:Apache License

private IStorage getSqlResource(IType type, String packageName, String typeQualifiedName) throws CoreException {
    IPackageFragmentRoot[] allPackageFragmentRoots = type.getJavaProject().getPackageFragmentRoots();
    for (IPackageFragmentRoot root : allPackageFragmentRoots) {
        IPackageFragment packageFragment = root.getPackageFragment(packageName);
        if (!packageFragment.exists()) {
            continue;
        }/*from   w w w .  j  a v a 2s  .  com*/
        IStorage sqlResource = searchPackageResource(packageFragment, typeQualifiedName);
        if (sqlResource != null) {
            return sqlResource;
        }
    }
    return null;
}

From source file:org.seasar.kijimuna.core.internal.dicon.model.autoregister.FileSystemComponentAutoRegister.java

License:Apache License

private void register(IPackageFragmentRoot root, ClassPattern pattern) throws Exception {

    String packageName = pattern.getPackageName();
    IPackageFragment fragment = root.getPackageFragment(packageName);
    if (fragment.exists()) {
        IJavaElement[] elements = fragment.getChildren();
        for (int i = 0; i < elements.length; i++) {
            if (elements[i] instanceof ICompilationUnit) {
                String sourceName = elements[i].getElementName();
                String className = sourceName.replaceFirst("\\.java$", "");
                processClass(packageName, className);
            }//  w w  w  .  j a v  a  2 s.c  o  m
        }
    }
}

From source file:org.seasar.s2junit4plugin.wizard.NewS2JUnit4TypeWizardPage.java

License:Apache License

protected IStatus containerChanged() {
    IStatus status = super.containerChanged();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    if ((fTypeKind == ANNOTATION_TYPE || fTypeKind == ENUM_TYPE) && !status.matches(IStatus.ERROR)) {
        if (root != null && !JavaModelUtil.is50OrHigher(root.getJavaProject())) {
            // error as createType will fail otherwise (bug 96928)
            return new StatusInfo(IStatus.ERROR,
                    Messages.format(NewWizardMessages.NewTypeWizardPage_warning_NotJDKCompliant,
                            root.getJavaProject().getElementName()));
        }//www  .j  a v a  2  s. c  o m
        if (fTypeKind == ENUM_TYPE) {
            try {
                // if findType(...) == null then Enum is unavailable
                if (findType(root.getJavaProject(), "java.lang.Enum") == null) //$NON-NLS-1$
                    return new StatusInfo(IStatus.WARNING,
                            NewWizardMessages.NewTypeWizardPage_warning_EnumClassNotFound);
            } catch (JavaModelException e) {
                JavaPlugin.log(e);
            }
        }
    }

    fCurrPackageCompletionProcessor.setPackageFragmentRoot(root);
    if (root != null) {
        fEnclosingTypeCompletionProcessor.setPackageFragment(root.getPackageFragment("")); //$NON-NLS-1$
    }
    return status;
}

From source file:org.seasar.s2junit4plugin.wizard.NewS2JUnit4TypeWizardPage.java

License:Apache License

/**
 * Creates the new type using the entered field values.
 * //www .  j av a  2 s . c o m
 * @param monitor a progress monitor to report progress.
 * @throws CoreException Thrown when the creation failed.
 * @throws InterruptedException Thrown when the operation was canceled.
 */
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }

    monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8);

    IPackageFragmentRoot root = getPackageFragmentRoot();
    IPackageFragment pack = getPackageFragment();
    if (pack == null) {
        pack = root.getPackageFragment(""); //$NON-NLS-1$
    }

    if (!pack.exists()) {
        String packName = pack.getElementName();
        pack = root.createPackageFragment(packName, true, new SubProgressMonitor(monitor, 1));
    } else {
        monitor.worked(1);
    }

    boolean needsSave;
    ICompilationUnit connectedCU = null;

    try {
        String typeName = getTypeNameWithoutParameters();

        boolean isInnerClass = isEnclosingTypeSelected();

        IType createdType;
        ImportsManager imports;
        int indent = 0;

        Set /* String (import names) */ existingImports;

        String lineDelimiter = null;
        if (!isInnerClass) {
            lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

            String cuName = getCompilationUnitName(typeName);
            ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, //$NON-NLS-1$
                    new SubProgressMonitor(monitor, 2));
            // create a working copy with a new owner

            needsSave = true;
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy
            connectedCU = parentCU;

            IBuffer buffer = parentCU.getBuffer();

            String simpleTypeStub = constructSimpleTypeStub();
            String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
            buffer.setContents(cuContent);

            CompilationUnit astRoot = createASTForImports(parentCU);
            existingImports = getExistingImports(astRoot);

            imports = new ImportsManager(astRoot);
            // add an import that will be removed again. Having this import solves 14661
            imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));

            String typeContent = null;
            if (isS2JUnit4()) {
                imports.addImport("org.junit.runner.RunWith");
                imports.addImport("org.seasar.framework.unit.Seasar2");
                typeContent = new StringBuffer("@RunWith(Seasar2.class)").append(lineDelimiter)
                        .append(constructTypeStub(parentCU, imports, lineDelimiter)).toString();

            } else {
                typeContent = constructTypeStub(parentCU, imports, lineDelimiter);
            }

            int index = cuContent.lastIndexOf(simpleTypeStub);
            if (index == -1) {
                AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
                int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
                int end = typeNode.getStartPosition() + typeNode.getLength();
                buffer.replace(start, end - start, typeContent);
            } else {
                buffer.replace(index, simpleTypeStub.length(), typeContent);
            }

            createdType = parentCU.getType(typeName);
        } else {
            IType enclosingType = getEnclosingType();

            ICompilationUnit parentCU = enclosingType.getCompilationUnit();

            needsSave = !parentCU.isWorkingCopy();
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy
            connectedCU = parentCU;

            CompilationUnit astRoot = createASTForImports(parentCU);
            imports = new ImportsManager(astRoot);
            existingImports = getExistingImports(astRoot);

            // add imports that will be removed again. Having the imports solves 14661
            IType[] topLevelTypes = parentCU.getTypes();
            for (int i = 0; i < topLevelTypes.length; i++) {
                imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
            }

            lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
            StringBuffer content = new StringBuffer();

            String comment = getTypeComment(parentCU, lineDelimiter);
            if (comment != null) {
                content.append(comment);
                content.append(lineDelimiter);
            }

            content.append(constructTypeStub(parentCU, imports, lineDelimiter));
            IJavaElement sibling = null;
            if (enclosingType.isEnum()) {
                IField[] fields = enclosingType.getFields();
                if (fields.length > 0) {
                    for (int i = 0, max = fields.length; i < max; i++) {
                        if (!fields[i].isEnumConstant()) {
                            sibling = fields[i];
                            break;
                        }
                    }
                }
            } else {
                IJavaElement[] elems = enclosingType.getChildren();
                sibling = elems.length > 0 ? elems[0] : null;
            }

            createdType = enclosingType.createType(content.toString(), sibling, false,
                    new SubProgressMonitor(monitor, 2));

            indent = StubUtility.getIndentUsed(enclosingType) + 1;
        }
        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // add imports for superclass/interfaces, so types can be resolved correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, new SubProgressMonitor(monitor, 1));

        JavaModelUtil.reconcile(cu);

        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // set up again
        CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));

        // add imports
        imports.create(false, new SubProgressMonitor(monitor, 1));

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

        IBuffer buf = cu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());
        Map options = pack.getJavaProject() != null ? pack.getJavaProject().getOptions(true) : null;
        String formattedContent = null;
        TextEdit edit = CodeFormatterUtil.format2(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, 0,
                originalContent.length(), indent, lineDelimiter, options);
        if (edit == null) {
            formattedContent = originalContent;
        } else {
            Document document = new Document(originalContent);
            try {
                edit.apply(document, TextEdit.NONE);
            } catch (BadLocationException e) {
                JavaPlugin.log(e); // bug in the formatter
                Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
            }
            formattedContent = document.get();
        }
        formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);
        if (!isInnerClass) {
            String fileComment = getFileComment(cu);
            if (fileComment != null && fileComment.length() > 0) {
                buf.replace(0, 0, fileComment + lineDelimiter);
            }
        }
        fCreatedType = createdType;

        if (needsSave) {
            cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
        } else {
            monitor.worked(1);
        }

    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
        monitor.done();
    }
}

From source file:org.sf.feeling.decompiler.util.SortMemberUtil.java

License:Open Source License

public static String sortMember(String packageName, String className, String code) {

    IPackageFragmentRoot sourceRootFragment = getDecompilerSourceFolder();
    if (sourceRootFragment == null)
        return code;

    try {//www .  j ava2  s .  c  om
        if (!sourceRootFragment.getJavaProject().isOpen()) {
            sourceRootFragment.getJavaProject().open(null);
        }

        if (!sourceRootFragment.getPackageFragment(packageName).exists()) {
            sourceRootFragment.createPackageFragment(packageName, false, null);
        }

        IPackageFragment packageFragment = sourceRootFragment.getPackageFragment(packageName);
        IProject project = sourceRootFragment.getJavaProject().getProject();
        IFolder sourceFolder = project.getFolder("src"); //$NON-NLS-1$

        long time = System.currentTimeMillis();

        String javaName = className.replaceAll("(?i)\\.class", //$NON-NLS-1$
                time + ".java"); //$NON-NLS-1$
        File locationFile = new File(sourceFolder.getFile(javaName).getLocation().toString());

        IFile javaFile = sourceFolder.getFile(javaName);

        if (!locationFile.getParentFile().exists()) {
            locationFile.getParentFile().mkdirs();
        }

        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(locationFile, false)));
        writer.println(code);
        writer.close();

        javaFile.refreshLocal(0, null);

        ICompilationUnit iCompilationUnit = packageFragment.getCompilationUnit(locationFile.getName());
        iCompilationUnit.makeConsistent(null);
        iCompilationUnit.getResource().setLocalTimeStamp(new Date().getTime());
        iCompilationUnit.becomeWorkingCopy(null);
        new SortMembersOperation(iCompilationUnit, null, true).run(null);
        iCompilationUnit.commitWorkingCopy(true, null);
        iCompilationUnit.save(null, true);
        String content = iCompilationUnit.getSource();
        iCompilationUnit.delete(true, null);
        iCompilationUnit.destroy();
        if (content != null)
            code = content;
        packageFragment.getJavaProject().close();
    } catch (IOException e) {
        JavaDecompilerPlugin.logError(e, ""); //$NON-NLS-1$
    } catch (CoreException e) {
        JavaDecompilerPlugin.logError(e, ""); //$NON-NLS-1$
    }
    return code;
}

From source file:org.springframework.ide.eclipse.beans.ui.editor.util.BeansJavaCompletionUtils.java

License:Open Source License

private static IPackageFragment getPackageFragment(IJavaProject project, String prefix)
        throws JavaModelException {
    int dot = prefix.lastIndexOf('.');
    if (dot > -1) {
        String packageName = prefix.substring(0, dot);
        for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
            IPackageFragment p = root.getPackageFragment(packageName);
            if (p != null && p.exists()) {
                return p;
            }/*from w w  w.  j av  a2s.  c o  m*/
        }
        IPackageFragment[] packages = project.getPackageFragments();
        for (IPackageFragment p : packages) {
            if (p.getElementName().equals(packageName))
                return p;
        }
    } else {
        for (IPackageFragmentRoot p : project.getAllPackageFragmentRoots()) {
            if (p.getKind() == IPackageFragmentRoot.K_SOURCE) {
                return p.getPackageFragment("");
            }
        }
    }
    return project.getPackageFragments()[0];
}

From source file:org.springframework.ide.eclipse.beans.ui.namespaces.DefaultNamespaceDefinition.java

License:Open Source License

private String getDefaultSchemaLocationFromClasspath(IResource resource) {
    IJavaProject jp = JdtUtils.getJavaProject(resource);
    Set<String> existingLocations = new HashSet<String>();
    try {//from  w w w.j ava2s  .  c o  m
        for (Map.Entry<Object, Object> entry : uriMapping.entrySet()) {

            // Check that we are looking for relevant entries only; e.g. util, tool and beans are in the same
            // package
            if (((String) entry.getKey()).startsWith(uri)) {
                String fileLocation = (String) entry.getValue();

                // Get the package name from the location
                String packageName = "";
                int ix = fileLocation.lastIndexOf('/');
                if (ix > 0) {
                    packageName = fileLocation.substring(0, ix).replace('/', '.');
                }

                // Search in all project packages
                for (IPackageFragmentRoot root : jp.getPackageFragmentRoots()) {
                    IPackageFragment pf = root.getPackageFragment(packageName);
                    if (pf.exists()) {
                        for (Object obj : pf.getNonJavaResources()) {
                            // Entry is coming from a JAR file on the classpath
                            if (obj instanceof JarEntryFile
                                    && ("/" + fileLocation)
                                            .equals((((JarEntryFile) obj).getFullPath().toString()))
                                    && locations.contains(entry.getKey())) {
                                existingLocations.add((String) entry.getKey());
                            }
                            // Entry is coming from the local project
                            else if (obj instanceof IFile && fileLocation.equals(
                                    pf.getElementName().replace('.', '/') + "/" + ((IFile) obj).getName())
                                    && locations.contains(entry.getKey())) {
                                existingLocations.add((String) entry.getKey());
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // We have a safe fall-back
    }

    // Search for the highest version among the existing resources
    String highestLocation = null;
    Version version = Version.MINIMUM_VERSION;
    for (String location : existingLocations) {
        Version tempVersion = Version.MINIMUM_VERSION;
        Matcher matcher = VERSION_PATTERN.matcher(location);
        if (matcher.matches()) {
            tempVersion = new Version(matcher.group(1));
        }
        if (tempVersion.compareTo(version) >= 0) {
            version = tempVersion;
            highestLocation = location;
        }
    }
    return highestLocation;
}

From source file:org.springframework.ide.eclipse.core.io.EclipsePathMatchingResourcePatternResolver.java

License:Open Source License

private Resource processRawResource(IPackageFragmentRoot[] roots, Resource resource)
        throws IOException, JavaModelException {
    if (resource instanceof FileSystemResource) {
        // This can only be something in the Eclipse workspace

        // first check the location in the project that this pattern resolver is associated with (most likely path)
        Path path = new Path(((FileSystemResource) resource).getPath());
        IPath projectLocation = this.project.getLocation();
        if (projectLocation.isPrefixOf(path)) {
            int segmentsToRemove = projectLocation.segmentCount();
            IPath projectRelativePath = path.removeFirstSegments(segmentsToRemove);
            IFile file = this.project.getFile(projectRelativePath);
            if (file != null && file.exists()) {
                return new FileResource(file);
            }/*from w w w. ja va  2s  .  c  o  m*/
        }

        // then check the simple getFileForLocation (faster in case it is not a linked resource)
        IFile fileForLocation = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
        if (fileForLocation != null) {
            return new FileResource(fileForLocation);
        }

        // fall back to full resolution via findFilesForLocationURI
        IResource[] allResourcesFor = ResourcesPlugin.getWorkspace().getRoot()
                .findFilesForLocationURI(resource.getURI());
        for (IResource res : allResourcesFor) {
            return new FileResource((IFile) res);
        }
    } else if (resource instanceof UrlResource) {
        URL url = resource.getURL();
        String path = url.getPath();
        int ix = path.indexOf('!');
        if (ix > 0) {
            String entryName = path.substring(ix + 1);
            path = path.substring(0, ix);

            try {
                return new ExternalFile(new File(new URI(path)), entryName, project);
            } catch (URISyntaxException e) {
            }
        } else {
            IResource[] allResourcesFor = ResourcesPlugin.getWorkspace().getRoot()
                    .findFilesForLocationURI(resource.getURI());
            for (IResource res : allResourcesFor) {
                return new FileResource((IFile) res);
            }
        }
    } else if (resource instanceof ClassPathResource) {
        String path = ((ClassPathResource) resource).getPath();
        String fileName = path;
        String packageName = "";
        int ix = path.lastIndexOf('/');
        if (ix > 0) {
            fileName = path.substring(ix + 1);
            packageName = path.substring(0, ix).replace('/', '.');
        }
        if (fileName.endsWith(ClassUtils.CLASS_FILE_SUFFIX)) {
            String typeName = packageName + "." + fileName.substring(0, fileName.length() - 6);
            for (IPackageFragmentRoot root : roots) {
                Resource storage = null;

                if ("".equals(packageName) && root.exists()) {
                    storage = processClassResource(path, fileName, typeName, root, root.getChildren());
                }

                IPackageFragment packageFragment = root.getPackageFragment(packageName);
                if (storage == null && packageFragment != null && packageFragment.exists()) {
                    storage = processClassResource(path, fileName, typeName, root,
                            packageFragment.getChildren());
                }

                if (storage != null) {
                    return storage;
                }
            }
        }

        else {
            for (IPackageFragmentRoot root : roots) {
                IStorage storage = null;

                // Look in the root of the package fragment root
                if ("".equals(packageName) && root.exists()) {
                    storage = contains(root.getNonJavaResources(), fileName);
                }

                // Check the package
                IPackageFragment packageFragment = root.getPackageFragment(packageName);
                if (storage == null && packageFragment != null && packageFragment.exists()) {
                    storage = contains(packageFragment.getNonJavaResources(), fileName);
                }

                // Check the root folder in case no package exists 
                if (storage == null) {
                    IResource rootResource = root.getUnderlyingResource();
                    if (rootResource instanceof IFolder) {
                        IFile file = ((IFolder) rootResource).getFile(path);
                        if (file.exists()) {
                            storage = file;
                        }
                    }
                }

                // Found the resource in the package fragment root? -> construct usable Resource
                if (storage != null) {
                    if (storage instanceof IFile) {
                        return new FileResource((IFile) storage);
                    } else if (storage instanceof IJarEntryResource) {

                        // Workspace jar or resource
                        if (root.getResource() != null) {
                            return new StorageResource(new ZipEntryStorage((IFile) root.getResource(),
                                    ((IJarEntryResource) storage).getFullPath().toString()), project);
                        }
                        // Workspace external jar
                        else {
                            File jarFile = root.getPath().toFile();
                            return new ExternalFile(jarFile,
                                    ((IJarEntryResource) storage).getFullPath().toString(), project);
                        }
                    }
                }
            }
        }
    }
    return null;
}