Example usage for org.eclipse.jdt.core IJavaProject findElement

List of usage examples for org.eclipse.jdt.core IJavaProject findElement

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject findElement.

Prototype

IJavaElement findElement(IPath path) throws JavaModelException;

Source Link

Document

Returns the IJavaElement corresponding to the given classpath-relative path, or null if no such IJavaElement is found.

Usage

From source file:com.android.ide.eclipse.cheatsheets.actions.SetBreakpoint.java

License:Open Source License

public void run(final String[] params, ICheatSheetManager manager) {
    // param1 - project
    // param2 - path
    // param3 - type name
    // param4 - line number
    if (params == null || params[0] == null || params[1] == null || params[2] == null || params[3] == null) {
        return;/*  w  ww.ja v a 2  s  . c  o  m*/
    }
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    IProject project = workspaceRoot.getProject(params[0]);
    if (project == null || !project.isOpen()) {
        Activator.log("Invalid the project " + params[0] + ".");
        return;
    }
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null || !javaProject.isOpen()) {
        Activator.log("Invalid the project: " + params[0] + ".");
        return;
    }
    IJavaElement element;
    try {
        element = javaProject.findElement(new Path(params[1]));

        if (element == null) {
            Activator.log("Invalid the path: " + params[1] + ".");
            return;
        }
        resource = element.getCorrespondingResource();
        if (resource == null || resource.getType() != IResource.FILE) {
            Activator.log("Invalid the path: " + params[1] + ".");
            return;
        }
    } catch (JavaModelException e1) {
        Activator.log("Invalid the " + params[1] + " path.");
        return;
    }
    String tname = params[2];
    Display.getDefault().syncExec(new Runnable() {

        public void run() {
            editor = openEditor(params, (IFile) resource);
        }
    });
    if (editor == null) {
        Activator.log("Cannot open the " + " " + params[0] + "file.");
        return;
    }
    try {
        //String markerType = "org.eclipse.jdt.debug.javaLineBreakpointMarker";
        int lnumber;
        try {
            lnumber = new Integer(params[3]).intValue();
        } catch (NumberFormatException e) {
            Activator.log("Invalid line number " + params[1]);
            return;
        }
        Map attributes = new HashMap(10);
        IDocumentProvider documentProvider = editor.getDocumentProvider();
        if (documentProvider == null) {
            return;
        }
        IDocument document = documentProvider.getDocument(editor.getEditorInput());
        int charstart = -1, charend = -1;
        try {
            IRegion line = document.getLineInformation(lnumber - 1);
            charstart = line.getOffset();
            charend = charstart + line.getLength();
        } catch (BadLocationException e) {
            Activator.log(e);
        }
        //BreakpointUtils.addJavaBreakpointAttributes(attributes, type);

        String handleId = element.getHandleIdentifier();
        attributes.put(HANDLE_ID, handleId);
        JavaCore.addJavaElementMarkerAttributes(attributes, element);
        IJavaLineBreakpoint breakpoint = JDIDebugModel.createLineBreakpoint(resource, tname, lnumber, charstart,
                charend, 0, true, attributes);

        IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
        breakpointManager.addBreakpoint(breakpoint);
    } catch (CoreException e) {
        Activator.log(e);
    }
}

From source file:com.centurylink.mdw.plugin.project.model.WorkflowProject.java

License:Apache License

public void viewSource(String className) {
    if (setJava()) {
        // dynamic java is preferred
        int lastDot = className.lastIndexOf('.');
        WorkflowAsset dynamicJava = null;
        if (lastDot == -1) {
            dynamicJava = getAsset(className);
            if (dynamicJava == null)
                dynamicJava = getAsset(className + ".java");
        } else {//www .  ja  v a  2  s  .  c  o  m
            String pkg = className.substring(0, lastDot);
            String cls = className.substring(lastDot + 1);
            dynamicJava = getAsset(pkg, cls);
            if (dynamicJava == null)
                dynamicJava = getAsset(pkg, cls + ".java");
        }
        if (dynamicJava != null) {
            dynamicJava.openFile(new NullProgressMonitor());
            return;
        }

        IJavaProject wfSourceJavaProject = getSourceJavaProject();
        try {
            Path sourcePath = new Path(className.replace('.', '/') + ".java");
            IJavaElement javaElement = wfSourceJavaProject.findElement(sourcePath);
            if (javaElement == null) {
                PluginMessages.uiMessage("Unable to find source code for '" + className + "'.", "View Source",
                        this, PluginMessages.INFO_MESSAGE);
                return;
            }
            JavaUI.openInEditor(javaElement);
        } catch (Exception ex) {
            PluginMessages.uiError(ex, "Open Java Source", this);
        }
    }
}

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

