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

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

Introduction

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

Prototype

IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException;

Source Link

Document

Returns all of the existing package fragment roots that exist on the classpath, in the order they are defined by the classpath.

Usage

From source file:org.eclipse.ajdt.internal.launching.LTWUtils.java

License:Open Source License

/**
 * Generate one aop-ajc.xml file for each source directory in the given project.
 * The aop-ajc.xml files will list all concrete aspects included in the active
 * build configuration./* w  ww  .j a v a  2  s. c  o m*/
 * @param project
 */
public static void generateLTWConfigFile(IJavaProject project) {
    try {
        // Get all the source folders in the project
        IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++) {
            IPackageFragmentRoot root = roots[i];
            if (!(root instanceof JarPackageFragmentRoot) && root.getJavaProject().equals(project)) {
                List aspects = getAspects(root);
                String path;
                if (root.getElementName().trim().equals("")) { //$NON-NLS-1$
                    path = AOP_XML_LOCATION;
                } else {
                    path = root.getElementName().trim().concat("/").concat(AOP_XML_LOCATION); //$NON-NLS-1$
                }
                IFile ltwConfigFile = (IFile) project.getProject().findMember(path);

                // If the source folder does not already contain an aop-ajc.xml file:
                if (ltwConfigFile == null) {
                    if (aspects.size() != 0) { // If there are aspects in the list

                        // Create the META-INF folder and the aop-ajc.xml file
                        IFolder metainf = (IFolder) ((Workspace) ResourcesPlugin.getWorkspace()).newResource(
                                project.getPath().append("/" + root.getElementName() + "/META-INF"), //$NON-NLS-1$ //$NON-NLS-2$
                                IResource.FOLDER);
                        IFile aopFile = (IFile) ((Workspace) ResourcesPlugin.getWorkspace())
                                .newResource(project.getPath().append(path), IResource.FILE);
                        if (metainf == null || !metainf.exists()) {
                            metainf.create(true, true, null);
                        }
                        aopFile.create(new ByteArrayInputStream(new byte[0]), true, null);
                        project.getProject().refreshLocal(4, null);

                        // Add the xml content to the aop-ajc.xml file
                        addAspectsToLTWConfigFile(false, aspects, aopFile);
                        copyToOutputFolder(aopFile, project, root.getRawClasspathEntry());
                    }

                    // Otherwise update the existing file   
                } else {
                    addAspectsToLTWConfigFile(true, aspects, ltwConfigFile);
                    copyToOutputFolder(ltwConfigFile, project, root.getRawClasspathEntry());
                }
            }
        }
    } catch (Exception e) {
    }

}

From source file:org.eclipse.ajdt.ui.tests.launching.LTWUtilsTest.java

License:Open Source License

public void testGetAspects() throws Exception {
    IProject project = createPredefinedProject("Tracing Example"); //$NON-NLS-1$
    waitForJobsToComplete();/*from w ww  . j av a2  s . c o  m*/
    IFile propertiesFile = project.getFile("tracelib.ajproperties"); //$NON-NLS-1$
    assertNotNull(propertiesFile);
    assertTrue(propertiesFile.exists());
    BuildConfigurationUtils.applyBuildConfiguration(propertiesFile);
    waitForJobsToComplete();
    IJavaProject jp = JavaCore.create(project);
    IPackageFragmentRoot[] roots = jp.getAllPackageFragmentRoots();
    List srcRoots = new ArrayList();
    for (int i = 0; i < roots.length; i++) {
        IPackageFragmentRoot root = roots[i];
        if (!(root instanceof JarPackageFragmentRoot)) {
            srcRoots.add(root);
        }
    }
    assertEquals("There should be one src directory", 1, srcRoots.size()); //$NON-NLS-1$
    List aspects = LTWUtils.getAspects((IPackageFragmentRoot) srcRoots.get(0));
    assertEquals("There should be two aspects", 2, aspects.size()); //$NON-NLS-1$
    String aspectOne = ((AspectElement) aspects.get(0)).getElementName();
    String aspectTwo = ((AspectElement) aspects.get(1)).getElementName();
    boolean foundOne = false;
    boolean foundTwo = false;
    if (aspectOne.equals("TraceMyClasses") || aspectTwo.equals("TraceMyClasses")) {
        foundOne = true;
    }
    if (aspectOne.equals("AbstractTrace") || aspectTwo.equals("AbstractTrace")) {
        foundTwo = true;
    }
    if (!foundOne) {
        fail("Expected to find TraceMyClasses:" + aspectOne + "," + aspectTwo);
    }
    if (!foundTwo) {
        fail("Expected to find AbstractTrace:" + aspectOne + "," + aspectTwo);
    }
}

