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

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

Introduction

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

Prototype

IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;

Source Link

Document

Returns all of the package fragment roots contained in this project, identified on this project's resolved classpath.

Usage

From source file:fede.workspace.dependencies.eclipse.java.util.TypeUtil.java

License:Apache License

/**
 * Find type./*from w w w  .  j  a va  2 s  . c o m*/
 * 
 * @param project
 *            the project
 * @param qualifiedPackage
 *            the qualified package
 * @param typeDef
 *            the type def
 * 
 * @return the i type
 */
public static IType findType(IProject project, String qualifiedPackage, String typeDef) {
    IJavaProject jp = JavaCore.create(project);
    if (!jp.exists())
        return null;

    try {
        IPackageFragmentRoot[] packagesRoot = jp.getPackageFragmentRoots();
        for (IPackageFragmentRoot packageFragmentRoot : packagesRoot) {
            if (packageFragmentRoot.isExternal())
                continue;
            IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(qualifiedPackage);
            if (packageFragment.exists()) {
                IType ret = TypeUtil.findType(packageFragment, typeDef);
                if (ret != null)
                    return ret;
            }
        }
    } catch (JavaModelException e) {
        WSPlugin.logException(e);
    }

    return null;
}

From source file:fede.workspace.eclipse.java.fields.IC_JavaClassForBrowser_Combo.java

License:Apache License

private void addProject(ArrayList<IPackageFragmentRoot> result, IProject p) throws JavaModelException {
    IJavaProject jp = JavaCore.create(p);
    if (jp == null) {
        return;/*from w w  w .  java2  s .  co  m*/
    }

    IPackageFragmentRoot[] roots = jp.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE || (roots[i].isArchive())) {
            result.add(roots[i]);
        }
    }

}

From source file:fede.workspace.eclipse.java.fields.JavaElementTreeController.java

License:Apache License

/**
 * Gets the package fragment root.// w w w .jav a  2 s .  co m
 * 
 * @return the package fragment root
 */
protected IPackageFragmentRoot[] getPackageFragmentRoot() {
    Item theCurrentItem = getItem();
    IJavaProject jp;
    try {
        jp = JavaProjectManager.getJavaProject(theCurrentItem);

    } catch (CoreException e) {
        WSPlugin.getDefault()
                .log(new Status(IStatus.ERROR, WSPlugin.PLUGIN_ID, 0,
                        MessageFormat.format("Cannot find the java projet or fragment root from the item {0}",
                                theCurrentItem.getName()),
                        null));
        return null;
    }
    // String fragmentone = (String) fd.get("package.fragmentroot-one");
    // if (fragmentone != null) {
    // IPackageFragmentRoot fr = jp.findPackageFragmentRoot()
    // }
    try {
        IPackageFragmentRoot[] ret = jp.getPackageFragmentRoots();
        ArrayList<IPackageFragmentRoot> retSelected = new ArrayList<IPackageFragmentRoot>();
        for (IPackageFragmentRoot pfr : ret) {
            if (selectFragmentRoot(pfr)) {
                retSelected.add(pfr);
            }
        }
        return retSelected.toArray(new IPackageFragmentRoot[retSelected.size()]);

    } catch (CoreException e) {
        WSPlugin.getDefault()
                .log(new Status(IStatus.ERROR, WSPlugin.PLUGIN_ID, 0,
                        MessageFormat.format("Cannot find the java projet or fragment root from the item {0}",
                                theCurrentItem.getName()),
                        null));

    }
    return null;
}

From source file:fede.workspace.eclipse.java.fields.PackageListController.java

License:Apache License

/**
 * Gets the package fragment root./*w  ww.  j  av a2s. c om*/
 * 
 * @return the package fragment root
 */
