Example usage for org.eclipse.jdt.core Flags isProtected

List of usage examples for org.eclipse.jdt.core Flags isProtected

Introduction

In this page you can find the example usage for org.eclipse.jdt.core Flags isProtected.

Prototype

public static boolean isProtected(int flags) 

Source Link

Document

Returns whether the given integer includes the protected modifier.

Usage

From source file:at.bestsolution.efxclipse.tooling.model.internal.FXCtrlEventMethod.java

License:Open Source License

@Override
public Visibility getVisibility() {
    try {/*from w  ww  .java  2 s .  c o m*/
        int flags = method.getFlags();

        if (Flags.isPublic(flags)) {
            return Visibility.PUBLIC;
        } else if (Flags.isPackageDefault(flags)) {
            return Visibility.PACKAGE;
        } else if (Flags.isProtected(flags)) {
            return Visibility.PROTECTED;
        } else {
            return Visibility.PRIVATE;
        }
    } catch (JavaModelException e) {
        FXPlugin.getLogger().log(LogService.LOG_ERROR,
                "Unable to retrieve visibility for method '" + method + "'", e);
    }

    return Visibility.PRIVATE;
}

From source file:at.bestsolution.fxide.jdt.corext.util.JavaModelUtil.java

License:Open Source License

/**
 * Evaluates if a member in the focus' element hierarchy is visible from
 * elements in a package.//from   ww w  .  jav  a 2s  .  c om
 * @param member The member to test the visibility for
 * @param pack The package of the focus element focus
 * @return returns <code>true</code> if the member is visible from the package
 * @throws JavaModelException thrown when the member can not be accessed
 */
public static boolean isVisibleInHierarchy(IMember member, IPackageFragment pack) throws JavaModelException {
    int type = member.getElementType();
    if (type == IJavaElement.INITIALIZER
            || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$
        return false;
    }

    int otherflags = member.getFlags();

    IType declaringType = member.getDeclaringType();
    if (Flags.isPublic(otherflags) || Flags.isProtected(otherflags)
            || (declaringType != null && isInterfaceOrAnnotation(declaringType))) {
        return true;
    } else if (Flags.isPrivate(otherflags)) {
        return false;
    }

    IPackageFragment otherpack = (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
    return (pack != null && pack.equals(otherpack));
}

From source file:at.bestsolution.fxide.jdt.corext.util.JdtFlags.java

License:Open Source License

public static boolean isProtected(IMember member) throws JavaModelException {
    return Flags.isProtected(member.getFlags());
}

From source file:bndtools.editor.components.ComponentNameProposalProvider.java

License:Open Source License

@Override
protected List<IContentProposal> doGenerateProposals(String contents, int position) {
    final String prefix = contents.substring(0, position);
    IJavaProject javaProject = searchContext.getJavaProject();
    final List<IContentProposal> result = new ArrayList<IContentProposal>(100);

    // Resource matches
    IProject project = javaProject.getProject();
    try {/* w ww .j a  v a  2 s  . c  om*/
        project.accept(new IResourceProxyVisitor() {
            public boolean visit(IResourceProxy proxy) throws CoreException {
                if (proxy.getType() == IResource.FILE) {
                    if (proxy.getName().toLowerCase().startsWith(prefix)
                            && proxy.getName().toLowerCase().endsWith(XML_SUFFIX)) {
                        result.add(new ResourceProposal(proxy.requestResource()));
                    }
                    return false;
                }
                // Recurse into everything else
                return true;
            }
        }, 0);
    } catch (CoreException e) {
        Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for resources.", e));
    }

    // Class matches
    final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
    final TypeNameRequestor requestor = new TypeNameRequestor() {
        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path) {
            if (!Flags.isAbstract(modifiers) && (Flags.isPublic(modifiers) || Flags.isProtected(modifiers))) {
                result.add(new JavaContentProposal(new String(packageName), new String(simpleTypeName), false));
            }
        };
    };
    final IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().searchAllTypeNames(null, 0, prefix.toCharArray(),
                        SearchPattern.R_PREFIX_MATCH, IJavaSearchConstants.CLASS, scope, requestor,
                        IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, monitor);
            } catch (JavaModelException e) {
                throw new InvocationTargetException(e);
            }
        }
    };
    IRunnableContext runContext = searchContext.getRunContext();
    try {
        if (runContext != null) {
            runContext.run(false, false, runnable);
        } else {
            runnable.run(new NullProgressMonitor());
        }
    } catch (InvocationTargetException e) {
        Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for classes.",
                e.getTargetException()));
    } catch (InterruptedException e) {
        // Reset the interruption status and continue
        Thread.currentThread().interrupt();
    }
    return result;
}

