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

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

Introduction

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

Prototype

IResource getCorrespondingResource() throws JavaModelException;

Source Link

Document

Returns the resource that corresponds directly to this element, or null if there is no resource that corresponds to this element.

Usage

From source file:edu.wpi.cs.jburge.SEURAT.views.RationaleExplorer.java

License:Open Source License

/**
 * This method is used to associate the java file with alternative in the ratinale 
 * explore in the java direction/*from  w ww  . j  a v  a2 s  . co m*/
 */
public void associateAlternative(RationaleUpdateEvent e)

{
    //get the Java element selected in the Package Explorer from the RationaleUpdateEvent
    navigatorSelection = e.getIJavaElement();

    if (navigatorSelection != null) {

        ISelection selection = viewer.getSelection();

        obj = ((IStructuredSelection) selection).getFirstElement();

        //whether an alternative is selected?
        if (obj != null && ((TreeParent) obj).getType() == RationaleElementType.ALTERNATIVE) {
            alternativeName = ((TreeParent) obj).getName();
        }
        //if there is no alternative selected, provide a select items of alternative
        else {
            SelectItem selectItem = new SelectItem(ourDisplay, RationaleElementType.fromString("Alternative"));
            //DEBUG: Is this where the infinite loop is? (YQ)
            if (selectItem == null) {
                System.out.println("NULL selectItem at line 2098");
            }
            if (selectItem.getNewItem() == null) {
                System.out.println("NULL Pointer at line 2099 in RationaleExplorer.java Expect Crashes");
            }
            alternativeName = selectItem.getNewItem().getName();
        }

        String assQ = "Associate '" + alternativeName + "' with " + navigatorSelection.getElementName() + "?";

        boolean selOk = showQuestion(assQ);
        if (selOk) {
            cstart = 0;

            ourRes = null;
            try {

                if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    ourRes = navigatorSelection.getCorrespondingResource();
                } else {
                    ourRes = navigatorSelection.getUnderlyingResource();
                    if (ourRes != null) {
                        //                     ***                        System.out.println("this one wasn't null?");
                    }
                    //find the enclosing class file
                    IJavaElement nextE = navigatorSelection.getParent();
                    while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) {
                        //                     ***                        System.out.println("Name = " + nextE.getElementName());
                        //                     ***                     System.out.println("Type = " + nextE.getElementType());
                        nextE = nextE.getParent();
                    }
                    try {
                        //                     ***                     System.out.println("getting our resource");
                        //                  ourRes = nextE.getUnderlyingResource();
                        ourRes = nextE.getCorrespondingResource();
                        ourRes = nextE.getResource();
                    } catch (JavaModelException ex) {
                        System.out.println("exception getting resource?");
                    }
                    //                  ***                     System.out.println("Final name = " + nextE.getElementName());
                    //                  ***                     System.out.println("Final type = " + nextE.getElementType());
                    if (ourRes == null) {
                        //see if we can get the element from the working copy
                        IJavaElement original = nextE.getPrimaryElement();
                        //                     Get working copy has been deprecated
                        //                     IJavaElement original = ((ICompilationUnit) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement();
                        ourRes = original.getCorrespondingResource();

                    }
                }
                //                  ourRes = navigatorSelection.getUnderlyingResource();
                if (ourRes == null) {
                    //                  ***                     System.out.println("why would our resource be null?");
                }
                //               ***                  System.out.println("FullPath = " + ourRes.getFullPath().toString());
                //               ***                  System.out.println("now checking file extension?");
                if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) {
                    //                  ***                     System.out.println("creating our file?");
                    IJavaElement myJavaElement = JavaCore.create((IFile) ourRes);
                    //                  ***                  System.out.println("created an element?");
                    if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                        //                     ***                     System.out.println("Compilation Unit");
                        ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement;

                        IType[] myTypes = myCompilationUnit.getTypes();
                        boolean found = false;
                        int i = 0;
                        while ((!found) && i < myTypes.length) {
                            //selected item was the class itself
                            if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                                //                           ***                            System.out.println("found the class");
                                if (myTypes[i].isClass()) {
                                    found = true;
                                    cstart = myTypes[i].getNameRange().getOffset();
                                }
                            } else if (navigatorSelection.getElementType() == IJavaElement.FIELD) {
                                //                           ***                            System.out.println("looking for types");
                                IField[] myFields = myTypes[i].getFields();
                                for (int j = 0; j < myFields.length; j++) {
                                    if (myFields[j].getElementName()
                                            .compareTo(navigatorSelection.getElementName()) == 0) {
                                        //                                 ***                               System.out.println("found a type");
                                        found = true;
                                        cstart = myFields[j].getNameRange().getOffset();
                                    }
                                }

                            } else if (navigatorSelection.getElementType() == IJavaElement.METHOD) {
                                //                           ***                            System.out.println("looking for a method");
                                IMethod[] myMethods = myTypes[i].getMethods();
                                for (int j = 0; j < myMethods.length; j++) {
                                    if (myMethods[j].getElementName()
                                            .compareTo(navigatorSelection.getElementName()) == 0) {
                                        //                                 ***                               System.out.println("found a method");
                                        found = true;
                                        cstart = myMethods[j].getNameRange().getOffset();
                                    }
                                }
                            }
                            //don't forget to increment!
                            i++;
                        } //end while
                    } else {
                        //                     ***                      System.out.println("not a compilation unit?");
                        System.out.println(myJavaElement.getElementType());
                    }
                    //ok... now what type is our selected item? 
                    System.out.println("got the resource?");
                    if (ourRes == null) {
                        System.out.println("null resource???");
                    }
                } else {
                    System.out.println("not a java file?");
                }
                //               from the newsgroup - in a runnable?                  
                ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
                    public void run(IProgressMonitor monitor) {
                        try {
                            //                        ***                  System.out.println("line number = " + new Integer(lineNumber).toString());
                            IMarker ratM = ourRes.createMarker("SEURAT.ratmarker");
                            String dbname = RationaleDB.getDbName();
                            String markD = "Alt: '" + alternativeName + "'   Rationale DB: '" + dbname + "'";
                            ratM.setAttribute(IMarker.MESSAGE, markD);
                            ratM.setAttribute(IMarker.CHAR_START, cstart);
                            ratM.setAttribute(IMarker.CHAR_END, cstart + 1);
                            ratM.setAttribute(IMarker.SEVERITY, 0);
                            //                        ratM.setAttribute(IMarker.LINE_NUMBER, lineNumber);
                            String artName = navigatorSelection.getElementName();
                            ratM.setAttribute("alternative", alternativeName);
                            SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "true");
                            RationaleDB d = RationaleDB.getHandle();
                            d.associateAlternative(alternativeName, navigatorSelection.getHandleIdentifier(),
                                    ourRes.getName(), artName, markD);

                        } catch (CoreException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
                //               ***                  System.out.println("adding persistent property");

                SEURATDecoratorManager.addSuccessResources(ourRes);
                //               ***                  System.out.println("added our property");  
                // Refresh the label decorations... Change it to DemoDecoratorWithImageCaching if image caching should be used
                //               ((TreeParent) obj).setStatus(RationaleErrorLevel.ERROR);
                //Is this the inf loop? (YQ)
                if (obj == null) {
                    System.out.println("CRITICAL ERROR: Obj is null at RationaleExplorer.java, line 2280");
                }
                if (viewer == null) {
                    System.out.println("Viewer is null at RationaleExplorer.java line 2283");
                }
                viewer.update((TreeParent) obj, null);
                SEURATLightWeightDecorator.getRatDecorator().refresh();
                //               ***                  System.out.println("refresh");

            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("an exception occured in AssociateArtifactAction");
            }

        } else {
            System.out.println("selection rejected");
        }
    }

    else {
        System.out.println("No java element selected...");
    }

}