protected IPackageFragmentRoot[] getPackageFragmentRoot() {
    Item theCurrentItem = getItem();

    ContentItem cm = theCurrentItem.getContentItem();
    IJavaProject jp;
    try {
        jp = JavaProjectManager.getJavaProject(theCurrentItem);

    } catch (CoreException e) {
        WSJavaPlugin.getDefault()
                .log(new Status(IStatus.ERROR, WSPlugin.PLUGIN_ID, 0,
                        MessageFormat.format("Cannot find the java projet or fragment root from the item {0}",
                                theCurrentItem.getName()),
                        null));
        return null;
    }
    if (cm instanceof IJavaItemManager) {
        IJavaElement[] je = ((IJavaItemManager) cm).getJavaElement(jp);
        if (je != null) {
            HashSet<IPackageFragmentRoot> ret = new HashSet<IPackageFragmentRoot>();
            for (int i = 0; i < je.length; i++) {
                if (je[i] instanceof IPackageFragmentRoot) {
                    ret.add((IPackageFragmentRoot) je[i]);
                } else if (je[i] instanceof IJavaProject) {
                    try {
                        ret.addAll(Arrays.asList(((IJavaProject) je[i]).getPackageFragmentRoots()));
                    } catch (JavaModelException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return ret.toArray(new IPackageFragmentRoot[ret.size()]);
        }
    }

    // String fragmentone = (String) fd.get("package.fragmentroot-one");
    // if (fragmentone != null) {
    // IPackageFragmentRoot fr = jp.findPackageFragmentRoot()
    // }
    try {
        IPackageFragmentRoot[] ret = jp.getPackageFragmentRoots();
        ArrayList<IPackageFragmentRoot> retSelected = new ArrayList<IPackageFragmentRoot>();
        for (IPackageFragmentRoot pfr : ret) {
            if (selectFragmentRoot(pfr)) {
                retSelected.add(pfr);
            }
        }
        return retSelected.toArray(new IPackageFragmentRoot[retSelected.size()]);

    } catch (CoreException e) {
        WSJavaPlugin.getDefault()
                .log(new Status(IStatus.ERROR, WSPlugin.PLUGIN_ID, 0,
                        MessageFormat.format("Cannot find the java projet or fragment root from the item {0}",
                                theCurrentItem.getName()),
                        null));

    }
    return null;
}

From source file:fede.workspace.eclipse.java.fields.StringToPackageValueController.java

License:Apache License

/**
 * Abstract to visual value.//from  w w w.j  av a 2s  .  c  o  m
 * 
 * @param value
 *            the value
 * 
 * @return the object
 */
public Object abstractToVisualValue(Object value) {
    List<String> packagesString = (List<String>) value;

    Item theCurrentItem = getItem();
    IJavaProject jp;
    try {
        jp = JavaProjectManager.getJavaProject(theCurrentItem);
    } catch (CoreException e) {
        IStatus status = new Status(IStatus.ERROR, WSJavaPlugin.PLUGIN_ID, 0,
                MessageFormat.format("Cannot find the java projet from the item {0}", theCurrentItem.getName()),
                null);
        WSJavaPlugin.getDefault().log(status);
        return new ArrayList<IPackageFragment>();
    }
    if (jp == null) {
        return new ArrayList<IPackageFragment>();
    }
    IPackageFragmentRoot[] rootPackages;
    try {
        rootPackages = jp.getPackageFragmentRoots();
    } catch (JavaModelException e) {
        WSJavaPlugin.getDefault().log(new Status(IStatus.ERROR, WSPlugin.PLUGIN_ID, 0, MessageFormat.format(
                "Cannot find the package fragment root from the item {0}", theCurrentItem.getName()), null));
        return new ArrayList<IPackageFragment>();
    }
    if (rootPackages == null || rootPackages.length == 0) {
        return new ArrayList<IPackageFragment>();
    }
    if (packagesString == null) {
        return new ArrayList<IPackageFragment>();
    }

    IPackageFragmentRoot packageSrc = null;
    for (IPackageFragmentRoot fr : rootPackages) {
        try {
            if (fr.getKind() == IPackageFragmentRoot.K_SOURCE) {
                packageSrc = fr;
                break;
            }
        } catch (JavaModelException e) {
            WSJavaPlugin.getDefault()
                    .log(new Status(IStatus.ERROR, WSPlugin.PLUGIN_ID, 0,
                            MessageFormat.format(
                                    "Cannot find the type of the package fragment root {1} from the item {0}",
                                    theCurrentItem.getId(), fr.getElementName()),
                            null));
        }
    }
    List<IPackageFragment> ret = new ArrayList<IPackageFragment>();
    for (String pString : packagesString) {
        IPackageFragment findPackage = null;
        for (IPackageFragmentRoot fr : rootPackages) {
            findPackage = fr.getPackageFragment(pString);
            if (findPackage.exists()) {
                break;
            }
        }
        if (packageSrc != null && (findPackage == null || !findPackage.exists())) {
            findPackage = packageSrc.getPackageFragment(pString);
        }
        if (findPackage != null) {
            ret.add(findPackage);
        }
    }
    return ret;
}

From source file:hydrograph.ui.expression.editor.sourceviewer.SourceViewer.java

License:Apache License

public SourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
        boolean showAnnotationsOverview, int styles, IAnnotationAccess annotationAccess,
        ISharedTextColors sharedColors, IDocument document) {
    super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, SWT.BOLD);
    int id = currentId++;
    filename = VIEWER_CLASS_NAME + id++ + ".java";
    this.sharedColors = sharedColors;
    this.annotationAccess = annotationAccess;
    this.fOverviewRuler = overviewRuler;
    oldAnnotations = new HashMap<ProjectionAnnotation, Position>();

    IJavaProject javaProject = JavaCore.create(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject());
    try {/*from w  w  w .j  a  v a  2s.  c  om*/
        IPackageFragmentRoot[] ipackageFragmentRootList = javaProject.getPackageFragmentRoots();
        IPackageFragmentRoot ipackageFragmentRoot = null;
        for (IPackageFragmentRoot tempIpackageFragmentRoot : ipackageFragmentRootList) {
            if (tempIpackageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE
                    && StringUtils.equals(PathConstant.TEMP_BUILD_PATH_SETTINGS_FOLDER,
                            tempIpackageFragmentRoot.getPath().removeFirstSegments(1).toString())) {
                ipackageFragmentRoot = tempIpackageFragmentRoot;
                break;
            }
        }

        IPackageFragment compilationUnitPackage = ipackageFragmentRoot
                .createPackageFragment(HYDROGRAPH_COMPILATIONUNIT_PACKAGE, true, new NullProgressMonitor());
        compilatioUnit = compilationUnitPackage.createCompilationUnit(filename, document.get(), true,
                new NullProgressMonitor());
    } catch (Exception exception) {
        LOGGER.warn("Exception occurred while initializing source viewer", exception);
    } finally {
        if (javaProject != null) {
            try {
                javaProject.close();
            } catch (JavaModelException javaModelException) {
                LOGGER.warn("Exception occurred while closing java-project", javaModelException);
            }
        }
    }
    initializeViewer(document);
    updateContents();
}

From source file:hydrograph.ui.validators.utils.ValidatorUtility.java

License:Apache License

/**
 * This method checks if java file is present under source folder or not.
 * @param filePath java file path. /*from   ww  w .ja  v a 2s.c o  m*/
 * @return true if file is present otherwise false.
 */
public boolean isClassFilePresentOnBuildPath(String filePath) {
    if (filePath.contains(".")) {
        String packageName = filePath.substring(0, filePath.lastIndexOf('.'));
        String JavaFileName = filePath.substring(filePath.lastIndexOf('.') + 1);

        IJavaProject javaProject = null;

        ISelectionService selectionService = Workbench.getInstance().getActiveWorkbenchWindow()
                .getSelectionService();
        ISelection selection = selectionService.getSelection();

        if (selection instanceof IStructuredSelection) {
            Object element = ((IStructuredSelection) selection).getFirstElement();
            if (element instanceof IResource) {
                IProject project = ((IResource) element).getProject();
                javaProject = JavaCore.create(project);
            } else {
                javaProject = createJavaProjectThroughActiveEditor();
            }
        } else if (selection instanceof TextSelection) {
            javaProject = createJavaProjectThroughActiveEditor();
        }

        IPackageFragmentRoot[] ipackageFragmentRootList = null;
        try {
            ipackageFragmentRootList = javaProject.getPackageFragmentRoots();
        } catch (JavaModelException e) {
            logger.error("Unable to get jars which are on build path of project ", e);
        }
        for (IPackageFragmentRoot tempIpackageFragmentRoot : ipackageFragmentRootList) {
            if (!tempIpackageFragmentRoot.getElementName().contains("-sources")) {
                IPackageFragment packageFragment = tempIpackageFragmentRoot.getPackageFragment(packageName);
                if (!packageFragment.exists())
                    continue;
                else {
                    if (packageFragment.getCompilationUnit(JavaFileName + ".java").exists()
                            || packageFragment.getClassFile(JavaFileName + ".class").exists())
                        return true;
                }
            }
        }
    }
    return false;
}

From source file:icy.icy4eclipse.core.Icy4EclipsePlugin.java

License:Open Source License

private void startIcyInternal(boolean debug, boolean bypassJarclassloader) throws CoreException {
    logInfo("Starting Icy - (debug = " + debug + ") (disableJCL = " + bypassJarclassloader + ")");

    // Check parameters
    try {//w w w  . ja v a2 s. co  m
        checkIcyConfiguration();
    } catch (Icy4EclipseException e) {
        logException(e);
        return;
    }

    String hd = getIcyHomeDir();
    File pluginsDirectory = new File(hd, ICY_PLUGINS_DIR);
    List<IcyProject> icyProjects = computeOpenIcyProjectsList();
    List<String> classpath = new ArrayList<String>();

    // Add Icy jars to system class loader if needed
    if (loadIcyJar()) {
        for (String s : ICY_JARS) {
            classpath.add(hd + File.separator + s);
        }
    }

    if (bypassJarclassloader) {
        // Add Eclipse Icy projects to system class loader
        for (IcyProject p : icyProjects) {
            IJavaProject project = p.getJavaProject();
            for (String s : JavaRuntime.computeDefaultRuntimeClassPath(project)) {
                classpath.add(s);
            }
        }

        // Add plugins jars to system class loader
        IPreferenceStore pref = getPreferenceStore();
        String bypassJars = pref.getString(ICY4ECLIPSE_PREF_BYPASS_JARS_KEY);
        List<Pattern> bypassRegexp = null;
        if (bypassJars != null) {
            bypassJars = bypassJars.trim();
            if (bypassJars.length() > 0) {
                String[] bypass = bypassJars.split(":");
                bypassRegexp = new ArrayList<Pattern>();
                for (String r : bypass) {
                    bypassRegexp.add(Pattern.compile("^(.*)" + r + "$", Pattern.CASE_INSENSITIVE));
                }
            }
        }

        if (pluginsDirectory.exists()) {
            List<File> jars = getAllJarFiles(pluginsDirectory);
            for (File f : jars) {
                boolean add = true;
                String path = f.getAbsolutePath();
                if (bypassRegexp != null) {
                    for (Pattern p : bypassRegexp) {
                        Matcher m = p.matcher(path);
                        if (m.matches()) {
                            logInfo(" - bypassing jar : " + p.pattern() + " -> " + path);
                            add = false;
                            break;
                        }
                    }
                }

                if (add) {
                    classpath.add(path);
                }
            }
        }
    }

    // Other launch arguments
    StringBuffer programArguments = new StringBuffer();
    for (String arg : ICY_PRG_ARGS) {
        programArguments.append(" " + arg);
    }
    if (bypassJarclassloader) {
        programArguments.append(" " + ICY_BYPASS_JARCLASSLOADER_ARG);
    }

    StringBuffer jvmArguments = new StringBuffer();
    for (String arg : ICY_VM_MANDATORY_ARGS) {
        jvmArguments.append(" " + arg);
    }
    jvmArguments.append(" -Xmx" + getIcyMemory() + "m");
    jvmArguments.append(" " + getOtherJVMArgs());

    // Launching the JVM
    ILaunchConfigurationType launchType = DebugPlugin.getDefault().getLaunchManager()
            .getLaunchConfigurationType("org.eclipse.jdt.launching.localJavaApplication");
    ILaunchConfigurationWorkingCopy config = launchType.newInstance(null, ICY4ECLIPSE_LABEL);
    config.setAttribute(IDebugUIConstants.ATTR_PRIVATE, false);
    config.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID,
            "org.eclipse.jdt.launching.sourceLocator.JavaSourceLookupDirector");

    if (bypassJarclassloader) {
        ISourceLookupDirector sourceLocator = new JavaSourceLookupDirector();
        ISourcePathComputer computer = DebugPlugin.getDefault().getLaunchManager()
                .getSourcePathComputer("org.eclipse.jdt.launching.sourceLookup.javaSourcePathComputer");
        sourceLocator.setSourcePathComputer(computer);

        ArrayList<ISourceContainer> sourceContainers = new ArrayList<ISourceContainer>();

        if (!icyProjects.isEmpty()) {
            for (IcyProject ip : icyProjects) {
                IJavaProject project = ip.getJavaProject();
                sourceContainers.add(new JavaProjectSourceContainer(project));
            }

            Set<IPath> external = new HashSet<IPath>();

            for (IcyProject ip : icyProjects) {
                IJavaProject project = ip.getJavaProject();

                IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
                for (int ri = 0; ri < roots.length; ri++) {
                    IPackageFragmentRoot root = roots[ri];
                    if (root.isExternal()) {
                        IPath location = root.getPath();
                        if (external.contains(location)) {
                            continue;
                        }
                        external.add(location);
                    }
                    sourceContainers.add(new PackageFragmentRootSourceContainer(root));
                }
            }
        }

        sourceContainers.add(new DefaultSourceContainer());

        sourceLocator.setSourceContainers(
                (ISourceContainer[]) sourceContainers.toArray(new ISourceContainer[sourceContainers.size()]));
        sourceLocator.initializeParticipants();
        config.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_MEMENTO, sourceLocator.getMemento());
    }

    ArrayList<String> classpathMementos = new ArrayList<String>();
    for (String s : classpath) {
        IRuntimeClasspathEntry cpEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(new Path(s));
        cpEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
        classpathMementos.add(cpEntry.getMemento());
    }

    IPath path = new Path(JavaRuntime.JRE_CONTAINER);
    try {
        IClasspathEntry cpEntry = JavaCore.newContainerEntry(path);
        IRuntimeClasspathEntry rcpEntry = JavaRuntime.newRuntimeContainerClasspathEntry(cpEntry.getPath(),
                IRuntimeClasspathEntry.STANDARD_CLASSES);
        classpathMementos.add(rcpEntry.getMemento());
    } catch (CoreException ex) {
        logException(ex);
    }

    config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
    config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpathMementos);
    config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, programArguments.toString());
    config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, jvmArguments.toString());
    config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, getIcyMainClass());
    config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, getIcyHomeDir());

    logInfo(" - home dir   : " + getIcyHomeDir());
    logInfo(" - main class : " + getIcyMainClass());
    logInfo(" - prog args  : " + programArguments);
    logInfo(" - jvm args   : " + jvmArguments);
    logInfo(" - classpath  : " + classpath);

    config.launch(debug ? ILaunchManager.DEBUG_MODE : ILaunchManager.RUN_MODE, null);

}