From source file:org.eclipse.ajdt.ui.tests.launching.LTWUtilsTest2.java

License:Open Source License

public void testGetAspects() throws Exception {
    IProject project = createPredefinedProject("Tracing Example2"); //$NON-NLS-1$
    waitForJobsToComplete();//from   w w  w . j  a v a2  s .c o  m
    IFile propertiesFile = project.getFile("tracelib.ajproperties"); //$NON-NLS-1$
    assertNotNull(propertiesFile);
    assertTrue(propertiesFile.exists());
    BuildConfigurationUtils.applyBuildConfiguration(propertiesFile);
    waitForJobsToComplete();
    IJavaProject jp = JavaCore.create(project);
    IPackageFragmentRoot[] roots = jp.getAllPackageFragmentRoots();
    List srcRoots = new ArrayList();
    for (int i = 0; i < roots.length; i++) {
        IPackageFragmentRoot root = roots[i];
        if (!(root instanceof JarPackageFragmentRoot)) {
            srcRoots.add(root);
        }
    }
    assertEquals("There should be one src directory", 1, srcRoots.size()); //$NON-NLS-1$
    List aspects = LTWUtils.getAspects((IPackageFragmentRoot) srcRoots.get(0));
    assertEquals("There should be two aspects", 2, aspects.size()); //$NON-NLS-1$
    String aspectOne = ((AspectElement) aspects.get(0)).getElementName();
    String aspectTwo = ((AspectElement) aspects.get(1)).getElementName();
    boolean foundOne = false;
    boolean foundTwo = false;
    if (aspectOne.equals("TraceMyClasses") || aspectTwo.equals("TraceMyClasses")) {
        foundOne = true;
    }
    if (aspectOne.equals("AbstractTrace") || aspectTwo.equals("AbstractTrace")) {
        foundTwo = true;
    }
    if (!foundOne) {
        fail("Expected to find TraceMyClasses:" + aspectOne + "," + aspectTwo);
    }
    if (!foundTwo) {
        fail("Expected to find AbstractTrace:" + aspectOne + "," + aspectTwo);
    }

}

From source file:org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundle.java

License:Open Source License

