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

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

Introduction

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

Prototype

IResource getUnderlyingResource() throws JavaModelException;

Source Link

Document

Returns the smallest underlying resource that contains this element, or null if this element is not contained in a resource.

Usage

From source file:org.fusesource.ide.branding.wizards.NewCamelXmlWizardPage.java

License:Open Source License

/**
 * Tests if the current workbench selection is a suitable container to use.
 *//*from   ww  w.  ja  v  a  2  s .c om*/
private void initialize() {
    if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) {
        IStructuredSelection ssel = (IStructuredSelection) selection;
        if (ssel.size() > 1)
            return;
        Object obj = ssel.getFirstElement();
        if (obj instanceof IJavaElement) {
            IJavaElement element = (IJavaElement) obj;
            try {
                obj = element.getUnderlyingResource();
            } catch (JavaModelException e) {
                Activator.getLogger().error("Failed to examine IJavaElement: " + e, e);
            }
        }
        if (obj instanceof IResource) {
            IContainer container;
            if (obj instanceof IContainer)
                container = (IContainer) obj;
            else
                container = ((IResource) obj).getParent();
            containerText.setText(container.getFullPath().toString());
        } else {
            Activator.getLogger().warning("Selection is not a resource so can't select it for the container: "
                    + obj + " " + obj.getClass().getCanonicalName());
        }
    }
    fileText.setText(DEFAULT_CAMEL_XML_NAME);
    updateStatus(null);
    dialogChanged();
}

From source file:org.jactr.eclipse.core.parser.ProjectSensitiveParserImportDelegate.java

License:Open Source License

/**
 * we've found the valid class name from the previous call to isValidClassName
 * if the super implementation can't find it, we check for any extensions that
 * provide one..//from w w w .j  a  v  a2s .co m
 * 
 * @param moduleClassName
 * @return
 */
@Override
protected IASTParticipant getASTParticipant(String moduleClassName) {
    IASTParticipant participant = super.getASTParticipant(moduleClassName);
    if (participant == null) {
        boolean participantIsDefined = false;

        /*
         * find one ourselves..
         */
        for (ASTParticipantDescriptor descriptor : org.jactr.eclipse.core.bundles.registry.ASTParticipantRegistry
                .getRegistry().getDescriptors(_project))
            if (descriptor.getContributingClassName().equals(moduleClassName)) {
                participantIsDefined = true;

                // the code block below is handled by jactr.io.activator.Activator
                // /*
                // * if we can instantiate this, let's do so.. im not sure if this
                // * should actually be installed since we are project specific.. if
                // we
                // * had different versions active, bad things could happen
                // */
                // try
                // {
                // participant = (IASTParticipant) descriptor.instantiate();
                // if (participant != null) return participant;
                // }
                // catch (Exception e)
                // {
                // CorePlugin.debug("Could not instantiate "
                // + descriptor.getContributingClassName() + " for "
                // + moduleClassName, e);
                // }

                /*
                 * construct and return. We know we can't use participantClass since
                 * this is a workspace extension, we have to use BasicASTParticipat
                 * and content location
                 */
                String contentLocation = descriptor.getContentLocation();
                IPath location = new Path(contentLocation);
                try {
                    IProject contributorProject = ResourcesPlugin.getWorkspace().getRoot()
                            .getProject(descriptor.getContributor());

                    // CorePlugin.debug(String.format("Checking %s(%s)",
                    // contributorProject.getName(), contributorProject.exists()));

                    IJavaProject project = JavaCore.create(contributorProject);
                    IResource resource = null;

                    IJavaElement containingPackage = project.findElement(location.removeLastSegments(1));

                    if (containingPackage != null
                            && containingPackage.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("Found package that contains " + location + " at "
                                    + containingPackage.getPath());

                        // CorePlugin.debug("Found package that contains " + location
                        // + " at " + containingPackage.getPath());

                        IResource tmp = containingPackage.getUnderlyingResource();
                        if (tmp instanceof IContainer) {
                            IContainer container = (IContainer) tmp;
                            resource = container.findMember(location.lastSegment());
                        }
                    }
                    // else
                    // CorePlugin.debug(location + " Containing package = "
                    // + containingPackage);

                    if (resource == null)
                        throw new RuntimeException(String.format("Could not find %s (%s) within %s' classpath",
                                contentLocation, location, _project.getName()));

                    URL contentURL = resource.getLocationURI().toURL();

                    // CorePlugin.debug(String.format(
                    // "Creating participant for content @ %s",
                    // contentURL.toExternalForm()));

                    participant = new IDEBasicASTParticipant(contentURL);
                } catch (Exception e) {
                    String message = "Could not create basic ast participant referencing " + contentLocation
                            + " in " + _project.getName();
                    if (LOGGER.isWarnEnabled())
                        LOGGER.warn(message, e);
                    CorePlugin.warn(message, e);
                    return null;
                }
            }

        if (participant == null && participantIsDefined) {
            /*
             * warn and log
             */
            String message = "Could not find a valid IASTParticipant in any dependencies for "
                    + moduleClassName;
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(message);
            CorePlugin.warn(message);
        }
    }

    return participant;
}

From source file:org.jboss.tools.cdi.seam.text.ext.hyperlink.XMLInjectedPointHyperlinkDetector.java

License:Open Source License