From source file:in.cypal.studio.gwt.core.common.Util.java

License:Apache License

public static List findModules(IJavaProject javaProject) throws CoreException {

    List moduleFiles = new ArrayList();

    for (int i = 0; i < javaProject.getPackageFragmentRoots().length; i++) {

        IPackageFragmentRoot aRoot = javaProject.getPackageFragmentRoots()[i];
        // check only in source folders. Skip others
        if (aRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
            continue;
        }//from  w w w.  j  av  a2s.c o m

        for (int j = 0; j < aRoot.getChildren().length; j++) {
            IJavaElement aPackage = aRoot.getChildren()[j];
            // look only for packages. Skip others
            if (!(aPackage instanceof IPackageFragment)) {
                continue;
            }
            Object[] nonJavaResources = ((IPackageFragment) aPackage).getNonJavaResources();
            for (int k = 0; k < nonJavaResources.length; k++) {

                Object aResource = nonJavaResources[k];
                // look only files. Skip others
                if (!(aResource instanceof IFile)) {
                    continue;
                }

                IFile aFile = (IFile) aResource;
                if (aFile.getName().endsWith(Constants.GWT_XML_EXT)) {
                    moduleFiles.add(aFile);
                }
            }
        }
    }
    return moduleFiles;
}

From source file:in.cypal.studio.gwt.core.common.Util.java

