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

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

Introduction

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

Prototype

int COMPILATION_UNIT

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

Click Source Link

Document

Constant representing a Java compilation unit.

Usage

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

License:Open Source License

private IPath getPath(IJavaElement element, boolean relativeToRoot) {
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        return Path.EMPTY;
    case IJavaElement.JAVA_PROJECT:
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        if (relativeToRoot)
            return Path.EMPTY;
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT:
        String relativePath = Util.concatWith(((PackageFragment) element).names, '/');
        return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath));
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.CLASS_FILE:
        return getPath(element.getParent(), relativeToRoot).append(new Path(element.getElementName()));
    default:// w ww .j a  va  2s.c om
        return getPath(element.getParent(), relativeToRoot);
    }
}

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

License:Open Source License

public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames,
        String path, AccessRestriction access) {

    // Get type//from  w  w w  . j ava 2 s.  com
    try {
        IType type = null;
        if (this.handleFactory != null) {
            //todo openable
            Openable openable = null;//this.handleFactory.createOpenable(path, this.scope);
            if (openable == null)
                return;
            switch (openable.getElementType()) {
            case IJavaElement.COMPILATION_UNIT:
                ICompilationUnit cu = (ICompilationUnit) openable;
                if (enclosingTypeNames != null && enclosingTypeNames.length > 0) {
                    type = cu.getType(new String(enclosingTypeNames[0]));
                    for (int j = 1, l = enclosingTypeNames.length; j < l; j++) {
                        type = type.getType(new String(enclosingTypeNames[j]));
                    }
                    type = type.getType(new String(simpleTypeName));
                } else {
                    type = cu.getType(new String(simpleTypeName));
                }
                break;
            case IJavaElement.CLASS_FILE:
                type = ((IClassFile) openable).getType();
                break;
            }
        } else {
            int separatorIndex = path.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR);
            type = separatorIndex == -1
                    ? createTypeFromPath(path, new String(simpleTypeName), enclosingTypeNames)
                    : createTypeFromJar(path, separatorIndex);
        }

        // Accept match if the type has been found
        if (type != null) {
            // hierarchy scopes require one more check:
            if (!(this.scope instanceof org.eclipse.jdt.internal.core.search.HierarchyScope)
                    || ((HierarchyScope) this.scope).enclosesFineGrained(type)) {

                // Create the match
                final JavaSearchTypeNameMatch match = new JavaSearchTypeNameMatch(type, modifiers);

                // Update match accessibility
                if (access != null) {
                    switch (access.getProblemId()) {
                    case IProblem.ForbiddenReference:
                        match.setAccessibility(IAccessRule.K_NON_ACCESSIBLE);
                        break;
                    case IProblem.DiscouragedReference:
                        match.setAccessibility(IAccessRule.K_DISCOURAGED);
                        break;
                    }
                }

                // Accept match
                this.requestor.acceptTypeNameMatch(match);
            }
        }
    } catch (JavaModelException e) {
        // skip
    }
}

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

License:Open Source License

public IJavaElement getPrimaryElement(boolean checkOwner) {
    if (checkOwner) {
        CompilationUnit cu = (CompilationUnit) getAncestor(COMPILATION_UNIT);
        if (cu.isPrimary())
            return this;
    }/*from  ww  w.  j  a va 2  s.c om*/
    IJavaElement primaryParent = this.parent.getPrimaryElement(false);
    switch (primaryParent.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
        return ((ICompilationUnit) primaryParent).getType(this.name);
    case IJavaElement.TYPE:
        return ((IType) primaryParent).getType(this.name);
    case IJavaElement.FIELD:
    case IJavaElement.INITIALIZER:
    case IJavaElement.METHOD:
        return ((IMember) primaryParent).getType(this.name, this.occurrenceCount);
    }
    return this;
}

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

License:Open Source License