From source file:hydrograph.ui.propertywindow.widgets.utility.FilterOperationClassUtility.java

License:Apache License

/**
 * Open file editor to view java file.//from  w  w w.j a v a 2  s  . co  m
 * 
 * @param fileName
 *            the file name
 * @return true, if successful
 */
@SuppressWarnings("restriction")
public boolean openFileEditor(Text filePath, String pathFile) {
    String fullQualifiedClassName = filePath.getText();
    try {
        logger.debug("Searching " + fullQualifiedClassName + " in project's source folder");
        PackageFragment packageFragment = null;
        String[] packages = StringUtils.split(fullQualifiedClassName, ".");
        String className = fullQualifiedClassName;
        String packageStructure = "";
        IFile javaFile = null;
        if (packages.length > 1) {
            className = packages[packages.length - 1];
            packageStructure = StringUtils.replace(fullQualifiedClassName, "." + className, "");
        }
        IFileEditorInput editorInput = (IFileEditorInput) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
                .getActivePage().getActiveEditor().getEditorInput();
        IProject project = editorInput.getFile().getProject();
        IJavaProject iJavaProject = JavaCore.create(project);
        IPackageFragmentRoot packageFragmentRoot = iJavaProject
                .getPackageFragmentRoot(project.getFolder(Constants.ProjectSupport_SRC));
        if (packageFragmentRoot != null) {
            for (IJavaElement iJavaElement : packageFragmentRoot.getChildren()) {
                if (iJavaElement instanceof PackageFragment
                        && StringUtils.equals(iJavaElement.getElementName(), packageStructure)) {
                    packageFragment = (PackageFragment) iJavaElement;
                    break;
                }
            }
        }
        if (packageFragment != null) {
            for (IJavaElement element : packageFragment.getChildren()) {
                if (element instanceof CompilationUnit && StringUtils.equalsIgnoreCase(element.getElementName(),
                        className + Constants.JAVA_EXTENSION)) {
                    javaFile = (IFile) element.getCorrespondingResource();
                    break;
                }
            }
        }
        if (javaFile != null && javaFile.exists()) {
            IFileStore fileStore = EFS.getLocalFileSystem().getStore(javaFile.getLocationURI());
            IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
            IDE.openEditorOnFileStore(page, fileStore);
            return true;
        }
    } catch (Exception e) {
        logger.error("Fail to open file");
        return false;
    }
    return false;

}