public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {

    this.viewer = textViewer;

    if (region == null || !canShowMultipleHyperlinks)
        return null;

    IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();

    if (!(editor instanceof EditorPartWrapper))
        return null;

    IEditorInput input = ((EditorPartWrapper) editor).getEditorInput();

    if (!(input instanceof FileEditorInput))
        return null;

    file = ((FileEditorInput) input).getFile();

    if (file == null)
        return null;

    CDICoreNature cdiNature = CDIUtil.getCDINatureWithProgress(file.getProject());
    if (cdiNature == null)
        return null;

    document = textViewer.getDocument();

    ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>();

    Node node = getTagNode(region.getOffset());
    if (node == null)
        return null;

    int offset = ((IndexedRegion) node).getStartOffset();

    String uri = getURI(node);/*ww w.ja v a  2s.  c om*/
    IJavaElement element = null;
    IType type = Util.resolveType(node.getLocalName(), uri, cdiNature);
    if (type != null) {
        element = type;
    } else {
        SeamMemberDefinition def = find(cdiNature, offset, file);
        if (def instanceof SeamFieldDefinition) {
            element = ((SeamFieldDefinition) def).getField();
        } else if (def instanceof SeamMethodDefinition) {
            element = ((SeamMethodDefinition) def).getMethod();
        }
    }
    if (element != null) {
        IFile elementFile = null;
        try {
            elementFile = (IFile) element.getUnderlyingResource();
        } catch (JavaModelException ex) {
            CDISeamExtPlugin.getDefault().logError(ex);
        }

        if (elementFile != null)
            findInjectedBeans(cdiNature, element, offset, elementFile.getFullPath(), hyperlinks,
                    editor.isDirty());

        if (hyperlinks != null && !hyperlinks.isEmpty()) {
            return (IHyperlink[]) hyperlinks.toArray(new IHyperlink[hyperlinks.size()]);
        }
    }
    return null;
}

From source file:org.jboss.tools.common.el.core.resolver.JavaMemberELSegmentImpl.java

License:Open Source License

/**
 * @param element the element to set/*from   www.j a  v a  2s  .c  o  m*/
 */
public void setElement(IJavaElement element) {
    this.element = element;
    try {
        setResource(element.getUnderlyingResource());
    } catch (JavaModelException e) {
        ELCorePlugin.getDefault().logError(e);
    }
}

From source file:org.projectusus.ui.internal.proportions.infopresenter.infomodel.UsusInfoBuilder.java

License:Open Source License

public static IUsusInfo of(IJavaElement element) {
    try {// w  w w .  j a va 2s .co m
        IJavaElement currentElement = element;
        while (currentElement != null) {
            if (currentElement.getElementType() == IJavaElement.METHOD) {
                return new UsusInfoForMethod((IMethod) currentElement);
            }
            if (currentElement.getElementType() == IJavaElement.TYPE) {
                return new UsusInfoForClass((IType) currentElement);
            }
            if (currentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                return new UsusInfoForFile(currentElement.getUnderlyingResource());
            }
            currentElement = currentElement.getParent();
        }
    } catch (JavaModelException e) {
        // do nothing
    }
    return new UnavailableUsusInfo(element);
}

From source file:org.seasar.kijimuna.core.internal.dicon.refactor.KijimunaRenameParticipant.java

License:Apache License

protected boolean initialize(Object element) {
    try {/*from   w  w  w  .  j a va2s .com*/
        IJavaElement targetElement = (IJavaElement) element;
        IProject prj = targetElement.getUnderlyingResource().getProject();
        nature = DiconNature.getInstance(prj);

        addElement(element, (RenameArguments) getArguments());
        return true;

    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.seasar.kijimuna.core.internal.dicon.refactor.KijimunaRenameParticipant.java

License:Apache License

public void addElement(Object element, RefactoringArguments arguments) {
    IJavaElement javaElement = (IJavaElement) element;
    String newName = ((RenameArguments) arguments).getNewName();
    renameElements.put(javaElement, newName);

    try {/*from  w ww. j av a 2 s .  com*/
        if (javaElement instanceof IPackageFragment) {
            // ??????dicon????
            IPackageFragment pkgFragment = (IPackageFragment) javaElement;
            ICompilationUnit[] cUnits = pkgFragment.getCompilationUnits();

            for (int i = 0; i < cUnits.length; i++) {
                ICompilationUnit cUnit = cUnits[i];
                IFile file = (IFile) cUnit.getUnderlyingResource();
                IFile[] dicon = nature.getModel().getRelatedFiles(file, true);
                diconList.addAll(Arrays.asList(dicon));
            }
        } else {
            // ?????dicon????
            IFile file = (IFile) javaElement.getUnderlyingResource();
            IFile[] dicon = nature.getModel().getRelatedFiles(file, true);
            diconList.addAll(Arrays.asList(dicon));
        }
    } catch (JavaModelException e) {
        KijimunaCore.reportException(e);
    }
}

From source file:org.springframework.ide.eclipse.core.model.java.JavaModelSourceLocation.java

License:Open Source License

public Resource getResource() {
    try {//from w ww .  j a  v a  2  s  .  c o  m
        IJavaElement element = JdtUtils.getByHandle(handleIdentifier);
        if (element != null) {
            IResource resource = element.getUnderlyingResource();
            if (resource != null) {
                return new FileResource(resource.getFullPath().toString());
            }
            resource = element.getCorrespondingResource();
            if (resource != null) {
                return new FileResource(resource.getFullPath().toString());
            }
            resource = element.getResource();
            if (resource != null) {
                return new FileResource(resource.getFullPath().toString());
            }
            IPath path = element.getPath();
            if (path != null && path.toFile().exists()) {
                if (path.isAbsolute()) {
                    return new FileSystemResource(path.toFile());
                } else {
                    return new FileResource(path.toString());
                }
            }
        }
    } catch (JavaModelException e) {
    }
    return null;
}