protected void runAction() {
    // First see if this is a "new wizard".
    IWizardDescriptor descriptor = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard(newBunldeWizard);
    // If not check if it is an "import wizard".
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(newBunldeWizard);
    }//from w  ww  . ja v a 2  s  .  c o  m
    // Or maybe an export wizard
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getExportWizardRegistry().findWizard(newBunldeWizard);
    }
    try {
        // Then if we have a wizard, open it.
        if (descriptor != null) {
            IWizard wizard = descriptor.createWizard();
            if (!(wizard instanceof IResourceBundleWizard)) {
                return;
            }

            IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
            String[] keySilbings = key.split("\\.");
            String rbName = keySilbings[keySilbings.length - 1];
            String packageName = "";

            rbw.setBundleId(rbName);

            // Set the default path according to the specified package name
            String pathName = "";
            if (keySilbings.length > 1) {
                try {
                    IJavaProject jp = JavaCore.create(resource.getProject());
                    packageName = key.substring(0, key.lastIndexOf("."));

                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        IPackageFragment pf = fr.getPackageFragment(packageName);
                        if (pf.exists()) {
                            pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                } catch (Exception e) {
                    pathName = "";
                }
            }

            try {
                IJavaProject jp = JavaCore.create(resource.getProject());
                if (pathName.trim().equals("")) {
                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        if (!fr.isReadOnly()) {
                            pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                pathName = "";
            }

            rbw.setDefaultPath(pathName);

            WizardDialog wd = new WizardDialog(Display.getDefault().getActiveShell(), wizard);
            wd.setTitle(wizard.getWindowTitle());
            if (wd.open() == WizardDialog.OK) {
                try {
                    resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, I18nBuilder.BUILDER_ID,
                            null, null);
                } catch (CoreException e) {
                    Logger.logError(e);
                }

                ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
                IPath path = resource.getRawLocation();
                try {
                    bufferManager.connect(path, null);
                    ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
                    IDocument document = textFileBuffer.getDocument();

                    if (document.get().charAt(start - 1) == '"' && document.get().charAt(start) != '"') {
                        start--;
                        end++;
                    }
                    if (document.get().charAt(end + 1) == '"' && document.get().charAt(end) != '"') {
                        end++;
                    }

                    document.replace(start, end - start,
                            "\"" + (packageName.equals("") ? "" : packageName + ".") + rbName + "\"");

                    textFileBuffer.commit(null, false);
                } catch (Exception e) {
                    Logger.logError(e);
                } finally {
                    try {
                        bufferManager.disconnect(path, null);
                    } catch (CoreException e) {
                        Logger.logError(e);
                    }
                }
            }
        }
    } catch (CoreException e) {
        Logger.logError(e);
    }
}

From source file:org.eclipse.babel.tapiji.tools.java.ui.autocompletion.CreateResourceBundleProposal.java

License:Open Source License

@SuppressWarnings("deprecation")
protected void runAction() {
    // First see if this is a "new wizard".
    IWizardDescriptor descriptor = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard(newBunldeWizard);
    // If not check if it is an "import wizard".
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(newBunldeWizard);
    }/*from ww  w.  ja v a  2  s .  c o  m*/
    // Or maybe an export wizard
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getExportWizardRegistry().findWizard(newBunldeWizard);
    }
    try {
        // Then if we have a wizard, open it.
        if (descriptor != null) {
            IWizard wizard = descriptor.createWizard();

            if (!(wizard instanceof IResourceBundleWizard)) {
                return;
            }

            IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
            String[] keySilbings = key.split("\\.");
            String rbName = keySilbings[keySilbings.length - 1];
            String packageName = "";

            rbw.setBundleId(rbName);

            // Set the default path according to the specified package name
            String pathName = "";
            if (keySilbings.length > 1) {
                try {
                    IJavaProject jp = JavaCore.create(resource.getProject());
                    packageName = key.substring(0, key.lastIndexOf("."));

                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        IPackageFragment pf = fr.getPackageFragment(packageName);
                        if (pf.exists()) {
                            pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                } catch (Exception e) {
                    pathName = "";
                }
            }

            try {
                IJavaProject jp = JavaCore.create(resource.getProject());
                if (pathName.trim().equals("")) {
                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        if (!fr.isReadOnly()) {
                            pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                pathName = "";
            }

            rbw.setDefaultPath(pathName);

            WizardDialog wd = new WizardDialog(Display.getDefault().getActiveShell(), wizard);

            wd.setTitle(wizard.getWindowTitle());
            if (wd.open() == WizardDialog.OK) {
                try {
                    resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, I18nBuilder.BUILDER_ID,
                            null, null);
                } catch (CoreException e) {
                    Logger.logError(e);
                }

                ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
                IPath path = resource.getRawLocation();
                try {
                    bufferManager.connect(path, LocationKind.NORMALIZE, null);
                    ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path,
                            LocationKind.NORMALIZE);
                    IDocument document = textFileBuffer.getDocument();

                    if (document.get().charAt(start - 1) == '"' && document.get().charAt(start) != '"') {
                        start--;
                        end++;
                    }
                    if (document.get().charAt(end + 1) == '"' && document.get().charAt(end) != '"') {
                        end++;
                    }

                    document.replace(start, end - start,
                            "\"" + (packageName.equals("") ? "" : packageName + ".") + rbName + "\"");

                    textFileBuffer.commit(null, false);
                } catch (Exception e) {
                } finally {
                    try {
                        bufferManager.disconnect(path, null);
                    } catch (CoreException e) {
                    }
                }
            }
        }
    } catch (CoreException e) {
    }
}