From source file:ca.uvic.chisel.diver.sequencediagrams.sc.java.editors.JavaSequenceLabelProvider.java

License:Open Source License

public Color getBackground(Object element) {
    if (element instanceof IAdaptable) {
        IJavaElement javaElement = (IJavaElement) ((IAdaptable) element).getAdapter(IJavaElement.class);
        if (javaElement instanceof IMember) {
            try {
                int flags = ((IMember) javaElement).getFlags();
                if (Flags.isAbstract(flags) || Flags.isInterface(flags)) {
                    return Display.getCurrent().getSystemColor(SWT.COLOR_GRAY);
                }/*ww  w  .  ja  v  a2s.c  o m*/
                if (javaElement instanceof IMethod) {
                    if (Flags.isPrivate(flags)) {
                        return ISketchColorConstants.PRIVATE_BG;
                    } else if (Flags.isProtected(flags)) {
                        return ISketchColorConstants.PROTECTED_BG;
                    } else if (Flags.isPackageDefault(flags)) {
                        return ISketchColorConstants.LIGHT_BLUE;
                    } else if (Flags.isPublic(flags)) {
                        return ISketchColorConstants.PUBLIC_BG;
                    }
                }
            } catch (JavaModelException e) {
                //just return null
            }
        } else if (javaElement instanceof IPackageFragment) {
            return ISketchColorConstants.PRIVATE_BG;
        }
    }
    return null;
}

From source file:com.codenvy.ide.ext.java.server.SourcesFromBytecodeGenerator.java

License:Open Source License

private String getModifiers(int flags, int typeFlags) {
    StringBuilder modifiers = new StringBuilder();
    //package private modifier has no string representation

    if (Flags.isPublic(flags)) {
        modifiers.append("public ");
    }/* w  w w. ja  v  a  2s.  c o  m*/

    if (Flags.isProtected(flags)) {
        modifiers.append("protected ");
    }

    if (Flags.isPrivate(flags)) {
        modifiers.append("private ");
    }

    if (Flags.isStatic(flags)) {
        modifiers.append("static ");
    }

    if (Flags.isAbstract(flags) && !Flags.isInterface(typeFlags)) {
        modifiers.append("abstract ");
    }

    if (Flags.isFinal(flags)) {
        modifiers.append("final ");
    }

    if (Flags.isNative(flags)) {
        modifiers.append("native ");
    }

    if (Flags.isSynchronized(flags)) {
        modifiers.append("synchronized ");
    }

    if (Flags.isVolatile(flags)) {
        modifiers.append("volatile ");
    }

    int len = modifiers.length();
    if (len == 0)
        return "";
    modifiers.setLength(len - 1);
    return modifiers.toString();
}

From source file:com.google.gwt.eclipse.core.editors.java.JsniMethodBodyCompletionProposalComputer.java

License:Open Source License

private static JavaCompletionProposal createProposal(int flags, String replacementString, int replacementOffset,
        int numCharsFilled, int numCharsToOverwrite, String displayString) {
    Image image;/*from w  ww .  j  a  va2  s .com*/
    GWTPlugin plugin = GWTPlugin.getDefault();
    if (Flags.isPublic(flags)) {
        image = plugin.getImage(GWTImages.JSNI_PUBLIC_METHOD_SMALL);
    } else if (Flags.isPrivate(flags)) {
        image = plugin.getImage(GWTImages.JSNI_PRIVATE_METHOD_SMALL);
    } else if (Flags.isProtected(flags)) {
        image = plugin.getImage(GWTImages.JSNI_PROTECTED_METHOD_SMALL);
    } else {
        image = plugin.getImage(GWTImages.JSNI_DEFAULT_METHOD_SMALL);
    }
    replacementString = replacementString.substring(numCharsFilled);
    return new JavaCompletionProposal(replacementString, replacementOffset, numCharsToOverwrite, image,
            "/*-{ " + displayString + " }-*/;", 0);
}

From source file:com.google.gwt.eclipse.core.uibinder.contentassist.ElExpressionFirstFragmentComputer.java

License:Open Source License

