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

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

Introduction

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

Prototype

IPath getPath();

Source Link

Document

Returns the path to the innermost resource enclosing this element.

Usage

From source file:org.eclipse.modisco.java.discoverer.internal.serialization.ElementsToAnalyzeSerializer.java

License:Open Source License

public ElementsToAnalyze deserialize(final String serializedValue) {
    try {/*w ww . ja  v a2  s  . c  o  m*/
        String[] elements = serializedValue.split("\\" + ElementsToAnalyzeSerializer.SEPARATOR1); //$NON-NLS-1$

        ElementsToAnalyze elementsToAnalyze = new ElementsToAnalyze(getJavaProject(unescape(elements[0])));

        for (int i = 1; i < elements.length; i++) {
            String element = elements[i];
            if (element.startsWith(ElementsToAnalyzeSerializer.PROJECT_PREFIX)) {
                String[] elementParts = element.substring(ElementsToAnalyzeSerializer.PROJECT_PREFIX.length())
                        .split("\\" + ElementsToAnalyzeSerializer.SEPARATOR2); //$NON-NLS-1$
                String projectName2 = unescape(elementParts[0]);
                IJavaProject javaProject = getJavaProject(projectName2);
                elementsToAnalyze.addElementToDiscover(javaProject);
                fillMapWithRemainingParts(elementParts, elementsToAnalyze.getDiscoveryOptions(javaProject));
            } else if (element.startsWith(ElementsToAnalyzeSerializer.ELEMENT_PREFIX)) {
                String[] elementParts = element.substring(ElementsToAnalyzeSerializer.ELEMENT_PREFIX.length())
                        .split("\\" + ElementsToAnalyzeSerializer.SEPARATOR2); //$NON-NLS-1$
                String elementName = elementParts[0];
                String[] parts = elementName.split("\\" //$NON-NLS-1$
                        + ElementsToAnalyzeSerializer.SEPARATOR3);
                IJavaProject containingProject = getJavaProject(unescape(parts[0]));
                for (IJavaElement javaElement : containingProject.getChildren()) {
                    if (unescape(parts[1]).equals(javaElement.getElementName())
                            && new Path(unescape(parts[2])).equals(javaElement.getPath())) {
                        elementsToAnalyze.addElementToDiscover(javaElement);
                        fillMapWithRemainingParts(elementParts,
                                elementsToAnalyze.getDiscoveryOptions(javaElement));
                        break;
                    }
                }
            } else {
                MoDiscoLogger.logError("unhandled element", JavaActivator.getDefault()); //$NON-NLS-1$
            }

        }

        return elementsToAnalyze;
    } catch (Exception e) {
        MoDiscoLogger.logError(e, "Error deserializing elements to analyze", //$NON-NLS-1$
                JavaActivator.getDefault());
        return new ElementsToAnalyze(null);
    }
}

From source file:org.eclipse.recommenders.codesearch.rcp.index.indexer.ResourcePathIndexer.java

License:Open Source License

public static File getFile(final IJavaElement e) {
    final IResource resource = e.getResource();
    final IPath path;
    if (resource == null) {
        path = e.getPath();
    } else {/*from  w w  w  .  j a  v a  2s  .  c o m*/
        path = resource.getRawLocation();
        if (path == null) {
            final URI uri = resource.getLocationURI();
            if (uri != null) {
                return new File(uri);
            }
        }
    }
    return path.toFile();
}

From source file:org.eclipse.umlgen.reverse.java.AbstractJava2UMLConverter.java

License:Open Source License

/**
 * Convert an Package or a Java project into a UML2 model.
 *
 * @param javaElement//w w  w  .j a  v  a  2s.  c  o m
 *            the JavaElement
 * @param actGen
 * @return The UML2 model or <code>null</code> if the IJavaElement is not a Package or a Java Project.
 * @throws CoreException
 *             , if the resource is null or some critical error occur while importing.
 */
