Example usage for org.eclipse.jdt.core ITypeRoot findPrimaryType

List of usage examples for org.eclipse.jdt.core ITypeRoot findPrimaryType

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ITypeRoot findPrimaryType.

Prototype

IType findPrimaryType();

Source Link

Document

Finds the primary type of this Java type root (that is, the type with the same name as the compilation unit, or the type of a class file), or null if no such a type exists.

Usage

From source file:ca.uvic.chisel.diver.mylyn.logger.logging.PageSelectionListener.java

License:Open Source License

/**
 * @param selection// w ww  .j  a  va 2 s  .c  o m
 * @return
 */
private Object getSelectionObject(IWorkbenchPart part, ISelection selection) {
    if (selection instanceof IStructuredSelection) {
        IStructuredSelection ss = (IStructuredSelection) selection;
        if (!ss.isEmpty()) {
            Object o = ss.getFirstElement();
            if (o instanceof IJavaElement) {
                return o;
            } else if (o instanceof ITraceModel) {
                return o;
            }
        }
    } else if (selection instanceof ITextSelection) {
        ITextSelection ts = (ITextSelection) selection;
        if (part instanceof ITextEditor) {
            ITextEditor editor = (ITextEditor) part;
            ITypeRoot typeRoot = null;
            IEditorInput input = editor.getEditorInput();
            //using internal stuff, but I don't care
            if (input instanceof IClassFileEditorInput) {
                typeRoot = ((IClassFileEditorInput) input).getClassFile();
            } else if (input instanceof IFileEditorInput) {
                IFile file = ((IFileEditorInput) input).getFile();
                IJavaElement element = JavaCore.create(file);
                if (element instanceof ITypeRoot) {
                    typeRoot = (ITypeRoot) element;
                }
            }
            if (typeRoot != null) {
                IType type = typeRoot.findPrimaryType();
                if (type != null) {
                    try {
                        IJavaElement je = typeRoot.getElementAt(ts.getOffset());
                        return je;
                    } catch (JavaModelException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return null;
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockRenamer.java

License:Open Source License

/********************************************************************************/

void rename(String proj, String bid, String file, int start, int end, String name, String handle,
        String newname, boolean keeporig, boolean getters, boolean setters, boolean dohier, boolean qual,
        boolean refs, boolean dosimilar, boolean textocc, boolean doedit, String filespat, IvyXmlWriter xw)
        throws BedrockException {
    ICompilationUnit icu = our_plugin.getCompilationUnit(proj, file);

    IJavaElement[] elts;/* w w  w  . j ava  2  s  . c o  m*/
    try {
        elts = icu.codeSelect(start, end - start);
    } catch (JavaModelException e) {
        throw new BedrockException("Bad location: " + e, e);
    }

    IJavaElement relt = null;
    for (IJavaElement ije : elts) {
        if (handle != null && !handle.equals(ije.getHandleIdentifier()))
            continue;
        if (name != null && !name.equals(ije.getElementName()))
            continue;
        relt = ije;
        break;
    }
    if (relt == null)
        throw new BedrockException("Item to rename not found");

    BedrockPlugin.logD("RENAME CHECK " + relt.getElementType() + " " + relt.getParent().getElementType());

    switch (relt.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
        throw new BedrockException("Compilation unit renaming not supported yet");
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
    case IJavaElement.PACKAGE_FRAGMENT:
        throw new BedrockException("Package renaming not supported yet");
    case IJavaElement.FIELD:
    case IJavaElement.LOCAL_VARIABLE:
    case IJavaElement.TYPE_PARAMETER:
        break;
    case IJavaElement.METHOD:
        IMethod mthd = (IMethod) relt;
        try {
            if (mthd.isConstructor())
                throw new BedrockException("Constructor renaming not supported yet");
        } catch (JavaModelException e) {
        }
        break;
    case IJavaElement.TYPE:
        IJavaElement pelt = relt.getParent();
        if (pelt.getElementType() == IJavaElement.COMPILATION_UNIT) {
            ITypeRoot xcu = (ITypeRoot) pelt;
            if (relt == xcu.findPrimaryType()) {
                throw new BedrockException("Compilation unit renaming based on type not supported yet");
            }
        }
        break;
    default:
        throw new BedrockException("Invalid element type to rename");
    }

    SearchPattern sp = SearchPattern.createPattern(relt, IJavaSearchConstants.ALL_OCCURRENCES,
            SearchPattern.R_EXACT_MATCH);

    List<ICompilationUnit> worku = new ArrayList<ICompilationUnit>();
    for (IJavaElement je : BedrockJava.getAllProjects()) {
        our_plugin.getWorkingElements(je, worku);
    }
    ICompilationUnit[] work = new ICompilationUnit[worku.size()];
    work = worku.toArray(work);

    int fg = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS;
    IJavaSearchScope scp = SearchEngine.createJavaSearchScope(work, fg);

    SearchEngine se = new SearchEngine(work);
    SearchParticipant[] parts = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    FindHandler fh = new FindHandler(xw, null);

    try {
        se.search(sp, parts, scp, fh, null);
    } catch (CoreException e) {
        throw new BedrockException("Problem doing find all search: " + e, e);
    }

    BedrockPlugin.logD("RENAME RESULT = " + xw.toString());
}

From source file:net.harawata.mybatipse.mybatis.JavaHyperlinkDetector.java

License:Open Source License

private IHyperlink[] getLinks(ITypeRoot typeRoot, IType triggerType, String expression, IRegion srcRegion)
        throws JavaModelException {
    IType primaryType = typeRoot.findPrimaryType();
    if (primaryType.isInterface() && (triggerType == null || primaryType.equals(triggerType))) {
        IJavaProject project = primaryType.getJavaProject();
        if (project != null) {
            IFile mapperFile = MapperNamespaceCache.getInstance().get(project,
                    primaryType.getFullyQualifiedName(), null);
            if (mapperFile != null) {
                IDOMNode domNode = MybatipseXmlUtil.getNodeByXpath(mapperFile, expression);
                if (domNode != null) {
                    Region destRegion = new Region(domNode.getStartOffset(),
                            domNode.getEndOffset() - domNode.getStartOffset());
                    String label = "Open <" + domNode.getNodeName() + "/> in XML mapper.";
                    return new IHyperlink[] { new ToXmlHyperlink(mapperFile, srcRegion, label, destRegion) };
                }//from  w  w  w .  java 2  s .  c  o m
            }
        }
    }
    return null;
}

From source file:org.eclipse.recommenders.internal.apidocs.rcp.JavadocProvider.java

License:Open Source License

@JavaSelectionSubscriber
public void onCompilationUnitSelection(final ITypeRoot root, final JavaElementSelectionEvent selection,
        final Composite parent) throws CoreException {
    final IType type = root.findPrimaryType();
    if (type != null) {
        render(type, parent);/*  w w w.  j  a va  2 s.  co m*/
    } else if (root.getParent() instanceof IPackageFragment) {
        IPackageFragment packageFragment = (IPackageFragment) root.getParent();
        render(packageFragment, parent);
    }
}

From source file:org.eclipse.recommenders.internal.apidocs.rcp.OverridesProvider.java

License:Open Source License

@JavaSelectionSubscriber
public void onTypeRootSelection(final ITypeRoot root, final JavaElementSelectionEvent event,
        final Composite parent) throws ExecutionException {
    final IType type = root.findPrimaryType();
    if (type != null) {
        onTypeSelection(type, event, parent);
    }/* ww w  . j  a v a2  s.  c o m*/
}

From source file:org.eclipse.recommenders.internal.apidocs.rcp.StaticHooksProvider.java

License:Open Source License

private void findStaticHooks(final TreeMultimap<IType, IMethod> index, final ITypeRoot root)
        throws JavaModelException {
    final IType type = root.findPrimaryType();
    if (type == null) {
        return;//from ww  w . j  a v a 2  s  . c  o  m
    }
    if (!type.isClass()) {
        return;
    }

    for (final IMethod m : type.getMethods()) {
        if (JdtFlags.isStatic(m) && JdtFlags.isPublic(m) && !JdtUtils.isInitializer(m)) {
            index.put(type, m);
        }
    }
}

From source file:org.eclipse.xtext.common.types.ui.trace.TraceForTypeRootProvider.java

License:Open Source License

protected String getJavaSimpleFileName(final ITypeRoot derivedResource) {
    IType type = derivedResource.findPrimaryType();
    if (type == null)
        return null;
    String sourceName = ((BinaryType) type).getSourceFileName(null);
    if (sourceName == null)
        return null;

    // the primary source in the .class file is .java (JSR-45 aka SMAP scenario)
    if (sourceName.endsWith(".java")) {
        return sourceName;
    }/*  w w  w. j  a v  a 2 s. c o m*/

    // xtend-as-primary-source-scenario.
    if (sourceName.endsWith(".xtend")) {
        String name = type.getElementName();
        int index = name.indexOf("$");
        if (index > 0)
            name = name.substring(0, index);
        return name + ".java";
    }
    return null;
}

From source file:org.jboss.tools.arquillian.ui.internal.detectors.ArquillianResourceHyperlinkDetector.java

License:Open Source License

@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || textEditor == null)
        return null;

    IEditorSite site = textEditor.getEditorSite();
    if (site == null)
        return null;

    ITypeRoot javaElement = JavaUI.getEditorInputTypeRoot(textEditor.getEditorInput());
    if (javaElement == null)
        return null;

    if (!ArquillianSearchEngine.isArquillianJUnitTest(javaElement.findPrimaryType(), false, false, false)) {
        return null;
    }//www  . j  a va 2 s. c o  m
    CompilationUnit ast = SharedASTProvider.getAST(javaElement, SharedASTProvider.WAIT_NO, null);
    if (ast == null)
        return null;

    ASTNode node = NodeFinder.perform(ast, region.getOffset(), 1);
    if (!(node instanceof StringLiteral))
        return null;

    if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY)
        return null;

    ASTNode parent = node.getParent();
    if (!(parent instanceof MethodInvocation)) {
        return null;
    }
    MethodInvocation methodInvocation = (MethodInvocation) parent;
    SimpleName name = methodInvocation.getName();
    String methodName = name.getFullyQualifiedName();
    if (!ArquillianUIUtil.ADD_AS_RESOURCE_METHOD.equals(methodName)
            && !ArquillianUIUtil.ADD_AS_MANIFEST_RESOURCE_METHOD.equals(methodName)
            && !ArquillianUIUtil.ADD_AS_WEB_INF_RESOURCE_METHOD.equals(methodName)) {
        return null;
    }
    while (parent != null) {
        parent = parent.getParent();
        if (parent instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) parent;

            int modifiers = methodDeclaration.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                IMethodBinding binding = methodDeclaration.resolveBinding();
                IMethod method = (IMethod) binding.getJavaElement();
                try {
                    String signature = method.getSignature();
                    if (!"()QArchive<*>;".equals(signature)) { //$NON-NLS-1$
                        break;
                    }
                } catch (JavaModelException e) {
                    ArquillianUIActivator.log(e);
                }
                IAnnotationBinding[] annotations = binding.getAnnotations();
                for (IAnnotationBinding annotationBinding : annotations) {
                    ITypeBinding typeBinding = annotationBinding.getAnnotationType();
                    if (ArquillianUtility.ORG_JBOSS_ARQUILLIAN_CONTAINER_TEST_API_DEPLOYMENT
                            .equals(typeBinding.getQualifiedName())) {
                        StringLiteral stringLiteral = (StringLiteral) node;
                        String resource = stringLiteral.getLiteralValue();
                        IFile file = getFile(resource, javaElement);
                        if (file != null) {
                            int start = node.getStartPosition();
                            int length = node.getLength();
                            if (length > 2) {
                                start++;
                                length -= 2;
                            }
                            IRegion stringLiteralRegion = new Region(start, length);
                            return new IHyperlink[] {
                                    new ArquillianResourceHyperlink(resource, stringLiteralRegion, file) };
                        }
                        break;
                    }

                }
            }
        }
    }

    return null;
}

From source file:org.springframework.ide.eclipse.data.internal.validation.InvalidDerivedQueryRule.java

License:Open Source License

private boolean supports(ITypeRoot typeRoot) {
    if (typeRoot == null)
        return false;

    IType type = typeRoot.findPrimaryType();

    // Skip non-interfaces
    try {//from  w  ww . j av  a 2  s .  c  o  m
        if (type == null || !type.isInterface() || type.isAnnotation()) {
            return false;
        }
    } catch (JavaModelException e) {
        SpringCore.log(e);
        return false;
    }

    // Skip non-spring-data repositories
    if (!RepositoryInformation.isSpringDataRepository(type)) {
        return false;
    }

    // resolve repository information and generate problem markers
    RepositoryInformation information = new RepositoryInformation(type);

    Class<?> domainClass = information.getManagedDomainClass();
    if (domainClass == null) {
        return false;
    }
    return true;
}

From source file:org.springframework.ide.eclipse.data.internal.validation.InvalidDerivedQueryRule.java

License:Open Source License

public void validate(CompilationUnit element, SpringDataValidationContext context, IProgressMonitor monitor) {

    try {//from   w  w  w  . ja  v  a 2  s  . co  m

        ITypeRoot typeRoot = element.getTypeRoot();
        IType type = typeRoot.findPrimaryType();

        if (!supports(typeRoot))
            return;

        // resolve repository information and generate problem markers
        RepositoryInformation information = new RepositoryInformation(type);

        Class<?> domainClass = information.getManagedDomainClass();
        if (domainClass == null) {
            return;
        }

        for (IMethod method : information.getMethodsToValidate()) {

            String methodName = method.getElementName();

            try {
                new PartTree(methodName, domainClass);
            } catch (PropertyReferenceException e) {
                element.setElementSourceLocation(new JavaModelSourceLocation(method));
                ValidationProblemAttribute start = new ValidationProblemAttribute(IMarker.CHAR_START,
                        method.getNameRange().getOffset());
                ValidationProblemAttribute end = new ValidationProblemAttribute(IMarker.CHAR_END,
                        method.getSourceRange().getOffset() + method.getSourceRange().getLength());
                context.error(element, "INVALID_DERIVED_QUERY", "Invalid derived query! " + e.getMessage(),
                        new ValidationProblemAttribute[] { start, end });
            }
        }

    } catch (JavaModelException e) {
        SpringCore.log(e);
    } catch (Exception e) {
        SpringCore.log(e);
    } catch (Error e) {
        SpringCore.log(e);
    }
}