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

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

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement 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.eclipse.objectteams.internal.jdt.nullity.quickfix.QuickFixes.java

License:Open Source License

public static String getNonNullAnnotationName(IJavaElement javaElement, boolean makeSimple) {
    String qualifiedName = javaElement.getJavaProject()
            .getOption(NullCompilerOptions.OPTION_NonNullAnnotationName, true);
    int lastDot;/*from ww w  . j  a v a2  s .c  om*/
    if (makeSimple && qualifiedName != null && (lastDot = qualifiedName.lastIndexOf('.')) != -1)
        return qualifiedName.substring(lastDot + 1);
    return qualifiedName;
}

From source file:org.eclipse.objectteams.otdt.debug.ui.internal.actions.OTBreakpointLocationVerifierJob.java

License:Open Source License

public IStatus run(IProgressMonitor monitor) {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    char[] source = fDocument.get().toCharArray();
    parser.setSource(source);//from  w w w  .  j a  va 2s  .  c  o  m
    IJavaElement javaElement = JavaCore.create(fResource);
    IJavaProject project = null;
    if (javaElement != null) {
        Map options = JavaCore.getDefaultOptions();
        project = javaElement.getJavaProject();
        String compilerCompliance = JavaCore.VERSION_1_5;
        String compilerSource = JavaCore.VERSION_1_5;
        if (project != null) {
            compilerCompliance = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            compilerSource = project.getOption(JavaCore.COMPILER_SOURCE, true);
        }
        options.put(JavaCore.COMPILER_COMPLIANCE, compilerCompliance);
        options.put(JavaCore.COMPILER_SOURCE, compilerSource);
        //{ObjectTeams: copy one more option to ensure proper parsing:
        if (project != null) {
            String isPureJava = project.getOption(OTDTPlugin.OT_COMPILER_PURE_JAVA, true);
            options.put(OTDTPlugin.OT_COMPILER_PURE_JAVA, isPureJava);
        }
        // SH}
        parser.setCompilerOptions(options);
    }
    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
    //{ObjectTeams: replace ValidBreakpointLocationLocator with own OTValidBreakpointLocationLocator
    OTValidBreakpointLocationLocator locator = new OTValidBreakpointLocationLocator(compilationUnit,
            fLineNumber, false, fBestMatch);
    //ike}
    compilationUnit.accept(locator);
    if (locator.isBindingsRequired()) {
        if (javaElement != null) {
            // try again with bindings if required and available
            String unitName = null;
            if (fType == null) {
                String name = fResource.getName();
                if (JavaCore.isJavaLikeFileName(name)) {
                    unitName = name;
                }
            } else {
                if (fType.isBinary()) {
                    String className = fType.getClassFile().getElementName();
                    int nameLength = className.indexOf('$');
                    if (nameLength < 0) {
                        nameLength = className.indexOf('.');
                    }
                    unitName = className.substring(0, nameLength) + ".java"; //$NON-NLS-1$
                } else {
                    unitName = fType.getCompilationUnit().getElementName();
                }
            }
            if (unitName != null) {
                parser = ASTParser.newParser(AST.JLS3);
                parser.setSource(source);
                parser.setProject(project);
                parser.setUnitName(unitName);
                parser.setResolveBindings(true);
                compilationUnit = (CompilationUnit) parser.createAST(null);
                //{ObjectTeams: replace ValidBreakpointLocationLocator with own OTValidBreakpointLocationLocator
                locator = new OTValidBreakpointLocationLocator(compilationUnit, fLineNumber, true, fBestMatch);
                //ike}
                compilationUnit.accept(locator);
            }
        }
    }
    int lineNumber = locator.getLineLocation();
    String typeName = locator.getFullyQualifiedTypeName();

    try {
        switch (locator.getLocationType()) {
        case ValidBreakpointLocationLocator.LOCATION_LINE:
            return manageLineBreakpoint(typeName, lineNumber);
        case ValidBreakpointLocationLocator.LOCATION_METHOD:
            if (fBreakpoint != null) {
                DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(fBreakpoint, true);
            }
            //{ObjectTeams use OTToggleBreakpointAdapter
            new OTToggleBreakpointAdapter().toggleMethodBreakpoints(fEditorPart,
                    new TextSelection(locator.getMemberOffset(), 0));
            //carp}
            break;
        case ValidBreakpointLocationLocator.LOCATION_FIELD:
            if (fBreakpoint != null) {
                DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(fBreakpoint, true);
            }
            //{ObjectTeams use OTToggleBreakpointAdapter
            new OTToggleBreakpointAdapter().toggleWatchpoints(fEditorPart,
                    new TextSelection(locator.getMemberOffset(), 0));
            //carp}
            break;
        default:
            // cannot find a valid location
            report(ActionMessages.BreakpointLocationVerifierJob_not_valid_location);
            if (fBreakpoint != null) {
                DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(fBreakpoint, true);
            }
            return new Status(IStatus.OK, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR,
                    ActionMessages.BreakpointLocationVerifierJob_not_valid_location, null);
        }
    } catch (CoreException e) {
        JDIDebugUIPlugin.log(e);
    }
    return new Status(IStatus.OK, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.OK,
            ActionMessages.BreakpointLocationVerifierJob_breakpoint_set, null);

}

