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:org.playframework.playclipse.handlers.BrowseToViewHandler.java

License:Apache License

static void printAstPath(IJavaElement elem) {
    System.out.println(elem.getClass() + ":" + elem.getElementType() + ":" + elem.getElementName());
    IJavaElement parent = elem.getParent();
    if (parent != null) {
        printAstPath(parent);/*from  www  . j  av a2  s. co  m*/
    }
}

From source file:org.playframework.playclipse.handlers.GoToViewHandler.java

License:Apache License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    EditorHelper editor = EditorHelper.getCurrent(event);
    IProject project = editor.getProject();
    IJavaProject jProject = JavaCore.create(project);

    if (editor != null) {
        String relativePath = ((IFileEditorInput) editor.textEditor.getEditorInput()).getFile()
                .getProjectRelativePath().toString();
        if (relativePath.startsWith("app/japidviews/") && relativePath.endsWith(".java")) {
            // bran: if we are in the japid derived Java template code, let's switch back to the html view
            String jFile = DirUtil.mapJavaToSrc(relativePath);
            IFile f = project.getFile(jFile);
            try {
                FilesAccess.openFile(f);
            } catch (CoreException e) {
                PlayPlugin.showError(e);
            }/*from w w  w.  java 2s .  c om*/
            return null;
        }
    }

    boolean useJapid = true;

    String line;
    String viewName = null;
    String title = editor.getTitle();
    String controllerName = title.replace(".java", "");

    String packageName = "";
    IEditorInput editorInput = editor.textEditor.getEditorInput();

    ITextSelection selection = (ITextSelection) editor.textEditor.getSelectionProvider().getSelection();
    IJavaElement elem = JavaUI.getEditorInputJavaElement(editorInput);
    ICompilationUnit unit = null;
    if (elem instanceof ICompilationUnit) {
        unit = (ICompilationUnit) elem;
        try {
            IPackageDeclaration[] packs = unit.getPackageDeclarations();
            if (packs.length < 1) {
                info("This action can only apply to controllers.");
                return null;
            } else {
                packageName = packs[0].getElementName();
                if (!packageName.startsWith("controllers")) {
                    info("This action can only apply to controllers.");
                    return null;
                }
            }

            // get the class declaration line
            IType type = unit.getType(controllerName);
            ITypeHierarchy superTypes = type.newSupertypeHierarchy(null);
            //            String name = JapidController.class.getName(); // this will require play.jar
            String name = "cn.bran.play.JapidController";
            IType japidController = jProject.findType(name);
            if (superTypes.contains(japidController)) {
                useJapid = true;
            } else {
                useJapid = false;
            }

            //            String superclassName = type.getSuperclassName();
            //            if (superclassName.toLowerCase().contains("japid")) {
            //               useJapid = true;
            //            }

            // current selected elem
            IJavaElement[] elements = unit.codeSelect(selection.getOffset(), selection.getLength());
            if (elements.length > 0) {
                // TODO extract the current selection to tell if the cursor in on renderJapidXXX line
                System.out.println(elements);
            }

        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println(elem.getElementType() + ":" + elem.getElementName());
    }

    viewName = getEnclosingActionName(selection, unit);

    int lineNo = editor.getCurrentLineNo();
    line = editor.getLine(lineNo);
    if (line.contains("render")) {
        if (!line.contains("renderJapid")) {
            Pattern pt = Pattern.compile("\"(.*)\"");
            Matcher m = pt.matcher(line);
            if (m.find()) {
                // render classic groovy
                useJapid = false;
                // There is a custom view, by renderTemplate()
                viewName = "app/views/" + m.group().replace("\"", "");
            }
        } else {
            // render japid
            useJapid = true;
            if (line.contains("renderJapidWith")) {
                // explicit template name
                Matcher m = stringPattern.matcher(line);
                if (m.find()) {
                    // There is a custom view
                    // the template strin is the view name in relative to the japidviews directory
                    viewName = "app/japidviews/" + m.group().replace("\"", "");
                } else {
                    System.out.println("the first param of renderJapidWith is not a String. Strange....");
                }
            }
        }
    }

    if (viewName == null) {
        String string = "Use this command in a controller action body, or on a render...() line";
        info(string);
    } else {
        if (!viewName.startsWith("app")) {

            viewName = "app/" + (useJapid ? "japidviews" : "views") + "/"
                    + (packageName.equals("controllers") ? ""
                            : packageName.substring(12).replace('.', '/') + "/")
                    + controllerName + "/" + viewName + ".html";
        }

        (new Navigation(editor)).goToViewAbs(viewName);
    }
    return null;
}