From source file:org.eclipse.che.jdt.internal.core.JavaModelManager.java

License:Open Source License

private Map secondaryTypesSearching(IJavaProject project, boolean waitForIndexes, IProgressMonitor monitor,
        final PerProjectInfo projectInfo) throws JavaModelException {
    if (VERBOSE || BasicSearchEngine.VERBOSE) {
        StringBuffer buffer = new StringBuffer("JavaModelManager.secondaryTypesSearch("); //$NON-NLS-1$
        buffer.append(project.getElementName());
        buffer.append(',');
        buffer.append(waitForIndexes);//  w w  w  . j a va 2 s  . co  m
        buffer.append(')');
        Util.verbose(buffer.toString());
    }

    final Hashtable secondaryTypes = new Hashtable(3);
    IRestrictedAccessTypeRequestor nameRequestor = new IRestrictedAccessTypeRequestor() {
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path, AccessRestriction access) {
            String key = packageName == null ? "" : new String(packageName); //$NON-NLS-1$
            HashMap types = (HashMap) secondaryTypes.get(key);
            if (types == null)
                types = new HashMap(3);
            types.put(new String(simpleTypeName), path);
            secondaryTypes.put(key, types);
        }
    };

    // Build scope using prereq projects but only source folders
    IPackageFragmentRoot[] allRoots = project.getAllPackageFragmentRoots();
    int length = allRoots.length, size = 0;
    IPackageFragmentRoot[] allSourceFolders = new IPackageFragmentRoot[length];
    for (int i = 0; i < length; i++) {
        if (allRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
            allSourceFolders[size++] = allRoots[i];
        }
    }
    if (size < length) {
        System.arraycopy(allSourceFolders, 0, allSourceFolders = new IPackageFragmentRoot[size], 0, size);
    }

    // Search all secondary types on scope
    new BasicSearchEngine(indexManager, (JavaProject) project).searchAllSecondaryTypeNames(allSourceFolders,
            nameRequestor, waitForIndexes, monitor);

    // Build types from paths
    Iterator packages = secondaryTypes.values().iterator();
    while (packages.hasNext()) {
        HashMap types = (HashMap) packages.next();
        HashMap tempTypes = new HashMap(types.size());
        Iterator names = types.entrySet().iterator();
        while (names.hasNext()) {
            Map.Entry entry = (Map.Entry) names.next();
            String typeName = (String) entry.getKey();
            String path = (String) entry.getValue();
            names.remove();
            if (Util.isJavaLikeFileName(path)) {
                File file = new File(path);// ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
                ICompilationUnit unit = JavaModelManager.createCompilationUnitFrom(file, null);
                IType type = unit.getType(typeName);
                tempTypes.put(typeName, type);
            }
        }
        types.putAll(tempTypes);
    }

    // Store result in per project info cache if still null or there's still an indexing cache (may have been set by another thread...)
    if (projectInfo.secondaryTypes == null || projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES) != null) {
        projectInfo.secondaryTypes = secondaryTypes;
        if (VERBOSE || BasicSearchEngine.VERBOSE) {
            System.out.print(Thread.currentThread() + "   -> secondary paths stored in cache: "); //$NON-NLS-1$
            System.out.println();
            Iterator entries = secondaryTypes.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                String qualifiedName = (String) entry.getKey();
                Util.verbose("      - " + qualifiedName + '-' + entry.getValue()); //$NON-NLS-1$
            }
        }
    }
    return projectInfo.secondaryTypes;
}

From source file:org.eclipse.che.plugin.java.server.JavaNavigation.java

License:Open Source License

public List<Jar> getProjectDependecyJars(IJavaProject project) throws JavaModelException {
    List<Jar> jars = new ArrayList<>();
    for (IPackageFragmentRoot fragmentRoot : project.getAllPackageFragmentRoots()) {
        if (fragmentRoot instanceof JarPackageFragmentRoot) {
            Jar jar = DtoFactory.getInstance().createDto(Jar.class);
            jar.setId(fragmentRoot.hashCode());
            jar.setName(fragmentRoot.getElementName());
            jars.add(jar);/*  w  w  w  . j a  va 2 s.c  o m*/
        }
    }

    return jars;
}