public TypeDeclaration findType(IType typeHandle) {
    IJavaElement parent = typeHandle.getParent();
    final char[] typeName = typeHandle.getElementName().toCharArray();
    final int occurenceCount = ((SourceType) typeHandle).occurrenceCount;
    final boolean findAnonymous = typeName.length == 0;
    class Visitor extends ASTVisitor {
        TypeDeclaration result;/*  w  ww.j a  va  2s .c om*/
        int count = 0;

        public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) {
            if (this.result != null)
                return false;
            if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
                if (findAnonymous && ++this.count == occurenceCount) {
                    this.result = typeDeclaration;
                }
            } else {
                if (!findAnonymous && CharOperation.equals(typeName, typeDeclaration.name)) {
                    this.result = typeDeclaration;
                }
            }
            return false; // visit only one level
        }
    }
    switch (parent.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
        TypeDeclaration[] types = this.unit.types;
        if (types != null) {
            for (int i = 0, length = types.length; i < length; i++) {
                TypeDeclaration type = types[i];
                if (CharOperation.equals(typeName, type.name)) {
                    return type;
                }
            }
        }
        break;
    case IJavaElement.TYPE:
        TypeDeclaration parentDecl = findType((IType) parent);
        if (parentDecl == null)
            return null;
        types = parentDecl.memberTypes;
        if (types != null) {
            for (int i = 0, length = types.length; i < length; i++) {
                TypeDeclaration type = types[i];
                if (CharOperation.equals(typeName, type.name)) {
                    return type;
                }
            }
        }
        break;
    case IJavaElement.FIELD:
        FieldDeclaration fieldDecl = findField((IField) parent);
        if (fieldDecl == null)
            return null;
        Visitor visitor = new Visitor();
        fieldDecl.traverse(visitor, null);
        return visitor.result;
    case IJavaElement.INITIALIZER:
        Initializer initializer = findInitializer((IInitializer) parent);
        if (initializer == null)
            return null;
        visitor = new Visitor();
        initializer.traverse(visitor, null);
        return visitor.result;
    case IJavaElement.METHOD:
        AbstractMethodDeclaration methodDecl = findMethod((IMethod) parent);
        if (methodDecl == null)
            return null;
        visitor = new Visitor();
        methodDecl.traverse(visitor, (ClassScope) null);
        return visitor.result;
    }
    return null;
}

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

License:Open Source License

/**
 * Create handle by adding child to parent obtained by recursing into parent scopes.
 *///from   w w w.j av a 2  s  .c  o m
private IJavaElement createElement(Scope scope, int elementPosition, ICompilationUnit unit,
        HashSet existingElements, HashMap knownScopes) {
    IJavaElement newElement = (IJavaElement) knownScopes.get(scope);
    if (newElement != null)
        return newElement;

    switch (scope.kind) {
    case Scope.COMPILATION_UNIT_SCOPE:
        newElement = unit;
        break;
    case Scope.CLASS_SCOPE:
        IJavaElement parentElement = createElement(scope.parent, elementPosition, unit, existingElements,
                knownScopes);
        switch (parentElement.getElementType()) {
        case IJavaElement.COMPILATION_UNIT:
            newElement = ((ICompilationUnit) parentElement)
                    .getType(new String(scope.enclosingSourceType().sourceName));
            break;
        case IJavaElement.TYPE:
            newElement = ((IType) parentElement).getType(new String(scope.enclosingSourceType().sourceName));
            break;
        case IJavaElement.FIELD:
        case IJavaElement.INITIALIZER:
        case IJavaElement.METHOD:
            IMember member = (IMember) parentElement;
            if (member.isBinary()) {
                return null;
            } else {
                newElement = member.getType(new String(scope.enclosingSourceType().sourceName), 1);
                // increment occurrence count if collision is detected
                if (newElement != null) {
                    while (!existingElements.add(newElement))
                        ((SourceRefElement) newElement).occurrenceCount++;
                }
            }
            break;
        }
        if (newElement != null) {
            knownScopes.put(scope, newElement);
        }
        break;
    case Scope.METHOD_SCOPE:
        IType parentType = (IType) createElement(scope.parent, elementPosition, unit, existingElements,
                knownScopes);
        MethodScope methodScope = (MethodScope) scope;
        if (methodScope.isInsideInitializer()) {
            // inside field or initializer, must find proper one
            TypeDeclaration type = methodScope.referenceType();
            int occurenceCount = 1;
            int length = type.fields == null ? 0 : type.fields.length;
            for (int i = 0; i < length; i++) {
                FieldDeclaration field = type.fields[i];
                if (field.declarationSourceStart <= elementPosition
                        && elementPosition <= field.declarationSourceEnd) {
                    switch (field.getKind()) {
                    case AbstractVariableDeclaration.FIELD:
                    case AbstractVariableDeclaration.ENUM_CONSTANT:
                        newElement = parentType.getField(new String(field.name));
                        break;
                    case AbstractVariableDeclaration.INITIALIZER:
                        newElement = parentType.getInitializer(occurenceCount);
                        break;
                    }
                    break;
                } else if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
                    occurenceCount++;
                }
            }
        } else {
            // method element
            AbstractMethodDeclaration method = methodScope.referenceMethod();
            newElement = parentType.getMethod(new String(method.selector),
                    Util.typeParameterSignatures(method));
            if (newElement != null) {
                knownScopes.put(scope, newElement);
            }
        }
        break;
    case Scope.BLOCK_SCOPE:
        // standard block, no element per se
        newElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
        break;
    }
    return newElement;
}

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

