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

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

Introduction

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

Prototype

IJavaProject getJavaProject();

Source Link

Document

Returns the Java project this element is contained in, or null if this element is not contained in any Java project (for instance, the IJavaModel is not contained in any Java project).

Usage

From source file:de.loskutov.bco.ui.JdtUtils.java

License:Open Source License

/**
 * @param javaElement/*from w w  w.  jav a2  s .  com*/
 * @return absolute path of generated bytecode package for given element
 * @throws JavaModelException
 */
private static String getPackageOutputPath(IJavaElement javaElement) throws JavaModelException {
    String dir = ""; //$NON-NLS-1$
    if (javaElement == null) {
        return dir;
    }

    IJavaProject project = javaElement.getJavaProject();

    if (project == null) {
        return dir;
    }
    // default bytecode location
    IPath path = project.getOutputLocation();

    IResource resource = javaElement.getUnderlyingResource();
    if (resource == null) {
        return dir;
    }
    // resolve multiple output locations here
    if (project.exists() && project.getProject().isOpen()) {
        IClasspathEntry entries[] = project.getRawClasspath();
        for (int i = 0; i < entries.length; i++) {
            IClasspathEntry classpathEntry = entries[i];
            if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath outputPath = classpathEntry.getOutputLocation();
                if (outputPath != null && classpathEntry.getPath().isPrefixOf(resource.getFullPath())) {
                    path = outputPath;
                    break;
                }
            }
        }
    }

    if (path == null) {
        // check the default location if not already included
        IPath def = project.getOutputLocation();
        if (def != null && def.isPrefixOf(resource.getFullPath())) {
            path = def;
        }
    }

    if (path == null) {
        return dir;
    }

    IWorkspace workspace = ResourcesPlugin.getWorkspace();

    if (!project.getPath().equals(path)) {
        IFolder outputFolder = workspace.getRoot().getFolder(path);
        if (outputFolder != null) {
            // linked resources will be resolved here!
            IPath rawPath = outputFolder.getRawLocation();
            if (rawPath != null) {
                path = rawPath;
            }
        }
    } else {
        path = project.getProject().getLocation();
    }

    // here we should resolve path variables,
    // probably existing at first place of path
    IPathVariableManager pathManager = workspace.getPathVariableManager();
    path = pathManager.resolvePath(path);

    if (path == null) {
        return dir;
    }

    if (isPackageRoot(project, resource)) {
        dir = path.toOSString();
    } else {
        String packPath = EclipseUtils.getJavaPackageName(javaElement).replace(Signature.C_DOT,
                PACKAGE_SEPARATOR);
        dir = path.append(packPath).toOSString();
    }
    return dir;
}

From source file:de.loskutov.bco.ui.JdtUtils.java

License:Open Source License

private static boolean isOnClasspath(IJavaElement javaElement) {
    IJavaProject project = javaElement.getJavaProject();
    if (project != null) {
        boolean result = project.isOnClasspath(javaElement);
        return result;
    }// w  w w. j  av  a2  s . c  o m
    return false;
}

From source file:de.loskutov.bco.ui.JdtUtils.java

License:Open Source License

public static ClassLoader getClassLoader(IJavaElement type) {
    ClassLoader cl;//w ww.  ja  v  a 2s  . co  m

    IJavaProject javaProject = type.getJavaProject();
    List<URL> urls = new ArrayList<URL>();

    getClassURLs(javaProject, urls);

    if (urls.isEmpty()) {
        cl = JdtUtils.class.getClassLoader();
    } else {
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    }
    return cl;
}

From source file:de.loskutov.eclipse.jdepend.views.TreeObject.java

License:Open Source License