License:Apache License

private boolean setNewInput(IEditorInput input) {
    if (input instanceof IFileEditorInput) {

        /* a local class file */
        IFileEditorInput fileEditorInput = (IFileEditorInput) input;
        IFile file = fileEditorInput.getFile();
        IProject project = file.getProject();

        /* create java project */
        IJavaProject javaProject = JavaCore.create(project);

        /* get class path */
        try {//from ww w . j  a v a  2s  .c om

            IPath projectPath = file.getProjectRelativePath();

            /* remove the source folder segment */
            IPath sourceFolder = projectPath.removeFirstSegments(1);

            IJavaElement javaElement = javaProject.findElement(sourceFolder);
            if (javaElement instanceof ICompilationUnit) {
                ICompilationUnit unit = (ICompilationUnit) javaElement;

                List<String> classList = new ArrayList<String>();

                IType[] types = unit.getTypes();
                for (IType t : types) {
                    ClassFileDocumentsUtils.collectNestedClasses(t, classList);
                }

                /* 
                 * If the compilation unit includes more than one class 
                 * declaration, ask the user to select a class to be opened.
                 */
                String className = "";
                if (classList.size() > 1) {
                    StringBuffer msg = new StringBuffer(
                            BytecodeVisualizerMessages.SourceContainsSeveralClassDefinitions);
                    msg.append(JavaLexicalConstants.NEWLINE);
                    msg.append(BytecodeVisualizerMessages.SelectClassToVisualize);
                    className = Messages.openSelectDialog(msg.toString(),
                            JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS), classList);
                    if (className == null) {
                        return false;
                    }
                } else {
                    if (classList.size() == 1) {
                        className = classList.get(0);
                    } else {
                        return false;
                    }
                }

                String[] classPath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);

                String packageName = ClassFileDocumentsUtils.getPackageNameFromCompilationUnit(unit);
                File f = JavaLangUtils.findFileResource(classPath, packageName, className);
                IPath classFilePath = new Path(f.getAbsolutePath());

                /* make path relative /<project>/<bin folder>/<package>/<class> */
                IPath workspace = project.getWorkspace().getRoot().getLocation();
                classFilePath = classFilePath.removeFirstSegments(workspace.segmentCount());

                /* Find the resource and set the new editor input */
                final IFile classFile = ResourcesPlugin.getWorkspace().getRoot().getFile(classFilePath);
                doSetInput(new FileEditorInput(classFile));
            }

            return true;

        } catch (CoreException e) {
            BytecodeVisualizerPlugin.log(e);
            return false;

        } catch (IOException e) {
            BytecodeVisualizerPlugin.log(e);
            return false;
        }

    }

    return false;
}

From source file:com.javapathfinder.vjp.verify.topics.link.LinkParser.java

License:Open Source License

private IFile findFile(String pathString) {
    IPath path = new Path(pathString);
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    try {/*from   w w  w  . j a va  2  s  .  co  m*/
        for (IProject project : projects) {
            if (project.exists() && project.isOpen() && project.hasNature(JavaCore.NATURE_ID)) {
                IJavaProject jproject = (IJavaProject) JavaCore.create(project);
                IJavaElement element = jproject.findElement(path);
                if (element != null) {
                    if (element.getResource() instanceof IFile) {
                        IFile file = (IFile) element.getResource();
                        return file;
                    }
                }
            }
        }
    } catch (CoreException e) {
        VJP.logError(e.getMessage(), e);
    }
    return null;
}

From source file:com.siteview.mde.internal.ui.editor.monitor.JavaAttributeWizard.java

License:Open Source License

