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

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

Introduction

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

Prototype

String getElementName();

Source Link

Document

Returns the name of this element.

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.SourceMapper.java

License:Open Source License

/**
 * Returns the <code>SourceRange</code> for the given element, or
 * {-1, -1} if no source range is known for the element.
 *//*from w  w  w.j av a2s  .  co m*/
public SourceRange getSourceRange(IJavaElement element) {
    switch (element.getElementType()) {
    case IJavaElement.METHOD:
        if (((IMember) element).isBinary()) {
            IJavaElement[] el = getUnqualifiedMethodHandle((IMethod) element, false);
            if (el[1] != null && this.sourceRanges.get(el[0]) == null) {
                element = getUnqualifiedMethodHandle((IMethod) element, true)[0];
            } else {
                element = el[0];
            }
        }
        break;
    case IJavaElement.TYPE_PARAMETER:
        IJavaElement parent = element.getParent();
        if (parent.getElementType() == IJavaElement.METHOD) {
            IMethod method = (IMethod) parent;
            if (method.isBinary()) {
                IJavaElement[] el = getUnqualifiedMethodHandle(method, false);
                if (el[1] != null && this.sourceRanges.get(el[0]) == null) {
                    method = (IMethod) getUnqualifiedMethodHandle(method, true)[0];
                } else {
                    method = (IMethod) el[0];
                }
                element = method.getTypeParameter(element.getElementName());
            }
        }
        break;
    case IJavaElement.LOCAL_VARIABLE:
        LocalVariableElementKey key = new LocalVariableElementKey(element.getParent(),
                element.getElementName());
        SourceRange[] ranges = (SourceRange[]) this.parametersRanges.get(key);
        if (ranges == null) {
            return UNKNOWN_RANGE;
        } else {
            return ranges[0];
        }
    }
    SourceRange[] ranges = (SourceRange[]) this.sourceRanges.get(element);
    if (ranges == null) {
        return UNKNOWN_RANGE;
    } else {
        return ranges[0];
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.SourceMapper.java

License:Open Source License

/**
 * Returns the type with the given <code>typeName</code>.  Returns inner classes
 * as well.//from w  w w  .  j a v a2  s.c om
 */
protected IType getType(String typeName) {
    if (typeName.length() == 0) {
        IJavaElement classFile = this.binaryType.getParent();
        String classFileName = classFile.getElementName();
        StringBuffer newClassFileName = new StringBuffer();
        int lastDollar = classFileName.lastIndexOf('$');
        for (int i = 0; i <= lastDollar; i++)
            newClassFileName.append(classFileName.charAt(i));
        newClassFileName.append(Integer.toString(this.anonymousCounter));
        PackageFragment pkg = (PackageFragment) classFile.getParent();
        return new BinaryType(new ClassFile(pkg, manager, newClassFileName.toString()), manager, typeName);
    } else if (this.binaryType.getElementName().equals(typeName))
        return this.binaryType;
    else
        return this.binaryType.getType(typeName);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.util.JavaElementFinder.java

License:Open Source License

public void consumeAnnotation() {
    if (!(this.element instanceof IAnnotatable))
        return;//  w  ww.java 2s  . c  o  m
    int size = this.types.size();
    if (size == 0)
        return;
    IJavaElement annotationType = ((org.eclipse.jdt.internal.core.util.JavaElementFinder) this.types
            .get(size - 1)).element;
    this.element = ((IAnnotatable) this.element).getAnnotation(annotationType.getElementName());
}

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

License:Open Source License

private void addValue(StringBuffer buf, IJavaElement element, Object value) throws URISyntaxException {
    // Note: To be bug-compatible with Javadoc from Java 5/6/7, we currently don't escape HTML tags in String-valued annotations.
    if (value instanceof ITypeBinding) {
        ITypeBinding typeBinding = (ITypeBinding) value;
        IJavaElement type = typeBinding.getJavaElement();
        if (type == null) {
            buf.append(typeBinding.getName());
        } else {/*from  w ww. ja  v a2s  .co  m*/
            String uri = JavaElementLinks.createURI(baseHref, type);
            String name = type.getElementName();
            addLink(buf, uri, name);
        }
        buf.append(".class"); //$NON-NLS-1$

    } else if (value instanceof IVariableBinding) { // only enum constants
        IVariableBinding variableBinding = (IVariableBinding) value;
        IJavaElement variable = variableBinding.getJavaElement();
        String uri = JavaElementLinks.createURI(baseHref, variable);
        String name = variable.getElementName();
        addLink(buf, uri, name);

    } else if (value instanceof IAnnotationBinding) {
        IAnnotationBinding annotationBinding = (IAnnotationBinding) value;
        addAnnotation(buf, element, annotationBinding);

    } else if (value instanceof String) {
        buf.append(ASTNodes.getEscapedStringLiteral((String) value));

    } else if (value instanceof Character) {
        buf.append(ASTNodes.getEscapedCharacterLiteral((Character) value));

    } else if (value instanceof Object[]) {
        Object[] values = (Object[]) value;
        buf.append('{');
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                buf.append(JavaElementLabels.COMMA_STRING);
            }
            addValue(buf, element, values[i]);
        }
        buf.append('}');

    } else { // primitive types (except char) or null
        buf.append(String.valueOf(value));
    }
}

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

License:Open Source License

private static IPackageFragment findSinglePackageChild(IPackageFragment fragment, IJavaElement[] children) {
    String prefix = fragment.getElementName() + '.';
    int prefixLen = prefix.length();
    IPackageFragment found = null;/*from   w w w  .  ja  v a  2 s. com*/
    for (int i = 0; i < children.length; i++) {
        IJavaElement element = children[i];
        String name = element.getElementName();
        if (name.startsWith(prefix) && name.length() > prefixLen && name.indexOf('.', prefixLen) == -1) {
            if (found == null) {
                found = (IPackageFragment) element;
            } else {
                return null;
            }
        }
    }
    return found;
}

From source file:com.drgarbage.bytecodevisualizer.compare.CompareElement.java

License:Apache License

/**
 * Returns the class name for the given java element.
 * @param javaElement//from w w w .j a  va 2s  .c om
 * @return class name
 */
private static String getClassName(IJavaElement javaElement) {
    String name;
    IClassFile classFile = (IClassFile) javaElement.getAncestor(IJavaElement.CLASS_FILE);
    if (classFile != null) {
        name = classFile.getPath().toOSString();
    } else {
        if (javaElement.getPath() != null) {
            name = javaElement.getPath().toOSString();
        } else {
            name = javaElement.getElementName();
        }
    }

    return name;
}

From source file:com.drgarbage.bytecodevisualizer.editors.BytecodeEditor.java

License:Apache License

/**
 * Selects the line for the given element:
 * - ClassFileSection//from  w  ww  .  j a v  a  2s .  c om
 * - MethodSection
 * - Variable
 * 
 * @param element
 * @param line
 * @param markLine true if the line has to be marked
 */
public void setSelection(IJavaElement element, int line, boolean markLine) {

    if (element == null) {
        return;
    }

    switch (element.getElementType()) {
    case IJavaElement.FIELD: /* select field */
        String fieldName = element.getElementName();
        IFieldSection fieldSection = byteCodeDocumentProvider.getClassFileDocument()
                .findFieldSection(fieldName);
        if (fieldSection != null) {
            selectBytecodeLineAndReveal(fieldSection.getBytecodeDocumentLine(), fieldName, IJavaElement.FIELD);
        }
        break;
    case IJavaElement.METHOD: /* select method */
        IMethod method = (IMethod) element;
        try {
            String methodName;
            if (method.isConstructor()) {
                methodName = "<init>";
            } else {
                methodName = method.getElementName();
            }

            String methodSignature = ClassFileDocumentsUtils.resolveMethodSignature(method);
            IMethodSection methodSection = byteCodeDocumentProvider.getClassFileDocument()
                    .findMethodSection(methodName, methodSignature);

            if (methodSection != null) {
                if (line == IClassFileEditor.INVALID_LINE || line == IClassFileEditor.METHOD_DECLARATION_LINE) {

                    if (method.isConstructor()) {
                        methodName = method.getElementName();
                    }
                    selectBytecodeLineAndReveal(methodSection.getFirstLine(), methodName, IJavaElement.METHOD);
                } else {
                    selectLineAndRevaluate2(methodSection.getBytecodeLine(line) - 1, markLine);
                }
                break;
            }

        } catch (JavaModelException e) {
            BytecodeVisualizerPlugin
                    .log(new Status(IStatus.ERROR, BytecodeVisualizerPlugin.PLUGIN_ID, e.getMessage(), e));
        }

    default:
        /* select class */
        IClassFileDocument doc = byteCodeDocumentProvider.getClassFileDocument();
        if (doc != null) {
            int docLine = doc.getClassSignatureDocumentLine();
            selectBytecodeLineAndReveal(docLine, element.getElementName(), IJavaElement.CLASS_FILE);
        }
    }

    /* call cursor hook */
    doHandleCursorPositionChanged();
}

From source file:com.drgarbage.sourcecodevisualizer.actions.OpenGraphInControlflowgraphFactory.java

License:Apache License

public void run() {

    IExternalCommunication comunicationObject = CorePlugin.getExternalCommunication();
    if (comunicationObject == null) {
        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ERROR_CFGF_is_not_installed;
        Messages.error(msg);/*  w  w w  .  j a v a 2 s . co  m*/
        return;
    }

    IMethod method = editor.getSelectedMethod();

    if (method == null) {
        String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + "The selected method object is null.";
        IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, null);
        CorePlugin.log(s);

        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ExceptionAdditionalMessage;
        Messages.error(msg);
        return;
    }

    String[] classPath = null;
    String packageName = null;
    String className = null;
    String methodName = null;
    String methodSig = null;

    IDocumentProvider p = editor.getDocumentProvider();
    if (p instanceof ICompilationUnitDocumentProvider) {
        ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
        ICompilationUnit unit = cp.getWorkingCopy(editor.getEditorInput());
        IJavaProject jp = unit.getJavaProject();

        try {
            /* get class path */
            classPath = JavaRuntime.computeDefaultRuntimeClassPath(jp);

            /* get package name and classes */
            IJavaElement[] elements = unit.getChildren();
            for (IJavaElement element : elements) {
                if (element.getElementType() == IJavaElement.PACKAGE_DECLARATION) {
                    packageName = element.getElementName();
                    break;
                }
            }

        } catch (JavaModelException e) {
            String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + "Can not get packege or class name.";
            IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
            CorePlugin.log(s);

            String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + CoreMessages.ExceptionAdditionalMessage;
            Messages.error(msg);

            return;

        } catch (CoreException e) {
            String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + "Can not compute runtime class path.";
            IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
            CorePlugin.log(s);

            String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + CoreMessages.ExceptionAdditionalMessage;
            Messages.error(msg);

            return;
        }

    }

    /* package and class name */
    IType classType = method.getDeclaringType();
    className = classType.getElementName();

    /* method name */
    methodName = method.getElementName();

    /* method name */
    try {
        if (method.isConstructor()) {
            methodName = constructorString;
        } else {
            methodName = method.getElementName();
        }

        /* resolve parameter signature */
        StringBuffer buf = new StringBuffer("(");
        String[] parameterTypes = method.getParameterTypes();
        String res = null;
        for (int i = 0; i < parameterTypes.length; i++) {
            res = ActionUtils.getResolvedTypeName(parameterTypes[i], method.getDeclaringType());
            buf.append(res);
        }
        buf.append(")");

        res = ActionUtils.getResolvedTypeName(method.getReturnType(), method.getDeclaringType());
        buf.append(res);

        methodSig = buf.toString();

    } catch (IllegalArgumentException e) {
        String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n' + e.getMessage();
        IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
        CorePlugin.log(s);

        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ExceptionAdditionalMessage;
        Messages.error(msg);

        return;

    } catch (JavaModelException e) {
        String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n' + e.getMessage();
        IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
        CorePlugin.log(s);

        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ExceptionAdditionalMessage;
        Messages.error(msg);

        return;
    }

    StringBuffer buf = new StringBuffer();
    buf.append(className);
    buf.append(".");
    if (methodName.equals(constructorString)) {
        buf.append(className);
    } else {
        buf.append(methodName);
    }

    buf.append(".src.graph");

    comunicationObject.generateGraph(buf.toString(), classPath, packageName, className, methodName, methodSig);
}