protected String getPackageOutputPath(IJavaElement jElement) throws JavaModelException {
    String dir = ""; //$NON-NLS-1$
    if (jElement == null) {
        return dir;
    }//w ww .  j  ava  2  s . co  m

    IJavaProject project = jElement.getJavaProject();

    if (project == null) {
        return dir;
    }
    IPath path = project.getOutputLocation();

    IResource resource = jElement.getUnderlyingResource();
    if (resource == null) {
        return dir;
    }
    // resolve multiple output locations here
    if (project.exists() && project.getProject().isOpen()) {
        IClasspathEntry entries[] = project.getRawClasspath();

        for (int i = 0; i < entries.length; i++) {
            IClasspathEntry classpathEntry = entries[i];
            if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath outputPath = classpathEntry.getOutputLocation();
                if (outputPath != null) {
                    // if this source folder contains specified java resource
                    // then take bytecode location from himself
                    if (classpathEntry.getPath().isPrefixOf(resource.getFullPath())) {
                        path = outputPath;
                        break;
                    }
                }
            }
        }
    }

    if (path == null) {
        // check the default location if not already included
        IPath def = project.getOutputLocation();
        if (def != null && def.isPrefixOf(resource.getFullPath())) {
            path = def;
        }
    }

    if (path == null) {
        return dir;
    }

    IWorkspace workspace = ResourcesPlugin.getWorkspace();

    if (!project.getPath().equals(path)) {
        IFolder outputFolder = workspace.getRoot().getFolder(path);
        if (outputFolder != null) {
            // linked resources will be resolved here!
            IPath rawPath = outputFolder.getRawLocation();
            if (rawPath != null) {
                path = rawPath;
            }
        }
    } else {
        path = project.getProject().getLocation();
    }

    if (path == null) {
        return dir;
    }

    // here we should resolve path variables,
    // probably existing at first place of path
    IPathVariableManager pathManager = workspace.getPathVariableManager();
    path = pathManager.resolvePath(path);

    if (path == null) {
        return dir;
    }

    boolean packageRoot = false;
    try {
        packageRoot = isPackageRoot(project, resource);
    } catch (JavaModelException e) {
        // seems to be a bug in 3.3
    }
    if (packageRoot) {
        dir = path.toOSString();
    } else {
        String packPath = getPackageName().replace('.', '/');
        dir = path.append(packPath).toOSString();
    }
    return dir;
}

From source file:de.plugins.eclipse.depclipse.JDependAdapter.java

License:Open Source License

/**
 * Create object tree and initialize map with new IResource->TreeObject
 * pairs.//  www.j av  a 2  s  .c  o m
 * 
 * @param resource
 * @return TreeParent
 */
private TreeFolder[] createTree(JDependData jdependData, IResource resource) {
    if (resource.getType() != IResource.FOLDER) {
        return new TreeFolder[0];
    }
    IContainer folder = (IContainer) resource;

    IResource[] resources = null;

    try {
        resources = folder.members();
    } catch (CoreException e) {
        DepclipsePlugin.handle(e);
    }

    if (resources == null || resources.length == 0) {
        return new TreeFolder[0];
    }

    boolean isPackageRoot = false;
    IJavaElement javaElement = JavaCore.create(folder);

    if (javaElement != null) {
        try {
            isPackageRoot = TreeObject.isPackageRoot(javaElement.getJavaProject(), folder);
        } catch (JavaModelException e) {

        }
    } else {
        isPackageRoot = false;
    }

    if (!isPackageRoot && jdependData.resourceMapContains(folder)) {
        return new TreeFolder[0];
    }

    TreeFolder tree = (TreeFolder) jdependData.getFromResourceMap(folder);
    ArrayList<TreeFolder> treeRoots = null;
    // add parent package, if not exist
    if (tree == null) {
        tree = new TreeFolder(javaElement);
        treeRoots = new ArrayList<TreeFolder>();
        treeRoots.add(tree);
        jdependData.putToResourceMap(folder, tree);

    }
    if (treeRoots == null) {
        return new TreeFolder[0];
    }
    TreeFolder[] results;
    TreeLeaf tleaf;
    IJavaElement javaChild;
    String tname;
    for (int i = 0; i < resources.length; i++) {
        if (resources[i].getType() == IResource.FOLDER) {
            results = createTree(jdependData, resources[i]);
            for (int j = 0; j < results.length; j++) {
                if (!treeRoots.contains(results[j])) {
                    treeRoots.add(results[j]);
                }
            }
        } else {
            tname = resources[i].getName();
            if (tname.endsWith(".java")) { //$NON-NLS-1$
                javaChild = JavaCore.create(resources[i]);
                if (javaChild == null) {
                    continue;
                }
                tleaf = new TreeLeaf(javaChild);
                jdependData.putToResourceMap(resources[i], tleaf);
                tree.addChild(tleaf);
            } else if (tname.endsWith(".class")) { //$NON-NLS-1$
                tleaf = new TreeLeaf(resources[i]);
                jdependData.putToResourceMap(resources[i], tleaf);
                tree.addChild(tleaf);
            }
        }
    }

    return (TreeFolder[]) treeRoots.toArray(new TreeFolder[treeRoots.size()]);
}