private Package convert(IJavaElement javaElement, ActivityGeneration actGen) throws CoreException {
    String path = null;
    IResource res = javaElement.getResource();
    if (res != null) {
        path = res.getLocation().toOSString();
    } else {
        path = javaElement.getPath().toString();
    }
    File dir = new File(path);
    Java2UMLLogListener listener = new Java2UMLLogListener(dir, modelName);
    logger.addLogListener(listener);
    LogUtils.resetTabbing();

    if (emfResource == null) {
        throwCoreException("The resource can't be null.");
    }

    switch (javaElement.getElementType()) {
    case IJavaElement.JAVA_PROJECT:
        javaProject = (IJavaProject) javaElement;
        return doConvertion((IJavaProject) javaElement, actGen);
    case IJavaElement.PACKAGE_FRAGMENT:
        javaProject = ((IPackageFragment) javaElement).getJavaProject();
        return doConvertion((IPackageFragment) javaElement, actGen);
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        javaProject = ((IPackageFragmentRoot) javaElement).getJavaProject();
        return doConvertion((IPackageFragmentRoot) javaElement, actGen);
    default:
        return null;
    }
}

From source file:org.eclipse.vjet.eclipse.javalaunch.utils.EclipseResourceUtils.java

License:Open Source License

public static File getSourceRoot(IJavaProject project, IJavaElement e) {
    try {/*from ww w .java  2 s .c om*/
        IPackageFragment frag = project.findPackageFragment(e.getPath());
        while (frag.isDefaultPackage() == false) {
            e = e.getParent();
            frag = project.findPackageFragment(e.getPath());
        }
        File f = e.getResource().getLocation().toFile();
        return f;
    } catch (JavaModelException e1) {
        throw new RuntimeException(e1);
    }
}

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

License:Open Source License

/**
 * {@inheritDoc}/*  w  ww . j av  a2s .c o m*/
 * @see org.eclipse.jface.wizard.Wizard#performFinish()
 */