License:Apache License

public static List findRemoteServices(IJavaProject javaProject) throws CoreException {

    List remoteServiceFiles = new ArrayList();

    IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < packageFragmentRoots.length; i++) {
        IPackageFragmentRoot aRoot = packageFragmentRoots[i];
        // check only in source folders. Skip others
        if (aRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
            continue;
        }//  www.  j a v  a  2  s. co m

        IJavaElement[] children = aRoot.getChildren();
        for (int j = 0; j < children.length; j++) {

            IJavaElement aPackage = children[j];
            // look only for packages. Skip others
            if (!(aPackage instanceof IPackageFragment)) {
                continue;
            }

            ICompilationUnit[] compilationUnits = ((IPackageFragment) aPackage).getCompilationUnits();
            for (int k = 0; k < compilationUnits.length; k++) {

                ICompilationUnit cu = compilationUnits[k];

                IResource resource = cu.getCorrespondingResource();
                if (aPackage.getResource().getName().equals(Constants.CLIENT_PACKAGE)
                        && resource instanceof IFile && resource.getName().endsWith(".java")) {//$NON-NLS-1$
                    // java file. Check whether its a remote service ...

                    // for every type declared in the java file
                    IType[] types = cu.getTypes();
                    for (int l = 0; l < types.length; l++) {
                        IType someType = types[l];
                        // for every interface implemented by that type

                        String[] superInterfaceNames = someType.getSuperInterfaceNames();
                        for (int m = 0; m < superInterfaceNames.length; m++) {
                            String aSuperInterface = superInterfaceNames[m];
                            if (aSuperInterface.equals(Constants.REMOTE_SERVICE_CLASS)) {
                                remoteServiceFiles.add(resource);
                            }
                        }
                    }
                }
            }
        }
    }
    return remoteServiceFiles;
}