/**
 * Computes possible first fragments for EL expressions.
 * //from   w  w w .ja v a2 s.  c o  m
 * @param document The document to compute the first fragments from
 * @param xmlFile The xml file the document came from. This is used to
 *          determine the java files that references this ui.xml file so that
 *          "package" of this ui.xml file can be determined for importing
 *          protected or package default fields. May be null, but protected /
 *          package default fields can't be checked for visibility.
 * @param javaProject The java project the document belongs to.
 * @param problemMarkerManager The problem marker manage to mark problems as
 *          the fragments are identified. May be null.
 * @return An ElExpressionFirstFragmentComputer that contains first fragments
 *         and duplicate first fragments.
 */
public static ElExpressionFirstFragmentComputer compute(Document document, final IFile xmlFile,
        final IJavaProject javaProject, final UiBinderProblemMarkerManager problemMarkerManager) {
    final Set<ElExpressionFirstFragment> fragments = new HashSet<ElExpressionFirstFragment>();
    final Set<ElExpressionFirstFragment> dupFragments = new HashSet<ElExpressionFirstFragment>();

    XmlUtilities.visitNodes(document, new NodeVisitor() {

        public boolean visitNode(Node node) {
            if (node.getNodeType() != Node.ELEMENT_NODE) {
                return true;
            }

            List<ElExpressionFirstFragment> currentFirstFragments = new ArrayList<ElExpressionFirstFragment>();

            if (!UiBinderXmlModelUtilities.isImportElement(node)) {
                ElExpressionFirstFragment elExpressionFirstFragment = createFirstFragmentWithFieldAttribute(
                        node);
                if (elExpressionFirstFragment == null) {
                    if (UiBinderXmlModelUtilities.isStyleElement(node)) {
                        elExpressionFirstFragment = new ElExpressionFirstFragment(
                                UiBinderConstants.UI_BINDER_STYLE_ELEMENT_IMPLICIT_FIELD_VALUE, node);
                    }
                }

                if (elExpressionFirstFragment != null) {
                    currentFirstFragments.add(elExpressionFirstFragment);
                }
            } else {
                List<ElExpressionFirstFragment> imports = getFirstFragmentsFromImport(node);
                currentFirstFragments.addAll(imports);
            }

            for (ElExpressionFirstFragment elExpressionFirstFragment : currentFirstFragments) {
                ElExpressionFirstFragment fragment = findFragment(elExpressionFirstFragment.getValue());
                if (fragment != null) {
                    /**
                     * The original is placed in fragments and dupFragments to reduce
                     * popping up misleading problems on {style.blah} where it would
                     * complain the fragment blah is not found.
                     */
                    dupFragments.add(fragment);
                    dupFragments.add(elExpressionFirstFragment);
                } else {
                    fragments.add(elExpressionFirstFragment);
                }
            }

            return true;
        }

        private ImportResult canImportField(IField field) {

            try {
                int flags = field.getFlags();

                if (!Flags.isStatic(flags)) {

                    // if it's an enum, then it doesn't have any of these modifiers, but
                    // can still be imported
                    if (Flags.isEnum(flags)) {
                        return ImportResult.YES;
                    } else {
                        // must be static
                        return ImportResult.FIELD_NOT_STATIC;
                    }

                } else if (Flags.isPrivate(flags)) {

                    return ImportResult.FIELD_NOT_VISIBLE;

                } else if (Flags.isProtected(flags) || Flags.isPackageDefault(flags)) {
                    // if it's protected / package default, packages must be the same
                    IPackageDeclaration[] decs = field.getCompilationUnit().getPackageDeclarations();
                    if (decs.length > 0 && xmlFile != null) {
                        String enclosingTypeDec = decs[0].getElementName();
                        Set<IType> ownerTypes = UiBinderUtilities.getSubtypesFromXml(xmlFile, javaProject);
                        for (IType type : ownerTypes) {
                            if (!enclosingTypeDec.equals(type.getPackageFragment().getElementName())) {
                                return ImportResult.FIELD_NOT_VISIBLE;
                            }
                        }

                    } else {
                        // default package
                        return ImportResult.TYPE_NOT_VISIBLE;
                    }
                }
            } catch (JavaModelException e) {
                return ImportResult.ERROR;
            }

            return ImportResult.YES;
        }

        /**
         * Checks if t1 is accessible from t2 for the purposes of UiBinder. In the
         * case of nested inner classes, t1 and all of its enclosing classes are
         * recursively checked for accessibility from t2, and the first
         * inaccessible type is returned.
         * 
         * @param t1 The target type to check for accessibility
         * @param t2 The source type to check for accessibility from
         * @return null if t1 is accessible from t2, or the first type found that
         *         is inaccessible
         */
        private IType computeFirstInaccessibleType(IType t1, IType t2) {

            int flags;
            try {
                flags = t1.getFlags();
            } catch (JavaModelException e) {
                return t1;
            }

            if (Flags.isPrivate(flags)) {
                return t1;
            } else if (Flags.isProtected(flags) || Flags.isPackageDefault(flags)) {
                // check if the type's packages are the same if t1 is protected or
                // package default.
                // don't need to worry about inheritance with the protected case
                // because UiBinder subtypes
                // can't inherit from arbitrary classes.

                boolean samePackage = t1.getPackageFragment().getElementName()
                        .equals(t2.getPackageFragment().getElementName());

                if (!samePackage) {
                    return t1;
                }
            }

            // don't need to check public because we're going to recurse up into
            // possible container classes until we hit null, which means we haven't
            // any problems (ie, public is never a problem)

            if (t1.getParent() instanceof IType) {
                return computeFirstInaccessibleType((IType) t1.getParent(), t2);
            } else {
                return null;
            }
        }

        private ElExpressionFirstFragment createFirstFragmentWithFieldAttribute(Node node) {

            Node fieldAttr = UiBinderXmlModelUtilities.getFieldAttribute(node);
            if (fieldAttr == null || fieldAttr.getNodeValue() == null) {
                return null;
            }

            ElExpressionFirstFragment elExpressionFirstFragment = new ElExpressionFirstFragment(
                    fieldAttr.getNodeValue(), node);
            return elExpressionFirstFragment;
        }

        private ElExpressionFirstFragment findFragment(String fragmentStr) {
            for (ElExpressionFirstFragment curFragment : fragments) {
                if (curFragment.getValue().equals(fragmentStr)) {
                    return curFragment;
                }
            }

            return null;
        }

        private List<ElExpressionFirstFragment> getFirstFragmentsFromImport(Node node) {

            Node importFieldNode = UiBinderXmlModelUtilities.getFieldAttribute(node);
            if (importFieldNode == null) {
                markProblem(node, ImportResult.IMPORT_MISSING_FIELD_ATTR);
                return Collections.emptyList();
            }

            String importFieldValue = importFieldNode.getNodeValue();
            String lastFragment = importFieldValue.substring(importFieldValue.lastIndexOf('.') + 1);

            // didn't enter anything!
            if (lastFragment.length() == 0) {
                markProblem(importFieldNode, ImportResult.TYPE_UNDEFINED);
                return Collections.emptyList();
            }

            // the class from which we're importing fields
            IType enclosingType = UiBinderXmlModelUtilities.resolveElementToJavaType((IDOMElement) node,
                    javaProject);

            // make sure the enclosing type exists
            if (enclosingType == null) {
                markProblem(importFieldNode, ImportResult.TYPE_UNDEFINED);
                return Collections.emptyList();
            }

            if (xmlFile != null) {
                boolean problemFound = false;
                // make sure the subtype can access the enclosing type
                Set<IType> subtypes = UiBinderUtilities.getSubtypesFromXml(xmlFile, javaProject);
                for (IType type : subtypes) {
                    IType inaccessibleType = computeFirstInaccessibleType(enclosingType, type);
                    if (inaccessibleType != null) {
                        markProblem(importFieldNode, ImportResult.TYPE_NOT_VISIBLE,
                                inaccessibleType.getFullyQualifiedName('.'));
                        problemFound = true;
                    }
                }

                if (problemFound) {
                    return Collections.emptyList();
                }
            }

            List<ElExpressionFirstFragment> fragments = new ArrayList<ElExpressionFirstFragment>();

            IField[] fields;
            try {
                fields = enclosingType.getFields();
            } catch (JavaModelException e) {
                GWTPluginLog.logError(e);
                return Collections.emptyList();
            }

            // import a glob, import everything we can from the type
            if ("*".equals(lastFragment)) {
                for (IField field : fields) {
                    if (canImportField(field) == ImportResult.YES) {
                        ElExpressionFirstFragment elExpressionFirstFragment = new ElExpressionFirstFragment(
                                field.getElementName(), node);
                        fragments.add(elExpressionFirstFragment);
                    }
                }

            } else { // import a single field

                IField field = JavaModelSearch.findField(enclosingType, lastFragment);
                if (field != null) {

                    ImportResult ir;
                    if ((ir = canImportField(field)) == ImportResult.YES) {

                        ElExpressionFirstFragment elExpressionFirstFragment = new ElExpressionFirstFragment(
                                lastFragment, node);
                        fragments.add(elExpressionFirstFragment);

                    } else {
                        markProblem(importFieldNode, ir);
                    }
                } else {
                    markProblem(importFieldNode, ImportResult.FIELD_UNDEFINED);
                }
            }
            return fragments;
        }

        private void markProblem(Node node, ImportResult ir) {
            markProblem(node, ir, null);
        }

        private void markProblem(Node node, ImportResult ir, String text) {
            if (problemMarkerManager != null) {

                if (text == null) {
                    text = node.getNodeValue();
                }

                IRegion region;
                if (node instanceof IDOMAttr) {
                    region = XmlUtilities.getAttributeValueRegion((IDOMAttr) node);
                } else if (node instanceof IDOMElement) {
                    int start = ((IDOMElement) node).getStartOffset();
                    int end = ((IDOMElement) node).getStartEndOffset();
                    region = new Region(start, end - start);
                } else {
                    return;
                }

                switch (ir) {
                case FIELD_NOT_STATIC:
                    problemMarkerManager.setFieldNotStaticError(region, text);
                    break;
                case FIELD_NOT_VISIBLE:
                    problemMarkerManager.setFieldNotVisibleError(region, text);
                    break;
                case FIELD_UNDEFINED:
                    problemMarkerManager.setFieldUndefinedError(region, text);
                    break;
                case TYPE_NOT_VISIBLE:
                    problemMarkerManager.setTypeNotVisibleError(region, text);
                    break;
                case TYPE_UNDEFINED:
                    problemMarkerManager.setTypeUndefinedError(region, text);
                    break;
                case IMPORT_MISSING_FIELD_ATTR:
                    problemMarkerManager.setImportMissingFieldAttr(region, text);
                    break;
                default:
                    GWTPluginLog.logWarning("Unknown UiBinder XML problem type: " + ir.toString());
                    break;
                }
            }
        }
    });

    return new ElExpressionFirstFragmentComputer(fragments, dupFragments);
}