From source file:lsclipse.views.TreeView.java

License:Open Source License

private void makeActions() {
    // Double click a Node to open the associated file.
    doubleClickListAction = new Action() {
        public void run() {
            int selind = list.getSelectionIndex();
            if (selind >= listDiffs.size())
                return;
            EditorInput file = listDiffs.get(selind);
            if (file == null)
                return;

            CompareUI.openCompareEditor(file);
        }/*from  w ww.j a  v  a 2 s .c o  m*/
    };

    // Double click a refactoring to display the associated information.
    doubleClickTreeAction = new Action() {
        public void run() {

            // clear list
            list.removeAll();
            listDiffs.clear();

            // Print out the list of code elements associated with this
            // refactoring
            int index = viewer.getSelectionIndex();
            if (index < 0 || index >= nodeList.size())
                return;

            Node node = nodeList.get(index);

            list.add(node.getName());
            listDiffs.add(null);
            list.add(node.params);
            listDiffs.add(null);
            // Seperator
            list.add(" ");
            listDiffs.add(null);

            int numtabs = 0;

            for (String statement : node.getDependents()) {
                StringBuilder output = new StringBuilder();
                if (statement.equals(")"))
                    --numtabs;

                for (int i = 0; i < numtabs; ++i) {
                    output.append("\t");
                }
                if (statement.equals("(")) {
                    output.append("(");
                    ++numtabs;
                } else {
                    output.append(statement);
                }
                list.add(output.toString());
                listDiffs.add(null);
            }

            if (!node.oldFacts.isEmpty()) {
                list.add("");
                listDiffs.add(null);
                list.add("Compare:");
                listDiffs.add(null);
                for (String display : node.oldFacts.keySet()) {
                    IJavaElement filenameBase = node.oldFacts.get(display);
                    IJavaElement filenameMod = node.newFacts.get(display);
                    list.add(display);
                    EditorInput ei = new EditorInput(new CompareConfiguration());
                    try {
                        ei.setBase(((IFile) filenameBase.getCorrespondingResource()).getContents());
                    } catch (Exception ex) {
                        ei.setBase("");
                    }
                    try {
                        ei.setMod(((IFile) filenameMod.getCorrespondingResource()).getContents());
                    } catch (Exception ex) {
                        ei.setMod("");
                    }
                    listDiffs.add(ei);
                }
            }

        }
    };
    // Select Action
    selectAction = new Action("Select version...") {
        public void run() {
            // collect information from seldiag
            final SelectProjectDialog seldiag = new SelectProjectDialog(parent.getShell());
            final int returncode = seldiag.open();
            if (returncode > 0)
                return;

            long start = System.currentTimeMillis();

            // remember base project (and new project)
            baseproj = ResourcesPlugin.getWorkspace().getRoot().getProject(seldiag.getProj1());
            newproj = ResourcesPlugin.getWorkspace().getRoot().getProject(seldiag.getProj2());

            // open new log box
            final ProgressBarDialog pbdiag = new ProgressBarDialog(parent.getShell());
            pbdiag.open();
            pbdiag.setStep(0);

            // do lsdiff (ish)
            if ((new LSDiffRunner()).doFactExtractionForRefFinder(seldiag.getProj1(), seldiag.getProj2(),
                    pbdiag)) {
                refreshTree();
            } else {
                System.out.println("Something went wrong - fact extraction failed");
            }
            pbdiag.setStep(5);
            pbdiag.setMessage("Cleaning up... ");
            pbdiag.appendLog("OK\n");

            pbdiag.dispose();
            long end = System.currentTimeMillis();
            System.out.println("Total time: " + (end - start));
        }
    };
    selectAction.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER));
}