From source file:org.eclipse.che.plugin.java.server.JavaNavigation.java

License:Open Source License

private IPackageFragmentRoot getPackageFragmentRoot(IJavaProject project, int hash) throws JavaModelException {
    IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
    IPackageFragmentRoot packageFragmentRoot = null;
    for (IPackageFragmentRoot root : roots) {
        if (root.hashCode() == hash) {
            packageFragmentRoot = root;//w w w .  ja  v  a2  s  .co m
            break;
        }
    }
    return packageFragmentRoot;
}

From source file:org.eclipse.e4.xwt.tools.ui.designer.dialogs.AccessorConfigurationDialog.java

License:Open Source License

/**
 * While user change the sourceFolderText or propertyFolderText's nameMap,refresh the root.
 * /*from   w w w . jav a  2 s  .  c o m*/
 * @param path
 */
private void setNewRoot(String path, boolean isClass) {
    int start = path.indexOf("/");
    IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(path));
    if (path.length() == 0 || container == null
            || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
        setRootNull(isClass);
    } else if ((path.indexOf("/", path.indexOf("/", start + 1) + 1) != -1) || (path.indexOf("\\") != -1)) {
        setRootNull(isClass);
    } else {
        try {
            final IFile file = ExternalizeStringsCommon.getIFile(path, "");
            IJavaProject javaProject = JavaCore.create(file.getProject());
            IPackageFragmentRoot fragmentRoot[] = javaProject.getAllPackageFragmentRoots();
            for (int i = 0; i < fragmentRoot.length; i++) {
                if (fragmentRoot[i].getResource() != null) {
                    if (isClass) {
                        classRoot = fragmentRoot[i];
                    } else {
                        propertyRoot = fragmentRoot[i];
                    }
                    break;
                }
            }

        } catch (CoreException e) {
            LoggerManager.log(e);
        }
    }
}

From source file:org.eclipse.e4.xwt.tools.ui.designer.loader.XWTVisualLoader.java

License:Open Source License

public synchronized Control loadWithOptions(URL url, Map<String, Object> options) throws Exception {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    String fileStr = url.getFile();
    if (fileStr.indexOf(PathHelper.WHITE_SPACE_ASCII) != -1) {
        fileStr = fileStr.replace(PathHelper.WHITE_SPACE_ASCII, " ");
    }//  ww  w  .j a v a2 s  .  c o m
    IFile file = root.getFileForLocation(new Path(fileStr));
    if (file != null) {
        try {
            // the url given an binary file of project, we need find the source file of it and the load and open.
            IProject project = file.getProject();
            String fullPath = file.getFullPath().toString();
            IJavaProject javaProject = JavaCore.create(project);
            String outputPath = javaProject.getOutputLocation().toString();
            if (fullPath != null && outputPath != null && fullPath.startsWith(outputPath)) {
                String fileSourcePath = fullPath.substring(outputPath.length());
                IPackageFragmentRoot[] allPackageFragmentRoots = javaProject.getAllPackageFragmentRoots();
                for (IPackageFragmentRoot pRoot : allPackageFragmentRoots) {
                    if (pRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                        IFolder resource = (IFolder) pRoot.getResource();
                        IFile sourceFile = resource.getFile(new Path(fileSourcePath));
                        if (sourceFile != null && sourceFile.exists()) {
                            file = sourceFile;
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
    }
    if (file != null) {
        IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        IEditorPart activeEditor = activePage.getActiveEditor();
        try {
            XWTDesigner designer = (XWTDesigner) activePage.openEditor(new FileEditorInput(file),
                    XWTDesigner.EDITOR_ID, false);
            XamlDocument xamlDocument = (XamlDocument) designer.getDocumentRoot();
            XWTModelBuilder builder = null;
            if (xamlDocument == null) {
                builder = new XWTModelBuilder();
                builder.doLoad(designer, null);
                xamlDocument = builder.getDiagram();
            }
            Control control = (Control) new XWTProxy(file).load(xamlDocument.getRootElement(), options);
            if (builder != null) {
                builder.dispose();
            }
            return control;
        } finally {
            activePage.activate(activeEditor);
        }
    }
    return null;
}