Example usage for org.eclipse.jdt.core IMember exists

List of usage examples for org.eclipse.jdt.core IMember exists

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IMember exists.

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.ajdt.internal.ui.refactoring.pullout.PullOutRefactoring.java

License:Open Source License

@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor monitor)
        throws CoreException, OperationCanceledException {

    RefactoringStatus status = new RefactoringStatus();
    monitor.beginTask("Checking preconditions...", 1);
    try {/*from  ww w. jav a2s.  c  o m*/
        if (memberMap == null || memberMap.isEmpty())
            status.merge(RefactoringStatus.createFatalErrorStatus("No pullout targets have been specified."));
        else {
            for (ICompilationUnit cu : memberMap.keySet()) {
                for (IMember member : memberMap.get(cu)) {
                    if (!member.exists()) {
                        status.merge(RefactoringStatus.createFatalErrorStatus(MessageFormat.format(
                                "Member ''{0}'' does not exist.", new Object[] { member.getElementName() })));
                    } else if (!isInTopLevelType(member)) {
                        status.merge(RefactoringStatus.createFatalErrorStatus(MessageFormat.format(
                                "Member ''{0}'' is not directly nested in a top-level type.",
                                new Object[] { member.getElementName() })));
                    } else if (member.isBinary()) {
                        status.merge(RefactoringStatus.createFatalErrorStatus(MessageFormat.format(
                                "Member ''{0}'' is not in source code. Binary methods can not be refactored.",
                                new Object[] { member.getElementName() })));
                    } else if (!member.getCompilationUnit().isStructureKnown()) {
                        status.merge(RefactoringStatus.createFatalErrorStatus(
                                MessageFormat.format("Compilation unit ''{0}'' contains compile errors.",
                                        new Object[] { cu.getElementName() })));
                    }
                }
            }
        }
    } finally {
        monitor.done();
    }
    return status;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.PushInRefactoring.java

License:Open Source License

private RefactoringStatus initialITDCheck(IMember itd) {
    RefactoringStatus status = new RefactoringStatus();

    if (itd == null) {
        status.merge(RefactoringStatus.createFatalErrorStatus("Intertype declaration has not been specified"));
        return status;
    }//from w  w w  . j  a  v  a 2s  .  c o m
    if (!(itd instanceof IAspectJElement)) {
        return status;
    }
    try {
        AJProjectModelFacade model = getModel(itd);
        if (!model.hasModel()) {
            status.merge(RefactoringStatus
                    .createFatalErrorStatus("No crosscutting model available.  Rebuild project."));
        }
        ICompilationUnit unit = itd.getCompilationUnit();
        Object[] itdName = new Object[] { unit.getElementName() };
        if (!itd.exists()) {
            status.merge(RefactoringStatus.createFatalErrorStatus(MessageFormat
                    .format("ITD ''{0}'' does not exist.", new Object[] { itd.getElementName() })));
        } else if (!unit.isStructureKnown()) {
            status.merge(RefactoringStatus.createFatalErrorStatus(
                    MessageFormat.format("Compilation unit ''{0}'' contains compile errors.", itdName)));
        } else
            try {
                if (unit.getResource().findMaxProblemSeverity(IMarker.MARKER, true,
                        IResource.DEPTH_ZERO) >= IMarker.SEVERITY_ERROR) {
                    status.merge(RefactoringStatus.createFatalErrorStatus(MessageFormat
                            .format("Compilation unit ''{0}'' contains compile errors.", itdName)));
                }
            } catch (CoreException e) {
                status.merge(RefactoringStatus.create(e.getStatus()));
            }
        // now check target types
        IMember[] targets = getTargets(Collections.singletonList(itd));
        if (targets.length > 0) {
            for (int i = 0; i < targets.length; i++) {
                IMember target = targets[i];
                if (!target.exists()) {
                    status.merge(RefactoringStatus.createFatalErrorStatus(MessageFormat.format(
                            "Target type ''{0}'' does not exist.", new Object[] { target.getElementName() })));
                } else if (target.isBinary()) {
                    status.merge(RefactoringStatus.createFatalErrorStatus(MessageFormat.format(
                            "Target type ''{0}'' is binary.", new Object[] { target.getElementName() })));
                } else if (!unit.isStructureKnown()) {
                    status.merge(RefactoringStatus.createFatalErrorStatus(
                            MessageFormat.format("Compilation unit ''{0}'' contains compile errors.",
                                    new Object[] { target.getCompilationUnit().getElementName() })));
                }
            }
        } else {
            status.merge(
                    RefactoringStatus.createWarningStatus(MessageFormat.format(
                            "ITD ''{0}'' has no target.  This refactoring will delete the declaration.  "
                                    + "Perhaps there is an unresolved compilation error?",
                            itd.getElementName())));
        }
    } catch (JavaModelException e) {
        status.addFatalError(
                "JavaModelException:\n\t" + e.getMessage() + "\n\t" + e.getJavaModelStatus().getMessage());
    }
    return status;
}

From source file:org.eclipse.objectteams.otdt.debug.tests.AbstractOTDTDebugTest.java

License:Open Source License

/**
 * Creates and returns a map of java element breakpoint attributes for a breakpoint on the
 * given java element, or <code>null</code> if none
 * /* ww w  .  ja v a  2 s  . c  om*/
 * @param element java element the breakpoint is associated with
 * @return map of breakpoint attributes or <code>null</code>
 * @throws Exception
 */
protected Map getExtraBreakpointAttributes(IMember element) throws Exception {
    if (element != null && element.exists()) {
        Map map = new HashMap();
        ISourceRange sourceRange = element.getSourceRange();
        int start = sourceRange.getOffset();
        int end = start + sourceRange.getLength();
        IType type = null;
        if (element instanceof IType) {
            type = (IType) element;
        } else {
            type = element.getDeclaringType();
        }
        BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(map, type, start, end);
        return map;
    }
    return null;
}

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

License:Open Source License

/**
 * Creates an {@link IApiProblem} for the given compatibility delta
 * //from   ww  w  . j a  v a 2s  .co  m
 * @param delta
 * @param jproject
 * @param reference
 * @param component
 * @return a new compatibility problem or <code>null</code>
 */
private IApiProblem createCompatibilityProblem(final IDelta delta, final IApiComponent reference,
        final IApiComponent component) {
    try {
        Version referenceVersion = new Version(reference.getVersion());
        Version componentVersion = new Version(component.getVersion());
        if ((referenceVersion.getMajor() < componentVersion.getMajor())
                && !reportApiBreakageWhenMajorVersionIncremented()) {
            // API breakage are ok in this case and we don't want them to be
            // reported
            fBuildState.addBreakingChange(delta);
            return null;
        }
        IResource resource = null;
        IType type = null;
        // retrieve line number, char start and char end
        int lineNumber = 0;
        int charStart = -1;
        int charEnd = 1;
        IMember member = null;
        if (fJavaProject != null) {
            try {
                type = fJavaProject.findType(delta.getTypeName().replace('$', '.'));
            } catch (JavaModelException e) {
                ApiPlugin.log(e);
            }
            IProject project = fJavaProject.getProject();
            resource = Util.getResource(project, type);
            if (resource == null) {
                return null;
            }
            if (!Util.isManifest(resource.getProjectRelativePath())) {
                member = Util.getIMember(delta, fJavaProject);
            }
            if (member != null && !member.isBinary() && member.exists()) {
                ISourceRange range = member.getNameRange();
                charStart = range.getOffset();
                charEnd = charStart + range.getLength();
                try {
                    IDocument document = Util.getDocument(member.getCompilationUnit());
                    lineNumber = document.getLineOfOffset(charStart);
                } catch (BadLocationException e) {
                    // ignore
                }
            }
        }
        String path = null;
        if (resource != null) {
            path = resource.getProjectRelativePath().toPortableString();
        }
        IApiProblem apiProblem = ApiProblemFactory.newApiProblem(path, delta.getTypeName(),
                delta.getArguments(),
                new String[] { IApiMarkerConstants.MARKER_ATTR_HANDLE_ID,
                        IApiMarkerConstants.API_MARKER_ATTR_ID },
                new Object[] { member == null ? null : member.getHandleIdentifier(),
                        new Integer(IApiMarkerConstants.COMPATIBILITY_MARKER_ID), },
                lineNumber, charStart, charEnd, IApiProblem.CATEGORY_COMPATIBILITY, delta.getElementType(),
                delta.getKind(), delta.getFlags());
        return apiProblem;

    } catch (CoreException e) {
        ApiPlugin.log(e);
    }
    return null;
}

From source file:org.fastcode.popup.actions.easycreate.CopyMemberAction.java

License:Open Source License

/**
 *
 * @param type/*from  w  ww .  ja  v a2  s.co  m*/
 * @param member
 * @param newMemberName
 * @param newFieldPart
 * @param selectedText
 * @param copyBody
 * @return
 * @throws Exception
 */
private IMember copyMemberAndSelect(final IType type, final IMember member, final IMember sibling,
        final String newMemberName, final String newFieldPart, final String selectedText,
        final boolean copyBody) throws Exception {
    final IJavaElement nextElement = findNextElement(type, sibling);
    IMember newMember = null;
    final GlobalSettings globalSettings = getInstance();
    if (member.getElementType() != IJavaElement.METHOD || copyBody) {
        member.copy(type, nextElement, newMemberName, false, null);
    } else { // Create a new method signature manually
        final IMethod method = (IMethod) member;
        int count = 0;
        final StringBuilder methodSrc = new StringBuilder();

        if (isJunitTest(type)) {
            final StringBuilder methAnnotations = new StringBuilder();
            final IPreferenceStore preferences = new ScopedPreferenceStore(new InstanceScope(),
                    FAST_CODE_PLUGIN_ID);
            final String methodAnnotations = preferences.getString(P_JUNIT_METHOD_ANNOTATIONS);
            if (methodAnnotations != null) {
                for (String methodAnnotation : methodAnnotations.split(NEWLINE)) {
                    methodAnnotation = replacePlaceHolder(methodAnnotation, "user", globalSettings.getUser());
                    final String currDate = computeDate(globalSettings.getDateFormat());
                    methodAnnotation = replacePlaceHolder(methodAnnotation, "curr_date", currDate);
                    methodAnnotation = replacePlaceHolder(methodAnnotation, "today", currDate);
                    methAnnotations.append(methodAnnotation + NEWLINE);
                }
            }
            methodSrc.append(methAnnotations.toString());
        } else {
            for (final IAnnotation annotation : method.getAnnotations()) {
                methodSrc.append("@" + annotation.getSource() + NEWLINE);
            }
        }

        if (isPrivate(method.getFlags())) {
            methodSrc.append("private");
        } else if (isProtected(method.getFlags())) {
            methodSrc.append("protected");
        } else if (isPublic(method.getFlags())) {
            methodSrc.append("public");
        }

        if (isStatic(method.getFlags())) {
            methodSrc.append(SPACE + "static");
        }
        methodSrc.append(SPACE + Signature.getSignatureSimpleName(method.getReturnType()));

        methodSrc.append(SPACE + newMemberName);

        methodSrc.append(LEFT_PAREN);
        for (final String paramName : method.getParameterNames()) {
            final String paramType = method.getParameterTypes()[count];
            methodSrc.append(Signature.getSignatureSimpleName(paramType) + SPACE + paramName);
            if (count < method.getParameterNames().length - 1) {
                methodSrc.append(COMMA + SPACE);
            }
            count++;
        }
        methodSrc.append(") {\n");
        methodSrc.append("}\n");
        newMember = type.createMethod(methodSrc.toString(), nextElement, false, null);
    }

    if (newMember == null || !newMember.exists()) {
        if (member instanceof IField) {
            newMember = type.getField(newMemberName);
        } else if (member instanceof IMethod) {
            newMember = type.getMethod(newMemberName, ((IMethod) member).getParameterTypes());
        }
    }

    ITextSelection sel = null;

    if (member.getElementName().equals(selectedText)) {
        sel = new TextSelection(newMember.getNameRange().getOffset(), newMember.getNameRange().getLength());
    } else {
        final String textToSelect = isEmpty(newFieldPart) ? COPYOF : newFieldPart;
        sel = new TextSelection(
                newMember.getNameRange().getOffset() + newMember.getElementName().indexOf(textToSelect),
                textToSelect.length());
    }

    this.editorPart.getEditorSite().getSelectionProvider().setSelection(sel);

    return newMember;
}

From source file:org.grails.ide.eclipse.editor.actions.UrlMappingHyperlinkDetector.java

License:Open Source License

/**
 * Handle these kinds of links:/*from  w  ww . j a  v a  2s.com*/
 * <pre>
 * "/product"(controller:"product", action:"list") // link support to the controller and the action
 * "/product"(controller:"product")  // link support only for the controller
 * "/help"(controller:"site",view:"help") // link support to the controller and to the view (and maybe to the action as well)
 * "403"(view: "/errors/forbidden"  // link support to the view
 * name personList: "/showPeople" {
 *     controller = 'person'  // link support to the controller
 *     action = 'list'  // link support to the action
 * }
 * "/showPeople" {
 *     controller = 'person'  // link support to the controller
 *     action = 'list'  // link support to the action
 * }
 * "/product/$id"(controller:"product"){
 *    action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]
 *  }    
 * </pre>
 * @param statements
 * @param offset
 * @return
 */
private IHyperlink findLink(Statement statement, int offset, GroovyCompilationUnit unit) {
    if (!(statement instanceof ExpressionStatement)) {
        return null;
    }
    Expression expr = ((ExpressionStatement) statement).getExpression();
    if (expr.getStart() > offset || expr.getEnd() < offset) {
        return null;
    }

    if (expr instanceof MethodCallExpression) {
        MethodCallExpression call = (MethodCallExpression) expr;
        Expression args = call.getArguments();
        if (!(args instanceof TupleExpression) || ((TupleExpression) args).getExpressions().size() == 0) {
            return null;
        }
        TupleExpression tuple = (TupleExpression) args;
        Expression firstArg = tuple.getExpression(0);
        Expression lastArg = tuple.getExpression(tuple.getExpressions().size() - 1);

        NameRegion[] components;
        if (lastArg instanceof ClosureExpression && firstArg == lastArg) {
            /* we have something like this:
             * "/showPeople" {
             *     controller = 'person'  // link support to the controller
             *     action = 'list'  // link support to the action
             * }
             */
            components = findLinkComponentsInClosure((ClosureExpression) lastArg, offset);
        } else if (firstArg instanceof MapExpression) {
            List<MapEntryExpression> mapEntryExpressions = ((MapExpression) firstArg).getMapEntryExpressions();
            if (mapEntryExpressions.size() > 0
                    && mapEntryExpressions.get(0).getValueExpression() instanceof MethodCallExpression) {
                MethodCallExpression innerCall = (MethodCallExpression) mapEntryExpressions.get(0)
                        .getValueExpression();
                if (innerCall.getArguments() instanceof ArgumentListExpression
                        && ((ArgumentListExpression) innerCall.getArguments()).getExpressions().size() == 1
                        && ((ArgumentListExpression) innerCall.getArguments())
                                .getExpression(0) instanceof ClosureExpression) {
                    /* we have something like this:
                     * name showPeople: "/showPeople" {
                     *     controller = 'person'  // link support to the controller
                     *     action = 'list'  // link support to the action
                     * }
                     */

                    components = findLinkComponentsInClosure(
                            (ClosureExpression) ((ArgumentListExpression) innerCall.getArguments())
                                    .getExpression(0),
                            offset);
                } else {
                    components = null;
                }
            } else {
                /* we have something like this:
                 * "/product"(controller:"product", action:"list") // link support to the controller and the action
                 */
                components = findLinkComponentsInCall((MapExpression) firstArg, offset);
                if (components != null && lastArg instanceof ClosureExpression) {
                    /* we have something like this:
                     * "/product/$id"(controller:"product"){
                     *    action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]
                     *  }
                     */
                    finishComponents((ClosureExpression) lastArg, components, offset);
                }
            }
        } else {
            components = null;
        }

        if (components != null) {
            NameRegion controllerNameRegion = components[0];
            NameRegion actionNameRegion = components[1];
            NameRegion viewNameRegion = components[2];
            // may as well link to all possibilities here
            IHyperlink link = null;
            if (controllerNameRegion != null) {
                IType type = findController(controllerNameRegion.name, unit.getJavaProject());
                if (type != null && type.exists()) {
                    // action name should go first
                    if (actionNameRegion != null) {
                        IMember action = findAction(type, actionNameRegion.name);
                        if (actionNameRegion.region != null && action != null && action.exists()) {
                            link = new JavaElementHyperlink(actionNameRegion.region, action);
                        }
                    }
                    if (controllerNameRegion.region != null) {
                        link = new JavaElementHyperlink(controllerNameRegion.region, type);
                    }
                }
            }
            if (viewNameRegion != null && viewNameRegion.region != null) {
                String viewName = viewNameRegion.name;
                // add a slash
                if (viewName.charAt(0) != '/') {
                    viewName = "/" + viewName;
                }
                // add controller name
                if (controllerNameRegion != null
                        && !viewName.startsWith("/" + controllerNameRegion.name + "/")) {
                    viewName = "/" + controllerNameRegion.name + viewName;
                }
                // add prefix
                if (!viewName.endsWith(".gsp")) {
                    viewName = viewName + ".gsp";
                }
                IFile file = unit.getJavaProject().getProject().getFile("grails-app/views" + viewName);
                if (file.exists()) {
                    link = new WorkspaceFileHyperlink(viewNameRegion.region, file);
                }
            }
            return link;
        }
    }
    return null;
}

From source file:org.grails.ide.eclipse.editor.groovy.controllers.ControllerCache.java

License:Open Source License

/**
 * Finds the associated {@link IJavaElement} for this action name.
 * @param actionName/* ww w. j a v  a  2  s .co  m*/
 * @return
 */
private IMember findMember(String actionName) {
    // first go for method...can have arbitrary number of parameters
    IMember member;
    try {
        IMethod[] allMethods = controllerType.getMethods();
        member = null;
        for (IMethod maybeMethod : allMethods) {
            if (maybeMethod.getElementName().equals(actionName)) {
                member = maybeMethod;
                break;
            }
        }
        if (member != null) {
            return member;
        }
    } catch (JavaModelException e) {
        GrailsCoreActivator.log(e);
    }
    member = controllerType.getField(actionName);
    if (member.exists()) {
        return member;
    }
    return null;
}

From source file:org.jboss.tools.vscode.java.internal.handlers.CompletionResolveHandler.java

License:Open Source License

@Override
public CompletionItem handle(CompletionItem param) {

    @SuppressWarnings("unchecked")
    Map<String, String> data = (Map<String, String>) param.getData();
    // clean resolve data
    param.setData(null);//w  w w.  j ava  2s. c  o  m

    if (data.containsKey(DATA_FIELD_URI) && data.containsKey(DATA_FIELD_DECLARATION_SIGNATURE)) {
        ICompilationUnit unit = JDTUtils.resolveCompilationUnit(data.get(DATA_FIELD_URI));
        String typeName = SignatureUtil
                .stripSignatureToFQN(String.valueOf(data.get(DATA_FIELD_DECLARATION_SIGNATURE)));
        try {
            IMember member = null;
            IType type = unit.getJavaProject().findType(typeName);

            if (type != null && data.containsKey(DATA_FIELD_NAME)) {
                String name = data.get(DATA_FIELD_NAME);
                String[] paramSigs = CharOperation.NO_STRINGS;
                if (data.containsKey(DATA_FIELD_SIGNATURE)) {
                    String[] parameters = Signature.getParameterTypes(String
                            .valueOf(SignatureUtil.fix83600(data.get(DATA_FIELD_SIGNATURE).toCharArray())));
                    for (int i = 0; i < parameters.length; i++) {
                        parameters[i] = SignatureUtil.getLowerBound(parameters[i]);
                    }
                    paramSigs = parameters;
                }
                IMethod method = type.getMethod(name, paramSigs);
                if (method.exists()) {
                    member = method;
                } else {
                    IField field = type.getField(name);
                    if (field.exists()) {
                        member = field;
                    }
                }
            } else {
                member = type;
            }

            if (member != null && member.exists()) {
                Reader reader = JavadocContentAccess.getHTMLContentReader(member, true, true);
                if (reader != null)
                    param.setDocumentation(getString(reader));
            }
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin.logException("Unable to resolve compilation", e);
        }
    }
    return param;
}