Example usage for org.eclipse.jdt.core ICompilationUnit getTypes

List of usage examples for org.eclipse.jdt.core ICompilationUnit getTypes

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ICompilationUnit getTypes.

Prototype

IType[] getTypes() throws JavaModelException;

Source Link

Document

Returns the top-level types declared in this compilation unit in the order in which they appear in the source.

Usage

From source file:at.bestsolution.efxclipse.robovm.RobovmSetupHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
    ICompilationUnit unit = (ICompilationUnit) selection.getFirstElement();

    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    Set<IPath> sourcePaths = new HashSet<>();
    Set<IPath> refProjectSourcePaths = new HashSet<>();
    Set<IPath> libsPaths = new HashSet<>();

    resolveDataProject(unit.getJavaProject(), sourcePaths, refProjectSourcePaths, libsPaths);

    BuildConfiguration config = new BuildConfiguration();
    config.buildDirectory = "robovm-build";

    {/* ww w.j av a2 s . co  m*/
        Set<String> set = new HashSet<String>();
        Set<File> set2 = new HashSet<File>();
        for (IPath p : libsPaths) {
            set.add(p.lastSegment());
            IFile file = root.getFile(p);
            if (file != null && file.exists()) {
                p = file.getLocation();
            }
            set2.add(p.toFile());
        }
        config.externalLibs = set;
        config.origExternalLibs = set2;
    }

    {
        Set<String> set = new HashSet<String>();
        Set<SetupDirectory> set2 = new HashSet<SetupDirectory>();
        for (IPath p : sourcePaths) {
            IFolder t = root.getFolder(p);
            set.add(t.getProjectRelativePath().toString());

            if (t.isLinked()) {
                set2.add(new SetupDirectory(t.getLocation().toFile().getParentFile(),
                        new File(t.getProjectRelativePath().toString())));
            } else {
                set2.add(new SetupDirectory(t.getProject().getLocation().toFile(),
                        new File(t.getProjectRelativePath().toString())));
            }
        }
        config.projectSourceDirs = set;
        config.origProjectSourceDirs = set2;
    }

    {
        Set<String> set = new HashSet<String>();
        Set<SetupDirectory> set2 = new HashSet<SetupDirectory>();
        for (IPath p : refProjectSourcePaths) {
            IFolder t = root.getFolder(p);
            set.add(t.getProject().getName() + "/" + t.getProjectRelativePath());
            set2.add(new SetupDirectory(t.getProject().getLocation().toFile().getParentFile(),
                    new File(t.getProject().getName() + "/" + t.getProjectRelativePath().toString())));

        }
        config.projectRefSourceDirs = set;
        config.origProjectRefSourceDirs = set2;
    }

    IProject p = unit.getJavaProject().getProject();
    config.projectName = getApplicationName(p);

    try {
        config.projectEncoding = p.getDefaultCharset();
        config.sourceCompliance = "1.7";//unit.getJavaProject().getOption( JavaCore.COMPILER_SOURCE, true );
        config.targetCompliance = "1.7";//unit.getJavaProject().getOption( JavaCore.COMPILER_COMPLIANCE, true );
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    IFolder buildFolder = p.getFolder(new Path(config.buildDirectory));
    if (!buildFolder.exists()) {
        try {
            buildFolder.create(true, true, null);
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    IFolder templateFolder = buildFolder.getFolder(new Path("robovm-template"));
    if (!templateFolder.exists()) {
        try {
            templateFolder.create(true, true, null);
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (!buildFolder.getFolder(new Path("robovm")).exists()) {
        try {
            File dir = buildFolder.getLocation().toFile();
            export("binaries/robovm-" + ROBOVM_VERSION + ".tar.gz", dir.getAbsolutePath(),
                    "robovm-" + ROBOVM_VERSION + ".tar.gz");
            Process exec = Runtime.getRuntime().exec(
                    new String[] { "tar", "xzvf", "robovm-" + ROBOVM_VERSION + ".tar.gz" }, new String[0], dir);
            exec.waitFor();
            Files.move(new File(dir, "robovm-" + ROBOVM_VERSION).toPath(), new File(dir, "robovm").toPath(),
                    StandardCopyOption.ATOMIC_MOVE);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (!buildFolder.getFolder(new Path("jfx78")).exists()) {
        try {
            File dir = new File(buildFolder.getLocation().toFile(), "jfx78");
            export("binaries/jfxrt.jar", dir.getAbsolutePath(), "jfxrt.jar");
            export("binaries/libdecora_sse_armv7.a", dir.getAbsolutePath(), "libdecora_sse_armv7.a");
            export("binaries/libglass.a", dir.getAbsolutePath(), "libglass.a");
            export("binaries/libjavafx_font.a", dir.getAbsolutePath(), "libjavafx_font.a");
            export("binaries/libjavafx_iio.a", dir.getAbsolutePath(), "libjavafx_iio.a");
            export("binaries/libprism_common.a", dir.getAbsolutePath(), "libprism_common.a");
            export("binaries/libprism_es2.a", dir.getAbsolutePath(), "libprism_es2.a");
            export("binaries/openjfx-78-backport-compat-" + OPENJFX_BACKPORT + ".jar", dir.getAbsolutePath(),
                    "openjfx-78-backport-compat.jar");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        File dir = buildFolder.getLocation().toFile();
        export("binaries/robovm-run.sh", dir.getAbsolutePath(), "robovm-run.sh");
        export("binaries/org.eclipse.fx.fxml.compiler_0.9.0-SNAPSHOT.jar", dir.getAbsolutePath(),
                "org.eclipse.fx.fxml.compiler.jar");
        new File(dir, "robovm-run.sh").setExecutable(true);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    RobovmBuild b = new RobovmBuild();

    {
        IFile f = buildFolder.getFile("robovm.properties");
        fillFile(b.generateBuildProperties(config.projectName), f);
    }

    {
        IFile f = buildFolder.getFile("robovm.xml");
        fillFile(b.generateConfigXML(config), f);
    }

    {
        IFile f = buildFolder.getFile("Info.plist.xml");
        fillFile(b.generatePlistContent(), f);
    }

    {
        IFile f = templateFolder.getFile(config.projectName + ".java");
        fillFile(b.generateBootstrapFile(config.projectName), f);
    }

    {
        IFile f = templateFolder.getFile(config.projectName + "Main.java");
        try {
            fillFile(b.generateFXMainFile(config.projectName, unit.getTypes()[0].getFullyQualifiedName()), f);
        } catch (JavaModelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    {
        IFile f = buildFolder.getFile("robovm-ant.xml");
        fillFile(b.generate(config), f);
    }

    //      System.err.println(sourcePaths);
    //      System.err.println(refProjectSourcePaths);
    //      System.err.println(libsPaths);

    // TODO Auto-generated method stub
    return null;
}

From source file:at.bestsolution.efxclipse.tooling.fxml.compile.FxmlAnnotationCompilationParticipant.java

License:Open Source License

/**
 * @param context//  w  w w.j  a  va  2 s  .  c  o  m
 */
private List<CategorizedProblem> checkCU(final ICompilationUnit unit,
        final Collection<CategorizedProblem> existingProblems) {
    List<CategorizedProblem> problems = new ArrayList<CategorizedProblem>();
    if (existingProblems != null) {
        problems.addAll(existingProblems);
    }
    List<String> fxmlMethods = new ArrayList<String>();
    try {
        IJavaProject project = unit.getJavaProject();
        for (IType type : unit.getTypes()) {
            for (IMethod method : type.getMethods()) {
                for (IAnnotation a : method.getAnnotations()) {
                    if ("FXML".equals(a.getElementName())) { ////$NON-NLS-1$
                        if (fxmlMethods.contains(method.getElementName())) {
                            DefaultProblem problem = new DefaultProblem(unit.getElementName().toCharArray(),
                                    "JavaFX controller method name is not unique: " //$NON-NLS-1$
                                            + method.getElementName(),
                                    IProblem.ExternalProblemNotFixable, new String[0],
                                    ProblemSeverities.Warning, method.getSourceRange().getOffset(),
                                    method.getSourceRange().getOffset() + method.getSourceRange().getLength(),
                                    getMethodLineNumber(type, method), 0);
                            problems.add(problem);
                        }
                        fxmlMethods.add(method.getElementName());

                        switch (method.getNumberOfParameters()) {
                        case 0:
                            break;
                        case 1: {
                            ILocalVariable pType = method.getParameters()[0];
                            String[][] resolvedType = type
                                    .resolveType(Signature.toString(pType.getTypeSignature()));
                            IType parameterType = null;
                            if (resolvedType != null) {
                                parameterType = project.findType(resolvedType[0][0] + "." + resolvedType[0][1]); //$NON-NLS-1$
                            }
                            if (resolvedType == null || !Util.assignable(parameterType,
                                    project.findType("javafx.event.Event"))) { ////$NON-NLS-1$
                                DefaultProblem problem = new DefaultProblem(unit.getElementName().toCharArray(),
                                        "Parameter '" //$NON-NLS-1$
                                                + pType.getElementName()
                                                + "' is not assignable to javafx.event.Event", //$NON-NLS-1$
                                        IProblem.ExternalProblemNotFixable, new String[0],
                                        ProblemSeverities.Warning, pType.getSourceRange().getOffset(),
                                        pType.getSourceRange().getOffset() + pType.getSourceRange().getLength(),
                                        getMethodLineNumber(type, method), 0);
                                problems.add(problem);
                            }

                        }
                            break;
                        default: {
                            DefaultProblem problem = new DefaultProblem(unit.getElementName().toCharArray(),
                                    "JavaFX controller method must have 0 or exactly 1 argument", //$NON-NLS-1$
                                    IProblem.ExternalProblemNotFixable, new String[0],
                                    ProblemSeverities.Warning, method.getSourceRange().getOffset(),
                                    method.getSourceRange().getOffset() + method.getSourceRange().getLength(),
                                    getMethodLineNumber(type, method), 0);
                            problems.add(problem);
                        }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return problems;
}

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

License:Open Source License

@Override
public void reconcile(ReconcileContext context) {
    IJavaElementDelta delta = context.getDelta();
    if (delta != null) {
        if (delta.getElement() instanceof ICompilationUnit) {

            ICompilationUnit u = (ICompilationUnit) delta.getElement();
            try {
                for (IType t : u.getTypes()) {
                    FXPlugin.getClassmodel().clearCache(t);
                }//  w ww.j  a  v a 2 s  .co  m
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    super.reconcile(context);
}

From source file:ca.mcgill.sable.soot.attributes.JavaAttributesComputer.java

License:Open Source License

private ArrayList getNames(ICompilationUnit cu) {
    ArrayList names = new ArrayList();
    try {//from   w w  w. j  a v a  2 s.c  o  m
        IType[] topLevelDecls = cu.getTypes();
        for (int i = 0; i < topLevelDecls.length; i++) {
            names.add(topLevelDecls[i].getFullyQualifiedName());
        }
    } catch (JavaModelException e) {
    }
    return names;
}

From source file:ca.ubc.cs.ferret.tests.support.TestProject.java

License:Open Source License

public IType createType(IPackageFragment pack, String cuName, String source) throws JavaModelException {
    StringBuffer buf = new StringBuffer();
    buf.append("package " + pack.getElementName() + ";\n");
    buf.append("\n");
    buf.append(source);/* w ww .j a v a  2s  .com*/
    ICompilationUnit cu = pack.createCompilationUnit(cuName, buf.toString(), false, null);
    return cu.getTypes()[0];
}

From source file:cfgrecognition.loader.SootClassLoader.java

License:Open Source License

protected void dfsDomTree(IJavaElement element) throws Exception {
    //      if (monitor.isCanceled()) {
    //         return;
    //      }/*from w  ww  .  j a va  2 s  .  c o  m*/

    if (element.isReadOnly())
        return;

    int elementType = element.getElementType();
    if (elementType == IJavaElement.COMPILATION_UNIT) {
        ICompilationUnit cu = (ICompilationUnit) element;
        IType[] allTypes = cu.getTypes();
        for (IType aType : allTypes) {
            dfsDomTree(aType);
        }
    } else if (elementType == IJavaElement.TYPE) {
        IType aType = (IType) element;

        if (aType.isClass()) {
            // Load a type in Soot
            load(aType.getFullyQualifiedName());
        }

        // Go inside the methods to look for Anonymous Inner Class
        for (IMethod m : aType.getMethods()) {
            IJavaElement[] elems = m.getChildren();
            for (IJavaElement elem : elems) {
                if (elem.getElementType() == IJavaElement.TYPE) {
                    dfsDomTree(elem);
                }
            }
        }

        // For inner classes
        IType[] allTypes = aType.getTypes();
        for (IType childType : allTypes) {
            dfsDomTree(childType);
        }
    }

}

From source file:ch.mlutz.plugins.t4e.handlers.AnalyzeHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    if (event.getCommand().getId().equals(Command.ANALYZE)) {

        // get workbench window
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
        // set selection service
        ISelectionService service = window.getSelectionService();
        // set structured selection
        IStructuredSelection structured = (IStructuredSelection) service.getSelection();

        //check if it is an IFile
        Object el = structured.getFirstElement();
        log.info(el.getClass().getName());

        ICompilationUnit compilationUnit = null;

        if (!(el instanceof ICompilationUnit) && el instanceof IFile) {
            IFile file = (IFile) el;//from   w  w  w. j a v a2  s .c  o  m

            compilationUnit = JavaCore.createCompilationUnitFrom((IFile) file);
            final IJavaElement javaElement = JavaCore.create((IFile) file);
            log.info(javaElement.toString());
            IPath path = file.getLocation();
            System.out.println(path.toPortableString());
        }

        if (el instanceof ICompilationUnit) {
            compilationUnit = (ICompilationUnit) el;

            log.info(compilationUnit.toString());
            try {
                log.info(compilationUnit.getTypes().toString());
            } catch (JavaModelException e) {
                log.warn("Getting types from compilation unit failed. ", e);
            }
        }

        /*
        //check if it is an ICompilationUnit
        if (structured.getFirstElement() instanceof ICompilationUnit) {
           ICompilationUnit cu = (ICompilationUnit) structured.getFirstElement();
           System.out.println(cu.getElementName());
        }
        */
    }

    return null;
}

From source file:ch.mlutz.plugins.t4e.tapestry.editor.hyperlink.OgnlHyperlinkDetectorDelegate.java

License:Open Source License

@Override
public List<SourceRangeHyperlink> detectHyperlinks(IDocument document, String content, IRegion region) {

    List<SourceRangeHyperlink> result = new ArrayList<SourceRangeHyperlink>();

    // go back until whitespace is found and
    int charIndex = region.getOffset();
    while (charIndex >= 0 && content.charAt(charIndex) != '"') {
        charIndex--;/*w w w . j  a v  a  2s  .  c  om*/
    }

    // charIndex might be -1, but that's ok
    String prefix = content.substring(charIndex + 1);

    final String expectedPrefix = "ognl:";
    if (!prefix.startsWith(expectedPrefix)) {
        return null;
    }

    int ognlExpressionStart = charIndex + 1 + expectedPrefix.length();

    charIndex = region.getOffset();
    while (charIndex < content.length() && content.charAt(charIndex) != '"'
            && content.charAt(charIndex) != '.') {
        charIndex++;
    }

    final int hyperLinkOffset = ognlExpressionStart;

    final int hyperLinkLength = charIndex - hyperLinkOffset;

    if (hyperLinkLength < 0) {
        // caret might rest on the first quote
        log.warn("OGNL hyperLinkLength: " + hyperLinkLength + "; charIndex: " + charIndex
                + "; hyperLinkOffset: " + hyperLinkOffset);
        return null;
    }

    final String hyperlinkText = content.substring(ognlExpressionStart, ognlExpressionStart + hyperLinkLength);

    TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex();
    IFile documentFile = tapestryIndex.getDocumentToFileMapping(document);

    if (documentFile == null) {
        return null;
    }

    ICompilationUnit javaCompilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile);

    if (javaCompilationUnit == null) {
        return null;
    }

    /*
    TapestryModule module= tapestryIndex.getModuleForResource(documentFile);
            
    TapestryHtmlElement linkedComponent= null;
    for (TapestryHtmlElement component: module.getComponents()) {
       if (hyperlinkText.equals(component.getPath())) {
    linkedComponent= component;
       }
    }
            
    final TapestryHtmlElement finalLinkedComponent= linkedComponent;
    */

    IType[] types = new IType[0];
    try {
        types = javaCompilationUnit.getTypes();
    } catch (JavaModelException e) {
        log.warn("Could not get types of compilation unit " + javaCompilationUnit.getElementName(), e);
    }

    IMethod methodMatch = null;
    outer: for (IType type : types) {
        try {
            if (type.isClass() && Flags.isPublic(type.getFlags())) {
                IMethod[] methods = type.getMethods();
                for (IMethod method : methods) {
                    String ognlMethodName = method.getElementName() + "()";
                    if (ognlMethodName.equals(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }

                    ognlMethodName = ognlMethodName.replaceAll("^(?:get|is)(.+)\\(\\)$", "$1");
                    // TODO: check this match!
                    if (ognlMethodName.equalsIgnoreCase(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }
                }
            }
        } catch (JavaModelException e) {
            log.warn("Could not get information for type " + type.getElementName(), e);
        }
    }

    IFile javaFile = null;
    try {
        javaFile = (IFile) javaCompilationUnit.getCorrespondingResource().getAdapter(IFile.class);
    } catch (JavaModelException e) {
        log.warn("Could not get corresponding resource for " + javaCompilationUnit.getElementName(), e);
    }
    final IFile finalJavaFile = javaFile;

    ISourceRange sourceRange = null;
    if (methodMatch != null) {
        try {
            sourceRange = methodMatch.getSourceRange();
        } catch (JavaModelException e) {
            log.warn("Could not get source range for method " + methodMatch.getElementName(), e);
        }
    }

    if (finalJavaFile != null) {
        SourceRangeHyperlink hyperlink = new SourceRangeHyperlink(new Region(hyperLinkOffset, hyperLinkLength),
                "Open method", javaFile, sourceRange, Constants.TAPESTRY_EDITOR_ID);
        result.add(hyperlink);
    }

    if (result.size() > 0) {
        return result;
    } else {
        return null;
    }
}

From source file:ch.mlutz.plugins.t4e.tapestry.editor.OgnlHyperlinkDetector.java

License:Open Source License

@Override
public IHyperlink[] detectHyperlinks(ITextViewer viewer, IRegion region, boolean canHandleMultipleLinks) {

    IDocument document = viewer.getDocument();
    String contentBefore;//from ww w .  j ava 2  s.  c  o m
    ITypedRegion partition;
    try {
        partition = document.getPartition(region.getOffset());

        if (!partition.getType().equals(TapestryPartitionScanner.XML_TAG)) {
            return null;
        }

        contentBefore = document.get(partition.getOffset(), partition.getLength());
    } catch (BadLocationException e) {
        log.warn("Could not detect hyperlinks: ", e);
        return null;
    }

    List<IHyperlink> result = new ArrayList<IHyperlink>();

    // go back until whitespace is found and
    int charIndex = region.getOffset() - partition.getOffset();
    while (charIndex >= 0 && contentBefore.charAt(charIndex) != '"') {
        charIndex--;
    }

    // charIndex might be -1, but that's ok
    String prefix = contentBefore.substring(charIndex + 1);

    final String expectedPrefix = "ognl:";
    if (!prefix.startsWith(expectedPrefix)) {
        return null;
    }

    int ognlExpressionStart = charIndex + 1 + expectedPrefix.length();

    charIndex = region.getOffset() - partition.getOffset();
    while (charIndex < contentBefore.length() && contentBefore.charAt(charIndex) != '"'
            && contentBefore.charAt(charIndex) != '.') {
        charIndex++;
    }

    final int hyperLinkOffset = partition.getOffset() + ognlExpressionStart;

    final int hyperLinkLength = partition.getOffset() + charIndex - hyperLinkOffset;

    if (hyperLinkLength < 0) {
        // caret might rest on the first quote
        log.warn(
                "OGNL hyperLinkLength: " + hyperLinkLength + "; partition.getOffset(): " + partition.getOffset()
                        + "; charIndex: " + charIndex + "; hyperLinkOffset: " + hyperLinkOffset);
        return null;
    }

    final String hyperlinkText = contentBefore.substring(ognlExpressionStart,
            ognlExpressionStart + hyperLinkLength);

    TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex();
    IFile documentFile = tapestryIndex.getDocumentToFileMapping(document);

    if (documentFile == null) {
        return null;
    }

    ICompilationUnit javaCompilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile);

    if (javaCompilationUnit == null) {
        return null;
    }

    /*
    TapestryModule module= tapestryIndex.getModuleForResource(documentFile);
            
    TapestryHtmlElement linkedComponent= null;
    for (TapestryHtmlElement component: module.getComponents()) {
       if (hyperlinkText.equals(component.getPath())) {
    linkedComponent= component;
       }
    }
            
    final TapestryHtmlElement finalLinkedComponent= linkedComponent;
    */

    IType[] types = new IType[0];
    try {
        types = javaCompilationUnit.getTypes();
    } catch (JavaModelException e) {
        log.warn("Could not get types of compilation unit " + javaCompilationUnit.getElementName(), e);
    }

    IMethod methodMatch = null;
    outer: for (IType type : types) {
        try {
            if (type.isClass() && Flags.isPublic(type.getFlags())) {
                IMethod[] methods = type.getMethods();
                for (IMethod method : methods) {
                    String ognlMethodName = method.getElementName() + "()";
                    if (ognlMethodName.equals(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }

                    ognlMethodName = ognlMethodName.replaceAll("^(?:get|is)(.+)\\(\\)$", "$1");
                    // TODO: check this match!
                    if (ognlMethodName.equalsIgnoreCase(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }
                }
            }
        } catch (JavaModelException e) {
            log.warn("Could not get information for type " + type.getElementName(), e);
        }
    }

    IFile javaFile = null;
    try {
        javaFile = (IFile) javaCompilationUnit.getCorrespondingResource().getAdapter(IFile.class);
    } catch (JavaModelException e) {
        log.warn("Could not get corresponding resource for " + javaCompilationUnit.getElementName(), e);
    }
    final IFile finalJavaFile = javaFile;

    ISourceRange sourceRange = null;
    if (methodMatch != null) {
        try {
            sourceRange = methodMatch.getSourceRange();
        } catch (JavaModelException e) {
            log.warn("Could not get source range for method " + methodMatch.getElementName(), e);
        }
    }

    final ISourceRange finalSourceRange = sourceRange;

    if (finalJavaFile != null) {
        result.add(new IHyperlink() {

            @Override
            public void open() {
                IWorkbench wb = PlatformUI.getWorkbench();
                IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
                IWorkbenchPage page = win.getActivePage();

                IEditorPart editorPart = EclipseTools.openFileInEditor(finalJavaFile, page);

                if (!(editorPart instanceof ITextEditor)) {
                    log.info("editorPart !instanceof ITextEditor");
                }

                if (finalSourceRange == null) {
                    log.info("finalSourceRange == null");
                }

                if (editorPart instanceof ITextEditor && finalSourceRange != null) {

                    log.info("Opening source range: " + finalSourceRange);

                    ((ITextEditor) editorPart).selectAndReveal(finalSourceRange.getOffset(),
                            finalSourceRange.getLength());
                }
            }

            @Override
            public String getTypeLabel() {
                return null;
            }

            @Override
            public String getHyperlinkText() {
                return "Open method";
            }

            @Override
            public IRegion getHyperlinkRegion() {
                return new Region(hyperLinkOffset, hyperLinkLength);
            }
        });
    }
    /*
    log.info("detectHyperlinks called: " + hyperLinkOffset + " / "
    + hyperLinkLength + ", size: " + result.size());
    */

    if (result.size() > 0) {
        return result.toArray(new IHyperlink[result.size()]);
    } else {
        return null;
    }
}

From source file:ch.mlutz.plugins.t4e.tapestry.editor.TagContentAssistProcessor.java

License:Open Source License

protected ICompletionProposal[] computeOgnlCompletionProposals(int offset, String ognlPrefix,
        IDocument document, IFile documentFile) {
    List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();
    int ognlPrefixLength = ognlPrefix.length();

    TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex();
    ICompilationUnit compilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile);

    if (compilationUnit != null) {
        Map<ICompletionProposal, Integer> proposalScoreMap = new HashMap<ICompletionProposal, Integer>();

        // TODO: improve this suffix computation as in computeAttributeCompletionProposals
        String suffix = "\"";
        int additionalCursorOffset = 1;
        try {//  w  w  w  . j a  va  2  s . c o  m
            if (offset < document.getLength() - 1 && document.get(offset, 1).equals("\"")) {
                suffix = "";
            }
        } catch (BadLocationException e) {
            log.warn("Could not compute suffix of completion proposals: ", e);
        }

        try {
            IType[] types = compilationUnit.getTypes();

            for (IType type : types) {
                if (type.isClass() && Flags.isPublic(type.getFlags())) {
                    IMethod[] methods = type.getMethods();
                    for (IMethod method : methods) {
                        String completionProposalString = method.getElementName() + "()";

                        String ognlProposalString = completionProposalString.replaceAll("^get(.+)\\(\\)?$",
                                "$1");

                        if (!ognlProposalString.equals(completionProposalString)) {
                            // ognlProposalString is different from
                            // original proposal => make sure first
                            // character is lower case
                            ognlProposalString = Character.toLowerCase(ognlProposalString.charAt(0))
                                    + ognlProposalString.substring(1);
                            completionProposalString = ognlProposalString;
                        }

                        if (completionProposalString.startsWith(ognlPrefix)) {
                            String displayName = completionProposalString;
                            String translatedSignature = translateSignatureToType(method.getReturnType());
                            if (translatedSignature != null) {
                                displayName += " - " + translatedSignature;
                            }

                            ICompletionProposal completionProposal = new CompletionProposal(
                                    completionProposalString + suffix, offset - ognlPrefixLength,
                                    ognlPrefixLength,
                                    completionProposalString.length() + additionalCursorOffset,
                                    Activator.getImage("icons/t4e.png"), displayName,
                                    getContextInformation("", ""), completionProposalString);

                            // compute score for this proposal
                            int proposalScore = getProposalScoreForMethod(method, ParameterType.STRING);

                            proposalScoreMap.put(completionProposal, proposalScore);

                            result.add(completionProposal);
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Collections.sort(result, new ScoreComparator<Integer>(proposalScoreMap));
    }

    return result.toArray(new ICompletionProposal[result.size()]);
}