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

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

Introduction

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

Prototype

IJavaProject getJavaProject();

Source Link

Document

Returns the Java project this element is contained in, or null if this element is not contained in any Java project (for instance, the IJavaModel is not contained in any Java project).

Usage

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

License:Apache License

/**
 * The method is called when the container has changed to validate if the project
 * is suited for the JUnit test class. Clients can override to modify or remove that validation.
 * /* w  w  w  .  java  2s . co  m*/
 * @return the status of the validation
 */
protected IStatus validateIfJUnitProject() {
    JUnitStatus status = new JUnitStatus();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    if (root != null) {
        try {
            IJavaProject project = root.getJavaProject();
            if (project.exists()) {
                if (isJUnit4()) {
                    if (!S2JUnit4StubUtility.is50OrHigher(project)) {
                        status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java5required);
                        return status;
                    }
                    if (project.findType(JUnitPlugin.JUNIT4_ANNOTATION_NAME) == null) {
                        status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit4NotOnbuildpath);
                        return status;
                    }
                } else {
                    if (project.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) == null) {
                        status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_junitNotOnbuildpath);
                        return status;
                    }
                }
            }
        } catch (JavaModelException e) {
        }
    }
    return status;
}

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()));
        }//from  w  w  w .  j a  v  a2s  .co 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

/**
 * 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>/*from w  w w.  j  a v a  2s  . c o  m*/
 * 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, intfname));
                return status;
            }
            if (type instanceof ParameterizedType && !JavaModelUtil.is50OrHigher(root.getJavaProject())) {
                status.setError(Messages.format(
                        NewWizardMessages.NewTypeWizardPage_error_SuperInterfaceNotParameterized, intfname));
                return status;
            }
        }
    }
    return status;
}

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 {//from  ww w  . j  a  v  a  2  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.BeansEditorUtils.java

License:Open Source License

/**
 * Returns the file the given document was read from.
 *///from   w  ww .ja v  a  2s.  co  m
public static final IFile getFile(IDocument document) {
    IFile resource = null;
    String baselocation = null;
    if (document != null) {
        IStructuredModel model = null;
        try {
            model = org.eclipse.wst.sse.core.StructuredModelManager.getModelManager()
                    .getExistingModelForRead(document);
            if (model != null) {
                baselocation = model.getBaseLocation();
            }
        } finally {
            if (model != null) {
                model.releaseFromRead();
            }
        }
    }
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    if (baselocation != null) {
        IPath path = new Path(baselocation);
        if (root.exists(path) && path.segmentCount() > 1) {
            resource = root.getFile(path);
        } else {
            // This is a fallback for XML stored in a jar or zip files
            IEditorPart editor = SpringUIUtils.getActiveEditor();
            IEditorInput input = editor.getEditorInput();
            if (input instanceof IFileEditorInput) {
                resource = ((IFileEditorInput) input).getFile();
            } else if (input instanceof ZipEntryEditorInput) {
                resource = (IFile) ((ZipEntryEditorInput) input).getAdapter(IFile.class);
            } else if (input instanceof JarEntryEditorInput) {
                JarEntryFile jarFile = (JarEntryFile) ((JarEntryEditorInput) input).getStorage();
                IPackageFragmentRoot jarPackageFragmentRoot = jarFile.getPackageFragmentRoot();
                resource = jarPackageFragmentRoot.getJavaProject().getProject().getFile(".project");
            }
        }
    }
    return resource;
}

From source file:org.springframework.ide.eclipse.beans.ui.properties.NonJavaResourceContentProvider.java

License:Open Source License

protected boolean isInternalLibrary(IJavaProject project, IPackageFragmentRoot root) {
    if (root.isArchive()) {
        IResource resource = root.getResource();
        if (resource != null) {
            IProject jarProject = resource.getProject();
            IProject container = root.getJavaProject().getProject();
            return container.equals(jarProject);
        }/*from   w  ww .j a v  a 2  s. co m*/
        return false;
    }
    return true;
}

From source file:org.springframework.ide.eclipse.boot.dash.cloudfoundry.JavaPackageFragmentRootHandler.java

License:Open Source License

/**
 *
 * Determines if the given package fragment root corresponds to the class
 * path entry path.//w w  w  .j av  a2  s .  c om
 * <p/>
 * Note that different package fragment roots may point to the same class
 * path entry.
 * <p/>
 * Example:
 * <p/>
 * A Java project may have the following package fragment roots:
 * <p/>
 * - src/main/java
 * <p/>
 * - src/main/resources
 * <p/>
 * Both may be using the same output folder:
 * <p/>
 * target/classes.
 * <p/>
 * In this case, the output folder will have a class path entry -
 * target/classes - and it will be the same for both roots, and this method
 * will return true for both roots if passed the entry for target/classes
 *
 * @param root
 *            to check if it corresponds to the given class path entry path
 * @param entry
 * @return true if root is at the given entry
 */
private static boolean isRootAtEntry(IPackageFragmentRoot root, IPath entry) {
    try {
        IClasspathEntry cpe = root.getRawClasspathEntry();
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath outputLocation = cpe.getOutputLocation();
            if (outputLocation == null) {
                outputLocation = root.getJavaProject().getOutputLocation();
            }

            IPath location = ResourcesPlugin.getWorkspace().getRoot().findMember(outputLocation).getLocation();
            if (entry.equals(location)) {
                return true;
            }
        }
    } catch (JavaModelException e) {
        BootDashActivator.log(e);
    }

    IResource resource = root.getResource();
    if (resource != null && entry.equals(resource.getLocation())) {
        return true;
    }

    IPath path = root.getPath();
    if (path != null && entry.equals(path)) {
        return true;
    }

    return false;
}

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