From source file:com.drgarbage.sourcecodevisualizer.editors.SourcecodeGraphUtils.java

License:Apache License

/**
 * Create a list of graphs./*from  w w  w . ja  v a2 s.  co  m*/
 * @return list of graphs
 */
public static List<IDirectedGraphExt> createGraphs(ICompilationUnit unit, IJavaProject jp) {

    String[] classpath = null;
    String packageName = "";
    List<String> classList = new ArrayList<String>();

    try {
        /* get class path */
        classpath = JavaRuntime.computeDefaultRuntimeClassPath(jp);

        /* get package name and classes */
        IJavaElement[] elements = unit.getChildren();
        for (IJavaElement element : elements) {
            if (element.getElementType() == IJavaElement.PACKAGE_DECLARATION) {
                packageName = element.getElementName();
            } else if (element.getElementType() == IJavaElement.TYPE) {
                ClassFileDocumentsUtils.collectNestedClasses((SourceType) element, classList);
            }
        }

    } catch (JavaModelException e) {
        handleException(e);
        return null;
    } catch (CoreException e) {
        handleException(e);
        return null;
    }

    List<IDirectedGraphExt> graphs = null;

    /* Load compiled class files */
    try {
        graphs = ControlFlowGraphGenerator.generateSourceCodeGraphs(classList, classpath, packageName, false,
                false, false);
    } catch (IOException e) {
        handleException(e);
        return null;
    } catch (ControlFlowGraphException e) {
        handleException(e);
        return null;
    }

    return graphs;
}

