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

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

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement FIELD.

Prototype

int FIELD

To view the source code for org.eclipse.jdt.core IJavaElement FIELD.

Click Source Link

Document

Constant representing a field.

Usage

From source file:org.eclipse.jst.jsp.ui.internal.hyperlink.JSPJavaHyperlinkDetector.java

License:Open Source License

private IHyperlink createHyperlink(IJavaElement element, IRegion region, IDocument document) {
    IHyperlink link = null;/*from w  ww.ja v  a  2  s. c o m*/
    if (region != null) {
        // open local variable in the JSP file...
        boolean isInTranslationCU = false;
        if (element instanceof ISourceReference) {
            IFile file = null;
            int jspOffset = 0;

            // try to locate the file in the workspace
            ITextFileBuffer textFileBuffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(document);
            if (textFileBuffer != null && textFileBuffer.getLocation() != null) {
                file = getFile(textFileBuffer.getLocation().toString());
            }

            // get Java range and translate to JSP range
            try {
                ISourceRange range = null;
                IJSPTranslation jspTranslation = getJSPTranslation(document);
                if (jspTranslation != null) {
                    // link to local variable definitions
                    if (element instanceof ILocalVariable) {
                        range = ((ILocalVariable) element).getNameRange();
                        Object cu = ((ILocalVariable) element).getAncestor(IJavaElement.COMPILATION_UNIT);
                        if (cu != null && cu.equals(jspTranslation.getCompilationUnit()))
                            isInTranslationCU = true;
                    }
                    // linking to fields of the same compilation unit
                    else if (element.getElementType() == IJavaElement.FIELD) {
                        Object cu = ((IField) element).getCompilationUnit();
                        if (cu != null && cu.equals(jspTranslation.getCompilationUnit())) {
                            range = ((ISourceReference) element).getSourceRange();
                            isInTranslationCU = true;
                        }
                    }
                    // linking to methods of the same compilation unit
                    else if (element.getElementType() == IJavaElement.METHOD) {
                        Object cu = ((IMethod) element).getCompilationUnit();
                        if (cu != null && cu.equals(jspTranslation.getCompilationUnit())) {
                            range = ((ISourceReference) element).getSourceRange();
                            isInTranslationCU = true;
                        }
                    }
                }

                if (jspTranslation != null && range != null && file != null) {
                    jspOffset = jspTranslation.getJspOffset(range.getOffset());
                    if (jspOffset >= 0) {
                        link = new WorkspaceFileHyperlink(region, file,
                                new Region(jspOffset, range.getLength()));
                    }
                }
            } catch (JavaModelException jme) {
                Logger.log(Logger.WARNING_DEBUG, jme.getMessage(), jme);
            }
        }
        if (link == null && !isInTranslationCU) { // Don't try to open the translation CU
            link = new JSPJavaHyperlink(region, element);
        }
    }
    return link;
}

From source file:org.eclipse.jst.jsp.ui.internal.java.refactoring.RenameElementHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    fEditor = HandlerUtil.getActiveEditor(event);

    IJavaElement element = getSelectedElement();
    if (element != null) {
        RenameSupport renameSupport = null;
        try {// w w w  . jav  a 2  s.c o m
            switch (element.getElementType()) {
            case IJavaElement.TYPE:
                renameSupport = RenameSupport.create((IType) element, element.getElementName(),
                        RenameSupport.UPDATE_REFERENCES);
                break;
            case IJavaElement.METHOD:
                renameSupport = RenameSupport.create((IMethod) element, element.getElementName(),
                        RenameSupport.UPDATE_REFERENCES);
                break;
            case IJavaElement.PACKAGE_FRAGMENT:
                renameSupport = RenameSupport.create((IPackageFragment) element, element.getElementName(),
                        RenameSupport.UPDATE_REFERENCES);
                break;
            case IJavaElement.FIELD:
                renameSupport = RenameSupport.create((IField) element, element.getElementName(),
                        RenameSupport.UPDATE_REFERENCES);
                break;
            }
            if (renameSupport != null) {
                renameSupport.openDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
                PlatformStatusLineUtil.clearStatusLine();
            }
        } catch (CoreException e) {
            Logger.logException(e);
        }
    } else {
        PlatformStatusLineUtil.displayErrorMessage(JSPUIMessages.JSPRenameElementAction_0); //$NON-NLS-1$
        PlatformStatusLineUtil.addOneTimeClearListener();
    }

    return null;
}