License:Open Source License

public static final boolean isExcluded(IJavaElement element) {
    int elementType = element.getElementType();
    switch (elementType) {
    case IJavaElement.JAVA_MODEL:
    case IJavaElement.JAVA_PROJECT:
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        return false;

    case IJavaElement.PACKAGE_FRAGMENT:
        PackageFragmentRoot root = (PackageFragmentRoot) element
                .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        File resource = ((PackageFragment) element).resource();
        return resource != null
                && isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars());

    case IJavaElement.COMPILATION_UNIT:
        root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        resource = ((CompilationUnit) element).resource();
        if (resource == null)
            return false;
        if (isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars()))
            return true;
        return isExcluded(element.getParent());

    default://ww  w. j  av a2s.  c om
        IJavaElement cu = element.getAncestor(IJavaElement.COMPILATION_UNIT);
        return cu != null && isExcluded(cu);
    }
}

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

License:Apache License

public static InputStream createStream(IJavaElement javaElement) throws CoreException {
    IClassFile classFile = (IClassFile) javaElement.getAncestor(IJavaElement.CLASS_FILE);

    InputStream stream = null;/*www  .  ja  v a2s .  c om*/
    if (classFile != null) {
        stream = new ByteArrayInputStream(classFile.getBytes());
    } else {
        if (javaElement.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) {
            IType t = (IType) javaElement;
            IJavaProject javaProject = t.getJavaProject();
            String fullyQualifiedName = t.getFullyQualifiedName();
            String className = JavaSourceUtils.getSimpleName(fullyQualifiedName);
            String packageName = JavaSourceUtils.getPackage(fullyQualifiedName);

            String classPath[] = JavaLangUtils.computeRuntimeClassPath(javaProject);
            try {
                stream = JavaLangUtils.findResource(classPath, packageName, className);
            } catch (IOException e) {
                throw new CoreException(
                        new Status(IStatus.ERROR, BytecodeVisualizerPlugin.PLUGIN_ID, e.getMessage(), e));
            }
        } else {
            return null;
        }
    }

    return stream;
}

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

License:Open Source License