From source file:org.playframework.playclipse.handlers.GoToViewHandler.java

License:Apache License

/**
 * @param selection/*from   w  w w.j  a va 2s .  c  o m*/
 * @param unit
 */
private String getEnclosingActionName(ITextSelection selection, ICompilationUnit unit) {
    IJavaElement selected;
    try {
        selected = unit.getElementAt(selection.getOffset());
        List<IJavaElement> path = getJavaElementsPath(selected);
        if (path.size() >= 7) {
            IJavaElement el = path.get(6);
            if (el.getElementType() == IJavaElement.METHOD) {
                IMethod sm = (IMethod) el;
                int flags = sm.getFlags();
                String actionMethodName = el.getElementName();
                if (/*Flags.isPublic(flags) &&*/ Flags.isStatic(flags)) {
                    return actionMethodName;
                } else {
                    info("The enclosig method " + actionMethodName
                            + " is not public static, thus not a valid action method.");
                }
            }
        }
    } catch (JavaModelException e) {
        PlayPlugin.showError(e);
    }
    return null;
}

From source file:org.playframework.playclipse.handlers.OpenWithBrowserHandler.java

License:Apache License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    EditorHelper editor = EditorHelper.getCurrent(event);
    IProject project = editor.getProject();

    String viewName = null;/* www .j av a  2  s . c  o m*/
    String title = editor.getTitle();
    String controllerName = title.replace(".java", "");

    String packageName = "";
    IEditorInput editorInput = editor.textEditor.getEditorInput();

    ITextSelection selection = (ITextSelection) editor.textEditor.getSelectionProvider().getSelection();
    IJavaElement elem = JavaUI.getEditorInputJavaElement(editorInput);
    ICompilationUnit unit = null;
    if (elem instanceof ICompilationUnit) {
        unit = (ICompilationUnit) elem;
        try {
            IPackageDeclaration[] packs = unit.getPackageDeclarations();
            if (packs.length < 1) {
                info("This action can only apply to controllers.");
                return null;
            } else {
                packageName = packs[0].getElementName();
                if (!packageName.startsWith("controllers")) {
                    info("This action can only apply to controllers.");
                    return null;
                }
            }

            //            // get the class declaration line
            //            IType type = unit.getType(controllerName);
            //            ITypeHierarchy superTypes = type.newSupertypeHierarchy(null);
            ////            String name = JapidController.class.getName(); // this will require play.jar
            //            String name = "cn.bran.play.JapidController";
            //            IType japidController = jProject.findType(name);
            //            
            // current selected elem
            IJavaElement[] elements = unit.codeSelect(selection.getOffset(), selection.getLength());
            if (elements.length > 0) {
                // TODO extract the current selection to tell if the cursor in on renderJapidXXX line
                //                  System.out.println(elements);
            }

        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println(elem.getElementType() + ":" + elem.getElementName());
    }

    viewName = getEnclosingActionName(selection, unit);

    if (viewName == null) {
        String string = "Use this command in a controller action body, or on a render...() line";
        info(string);
    } else {
        if (!viewName.startsWith("app")) {

            viewName = (packageName.equals("controllers") ? "" : packageName.substring(12) + ".")
                    + controllerName + "/" + viewName;
            // let's parsing the application.conf
            IFile confFile = project.getFile("conf/application.conf");
            InputStream contents = null;
            try {
                String portpart = "9000";
                contents = confFile.getContents();
                BufferedReader br = new BufferedReader(new InputStreamReader(contents, "UTF-8"));
                String line = "";

                while ((line = br.readLine()) != null) {
                    line = line.trim();
                    if (!line.startsWith("#")) {
                        Matcher matcher = portlinePattern.matcher(line);
                        if (matcher.matches()) {
                            portpart = matcher.group(1);
                            break;
                            // open the browser
                        }
                    }
                }
                PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser()
                        .openURL(new URL("http://localhost:" + portpart + "/" + viewName));
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    contents.close();
                } catch (Exception ee) {
                }
            }
        }
    }
    return null;
}