From source file:net.sourceforge.taggerplugin.jdt.action.PackageTagAssociationFilter.java

License:Open Source License

/**
 * @see ViewerFilter#select(Viewer, Object, Object)
 *///ww w .  j  av a  2s  .c om
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
    final IAdaptable adaptable = (IAdaptable) element;

    // closed projects fail fast
    if (isClosedProject(adaptable))
        return (false);

    boolean tagged = isTagged(adaptable, tags);
    if (!tagged) {
        final Holder holder = new Holder();

        // check the children of the resource to see if any of them are tagged
        try {
            final IJavaElement javaElt = (IJavaElement) adaptable
                    .getAdapter(org.eclipse.jdt.core.IJavaElement.class);
            if (javaElt != null) {
                final IResource resource = javaElt.getCorrespondingResource();
                if (resource != null) {
                    resource.accept(new IResourceVisitor() {
                        public boolean visit(IResource resource) throws CoreException {
                            if (!holder.accept) {
                                holder.accept = isTagged(resource, tags);
                            }
                            return (true);
                        }
                    });
                }
            }
        } catch (CoreException ce) {
            TaggerLog.error("Unable to filter resources: " + ce.getMessage(), ce);
        }

        tagged = holder.accept;
    }
    return (tagged);
}

From source file:org.datanucleus.ide.eclipse.popup.actions.CreatePersistenceXmlAction.java

License:Open Source License

public void run(IAction action) {
    if (lastSelection != null && lastSelection.isEmpty() == false
            && lastSelection instanceof IStructuredSelection) {
        IStructuredSelection ssel = (IStructuredSelection) lastSelection;
        if (ssel.size() > 1) {
            // More than 1 selection?
            return;
        }//from  w w w.ja v a  2s .  c o m

        Object obj = ssel.getFirstElement();
        IPackageFragment pkg = null;
        if (obj instanceof IJavaElement) {
            if (obj instanceof ICompilationUnit) {
                // selection is an ICompilationUnit
                ICompilationUnit compilationUnit = (ICompilationUnit) obj;
                pkg = (IPackageFragment) compilationUnit.getParent();
            } else if (obj instanceof IPackageFragment) {
                // selection is an IPackageFragment
                pkg = (IPackageFragment) obj;
            }
        }

        if (pkg != null) {
            // Find root of package structure
            boolean moreLevels = true;
            IJavaElement root = pkg;
            while (moreLevels) {
                IJavaElement parent = pkg.getParent();
                if (parent != null && parent instanceof IPackageFragment) {
                    pkg = (IPackageFragment) parent;
                } else if (parent != null && !(parent instanceof IPackageFragment)) {
                    // First non-package level, hence the root
                    moreLevels = false;
                    root = parent;
                } else {
                    moreLevels = false;
                }
            }

            try {
                IResource resource = root.getCorrespondingResource();
                IContainer container = (IContainer) resource;
                try {
                    // Make sure META-INF exists
                    IFolder metaInfDir = container.getFolder(new Path("META-INF"));
                    if (!metaInfDir.exists()) {
                        metaInfDir.create(true, true, null);
                    }

                    // Create persistence.xml with the desired contents
                    final IFile file = metaInfDir.getFile(new Path("persistence.xml"));
                    String contents = getContents(pkg);
                    InputStream stream = new ByteArrayInputStream(contents.toString().getBytes());
                    if (file.exists()) {
                        file.setContents(stream, true, true, null);
                    } else {
                        file.create(stream, true, null);
                    }
                    stream.close();

                    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                    try {
                        IDE.openEditor(page, file, true);
                    } catch (PartInitException e) {
                    }
                } catch (CoreException e) {
                } catch (IOException e) {
                }
            } catch (JavaModelException jme) {

            }
        }
    }
}