From source file:de.tobject.findbugs.builder.WorkItem.java

License:Open Source License

public WorkItem(IJavaElement javaElt) {
    this(null, javaElt, javaElt.getJavaProject().getProject());
}

From source file:de.tobject.findbugs.reporter.JdtUtils.java

License:Open Source License

/**
 * @param javaElt//from   w  w w .  j  a  v  a 2  s  . com
 * @return true, if corresponding java project has compiler setting to
 *         generate bytecode for jdk 1.5 and above
 */
private static boolean is50OrHigher(IJavaElement javaElt) {
    IJavaProject project = javaElt.getJavaProject();
    String option = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
    boolean result = JavaCore.VERSION_1_5.equals(option);
    if (result) {
        return result;
    }
    // probably > 1.5?
    result = JavaCore.VERSION_1_4.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_3.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_2.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_1.equals(option);
    if (result) {
        return false;
    }
    // unknown = > 1.5
    return true;
}

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

License:Open Source License

/********************************************************************************/

void handleFindHierarchy(String proj, String pkg, String cls, boolean all, IvyXmlWriter xw)
        throws BedrockException {
    IJavaProject ijp = getJavaProject(proj);
    IRegion rgn = JavaCore.newRegion();/*from ww  w  . jav  a2s  .  c  o  m*/
    IType fortype = null;

    boolean havejp = (ijp != null);

    if (ijp == null && (pkg != null || cls != null)) {
        IJavaElement[] aps = getAllProjects();
        if (aps.length == 0)
            return;
        if (cls != null) {
            for (IJavaElement ije : aps) {
                IJavaProject xjp = ije.getJavaProject();
                try {
                    if (xjp.findType(cls) != null) {
                        ijp = xjp;
                        break;
                    }
                } catch (JavaModelException e) {
                }
            }
        }
        if (ijp == null)
            ijp = aps[0].getJavaProject();
    }

    int addct = 0;

    if (cls != null && ijp != null) {
        try {
            IType typ = ijp.findType(cls);
            fortype = typ;
            // rgn.add(typ);
            // ++addct;
        } catch (JavaModelException e) {
            BedrockPlugin.logE("Problem getting type by name: " + e);
        }
    }

    if (pkg != null && ijp != null) {
        String ppth = "/" + pkg.replace(".", "/");
        try {
            for (IPackageFragmentRoot ipr : ijp.getPackageFragmentRoots()) {
                IPath rpath = ipr.getPath();
                Path npath = new Path(rpath.toString() + ppth);
                IPackageFragment ipf = ijp.findPackageFragment(npath);
                if (ipf != null) {
                    rgn.add(ipf);
                    ++addct;
                }
            }
        } catch (Exception e) {
            BedrockPlugin.logE("Problem getting package fragments for " + ppth + ": " + e);
        }
    } else if (havejp && ijp != null) {
        if (all) {
            rgn.add(ijp);
            ++addct;
        } else {
            try {
                for (IPackageFragment ipf : ijp.getPackageFragments()) {
                    for (ICompilationUnit icu : ipf.getCompilationUnits()) {
                        IType ity = ((ITypeRoot) icu).findPrimaryType();
                        if (ity != null) {
                            rgn.add(ity);
                            ++addct;
                        }
                    }
                }
            } catch (Throwable e) {
                BedrockPlugin.logE("Problem getting package fragments: " + e);
            }
        }
    } else {
        for (IJavaElement pi : getAllProjects()) {
            IJavaProject xjp = pi.getJavaProject();
            if (xjp != null && !rgn.contains(xjp)) {
                rgn.add(xjp);
                ++addct;
            }
            // String pnm = pi.getJavaProject().getProject().getName();
            // handleFindHierarchy(pnm,null,null,all,xw);
        }
    }

    if (addct > 0 && ijp != null) {
        try {
            BedrockPlugin.logD("FIND TYPE HIERARCHY FOR " + fortype + " " + addct + " " + rgn);

            ITypeHierarchy ith;
            if (fortype != null)
                ith = ijp.newTypeHierarchy(fortype, rgn, null);
            else
                ith = ijp.newTypeHierarchy(rgn, null);
            BedrockUtil.outputTypeHierarchy(ith, xw);
        } catch (JavaModelException e) {
            BedrockPlugin.logE("Problem outputing type hierarchy: " + e);
        } catch (NullPointerException e) {
            // this is a bug in Eclipse that should be fixed
        }
    }
}

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