@Override
protected CommonViewer createCommonViewerObject(Composite aParent) {

    CommonViewer viewer = super.createCommonViewerObject(aParent);
    viewer.addDoubleClickListener(new IDoubleClickListener() {

        @Override/*  ww  w  .  ja  v  a 2 s. c  om*/
        public void doubleClick(DoubleClickEvent event) {

            if (event.getSelection() instanceof IStructuredSelection) {
                Iterator<?> it = ((IStructuredSelection) event.getSelection()).iterator();
                while (it.hasNext()) {

                    ICompilationUnit cu = null;
                    Object o = it.next();
                    if (o instanceof IJavaElement
                            && ((IJavaElement) o).getElementType() == IJavaElement.COMPILATION_UNIT)
                        cu = (ICompilationUnit) o;

                    if (cu != null) {
                        try {
                            JavaUI.openInEditor(cu);

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

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

    return viewer;
}

From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderContext.java

License:Open Source License

private void prepareBinderNames() throws Exception {
    // template/*w ww.j a v  a2 s.  c o  m*/
    IPath templatePath = m_file.getFullPath();
    String templatePathString = templatePath.toPortableString();
    // package
    IPackageFragment uiPackage;
    {
        if (!(m_file.getParent() instanceof IFolder)) {
            throw new DesignerException(IExceptionConstants.NO_FORM_PACKAGE, templatePathString);
        }
        // prepare package
        IFolder uiFolder = (IFolder) m_file.getParent();
        IJavaElement uiElement = JavaCore.create(uiFolder);
        if (!(uiElement instanceof IPackageFragment)) {
            throw new DesignerException(IExceptionConstants.NO_FORM_PACKAGE, templatePathString);
        }
        uiPackage = (IPackageFragment) uiElement;
        // has client package
        if (!Utils.isModuleSourcePackage(uiPackage)) {
            throw new DesignerException(IExceptionConstants.NOT_CLIENT_PACKAGE, templatePathString);
        }
    }
    // binder resource
    m_binderResourceName = uiPackage.getElementName().replace('.', '/') + "/" + m_file.getName();
    // try current package
    {
        String formName = StringUtils.removeEnd(m_file.getName(), ".ui.xml");
        m_formClassName = uiPackage.getElementName() + "." + formName;
        m_formType = m_javaProject.findType(m_formClassName);
        if (m_formType != null) {
            m_formFile = (IFile) m_formType.getCompilationUnit().getUnderlyingResource();
            prepareBinderClass();
            if (m_binderClassName != null) {
                return;
            }
        }
    }
    // try @UiTemplate
    IType uiTemplateType = m_javaProject.findType("com.google.gwt.uibinder.client.UiTemplate");
    List<IJavaElement> references = CodeUtils.searchReferences(uiTemplateType);
    for (IJavaElement reference : references) {
        if (reference instanceof IAnnotation) {
            IAnnotation annotation = (IAnnotation) reference;
            IMemberValuePair[] valuePairs = annotation.getMemberValuePairs();
            if (valuePairs.length == 1 && valuePairs[0].getValue() instanceof String) {
                String templateName = (String) valuePairs[0].getValue();
                // prepare ICompilationUnit
                ICompilationUnit compilationUnit = (ICompilationUnit) annotation
                        .getAncestor(IJavaElement.COMPILATION_UNIT);
                // prepare qualified template name
                templateName = StringUtils.removeEnd(templateName, ".ui.xml");
                if (templateName.contains(".")) {
                    templateName = templateName.replace('.', '/');
                } else {
                    String packageName = compilationUnit.getPackageDeclarations()[0].getElementName();
                    templateName = packageName.replace('.', '/') + "/" + templateName;
                }
                templateName += ".ui.xml";
                // if found, initialize "form" element
                if (m_binderResourceName.equals(templateName)) {
                    m_formType = (IType) annotation.getParent().getParent();
                    m_formClassName = m_formType.getFullyQualifiedName();
                    m_formFile = (IFile) m_formType.getCompilationUnit().getUnderlyingResource();
                    prepareBinderClass();
                    if (m_binderClassName != null) {
                        return;
                    }
                }
            }
        }
    }
    // no Java form
    throw new DesignerException(IExceptionConstants.NO_FORM_TYPE, m_binderResourceName);
}

From source file:com.google.gdt.eclipse.designer.wizards.ui.JUnitWizardPage.java

License:Open Source License

private void handleSelectClassUnderTest(IJavaElement element) {
    try {//from  w w  w  .ja v a2s.  c o m
        if (element == null || !element.exists() || element.getJavaProject() == null) {
            setErrorState();
        } else {
            IJavaProject javaProject = element.getJavaProject();
            if (Utils.isGWTProject(javaProject)) {
                IPackageFragmentRoot testSourceFragmentRoot = handleTestSourceFolder(javaProject);
                IPackageFragment elementPackage = handleTestPackage(element, testSourceFragmentRoot);
                // handle class under test
                IType classUnderTestType = (IType) element.getAncestor(IJavaElement.TYPE);
                if (classUnderTestType == null) {
                    ICompilationUnit compilationUnit = (ICompilationUnit) element
                            .getAncestor(IJavaElement.COMPILATION_UNIT);
                    if (compilationUnit != null) {
                        classUnderTestType = compilationUnit.findPrimaryType();
                    }
                }
                if (classUnderTestType == null) {
                    setErrorState();
                } else {
                    m_classUnderTestField.setText(classUnderTestType.getFullyQualifiedName());
                    setTypeName(classUnderTestType.getElementName() + "Test", true);
                    m_classUnderTestStatus = new Status(IStatus.OK, Activator.PLUGIN_ID, IStatus.OK, null,
                            null);
                    //
                    ModuleDescription module = Utils.getSingleModule(elementPackage);
                    if (module == null) {
                        setErrorState(
                                "GWT module for " + classUnderTestType.getFullyQualifiedName() + " not found.");
                    } else {
                        m_moduleId = module.getId();
                    }
                }
            } else {
                setErrorState();
            }
        }
    } catch (Throwable e) {
        DesignerPlugin.log(e);
        setErrorState("InternalError: " + e.getMessage());
    } finally {
        doStatusUpdate();
    }
}