From source file:org.eclipse.jst.jsp.ui.tests.contentassist.JSPTranslationTest.java

License:Open Source License

private void verifyTranslationHasNoSessionVariables(IFile file) throws JavaModelException {
    IDOMModel model = null;/*from   w  w  w  .  j a  v a2  s  .  co m*/
    try {
        model = (IDOMModel) getStructuredModelForRead(file);
        setupAdapterFactory(model);

        JSPTranslationAdapter adapter = (JSPTranslationAdapter) model.getDocument()
                .getAdapterFor(IJSPTranslation.class);
        ICompilationUnit cu = adapter.getJSPTranslation().getCompilationUnit();
        cu.makeConsistent(new NullProgressMonitor());
        IType[] types = cu.getAllTypes();
        for (int i = 0; i < types.length; i++) {
            IJavaElement[] members = types[i].getChildren();
            for (int k = 0; k < members.length; k++) {
                // check fields for name "session"
                if (members[k].getElementType() == IJavaElement.FIELD) {
                    assertFalse("field named \"session\" exists",
                            members[k].getElementName().equals(JSP11Namespace.ATTR_NAME_SESSION));
                }
                /*
                 * check "public void
                 * _jspService(javax.servlet.http.HttpServletRequest
                 * request, javax.servlet.http.HttpServletResponse
                 * response)" for local variables named "session"
                 */
                else if (members[k].getElementType() == IJavaElement.METHOD
                        && members[k].getElementName().startsWith("_jspService")) {
                    ICompilationUnit compilationUnit = ((IMethod) members[k]).getCompilationUnit();
                    compilationUnit.makeConsistent(new NullProgressMonitor());
                    ASTParser parser = ASTParser.newParser(AST.JLS3);
                    parser.setSource(cu);
                    ASTNode node = parser.createAST(null);
                    node.accept(new ASTVisitor() {
                        public boolean visit(VariableDeclarationStatement node) {
                            Iterator fragments = node.fragments().iterator();
                            while (fragments.hasNext()) {
                                VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments
                                        .next();
                                if (fragment.getName().getFullyQualifiedName()
                                        .equals(JSP11Namespace.ATTR_NAME_SESSION)) {
                                    String typeName = ((SimpleType) node.getType()).getName()
                                            .getFullyQualifiedName();
                                    assertFalse(
                                            "local variable of type \"javax.servlet.http.HttpSession\" and named \"session\" exists",
                                            typeName.equals("javax.servlet.http.HttpSession"));
                                }
                            }
                            return super.visit(node);
                        }
                    });
                }
            }
        }
    } finally {
        if (model != null)
            model.releaseFromRead();
    }
}

From source file:org.eclipse.linuxtools.changelog.parsers.java.JavaParser.java

License:Open Source License

/**
 * @see IParserChangeLogContrib#parseCurrentFunction(IEditorPart)
 *//*from   ww w.  j a  va 2 s.  com*/