License:Open Source License

private Resource processClassResource(String path, String fileName, String typeName, IPackageFragmentRoot root,
        IJavaElement[] children) throws JavaModelException {
    for (IJavaElement je : children) {
        if (je instanceof ICompilationUnit) {
            for (IType type : ((ICompilationUnit) je).getAllTypes()) {
                if (type.getFullyQualifiedName('$').equals(typeName)) {
                    if (root.getRawClasspathEntry().getEntryKind() == IClasspathEntry.CPE_SOURCE) {

                        IPath outputLocation = root.getRawClasspathEntry().getOutputLocation();
                        if (outputLocation == null) {
                            outputLocation = root.getJavaProject().getOutputLocation();
                        }/*from  w  w w  . ja va 2s. c  om*/
                        IResource classResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(outputLocation.append(path));
                        if (classResource != null) {
                            return new FileResource((IFile) classResource);
                        }
                    }
                }
            }
        } else if (je instanceof IClassFile) {
            if (((IClassFile) je).getElementName().equals(fileName)) {
                // Workspace jar or resource
                if (root.getResource() != null) {
                    return new StorageResource(new ZipEntryStorage((IFile) root.getResource(), path), project);
                }
                // Workspace external jar
                else {
                    File jarFile = root.getPath().toFile();
                    return new ExternalFile(jarFile, path, project);
                }
            }
        }
    }
    return null;
}

From source file:org.springframework.tooling.jdt.ls.commons.java.JavaData.java

License:Open Source License

private ClasspathEntryData createClasspathEntryData(IMember member) {
    ClasspathEntryData data = new ClasspathEntryData();

    IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) member
            .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    if (packageFragmentRoot != null) {
        try {//  w  w w  . j  av a2 s . co m
            IClasspathEntry entry = packageFragmentRoot.getResolvedClasspathEntry();
            if (entry != null) {
                List<CPE> cpes = ClasspathUtil.createCpes(packageFragmentRoot.getJavaProject(), entry);
                Assert.isTrue(cpes.size() < 2);
                if (!cpes.isEmpty()) {
                    data.setCpe(cpes.get(0));
                }
            }
        } catch (JavaModelException | MalformedURLException e) {
            logger.log(e);
        }
    }

    ITypeRoot typeRoot = member.getTypeRoot();
    try {
        if (typeRoot != null && typeRoot.getModule() != null) {
            data.setModule(typeRoot.getModule().getElementName());
        }
    } catch (JavaModelException e) {
        logger.log(e);
    }

    return data;
}

From source file:org.summer.dsl.builder.impl.javasupport.ProjectClasspathChangeListener.java

License:Open Source License

protected Set<IJavaProject> getJavaProjectsWithClasspathChange(IJavaElementDelta delta) {
    IJavaElement element = delta.getElement();
    if (element instanceof IPackageFragmentRoot) {
        IPackageFragmentRoot root = (IPackageFragmentRoot) element;
        if (delta.getKind() == IJavaElementDelta.REMOVED || delta.getKind() == IJavaElementDelta.ADDED
                || (delta.getFlags() & IJavaElementDelta.F_REORDER) != 0
                || (delta.getFlags() & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0
                || (delta.getFlags() & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0
                || (root.isExternal() && (delta.getFlags() & // external folders change
                        (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_SOURCEATTACHED
                                | IJavaElementDelta.F_SOURCEDETACHED)) == delta.getFlags())) {
            return Collections.singleton(root.getJavaProject());
        }//  www  . ja  v a  2s . co  m
    } else if (element instanceof IJavaModel) {
        return getPackageFragmentRootDeltas(delta.getAffectedChildren());
    } else if (element instanceof IJavaProject) {
        if ((delta.getFlags() & IJavaElementDelta.F_CLASSPATH_CHANGED) != 0
                || (delta.getFlags() & IJavaElementDelta.F_RESOLVED_CLASSPATH_CHANGED) != 0)
            return Collections.singleton((IJavaProject) element);
        return getPackageFragmentRootDeltas(delta.getAffectedChildren());
    }
    return Collections.emptySet();
}