public boolean performFinish() {
    IRunnableWithProgress op = new WorkspaceModifyOperation() {
        protected void execute(IProgressMonitor monitor) throws CoreException, InterruptedException {
            fMainPage.createType(monitor);
        }//ww w. j a  va2 s .  c o  m
    };
    try {
        PlatformUI.getWorkbench().getProgressService().runInUI(MDEPlugin.getActiveWorkbenchWindow(), op,
                MDEPlugin.getWorkspace().getRoot());
        IResource resource = fMainPage.getModifiedResource();
        if (resource != null) {
            selectAndReveal(resource);
            if (fProject.hasNature(JavaCore.NATURE_ID)) {
                IJavaProject jProject = JavaCore.create(fProject);
                IJavaElement jElement = jProject
                        .findElement(resource.getProjectRelativePath().removeFirstSegments(1));
                if (jElement != null)
                    JavaUI.openInEditor(jElement);
            } else if (resource instanceof IFile) {
                IWorkbenchPage page = MDEPlugin.getActivePage();
                IDE.openEditor(page, (IFile) resource, true);
            }
        }
    } catch (InvocationTargetException e) {
        MDEPlugin.logException(e);
    } catch (InterruptedException e) {
        MDEPlugin.logException(e);
    } catch (CoreException e) {
        MDEPlugin.logException(e);
    }
    return true;
}

From source file:de.devboost.eclipse.jdtutilities.JDTUtility.java

License:Open Source License

/**
 * Returns the Java element contained in the resource located at the
 * given path or <code>null</code> if the resource does not contain a Java
 * element./* w  w  w . ja v a 2 s  . c o m*/
 */
public IJavaElement getJavaElement(String path) throws JavaModelException {

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IFile file = root.getFile(new Path(path));
    IJavaProject javaProject = getJavaProject(file);
    if (javaProject == null) {
        return null;
    }

    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (IPackageFragmentRoot packageFragmentRoot : roots) {
        IPath fragmentPath = packageFragmentRoot.getPath();
        String fragmentPathString = fragmentPath.toString();
        if (path.startsWith(fragmentPathString + "/")) {
            // resource is contained in this package fragment root
            String classPathRelativePath = path.substring(fragmentPathString.length() + 1);
            IJavaElement element = javaProject.findElement(new Path(classPathRelativePath));
            if (element != null) {
                return element;
            }
        }
    }
    return null;
}

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

License:Open Source License