public String parseCurrentFunction(IEditorInput input, int offset) throws CoreException {

    String currentElementName;
    int elementType;

    // Get the working copy and connect to input.
    IWorkingCopyManager manager = JavaUI.getWorkingCopyManager();
    manager.connect(input);

    // Retrieve the Java Element in question.
    // The following internal access is done because the getWorkingCopy() method
    // for the WorkingCopyManager returns null for StorageEditorInput, however,
    // there is a working copy available through the ICompilationUnitDocumentProvider.
    //      ICompilationUnit workingCopy = manager.getWorkingCopy(input);
    ICompilationUnitDocumentProvider x = (ICompilationUnitDocumentProvider) JavaUI.getDocumentProvider();
    // Retrieve the Java Element in question.
    ICompilationUnit workingCopy = x.getWorkingCopy(input);

    if (workingCopy == null)
        return "";

    IJavaElement method = workingCopy.getElementAt(offset);

    manager.disconnect(input);

    // no element selected
    if (method == null)
        return "";

    // Get the current element name, to test it.
    currentElementName = method.getElementName();

    // Element doesn't have a name. Can go no further.
    if (currentElementName == null)
        return "";

    // Get the Element Type to test.
    elementType = method.getElementType();

    switch (elementType) {
    case IJavaElement.METHOD:
    case IJavaElement.FIELD:
        break;
    case IJavaElement.COMPILATION_UNIT:
        return "";
    case IJavaElement.INITIALIZER:
        return STATIC_INITIALIZER_NAME;

    // So it's not a method, field, type, or static initializer. Where are we?
    default:
        IJavaElement tmpMethodType;
        if (((tmpMethodType = method.getAncestor(IJavaElement.METHOD)) == null)
                && ((tmpMethodType = method.getAncestor(IJavaElement.TYPE)) == null)) {
            return "";
        } else {
            // In a class, but not in a method. Return class name instead.
            method = tmpMethodType;
            currentElementName = method.getElementName();
        }
    }

    // Build all ancestor classes.
    // Append all ancestor class names to string

    IJavaElement tmpParent = method.getParent();
    boolean firstLoop = true;

    while (tmpParent != null) {
        IJavaElement tmpParentClass = tmpParent.getAncestor(IJavaElement.TYPE);
        if (tmpParentClass != null) {
            String tmpParentClassName = tmpParentClass.getElementName();
            if (tmpParentClassName == null)
                return "";
            currentElementName = tmpParentClassName + "." + currentElementName;
        } else {
            // cut root class name
            int rootClassPos = currentElementName.indexOf(".");
            if (rootClassPos >= 0)
                currentElementName = currentElementName.substring(rootClassPos + 1);
            if (firstLoop)
                return "";
            else
                return currentElementName;
        }
        tmpParent = tmpParentClass.getParent();
        firstLoop = false;

    }

    return "";
}

From source file:org.eclipse.linuxtools.internal.changelog.parsers.java.JavaParser.java

License:Open Source License

@Override
public String parseCurrentFunction(IEditorInput input, int offset) throws CoreException {

    String currentElementName;/*from w  ww  .j  a va  2  s .c o  m*/
    int elementType;

    // Get the working copy and connect to input.
    IWorkingCopyManager manager = JavaUI.getWorkingCopyManager();
    manager.connect(input);

    // Retrieve the Java Element in question.
    // The following internal access is done because the getWorkingCopy()
    // method
    // for the WorkingCopyManager returns null for StorageEditorInput,
    // however,
    // there is a working copy available through the
    // ICompilationUnitDocumentProvider.
    ICompilationUnitDocumentProvider x = (ICompilationUnitDocumentProvider) JavaUI.getDocumentProvider();
    // Retrieve the Java Element in question.
    ICompilationUnit workingCopy = x.getWorkingCopy(input);

    if (workingCopy == null) {
        return "";
    }

    IJavaElement method = workingCopy.getElementAt(offset);

    manager.disconnect(input);

    // no element selected
    if (method == null) {
        return "";
    }

    // Get the current element name, to test it.
    currentElementName = method.getElementName();

    // Element doesn't have a name. Can go no further.
    if (currentElementName == null) {
        return "";
    }

    // Get the Element Type to test.
    elementType = method.getElementType();

    switch (elementType) {
    case IJavaElement.METHOD:
    case IJavaElement.FIELD:
        break;
    case IJavaElement.COMPILATION_UNIT:
        return "";
    case IJavaElement.INITIALIZER:
        return STATIC_INITIALIZER_NAME;

    // So it's not a method, field, type, or static initializer. Where
    // are we?
    default:
        IJavaElement tmpMethodType;
        if (((tmpMethodType = method.getAncestor(IJavaElement.METHOD)) == null)
                && ((tmpMethodType = method.getAncestor(IJavaElement.TYPE)) == null)) {
            return "";
        } else {
            // In a class, but not in a method. Return class name instead.
            method = tmpMethodType;
            currentElementName = method.getElementName();
        }
    }

    // Build all ancestor classes.
    // Append all ancestor class names to string

    IJavaElement tmpParent = method.getParent();
    boolean firstLoop = true;

    while (tmpParent != null) {
        IJavaElement tmpParentClass = tmpParent.getAncestor(IJavaElement.TYPE);
        if (tmpParentClass != null) {
            String tmpParentClassName = tmpParentClass.getElementName();
            if (tmpParentClassName == null) {
                return "";
            }
            currentElementName = tmpParentClassName + "." + currentElementName;
        } else {
            // cut root class name
            int rootClassPos = currentElementName.indexOf('.');
            if (rootClassPos >= 0) {
                currentElementName = currentElementName.substring(rootClassPos + 1);
            }
            if (firstLoop) {
                return "";
            } else {
                return currentElementName;
            }
        }
        tmpParent = tmpParentClass.getParent();
        firstLoop = false;

    }

    return "";
}