From source file:org.eclipse.objectteams.otdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

/**
 * Initializes all fields provided by the page with a given selection.
 * /*  w ww . ja v a  2s .com*/
 * @param elem the selection used to intialize this page or <code>
 * null</code> if no selection was available
 */
protected void initTypePage(IJavaElement elem) {
    getInlineSelectionDialogField().setEnabled(false);

    initAccessModifierButtons();
    initOtherModifierButtons();
    initMethodStubButtons();
    initBindingEditorButtons();

    IJavaProject project = null;
    if (elem != null) {
        project = elem.getJavaProject();
        initPackageAndEnclosingType(elem);
    }
    setTypeName(""); //$NON-NLS-1$
    setSuperInterfaces(new ArrayList<Object>(5));
    setAddComments(StubUtility.doAddComments(project), true); // from project or workspace
}

From source file:org.eclipse.pde.api.tools.internal.ApiDescriptionManager.java

License:Open Source License

/**
 * Flushes the changed element from the model cache
 * //from   ww  w . j  a  v  a 2s .c  om
 * @param element
 */
void flushElementCache(IJavaElement element) {
    switch (element.getElementType()) {
    case IJavaElement.COMPILATION_UNIT: {
        ICompilationUnit unit = (ICompilationUnit) element;
        IType type = unit.findPrimaryType();
        if (type != null) {
            ApiModelCache.getCache().removeElementInfo(ApiBaselineManager.WORKSPACE_API_BASELINE_ID,
                    element.getJavaProject().getElementName(), type.getFullyQualifiedName(), IApiElement.TYPE);
        }
        break;
    }
    case IJavaElement.JAVA_PROJECT: {
        ApiModelCache.getCache().removeElementInfo(ApiBaselineManager.WORKSPACE_API_BASELINE_ID,
                element.getElementName(), null, IApiElement.COMPONENT);
        break;
    }
    default:
        break;
    }
}

From source file:org.eclipse.pde.api.tools.ui.internal.completion.APIToolsJavadocCompletionProposalComputer.java

License:Open Source License

/**
 * Collects the existing tags on the {@link IJavaElement} we have been
 * activated on//from   w w w . j  ava2s . c o  m
 * 
 * @param element
 * @param jcontext
 * @throws JavaModelException
 * @throws BadLocationException
 */