License:Open Source License

private static void outputJavaElementImpl(IJavaElement elt, Set<String> files, boolean children,
        IvyXmlWriter xw) {/*from  w ww. j av a2s.c o  m*/
    if (elt == null)
        return;

    String close = null;

    switch (elt.getElementType()) {
    case IJavaElement.CLASS_FILE:
        return;
    case IJavaElement.PACKAGE_FRAGMENT:
        IOpenable opn = (IOpenable) elt;
        if (!opn.isOpen()) {
            try {
                opn.open(null);
            } catch (JavaModelException e) {
                BedrockPlugin.logE("Package framgent " + elt.getElementName() + " not open");
                return;
            }
        }
        try {
            outputNameDetails((IPackageFragment) elt, xw);
        } catch (JavaModelException e) {
        }
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        IPackageFragmentRoot pfr = (IPackageFragmentRoot) elt;
        try {
            if (!pfr.isOpen() && pfr.getKind() == IPackageFragmentRoot.K_SOURCE) {
                pfr.open(null);
            }
        } catch (JavaModelException e) {
            return;
        }
        outputNameDetails(pfr, xw);
        break;
    case IJavaElement.JAVA_PROJECT:
        IJavaProject ijp = (IJavaProject) elt;
        outputNameDetails(ijp, xw);
        break;
    case IJavaElement.JAVA_MODEL:
    case IJavaElement.IMPORT_CONTAINER:
    case IJavaElement.IMPORT_DECLARATION:
    case IJavaElement.TYPE_PARAMETER:
    default:
        break;
    case IJavaElement.COMPILATION_UNIT:
        IProject ip = elt.getJavaProject().getProject();
        File f = getFileForPath(elt.getPath(), ip);
        if (files != null && !files.contains(f.getPath()) && !files.contains(f.getAbsolutePath())) {
            return;
        }
        xw.begin("FILE");
        xw.textElement("PATH", f.getAbsolutePath());
        String root = getRootForPath(elt.getPath(), ip);
        if (root != null)
            xw.textElement("PATHROOT", root);
        close = "FILE";
        break;
    case IJavaElement.TYPE:
        try {
            outputNameDetails((IType) elt, xw);
        } catch (JavaModelException e) {
        }
        break;
    case IJavaElement.FIELD:
        try {
            outputNameDetails((IField) elt, xw);
        } catch (JavaModelException e) {
        }
        break;
    case IJavaElement.METHOD:
        try {
            outputNameDetails((IMethod) elt, xw);
        } catch (JavaModelException e) {
        }
        break;
    case IJavaElement.INITIALIZER:
        outputNameDetails((IInitializer) elt, xw);
        break;
    case IJavaElement.PACKAGE_DECLARATION:
        outputNameDetails((IPackageDeclaration) elt, xw);
        break;
    case IJavaElement.LOCAL_VARIABLE:
        outputNameDetails((ILocalVariable) elt, xw);
        break;
    }

    if (children && elt instanceof IParent) {
        try {
            for (IJavaElement c : ((IParent) elt).getChildren()) {
                outputJavaElementImpl(c, files, children, xw);
            }
        } catch (JavaModelException e) {
        }
    }

    if (close != null)
        xw.end(close);
}

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

License:Open Source License