From source file:org.eclipse.modisco.java.discoverer.internal.io.library.ClassFileParser.java

License:Open Source License

/**
 * Complete the MoDisco modifier with the informations of the flags.
 * //  w  w w .j av a  2  s.co m
 * @param flags
 *            the flags
 * @param modiscoModifier
 *            the MoDisco Modifier
 * @see Flags
 */
private static void manageModifier(final Modifier modiscoModifier, final int flags,
        final IJavaElement element) {
    int kind = element.getElementType();
    // static is applicable on types, methods, fields, and initializers.
    if (!modiscoModifier.isStatic()) {
        if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.FIELD) {
            modiscoModifier.setStatic(Flags.isStatic(flags));
        }
    }
    // native is applicable to methods
    if (!modiscoModifier.isNative()) {
        if (kind == IJavaElement.METHOD) {
            modiscoModifier.setNative(Flags.isNative(flags));
        }
    }
    // strictfp is applicable to types and methods
    if (!modiscoModifier.isStrictfp()) {
        if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD) {
            modiscoModifier.setStrictfp(Flags.isStrictfp(flags));
        }
    }
    // synchronized is applicable only to methods
    if (!modiscoModifier.isSynchronized()) {
        if (kind == IJavaElement.METHOD) {
            modiscoModifier.setSynchronized(Flags.isSynchronized(flags));
        }
    }
    // transient is applicable only to fields
    if (!modiscoModifier.isTransient()) {
        if (kind == IJavaElement.FIELD) {
            modiscoModifier.setTransient(Flags.isTransient(flags));
        }
    }
    // volatile is applicable only to fields
    if (!modiscoModifier.isVolatile()) {
        if (kind == IJavaElement.FIELD) {
            modiscoModifier.setVolatile(Flags.isVolatile(flags));
        }
    }

    // visibility modifiers are applicable to types, methods, constructors,
    // and fields.
    if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.FIELD) {
        if (Flags.isPrivate(flags)) {
            modiscoModifier.setVisibility(VisibilityKind.PRIVATE);
        } else if (Flags.isProtected(flags)) {
            modiscoModifier.setVisibility(VisibilityKind.PROTECTED);
        } else if (Flags.isPublic(flags)) {
            modiscoModifier.setVisibility(VisibilityKind.PUBLIC);
        }
    }

    // abstract is applicable to types and methods
    // final is applicable to types, methods and variables
    if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD) {
        if (Flags.isAbstract(flags)) {
            modiscoModifier.setInheritance(InheritanceKind.ABSTRACT);
        } else if (Flags.isFinal(flags)) {
            modiscoModifier.setInheritance(InheritanceKind.FINAL);
        }
    }
}

From source file:org.eclipse.mylyn.internal.java.ui.JavaStructureBridge.java

License:Open Source License

/**
 * Some copying from://from www  . j av a  2s. c  o  m
 * 
 * @see org.eclipse.jdt.ui.ProblemsLabelDecorator
 */
public boolean containsProblem(IInteractionElement node) {
    try {
        IJavaElement element = (IJavaElement) getObjectForHandle(node.getHandleIdentifier());
        switch (element.getElementType()) {
        case IJavaElement.JAVA_PROJECT:
        case IJavaElement.PACKAGE_FRAGMENT_ROOT:
            return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null);
        case IJavaElement.PACKAGE_FRAGMENT:
        case IJavaElement.COMPILATION_UNIT:
        case IJavaElement.CLASS_FILE:
            return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
        case IJavaElement.PACKAGE_DECLARATION:
        case IJavaElement.IMPORT_DECLARATION:
        case IJavaElement.IMPORT_CONTAINER:
        case IJavaElement.TYPE:
        case IJavaElement.INITIALIZER:
        case IJavaElement.METHOD:
        case IJavaElement.FIELD:
        case IJavaElement.LOCAL_VARIABLE:
            ICompilationUnit cu = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
            }
        }
    } catch (CoreException e) {
        // ignore
    }
    return false;
}

From source file:org.eclipse.objectteams.otdt.core.OTModelManager.java

License:Open Source License