private void collectExistingTags(IJavaElement element, JavaContentAssistInvocationContext jcontext)
        throws JavaModelException {
    if (element instanceof IMember) {
        IMember member = (IMember) element;
        ICompilationUnit cunit = jcontext.getCompilationUnit();
        if (cunit != null) {
            if (cunit.isWorkingCopy()) {
                cunit.reconcile(ICompilationUnit.NO_AST, false, false, null, null);
            }
            fParser.setSource(member.getSource().toCharArray());
            fParser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
            Map<String, String> options = element.getJavaProject().getOptions(true);
            options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
            fParser.setCompilerOptions(options);
            fParser.setStatementsRecovery(false);
            fParser.setResolveBindings(false);
            fParser.setBindingsRecovery(false);
            ASTNode ast = fParser.createAST(null);
            TagCollector collector = new TagCollector();
            if (ast.getNodeType() == ASTNode.TYPE_DECLARATION) {
                TypeDeclaration typeDeclaration = (TypeDeclaration) ast;
                List<BodyDeclaration> bodyDeclarations = typeDeclaration.bodyDeclarations();
                if (bodyDeclarations.size() == 1) {
                    // only one element should be there as we are parsing a
                    // specific member
                    BodyDeclaration bodyDeclaration = bodyDeclarations.iterator().next();
                    Javadoc javadoc = bodyDeclaration.getJavadoc();
                    if (javadoc != null) {
                        javadoc.accept(collector);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.pde.api.tools.ui.internal.wizards.CompareOperation.java

License:Open Source License

/**
 * @param structuredSelection//from w w w  . ja  v  a2 s.  c o m
 * @param monitor
 * @return the scope
 */
public static ApiScope walkStructureSelection(IStructuredSelection structuredSelection,
        IProgressMonitor monitor) {
    Object[] selected = structuredSelection.toArray();
    ApiScope scope = new ApiScope();
    IApiBaseline workspaceBaseline = ApiBaselineManager.getManager().getWorkspaceBaseline();
    if (workspaceBaseline == null) {
        return scope;
    }
    Arrays.sort(selected, new Comparator<Object>() {
        @Override
        public int compare(Object o1, Object o2) {
            if (o1 instanceof IJavaElement && o2 instanceof IJavaElement) {
                IJavaElement element = (IJavaElement) o1;
                IJavaElement element2 = (IJavaElement) o2;
                return element.getElementType() - element2.getElementType();
            }
            return 0;
        }
    });
    int length = selected.length;
    for (int i = 0; i < length; i++) {
        Object currentSelection = selected[i];
        if (currentSelection instanceof IJavaElement) {
            IJavaElement element = (IJavaElement) currentSelection;
            IJavaProject javaProject = element.getJavaProject();
            try {
                switch (element.getElementType()) {
                case IJavaElement.COMPILATION_UNIT: {
                    ICompilationUnit compilationUnit = (ICompilationUnit) element;
                    IApiComponent apiComponent = workspaceBaseline
                            .getApiComponent(javaProject.getElementName());
                    if (apiComponent != null) {
                        addElementFor(compilationUnit, apiComponent, scope);
                    }
                    break;
                }
                case IJavaElement.PACKAGE_FRAGMENT: {
                    IPackageFragment fragment = (IPackageFragment) element;
                    IApiComponent apiComponent = workspaceBaseline
                            .getApiComponent(javaProject.getElementName());
                    IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) fragment
                            .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
                    boolean isArchive = false;
                    if (packageFragmentRoot != null) {
                        isArchive = packageFragmentRoot.isArchive();
                    }
                    if (apiComponent != null) {
                        addElementFor(fragment, isArchive, apiComponent, scope);
                    }
                    break;
                }
                case IJavaElement.PACKAGE_FRAGMENT_ROOT: {
                    IPackageFragmentRoot fragmentRoot = (IPackageFragmentRoot) element;
                    IApiComponent apiComponent = workspaceBaseline
                            .getApiComponent(javaProject.getElementName());
                    if (apiComponent != null) {
                        addElementFor(fragmentRoot, apiComponent, scope);
                    }
                    break;
                }
                case IJavaElement.JAVA_PROJECT:
                    IApiComponent apiComponent = workspaceBaseline
                            .getApiComponent(javaProject.getElementName());
                    if (apiComponent != null) {
                        scope.addElement(apiComponent);
                    }
                    break;
                default:
                    break;
                }
            } catch (JavaModelException e) {
                ApiPlugin.log(e);
            } catch (CoreException e) {
                ApiPlugin.log(e);
            }
        }
    }
    return scope;
}

From source file:org.eclipse.pde.ds.internal.annotations.ComponentPropertyTester.java

License:Open Source License

@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
    if (!"containsComponentWithImplicitName".equals(property)) //$NON-NLS-1$
        return false;

    if (!(receiver instanceof IType) && !(receiver instanceof IPackageFragment))
        return false;

    IJavaElement element = (IJavaElement) receiver;
    IJavaProject javaProject = element.getJavaProject();

    boolean enabled = Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, Activator.PREF_ENABLED,
            false, new IScopeContext[] { new ProjectScope(javaProject.getProject()), InstanceScope.INSTANCE,
                    DefaultScope.INSTANCE });
    if (!enabled)
        return false;

    try {//  www .  j ava2s  . c o  m
        return element.getElementType() == IJavaElement.TYPE ? containsImplicitName((IType) receiver)
                : containsImplicitName((IPackageFragment) receiver);
    } catch (JavaModelException e) {
        if (debug.isDebugging())
            debug.trace(
                    String.format("Error searching for components with implicit names in element: %s", element), //$NON-NLS-1$
                    e);
    }

    return false;
}

From source file:org.eclipse.pde.ds.internal.annotations.ComponentRefactoringHelper.java

License:Open Source License

public RefactoringStatus checkConditions(IProgressMonitor monitor, CheckConditionsContext context)
        throws OperationCanceledException {
    SubMonitor progress = SubMonitor.convert(monitor,
            Messages.ComponentRefactoringHelper_checkConditionsTaskLabel, elements.size());
    try {// w  w w  .  j a  va 2 s .  c o m
        modelFiles = new HashMap<>(elements.size());
        componentNames = new HashMap<>(elements.size());
        renames = new HashMap<>(elements.size());
        HashMap<IJavaProject, ProjectState> states = new HashMap<>();
        HashSet<IJavaProject> unmanaged = new HashSet<>();

        ResourceChangeChecker checker = (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
        IResourceChangeDescriptionFactory deltaFactory = checker.getDeltaFactory();
        for (Map.Entry<Object, RefactoringArguments> entry : elements.entrySet()) {
            if (progress.isCanceled())
                throw new OperationCanceledException();

            progress.worked(1);

            RefactoringArguments args = entry.getValue();
            if (!getUpdateReferences(args))
                continue;

            IJavaElement element = (IJavaElement) entry.getKey();
            IJavaProject javaProject = element.getJavaProject();
            if (unmanaged.contains(javaProject))
                continue;

            ProjectState state = states.get(javaProject);
            if (state == null) {
                state = DSAnnotationCompilationParticipant.getState(javaProject);
            }

            if (state == null) {
                unmanaged.add(javaProject);
                continue;
            }

            states.put(javaProject, state);

            if (element.getElementType() == IJavaElement.TYPE)
                createRenames((IType) element, args, state, deltaFactory);
            else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
                createRenames((IPackageFragment) element, args, state, deltaFactory);
        }

        return new RefactoringStatus();
    } catch (JavaModelException e) {
        // TODO double-check!
        return RefactoringStatus.create(e.getStatus());
    }
}

From source file:org.eclipse.pde.internal.ui.correction.java.QuickFixProcessor.java

License:Open Source License

public boolean hasCorrections(ICompilationUnit unit, int problemId) {
    switch (problemId) {
    case IProblem.ForbiddenReference:
    case IProblem.UndefinedName: // fall through
    case IProblem.ImportNotFound: // fall through
    case IProblem.UndefinedType: // fall through
    case IProblem.UnresolvedVariable: // fall through
    case IProblem.MissingTypeInMethod: // fall through
    case IProblem.MissingTypeInConstructor:
        IJavaElement parent = unit.getParent();
        if (parent != null) {
            IJavaProject project = parent.getJavaProject();
            if (project != null)
                return WorkspaceModelManager.isPluginProject(project.getProject());
        }//from  w ww.ja  v a 2 s.c  o m
    }
    return false;
}

From source file:org.eclipse.recommenders.internal.types.rcp.TypesIndexService.java

License:Open Source License

private void process(IJavaElementDelta delta) {
    IJavaElement element = delta.getElement();
    IJavaProject project = element.getJavaProject();
    boolean resolvedClasspathChanged = (delta.getFlags() & IJavaElementDelta.F_RESOLVED_CLASSPATH_CHANGED) != 0;
    if (element instanceof IJavaProject && resolvedClasspathChanged) {
        rebuildIndex(element.getJavaProject());
        return;/* w ww .ja va  2s .  com*/
    }

    if (isChildAffectedByChange(delta)) {
        for (IJavaElementDelta child : delta.getAffectedChildren()) {
            process(child);
        }
        return;
    }

    switch (delta.getKind()) {
    case IJavaElementDelta.ADDED:
        processElementAdded(element, project);
        break;
    case CHANGED:
        processElementChanged(delta, element, project);
        break;
    case REMOVED:
        processElementRemoved(element, project);
        break;
    }
}