@Override
public boolean performFinish() {
    try {
        createSimpleJavaProject();
        /* We first show the graph view to see the Zest representation of the new DOT file: */
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ZestGraphView.ID);
        IJavaElement javaElement = javaPage.getJavaProject();
        IPath path = javaElement.getPath();
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IResource newProject = root.findMember(path);
        File outRoot = new File(newProject.getLocationURI());
        /*
         * We copy the required resources from this bundle to the new project and setup the
         * project's classpath (which uses the copied resources):
         */
        DotFileUtils.copyAllFiles(resourcesDirectory(), outRoot);
        setupProjectClasspath(javaElement, root, newProject);
        newProject.refreshLocal(IResource.DEPTH_INFINITE, null);
        runGeneratedZestGraphs(javaElement);
        openDotFiles(javaElement);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (CoreException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:org.entirej.ide.ui.editors.form.FormDesignTreeSection.java

License:Apache License

public Action createGenerateRefBlockAction(final EJPluginBlockProperties properties) {
    return new Action("Generate Referenced Block") {
        String P_FORM_HEIGHT = "FORM_HEIGHT";
        String P_FORM_WIDTH = "FORM_WIDTH";

        @Override// w  ww.j  a v  a  2 s  .  c om
        public void runWithEvent(Event event) {

            final EJPluginFormProperties lformProperties = editor.getFormProperties();
            final List<String> reusableBlockNames;
            if (lformProperties.getEntireJProperties().getReusableBlocksLocation() != null
                    && lformProperties.getEntireJProperties().getReusableBlocksLocation().trim().length() > 0) {

                reusableBlockNames = lformProperties.getEntireJProperties().getReusableBlockNames();
            } else
                reusableBlockNames = null;

            InputDialog dlg = new InputDialog(EJUIPlugin.getActiveWorkbenchShell(),
                    String.format("Generate Referenced Block using [%s]", properties.getName()), "Block Name",
                    properties.getName(), new IInputValidator() {

                        public String isValid(String newText) {
                            if (reusableBlockNames == null) {
                                return "No Referenced Block Location is specified then it will not be possible to generate Reusable Blocks.";
                            }
                            if (newText == null || newText.trim().length() == 0)
                                return "Referenced Block name can't be empty.";
                            if (reusableBlockNames.contains(newText.trim()))
                                return "Referenced Block with this name already exists.";
                            return null;
                        }
                    });
            if (dlg.open() == Window.OK) {
                IJavaElement element;
                try {
                    IJavaProject project = editor.getJavaProject();
                    element = editor.getJavaProject().findElement(
                            new Path(lformProperties.getEntireJProperties().getReusableBlocksLocation()));

                    if (element == null) {
                        return;
                    }
                    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

                    IFolder folder = root.getFolder(element.getPath());
                    if (!folder.exists()) {
                        folder.create(false, true, null);
                    }

                    final IFile formFile = folder.getFile(new Path(
                            dlg.getValue() + "." + EJDevConstants.REFERENCED_BLOCK_PROPERTIES_FILE_SUFFIX));

                    EJPluginFormProperties formProperties = new EJPluginFormProperties(dlg.getValue(), project);

                    int height = EJPropertyRetriever.getIntValue(project.getProject(), P_FORM_HEIGHT);
                    int width = EJPropertyRetriever.getIntValue(project.getProject(), P_FORM_WIDTH);

                    formProperties.setFormHeight(height);
                    formProperties.setFormWidth(width);
                    formProperties.setNumCols(1);

                    String oblockName = properties.getName();
                    properties.internalSetName(dlg.getValue());
                    formProperties.getBlockContainer().addBlockProperties(properties);

                    // read lov usage in mapping
                    EJPluginLovDefinitionContainer lovDefinitionContainer = formProperties
                            .getLovDefinitionContainer();
                    for (EJPluginLovMappingProperties map : properties.getLovMappingContainer()
                            .getAllLovMappingProperties()) {

                        String definitionName = map.getLovDefinitionName();
                        if (lovDefinitionContainer.contains(definitionName))
                            continue;
                        EJPluginLovDefinitionProperties def = properties.getFormProperties()
                                .getLovDefinitionProperties(definitionName);
                        if (def != null) {
                            lovDefinitionContainer.addLovDefinitionProperties(def);
                        }
                    }

                    String canvasName = properties.getCanvasName();
                    try {
                        properties.setCanvasName(null);
                        FormPropertiesWriter writer = new FormPropertiesWriter();
                        writer.saveForm(formProperties, formFile, new NullProgressMonitor());
                        EJPluginEntireJPropertiesLoader.reload(formProperties.getJavaProject());
                        folder.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
                        properties.internalSetName(oblockName);
                        properties.setReferencedBlockName(dlg.getValue());
                        properties.setIsReferenced(true);
                    } finally {
                        properties.setCanvasName(canvasName);
                    }
                    EJUIPlugin.getStandardDisplay().asyncExec(new Runnable() {

                        public void run() {

                            editor.setDirty(true);
                            refresh(findNode(lformProperties.getBlockContainer()), true);

                        }
                    });
                } catch (JavaModelException e) {
                    EJCoreLog.logException(e);
                } catch (CoreException e) {
                    EJCoreLog.logException(e);
                }
            }

        }
    };
}

From source file:org.evolizer.da4java.plugin.selectionhandler.TextSelectionHandler.java

License:Apache License

/**
 * FamixMethod that returns a List of FamixEntities corresponding to the given EditorSelection
 * Returns null if the given selection is not of type EditorSelection.
 * // www  .  j  av a  2  s .c  om
 * @param snapshotAnalyzer the snapshot analyzer
 * 
 * @return the selected entities
 */
@SuppressWarnings({ "unchecked", "restriction" })
@Override
public List<AbstractFamixEntity> getSelectedEntities(SnapshotAnalyzer snapshotAnalyzer) {
    List<AbstractFamixEntity> selectedEntities = new ArrayList<AbstractFamixEntity>();
    if (getSelection() instanceof EditorSelection) {
        EditorSelection editorSelection = (EditorSelection) getSelection();
        IJavaElement compilationUnit = editorSelection.getCompilationUnit();
        IPath cuPath = compilationUnit.getPath();
        String path = cuPath.toString().substring(1);

        ITextSelection textSelection = editorSelection.getTextSelection();
        String offset = Integer.toString(textSelection.getOffset());
        try {
            @SuppressWarnings("unused")
            List result = snapshotAnalyzer.getHibernateSession()
                    .createSQLQuery("SELECT fe.* FROM famixentity fe, sourceanchor sa "
                            + " WHERE fe.sourceanchor_fk = sa.id AND sa.file like '%" + path + "'"
                            + " AND fe.uniqueName not like '%.<clinit>()' and fe.uniqueName not like '%.<oinit>()'"
                            + " AND sa.start < " + offset + " AND sa.end > " + offset)
                    .addEntity(AbstractFamixEntity.class).list();

            // selectedEntities = new Vector(filterResult(result));

            editorSelection.setSelectionName(selectedEntities.get(0).getName());
        } catch (HibernateException e) {
            e.printStackTrace();
        } catch (EvolizerException e) {
            e.printStackTrace();
        }
    }

    return selectedEntities;
}

From source file:org.granite.builder.util.ProjectUtil.java

License:Open Source License

public static JavaClassInfo getJavaClassInfo(IJavaProject project, IFile resource) throws CoreException {
    // classPath = "<project name>/<output folder>/<package>/<file>.class"
    IPath classPath = resource.getFullPath().makeRelative();

    // Find output folder: "<project name>/<output folder>".
    IPath outputFolder = null;//w  w w  . j  a v  a2  s  . c om
    if (project.getOutputLocation() != null && project.getOutputLocation().isPrefixOf(classPath))
        outputFolder = project.getOutputLocation();
    else {
        for (IClasspathEntry cpe : project.getRawClasspath()) {
            if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath output = cpe.getOutputLocation();
                if (output != null && output.isPrefixOf(classPath)) {
                    outputFolder = output;
                    break;
                }
            }
        }
    }

    if (outputFolder == null)
        return null;

    // Compute class name.
    IPath relativeClassPath = classPath.removeFirstSegments(outputFolder.segmentCount());
    IPath relativeClassName = relativeClassPath.removeFileExtension();
    String className = relativeClassName.toPortableString().replace('/', '.');

    // Compute java source path: "<package>/<class name>[$<inner class>].java".
    String javaFullPath = relativeClassName.addFileExtension("java").toPortableString();
    String javaFilePath = javaFullPath;
    int iDollar = javaFilePath.indexOf('$');
    if (iDollar != -1)
        javaFilePath = javaFilePath.substring(0, iDollar) + ".java";

    IJavaElement javaElement = project.findElement(new Path(javaFilePath));
    if (javaElement == null)
        return null;

    IJavaElement sourceFolder = javaElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    if (sourceFolder == null)
        return null;

    IPath folderPath = sourceFolder.getPath().makeRelative();
    if (folderPath.segmentCount() > 0)
        folderPath = folderPath.removeFirstSegments(1);

    // Fix issues with project not in the workspace directory.
    outputFolder = project.getProject().getWorkspace().getRoot().findMember(outputFolder).getLocation();

    return new JavaClassInfo(folderPath.toPortableString(), javaFullPath, className,
            new File(outputFolder.toPortableString(), relativeClassPath.toPortableString()));
}

From source file:org.gw4e.eclipse.facade.JDTManager.java

License:Open Source License

/**
 * @param elt/*from w  w  w.j a  v a  2  s  . c o m*/
 * @return
 * @throws JavaModelException
 */
public static String getFullyQualifiedName(IJavaElement elt) throws JavaModelException {
    IPackageFragmentRoot[] roots = elt.getJavaProject().getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].getPath().isPrefixOf(elt.getPath())) {
            IPath p = elt.getPath().makeRelativeTo(roots[i].getPath());
            return p.toString();
        }
    }
    return elt.getElementName();
}

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 ww .j a v a 2  s  . 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;
}