From source file:com.inepex.classtemplater.plugin.logic.Attribute.java

License:Eclipse Public License

public Attribute(IField field) throws Exception {
    String sign = field.getTypeSignature();
    processSignature(sign);/* ww w .ja v a 2s  .c om*/

    String visibility = "";
    if (Flags.isPublic(field.getFlags()))
        visibility = "public";
    else if (Flags.isPrivate(field.getFlags()))
        visibility = "private";
    else if (Flags.isProtected(field.getFlags()))
        visibility = "protected";
    else
        visibility = "public";

    name = field.getElementName();
    this.visibility = visibility;
    setVisibility(visibility);
    isStatic = Flags.isStatic(field.getFlags());
    isAbstract = Flags.isAbstract(field.getFlags());
    isFinal = Flags.isFinal(field.getFlags());

    try {
        String[][] type = field.getDeclaringType()
                .resolveType(field.getTypeSignature().substring(1, field.getTypeSignature().length() - 1));
        isEnum = field.getJavaProject().findType(type[0][0] + "." + type[0][1]).isEnum();
    } catch (Exception e) {
        System.out.println("Error at enum check" + e.getMessage());
    }

    //annotations
    annotations = Annotation.getAnnotationsOf(field, field.getCompilationUnit());

    workspaceRelativePath = ResourceUtil.getWorkspaceRelativePath(field.getCompilationUnit());

    packageName = ((ICompilationUnit) field.getParent().getParent()).getPackageDeclarations()[0]
            .getElementName();
}

From source file:com.iw.plugins.spindle.core.util.CoreUtils.java

License:Mozilla Public License

/**
 * Evaluates if a member (possible from another package) is visible from elements in a package.
 * //from   w  ww.  jav  a2 s  .com
 * @param member
 *            The member to test the visibility for
 * @param pack
 *            The package in focus
 */
public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException {
    int otherflags = member.getFlags();

    if (Flags.isPublic(otherflags) || Flags.isProtected(otherflags)) {
        return true;
    } else if (Flags.isPrivate(otherflags)) {
        return false;
    }

    IPackageFragment otherpack = (IPackageFragment) findElementOfKind(member, IJavaElement.PACKAGE_FRAGMENT);
    return (pack != null && pack.equals(otherpack));
}