private static void outputSymbol(IJavaElement elt, String what, String nm, String key, IvyXmlWriter xw) {
    if (what == null || nm == null)
        return;// w  w  w.  j ava  2 s  .c  o m

    xw.begin("ITEM");
    xw.field("TYPE", what);
    xw.field("NAME", nm);
    xw.field("HANDLE", elt.getHandleIdentifier());

    xw.field("WORKING", (elt.getPrimaryElement() != elt));
    ICompilationUnit cu = (ICompilationUnit) elt.getAncestor(IJavaElement.COMPILATION_UNIT);
    if (cu != null) {
        xw.field("CUWORKING", cu.isWorkingCopy());
    }
    try {
        xw.field("KNOWN", elt.isStructureKnown());
    } catch (JavaModelException e) {
    }

    if (elt instanceof ISourceReference) {
        try {
            ISourceRange rng = ((ISourceReference) elt).getSourceRange();
            if (rng != null) {
                xw.field("STARTOFFSET", rng.getOffset());
                xw.field("ENDOFFSET", rng.getOffset() + rng.getLength());
                xw.field("LENGTH", rng.getLength());
            }
        } catch (JavaModelException e) {
            BedrockPlugin.logE("Problem getting source range: " + e);
        }
    }

    if (elt instanceof ILocalVariable) {
        ILocalVariable lcl = (ILocalVariable) elt;
        xw.field("SIGNATURE", lcl.getTypeSignature());
    }

    if (elt instanceof IMember) {
        try {
            IMember mem = ((IMember) elt);
            int fgs = mem.getFlags();
            if (mem.getParent() instanceof IType && !(elt instanceof IType)) {
                IType par = (IType) mem.getParent();
                if (par.isInterface()) {
                    if (elt instanceof IMethod)
                        fgs |= Flags.AccAbstract;
                    fgs |= Flags.AccPublic;
                }
                xw.field("QNAME", par.getFullyQualifiedName() + "." + nm);
            }
            xw.field("FLAGS", fgs);
        } catch (JavaModelException e) {
        }
    }

    if (elt instanceof IPackageFragment || elt instanceof IType) {
        Display d = BedrockApplication.getDisplay();
        if (d != null) {
            JavadocUrl ju = new JavadocUrl(elt);
            d.syncExec(ju);
            URL u = ju.getResult();
            if (u != null) {
                xw.field("JAVADOC", u.toString());
            }
        }
    }

    xw.field("SOURCE", "USERSOURCE");
    if (key != null)
        xw.field("KEY", key);

    boolean havepath = false;
    for (IJavaElement pe = elt.getParent(); pe != null; pe = pe.getParent()) {
        if (pe.getElementType() == IJavaElement.COMPILATION_UNIT) {
            IProject ip = elt.getJavaProject().getProject();
            File f = BedrockUtil.getFileForPath(elt.getPath(), ip);
            xw.field("PATH", f.getAbsolutePath());
            havepath = true;
            break;
        }
    }
    IJavaProject ijp = elt.getJavaProject();
    if (ijp != null)
        xw.field("PROJECT", ijp.getProject().getName());
    IPath p = elt.getPath();
    if (p != null) {
        xw.field("XPATH", p);
        if (!havepath) {
            IProject ip = elt.getJavaProject().getProject();
            File f = getFileForPath(elt.getPath(), ip);
            xw.field("PATH", f.getAbsolutePath());
        }
    }

    if (elt instanceof IMethod) {
        IMethod m = (IMethod) elt;
        try {
            xw.field("RESOLVED", m.isResolved());
            ISourceRange rng = m.getNameRange();
            if (rng != null) {
                xw.field("NAMEOFFSET", rng.getOffset());
                xw.field("NAMELENGTH", rng.getLength());
            }
            xw.field("RETURNTYPE", m.getReturnType());
            xw.field("NUMPARAM", m.getNumberOfParameters());
            String[] pnms = m.getParameterNames();
            String[] ptys = m.getParameterTypes();
            for (int i = 0; i < ptys.length; ++i) {
                xw.begin("PARAMETER");
                if (i < pnms.length)
                    xw.field("NAME", pnms[i]);
                xw.field("TYPE", ptys[i]);
                xw.end();
            }
            for (String ex : m.getExceptionTypes()) {
                xw.begin("EXCEPTION");
                xw.field("TYPE", ex);
                xw.end();
            }
        } catch (JavaModelException e) {
        }
    }

    // TODO: output parameters as separate elements with type and name

    if (elt instanceof IAnnotatable) {
        IAnnotatable ann = (IAnnotatable) elt;
        try {
            IAnnotation[] ans = ann.getAnnotations();
            for (IAnnotation an : ans) {
                xw.begin("ANNOTATION");
                xw.field("NAME", an.getElementName());
                xw.field("COUNT", an.getOccurrenceCount());
                try {
                    for (IMemberValuePair mvp : an.getMemberValuePairs()) {
                        xw.begin("VALUE");
                        xw.field("NAME", mvp.getMemberName());
                        if (mvp.getValue() != null)
                            xw.field("VALUE", mvp.getValue().toString());
                        xw.field("KIND", mvp.getValueKind());
                        xw.end("VALUE");
                    }
                } catch (JavaModelException e) {
                }
                xw.end("ANNOTATION");
            }
        } catch (JavaModelException e) {
        }
    }

    xw.end("ITEM");
}