@Override
public void run(IAction action) {
    IWorkbenchPage page = our_window.getActivePage();

    if (page != null) {
        if (!(page.getActiveEditor() instanceof ITextEditor))
            return;

        ITextEditor fileEditor = (ITextEditor) page.getActiveEditor();

        IFileEditorInput fileEditorInput = (IFileEditorInput) fileEditor.getEditorInput();
        String path = fileEditorInput.getFile().getProjectRelativePath().toOSString();
        String filePath = path;/*w w  w. j  a  va  2  s. co m*/
        IProject project = fileEditorInput.getFile().getProject();

        IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel()
                .getJavaProject(project.getName());

        try {
            for (IClasspathEntry entry : javaProject.getRawClasspath()) {
                if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    String sourcePath = entry.getPath().toOSString().substring(project.getName().length() + 2);

                    if (path.startsWith(sourcePath)) {
                        path = path.substring(sourcePath.length() + 1);
                        path = path.replace(File.separatorChar, '$');
                        path = path.substring(0, path.indexOf("."));

                        filePath = filePath.substring(sourcePath.length() + 1);

                        break;
                    }
                }
            }
        } catch (Exception e1) {
            BedrockPlugin.log("Exception : " + e1.getMessage() + ", " + e1.getClass().toString());
        }

        try {
            IJavaElement javaElement = javaProject.findElement(new Path(filePath));

            if (!(javaElement instanceof ICompilationUnit))
                return;

            ICompilationUnit icu = (ICompilationUnit) javaElement;

            ISelectionProvider selectionProvider = fileEditor.getSelectionProvider();
            ISelection selection = selectionProvider.getSelection();

            if (selection instanceof ITextSelection) {
                ITextSelection textSelection = (ITextSelection) selection;
                int offset = textSelection.getOffset();

                IJavaElement element = icu.getElementAt(offset);

                IvyXmlWriter xw = BedrockPlugin.getPlugin().beginMessage("OPENEDITOR");
                xw.field("PROJECT", project.getName());

                if (element == null) {
                    xw.field("RESOURCEPATH", path);
                } else {
                    boolean isFirstElement = true;
                    boolean isMethod = false;

                    String fileName = path.substring(path.lastIndexOf('$') + 1);

                    List<String> list = new ArrayList<String>();

                    while (element != null && (!element.getElementName().equals(fileName)
                            || element.getElementType() == IJavaElement.METHOD)) {
                        if (isFirstElement && (element.getElementType() == IJavaElement.METHOD
                                || element.getElementType() == IJavaElement.TYPE)) {
                            list.add(element.getElementName());

                            if (element.getElementType() == IJavaElement.METHOD) {
                                isMethod = true;
                            }

                            isFirstElement = false;
                        } else if (!isFirstElement) {
                            list.add(element.getElementName());
                        }

                        element = element.getParent();

                        if ("".equals(element.getElementName())) {
                            xw.field("RESOURCEPATH", path);
                            BedrockPlugin.getPlugin().finishMessage(xw);

                            return;
                        }
                    }

                    String[] aryPath = new String[list.size()];
                    list.toArray(aryPath);

                    for (int i = aryPath.length - 1; i >= 0; i--) {
                        path += ("$" + aryPath[i]);
                    }

                    xw.field("RESOURCEPATH", path);

                    if (isMethod)
                        xw.field("RESOURCETYPE", "Function");
                }

                BedrockPlugin.getPlugin().finishMessage(xw);
            }
        } catch (Exception e2) {
            BedrockPlugin.log("Exception : " + e2.getMessage() + ", " + e2.getClass().toString());
        }
    }
}

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

License:Open Source License

private ICompilationUnit checkFilePrefix(IJavaProject ijp, String pfx, String file) {
    if (ijp == null)
        return null;

    if (pfx != null) {
        if (!file.startsWith(pfx))
            return null;
        int ln = pfx.length();
        if (file.charAt(ln) == File.separatorChar || file.charAt(ln) == '/')
            ++ln;//from  w ww  .jav  a2s.co m
        file = file.substring(ln);
    }

    try {
        IPath fp = new Path(file);
        IJavaElement je = ijp.findElement(fp);
        if (je != null && je instanceof ICompilationUnit) {
            return (ICompilationUnit) je;
        }
    } catch (JavaModelException e) {
    }

    file = file.replace('\\', '/');

    try {
        IPath fp = new Path(file);
        IJavaElement je = ijp.findElement(fp);
        if (je != null && je instanceof ICompilationUnit) {
            return (ICompilationUnit) je;
        }
    } catch (JavaModelException e) {
    }

    return null;
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

License:Open Source License

/**
 * Finds a compilation unit by looking in all the java project of the supplied
 * name.//w ww  .j  a  v  a 2  s  .  c o  m
 *
 * @param project The name of the project to locate the file in.
 * @param file The src dir relative file path to find.
 * @return The compilation unit or null if not found.
 */
public static ICompilationUnit findCompilationUnit(String project, String file) throws Exception {
    IPath path = Path.fromOSString(file);

    IJavaProject javaProject = getJavaProject(project);
    javaProject.open(null);
    //javaProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);

    ICompilationUnit src = (ICompilationUnit) javaProject.findElement(path);

    return src;
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

License:Open Source License

/**
 * Finds a compilation unit by looking in all the available java projects.
 *
 * @param file The src directory relative file to find.
 * @return The compilation unit or null if not found.
 */// w ww.ja  va  2 s  .co m
public static ICompilationUnit findCompilationUnit(String file) throws Exception {
    IPath path = Path.fromOSString(file);
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    for (IProject project : projects) {
        if (project.hasNature(JavaCore.NATURE_ID)) {
            IJavaProject javaProject = getJavaProject(project);
            javaProject.open(null);
            //javaProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);

            ICompilationUnit src = (ICompilationUnit) javaProject.findElement(path);
            if (src != null) {
                return src;
            }
        }
    }
    return null;
}