From source file:com.ebmwebsourcing.petals.common.internal.provisional.projectscnf.PetalsProjectsSorter.java

License:Open Source License

/**
 * Compares Java elements./*w w w  .j  a v a 2 s.  c  o m*/
 * @param j1
 * @param j2
 * @return an integer for sorting (0 if equivalent, <0 to display j1 first, >0 to display j2 first)
 */
private int compareJavaElements(IJavaElement j1, IJavaElement j2) {

    // Fragment roots have a special treatment
    if (j1 instanceof IPackageFragmentRoot && j2 instanceof IPackageFragmentRoot) {
        IPackageFragmentRoot p1 = (IPackageFragmentRoot) j1;
        IPackageFragmentRoot p2 = (IPackageFragmentRoot) j2;

        try {
            if (p1.getKind() == p2.getKind())
                return p1.getElementName().compareTo(p2.getElementName());
            else if (p1.getKind() == IPackageFragmentRoot.K_SOURCE)
                return -1;
            else
                return 1;

        } catch (JavaModelException e) {
            PetalsCommonPlugin.log(e, IStatus.ERROR);
        }

        return p1.getElementName().compareTo(p2.getElementName());
    }

    // Otherwise, it depends on the element type
    if (j1.getElementType() == j2.getElementType())
        return j1.getElementName().compareTo(j2.getElementName());
    else
        return j1.getElementType() - j2.getElementType();
}