From source file:org.eclipse.ajdt.internal.ui.wizards.exports.AJJarPackageWizardPage.java

License:Open Source License

private Set getCorrespondingContainers(Set elements) {
    Set javaElementResources = new HashSet(elements.size());
    Iterator iter = elements.iterator();
    while (iter.hasNext()) {
        Object element = iter.next();
        if (element instanceof IJavaElement) {
            IJavaElement je = (IJavaElement) element;
            int type = je.getElementType();
            if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT
                    || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
                // exclude default package since it is covered by the root
                if (!(type == IJavaElement.PACKAGE_FRAGMENT
                        && ((IPackageFragment) element).isDefaultPackage())) {
                    Object resource;
                    try {
                        resource = je.getCorrespondingResource();
                    } catch (JavaModelException ex) {
                        resource = null;
                    }/*from   w w  w. j a  v  a 2s  . c o m*/
                    if (resource != null)
                        javaElementResources.add(resource);
                }
            }
        }
    }
    return javaElementResources;
}

From source file:org.eclipse.ant.tests.ui.debug.AbstractAntDebugTest.java

License:Open Source License

protected IResource getBreakpointResource(String typeName) throws Exception {
    IJavaElement element = getJavaProject().findElement(new Path(typeName + ".java")); //$NON-NLS-1$
    IResource resource = element.getCorrespondingResource();
    if (resource == null) {
        resource = getJavaProject().getProject();
    }/* w  ww .j  ava2  s .c  o m*/
    return resource;
}

From source file:org.eclipse.jst.ws.internal.common.ResourceUtils.java

License:Open Source License

/**
 * Returns the IResource represented by the given selection.
 * /* www  . ja  v  a2s .  c om*/
 * @param object
 *            The selection
 * @return IResource if the selection represents an IResource. Returns null
 *         otherwise.
 * @throws CoreException
 */
static public IResource getResourceFromSelection(Object obj) throws CoreException {
    IResource res = null;
    if (obj != null) {
        if (obj instanceof IResource) {
            res = (IResource) obj;
        } else if (obj instanceof IJavaElement) {
            IJavaElement javaElement = (IJavaElement) obj;
            res = javaElement.getCorrespondingResource();
        } else if (obj instanceof EnterpriseBean) {
            EnterpriseBean ejbBean = (EnterpriseBean) obj;
            IProject ejbProject = ProjectUtilities.getProject(ejbBean);
            if (ejbProject != null)
                res = ejbProject;
        } else if (obj instanceof SessionBean) {
            SessionBean JEE5Bean = (SessionBean) obj;
            IProject ejbProject = ProjectUtilities.getProject(JEE5Bean);
            if (ejbProject != null)
                res = ejbProject;
        }

    }

    return res;
}

From source file:org.eclipse.objectteams.otdt.debug.tests.AbstractOTDTDebugTest.java

License:Open Source License

protected IResource getBreakpointResource(String typeName) throws Exception {
    IJavaElement element = getJavaProject().findElement(new Path(typeName + ".java"));
    IResource resource = element.getCorrespondingResource();
    if (resource == null) {
        resource = getJavaProject().getProject();
    }// w  w  w. j ava 2s  .  co m
    return resource;
}

From source file:org.eclipse.zest.dot.internal.TestZestProjectWizard.java

License:Open Source License

private IProject getNewProject(ZestProjectWizard wizard) {
    IJavaElement createdElement = wizard.getCreatedProject();
    try {//from  w w w.j av  a  2s  .co m
        return createdElement.getCorrespondingResource().getProject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}