From source file:org.playframework.playclipse.handlers.OpenWithBrowserHandler.java

License:Apache License

/**
 * @param selection/*from  www .j a va  2s . c  o m*/
 * @param unit
 */
private String getEnclosingActionName(ITextSelection selection, ICompilationUnit unit) {
    IJavaElement selected;
    try {
        selected = unit.getElementAt(selection.getOffset());
        List<IJavaElement> path = getJavaElementsPath(selected);
        if (path.size() >= 7) {
            IJavaElement el = path.get(6);
            if (el.getElementType() == IJavaElement.METHOD) {
                IMethod sm = (IMethod) el;
                int flags = sm.getFlags();
                String actionMethodName = el.getElementName();
                if (Flags.isPublic(flags) && Flags.isStatic(flags)) {
                    return actionMethodName;
                } else {
                    info("The enclosig method " + actionMethodName
                            + " is not public static, thus not a valid action method.");
                }
            }
        }
    } catch (JavaModelException e) {
        PlayPlugin.showError(e);
    }
    return null;
}

From source file:org.polarsys.reqcycle.jdt.model.JDTReachableObject.java

License:Open Source License

private IJavaElement findMethodRecursively(IParent aClass, final String[] javaElement) {
    try {//  w ww. j a  v  a  2 s.c o m
        IJavaElement result = null;
        boolean found = false;
        IParent currentContainer = aClass;
        int i = 0;
        for (String s : javaElement) {
            found = false;
            if (currentContainer != null) {
                for (IJavaElement j : currentContainer.getChildren()) {
                    if (s.equals(j.getElementName())) {
                        if (i == javaElement.length - 1) {
                            result = j;
                            found = true;
                        } else if (j instanceof IParent) {
                            currentContainer = (IParent) j;
                        }
                        break;
                    }
                }
            }
            i++;
        }
        if (found && result != null) {
            return result;
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.polarsys.reqcycle.jdt.utils.JDTUtils.java

License:Open Source License

protected static String getQualifiedURI(IJavaElement element) {
    StringBuilder result = new StringBuilder();
    if ((element == null) || (element.getResource() == null)) {
        return null;
    }// www. j av  a  2  s.  c o  m
    result.append(PLATFORM).append(element.getResource().getFullPath().toString()).append("#");
    List<String> names = new LinkedList<String>();
    names.add(element.getElementName());
    IJavaElement parent = element.getParent();
    while (parent != null && !(parent instanceof ICompilationUnit)) {
        names.add(0, parent.getElementName());
        parent = parent.getParent();
    }
    result.append(Joiner.on(SEPARATOR).join(names));
    return result.toString();
}

From source file:org.python.pydev.ast.codecompletion.revisited.jython.JythonFindDefinitionTestWorkbench.java

License:Open Source License

public void testFind2() throws Exception {
    String d = "" + "import java.lang.Class";

    Document doc = new Document(d);
    IModule module = AbstractModule.createModuleFromDoc("", null, doc, nature, true);
    Definition[] defs = (Definition[]) module.findDefinition(
            CompletionStateFactory.getEmptyCompletionState("java.lang.Class", nature, new CompletionCache()), 1,
            20, nature);/* w  w w  .ja v a 2s  .  c o  m*/

    assertEquals(1, defs.length);
    assertEquals("", defs[0].value);
    assertTrue(defs[0].module instanceof JavaZipModule);
    IJavaElement javaElement = ((JavaDefinition) defs[0]).javaElement;
    assertTrue(javaElement != null);
    assertTrue(defs[0] instanceof JavaDefinition);
    assertEquals("java.lang.Class", defs[0].module.getName());
    assertEquals("Class", javaElement.getElementName());
}

From source file:org.python.pydev.ast.codecompletion.revisited.jython.JythonFindDefinitionTestWorkbench.java

License:Open Source License

public void testFind3() throws Exception {
    String d = "" + "import java.lang.Class\n" + "java.lang.Class.asSubclass";

    Document doc = new Document(d);
    IModule module = AbstractModule.createModuleFromDoc("", null, doc, nature, true);
    Definition[] defs = (Definition[]) module.findDefinition(CompletionStateFactory.getEmptyCompletionState(
            "java.lang.Class.asSubclass", nature, new CompletionCache()), 2, 20, nature);

    assertEquals(1, defs.length);//from  www.  java  2 s  . co m
    assertEquals("asSubclass", defs[0].value);
    assertTrue(defs[0].module instanceof JavaZipModule);
    IJavaElement javaElement = ((JavaDefinition) defs[0]).javaElement;
    assertTrue(javaElement != null);
    assertEquals("asSubclass", javaElement.getElementName());
    assertTrue(defs[0] instanceof JavaDefinition);
    assertEquals("java.lang.Class", defs[0].module.getName());
}

From source file:org.python.pydev.editor.codecompletion.revisited.javaintegration.AbstractJavaClassModule.java

License:Open Source License

/**
 * This method will create the tokens for a given package.
 *//*from w w w .  j a  v  a2 s.co m*/
protected CompiledToken[] createTokens(String packagePlusactTok) {
    ArrayList<CompiledToken> lst = new ArrayList<CompiledToken>();

    try {

        //TODO: if we don't want to depend on jdt inner classes, we should create a org.eclipse.jdt.core.CompletionRequestor
        //(it's not currently done because its API is not as easy to handle).
        //we should be able to check the CompletionProposalCollector to see how we can transform the info we want...
        //also, making that change, it should be faster, because we won't need to 1st create a java proposal to then
        //create a pydev token (it would be a single step to transform it from a Completion Proposal to an IToken).

        List<Tuple<IJavaElement, CompletionProposal>> elementsFound = getJavaCompletionProposals(
                packagePlusactTok, null);

        HashMap<String, IJavaElement> generatedProperties = new HashMap<String, IJavaElement>();

        FastStringBuffer tempBuffer = new FastStringBuffer(128);
        for (Tuple<IJavaElement, CompletionProposal> element : elementsFound) {
            IJavaElement javaElement = element.o1;
            String args = "";
            if (javaElement instanceof IMethod) {
                tempBuffer.clear();
                tempBuffer.append("()");
                IMethod method = (IMethod) javaElement;
                for (String param : method.getParameterTypes()) {
                    if (tempBuffer.length() > 2) {
                        tempBuffer.insert(1, ", ");
                    }

                    //now, let's make the parameter 'pretty'
                    String lastPart = FullRepIterable.getLastPart(param);
                    if (lastPart.length() > 0) {
                        lastPart = PyAction.lowerChar(lastPart, 0);
                        if (lastPart.charAt(lastPart.length() - 1) == ';') {
                            lastPart = lastPart.substring(0, lastPart.length() - 1);
                        }
                    }

                    //we may have to replace it for some other word
                    String replacement = replacementMap.get(lastPart);
                    if (replacement != null) {
                        lastPart = replacement;
                    }
                    tempBuffer.insert(1, lastPart);
                }
                args = tempBuffer.toString();

                String elementName = method.getElementName();
                if (elementName.startsWith("get") || elementName.startsWith("set")) {
                    //Create a property for it
                    tempBuffer.clear();
                    elementName = elementName.substring(3);
                    if (elementName.length() > 0) {
                        tempBuffer.append(Character.toLowerCase(elementName.charAt(0)));
                        tempBuffer.append(elementName.substring(1));

                        String propertyName = tempBuffer.toString();
                        IJavaElement existing = generatedProperties.get(propertyName);
                        if (existing != null) {
                            if (existing.getElementName().startsWith("set")) {
                                //getXXX has precedence over the setXXX.
                                generatedProperties.put(propertyName, javaElement);
                            }
                        } else {
                            generatedProperties.put(propertyName, javaElement);
                        }
                    }
                }

            }
            if (DEBUG_JAVA_COMPLETIONS) {
                System.out.println("Element: " + javaElement);
            }

            lst.add(new JavaElementToken(javaElement.getElementName(), "", args, this.name,
                    getType(javaElement.getElementType()), javaElement, element.o2));

        }

        //Fill our generated properties.
        for (Entry<String, IJavaElement> entry : generatedProperties.entrySet()) {
            IJavaElement javaElement = entry.getValue();
            lst.add(new JavaElementToken(entry.getKey(), "", "", this.name, IToken.TYPE_ATTR, javaElement,
                    PyCodeCompletionImages.getImageForType(IToken.TYPE_ATTR)));
        }
    } catch (Exception e) {
        Log.log(e);
    }

    return lst.toArray(new CompiledToken[lst.size()]);
}