/**
 * Add the propriate Object Teams Model element for a given IType 
 *///from   w w w  .  j a v  a  2  s . c  o m
public IOTType addType(IType elem, int typeDeclFlags, String baseClassName, String baseClassAnchor,
        boolean isRoleFile) {
    IJavaElement parent = elem.getParent();
    IOTType result = null;

    switch (parent.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.CLASS_FILE:
        if (isRoleFile) { //  could also be a teeam, which is handled inside the constructor
            if (elem.isBinary()) {
                MAPPING.addOTElement(result = new BinaryRoleType(elem, parent, typeDeclFlags, baseClassName,
                        baseClassAnchor));
            } else {
                MAPPING.addOTElement(
                        result = new RoleFileType(elem, parent, typeDeclFlags, baseClassName, baseClassAnchor));
            }
        } else if (TypeHelper.isTeam(typeDeclFlags)) {
            MAPPING.addOTElement(result = new OTType(IOTJavaElement.TEAM, elem, null, typeDeclFlags));
        }
        break;
    case IJavaElement.TYPE:
        IType encType = (IType) parent;
        IOTType otmParent = MAPPING.getOTElement(encType);

        result = maybeAddRoleType(elem, otmParent, typeDeclFlags, baseClassName, baseClassAnchor);
        break;
    //do nothing if anonymous type
    case IJavaElement.METHOD:
        break;
    case IJavaElement.INITIALIZER:
        break;
    case IJavaElement.FIELD:
        break;
    //TODO (jwl) Wether anonymous types are roles or not will be discoverable with 
    //           a future implementation (probably with the help of a newer version of the compiler)

    //             case IJavaElement.METHOD:
    //              IMethod encMethod   = (IMethod)parent;
    //              otmParent = MAPPING.getOTElement(encMethod.getDeclaringType());
    //              
    //              addRoleType(elem, otmParent, typeDeclFlags, baseClassName);
    //              break;
    //          case IJavaElement.INITIALIZER:
    //              IInitializer encInitializer   = (IInitializer)parent;
    //              otmParent = MAPPING.getOTElement(encInitializer.getDeclaringType());
    //              
    //              addRoleType(elem, otmParent, typeDeclFlags, baseClassName);
    //              break;
    //          case IJavaElement.FIELD:
    //              IField encField   = (IField)parent;
    //              otmParent = MAPPING.getOTElement(encField.getDeclaringType());
    //              
    //              addRoleType(elem, otmParent, typeDeclFlags, baseClassName);
    //              break;
    default:
        new Throwable("Warning: unexpected parent for OT element: " + parent).printStackTrace(); //$NON-NLS-1$
        break;
    }
    return result;
}

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

License:Open Source License

/**
 * Returns the IType associated with the <code>IJavaElement</code> passed in
 * @param element the <code>IJavaElement</code> to get the type from
 * @return the corresponding <code>IType</code> for the <code>IJavaElement</code>, or <code>null</code> if there is not one.
 * @since 3.3//from   ww w . ja v a  2 s.  c om
 */
protected IType getType(IJavaElement element) {
    switch (element.getElementType()) {
    case IJavaElement.FIELD: {
        return ((IField) element).getDeclaringType();
    }
    case IJavaElement.METHOD: {
        return ((IMethod) element).getDeclaringType();
    }
    case IJavaElement.TYPE: {
        return (IType) element;
    }
    default: {
        return null;
    }
    }
}

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

License:Open Source License

/**
 * Returns if the text selection is a field selection or not
 * @param selection the text selection/*from   w  w w  . j a v a 2s .  c o m*/
 * @param part the associated workbench part
 * @return true if the text selection is a valid field for a watchpoint, false otherwise
 * @since 3.3
 */
private boolean isField(ITextSelection selection, IWorkbenchPart part) {
    ITextEditor editor = getTextEditor(part);
    if (editor != null) {
        IJavaElement element = getJavaElement(editor.getEditorInput());
        if (element != null) {
            try {
                if (element instanceof ICompilationUnit) {
                    element = ((ICompilationUnit) element).getElementAt(selection.getOffset());
                } else if (element instanceof IClassFile) {
                    element = ((IClassFile) element).getElementAt(selection.getOffset());
                }
                return element != null && element.getElementType() == IJavaElement.FIELD;
            } catch (JavaModelException e) {
                return false;
            }
        }
    }
    return false;
}