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

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

Introduction

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

Prototype

IPath getPath();

Source Link

Document

Returns the path to the innermost resource enclosing this element.

Usage

From source file:org.eclipse.ajdt.core.buildpath.BuildConfigurationUtils.java

License:Open Source License

public static void applyBuildConfiguration(IFile ifile) {
    File file = ifile.getLocation().toFile();
    BufferedReader br = null;/*  ww  w . j  av a  2s  .  co m*/
    try {
        IJavaProject project = JavaCore.create(ifile.getProject());
        List classpathEntries = new ArrayList();
        IClasspathEntry[] originalEntries = project.getRawClasspath();
        for (int i = 0; i < originalEntries.length; i++) {
            IClasspathEntry entry = originalEntries[i];
            if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
                classpathEntries.add(entry);
            }
        }
        List srcFolders = new ArrayList();
        Map srcFoldersToIncludes = new HashMap();
        Map srcFoldersToExcludes = new HashMap();
        br = new BufferedReader(new FileReader(file));
        Properties properties = new Properties();
        properties.load(ifile.getContents());
        Enumeration iter = properties.keys();

        // first stage - find any source folders
        while (iter.hasMoreElements()) {
            String name = iter.nextElement().toString();
            String value = properties.get(name).toString();
            String[] values = value.split(","); //$NON-NLS-1$
            if (name.equals("src.includes")) { //$NON-NLS-1$
                for (int i = 0; i < values.length; i++) {
                    String inc = values[i];
                    if (inc.equals("/")) { //$NON-NLS-1$
                        srcFolders.add(inc);
                    } else if (inc.indexOf("/") == inc.length() - 1) { //$NON-NLS-1$
                        if (project.getProject().getFolder(inc) != null
                                && project.getProject().getFolder(inc).exists()) {
                            srcFolders.add(inc);
                        }
                    }
                }
            }
        }

        // second stage - identify include and exclude filters
        iter = properties.keys();
        if (srcFolders.isEmpty()) {
            srcFolders.add(""); //$NON-NLS-1$
        }
        while (iter.hasMoreElements()) {
            String name = iter.nextElement().toString();
            String value = properties.get(name).toString();
            String[] values = value.split(","); //$NON-NLS-1$
            if (name.equals("src.inclusionpatterns")) { //$NON-NLS-1$
                for (int i = 0; i < values.length; i++) {
                    String inc = values[i];
                    for (Iterator iterator = srcFolders.iterator(); iterator.hasNext();) {
                        String srcFolder = (String) iterator.next();
                        if (inc.startsWith(srcFolder)) {
                            List incs = (List) srcFoldersToIncludes.get(srcFolder);
                            if (incs == null) {
                                incs = new ArrayList();
                            }
                            incs.add(inc);
                            srcFoldersToIncludes.put(srcFolder, incs);
                        }
                    }
                }
            } else if (name.equals("src.excludes")) { //$NON-NLS-1$
                for (int i = 0; i < values.length; i++) {
                    String exc = values[i];
                    for (Iterator iterator = srcFolders.iterator(); iterator.hasNext();) {
                        String srcFolder = (String) iterator.next();
                        if (srcFolder.equals("/") || exc.startsWith(srcFolder)) { //$NON-NLS-1$
                            List excs = (List) srcFoldersToExcludes.get(srcFolder);
                            if (excs == null) {
                                excs = new ArrayList();
                            }
                            excs.add(exc);
                            srcFoldersToExcludes.put(srcFolder, excs);
                        }
                    }
                }
            }
        }

        // third stage - create classpath entries
        IClasspathEntry[] entries = new IClasspathEntry[srcFolders.size() + classpathEntries.size()];
        for (int i = 0; i < entries.length; i++) {
            if (srcFolders.size() > i) {
                String srcFolder = (String) srcFolders.get(i);
                IPath path = project.getPath().append(stripSlash(srcFolder));
                List exclusions = (List) srcFoldersToExcludes.get(srcFolder);
                if (exclusions == null) {
                    exclusions = Collections.EMPTY_LIST;
                }
                List inclusions = (List) srcFoldersToIncludes.get(srcFolder);
                if (inclusions == null) {
                    inclusions = Collections.EMPTY_LIST;
                }
                IPath[] exclusionPatterns = new IPath[exclusions.size()];
                for (int j = 0; j < exclusionPatterns.length; j++) {
                    String exclusionPathStr = (String) exclusions.get(j);
                    if (exclusionPathStr.startsWith(srcFolder)) {
                        exclusionPathStr = exclusionPathStr.substring(srcFolder.length());
                    }
                    IPath exclusionPath = new Path(exclusionPathStr);
                    exclusionPatterns[j] = exclusionPath;

                }
                IPath[] inclusionPatterns = new IPath[inclusions.size()];
                for (int j = 0; j < inclusionPatterns.length; j++) {
                    String inclusionPathStr = (String) inclusions.get(j);
                    if (inclusionPathStr.startsWith(srcFolder)) {
                        inclusionPathStr = inclusionPathStr.substring(srcFolder.length());
                    }
                    IPath inclusionPath = new Path(inclusionPathStr);
                    inclusionPatterns[j] = inclusionPath;

                }
                IClasspathEntry classpathEntry = JavaCore.newSourceEntry(path, exclusionPatterns);
                //new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_SOURCE, path, ClasspathEntry.INCLUDE_ALL, exclusionPatterns, null, null, null, true, ClasspathEntry.NO_ACCESS_RULES, false, ClasspathEntry.NO_EXTRA_ATTRIBUTES);
                entries[i] = classpathEntry;
            } else {
                entries[i] = (IClasspathEntry) classpathEntries.get(i - srcFolders.size());
            }
        }
        project.setRawClasspath(entries, null);
    } catch (FileNotFoundException e) {
    } catch (JavaModelException e) {
    } catch (IOException e) {
    } catch (CoreException e) {
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.eclipse.ajdt.internal.core.ClasspathModifier.java

License:Open Source License

/**
 * Find out whether one of the <code>IResource</code>'s parents
 * is excluded./*w w w .  j  ava 2 s. co  m*/
 * 
 * @param resource check the resources parents whether they are
 * excluded or not
 * @param project the Java project
 * @return <code>true</code> if there is an excluded parent, 
 * <code>false</code> otherwise
 * @throws JavaModelException
 */
public static boolean parentExcluded(IResource resource, IJavaProject project) throws JavaModelException {
    if (resource.getFullPath().equals(project.getPath()))
        return false;
    IPackageFragmentRoot root = getFragmentRoot(resource, project, null);
    if (root == null) {
        return true;
    }
    IPath path = resource.getFullPath().removeFirstSegments(root.getPath().segmentCount());
    IClasspathEntry entry = root.getRawClasspathEntry();
    if (entry == null)
        return true; // there is no build path entry, this is equal to the fact that the parent is excluded
    while (path.segmentCount() > 0) {
        if (contains(path, entry.getExclusionPatterns()))
            return true;
        path = path.removeLastSegments(1);
    }
    return false;
}

From source file:org.eclipse.ajdt.internal.core.ClasspathModifier.java

License:Open Source License

/**
 * Get the source folder of a given <code>IResource</code> element,
 * starting with the resource's parent.//from   w ww.j a  v a  2 s.  co  m
 * 
 * @param resource
 *            the resource to get the fragment root from
 * @param project
 *            the Java project
 * @param monitor
 *            progress monitor, can be <code>null</code>
 * @return resolved fragment root
 * @throws JavaModelException
 */
public static IPackageFragmentRoot getFragmentRoot(IResource resource, IJavaProject project,
        IProgressMonitor monitor) throws JavaModelException {
    IJavaElement javaElem = null;
    if (resource.getFullPath().equals(project.getPath()))
        return project.getPackageFragmentRoot(resource);
    IContainer container = resource.getParent();
    do {
        if (container instanceof IFolder)
            javaElem = JavaCore.create((IFolder) container);
        if (container.getFullPath().equals(project.getPath())) {
            javaElem = project;
            break;
        }
        container = container.getParent();
        if (container == null)
            return null;
    } while (javaElem == null || !(javaElem instanceof IPackageFragmentRoot));
    if (javaElem instanceof IJavaProject)
        javaElem = project.getPackageFragmentRoot(project.getResource());
    return (IPackageFragmentRoot) javaElem;
}

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.//from  w  w  w . j  a  v a2 s  . co  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.internal.ui.wizards.PathBlock.java

License:Open Source License

/**
 * Checks for duplicate entries on the inpath compared to the Java build
 * path//from www . ja va  2  s .c  o m
 * 
 * This checks to make sure that duplicate entries are not being referred
 * to. For example, it is possible for the JUnit jar to be referred to
 * through a classpath variable as well as a classpath container. This
 * method checks for such duplicates
 * 
 * 1. if an inpath entry is on the build path, then remove it from checking
 * 2. resolve the remaining inpath entries 3. resolve the build path 4.
 * there should be no overlap
 */
private IJavaModelStatus checkForDuplicates(IJavaProject currJProject, IClasspathEntry[] entries) {
    try {
        Map<String, IClasspathEntry> allEntries = new HashMap<String, IClasspathEntry>(entries.length, 1.0f);
        for (int i = 0; i < entries.length; i++) {
            // ignore entries that are inside of a container
            if (getClasspathContainer(entries[i]) == null) {
                allEntries.put(entries[i].getPath().toPortableString(), entries[i]);
            }
        }

        IClasspathEntry[] rawProjectClasspath = currJProject.getRawClasspath();
        for (int i = 0; i < rawProjectClasspath.length; i++) {
            allEntries.remove(rawProjectClasspath[i].getPath().toPortableString());
        }

        IClasspathEntry[] resolvedProjectClasspath = currJProject.getResolvedClasspath(true);
        Map<String, IClasspathEntry> resolvedEntries = new HashMap<String, IClasspathEntry>();
        Iterator<IClasspathEntry> allEntriesIter = allEntries.values().iterator();
        while (allEntriesIter.hasNext()) {
            ClasspathEntry rawEntry = (ClasspathEntry) allEntriesIter.next();
            switch (rawEntry.entryKind) {
            case IClasspathEntry.CPE_SOURCE:
            case IClasspathEntry.CPE_LIBRARY:
            case IClasspathEntry.CPE_VARIABLE:
                IClasspathEntry resolvedEntry = JavaCore.getResolvedClasspathEntry(rawEntry);
                resolvedEntries.put(resolvedEntry.getPath().toPortableString(), resolvedEntry);
                break;
            case IClasspathEntry.CPE_CONTAINER:
                List containerEntries = AspectJCorePreferences.resolveClasspathContainer(rawEntry,
                        currJProject.getProject());

                for (Iterator containerIter = containerEntries.iterator(); containerIter.hasNext();) {
                    IClasspathEntry containerEntry = (IClasspathEntry) containerIter.next();
                    resolvedEntries.put(containerEntry.getPath().toPortableString(), containerEntry);
                }
                break;

            case IClasspathEntry.CPE_PROJECT:
                IProject thisProject = currJProject.getProject();
                IProject requiredProj = thisProject.getWorkspace().getRoot()
                        .getProject(rawEntry.getPath().makeRelative().toPortableString());
                if (!requiredProj.getName().equals(thisProject.getName()) && requiredProj.exists()) {
                    List containerEntries2 = AspectJCorePreferences.resolveDependentProjectClasspath(rawEntry,
                            requiredProj);
                    for (Iterator containerIter = containerEntries2.iterator(); containerIter.hasNext();) {
                        IClasspathEntry containerEntry = (IClasspathEntry) containerIter.next();
                        resolvedEntries.put(containerEntry.getPath().toPortableString(), containerEntry);
                    }

                }
                break;
            }
        }

        for (int i = 0; i < resolvedProjectClasspath.length; i++) {
            if (resolvedEntries.containsKey(resolvedProjectClasspath[i].getPath().toPortableString())) {
                // duplicate found.
                return new JavaModelStatus(IStatus.WARNING, IStatus.WARNING, currJProject,
                        currJProject.getPath(),
                        UIMessages.InPathBlock_DuplicateBuildEntry + resolvedProjectClasspath[i].getPath());
            }
        }

        return JavaModelStatus.VERIFIED_OK;
    } catch (JavaModelException e) {
        return new JavaModelStatus(e);
    }

}

From source file:org.eclipse.ajdt.ui.tests.builder.ProjectDependenciesUtils.java

License:Open Source License

public static boolean projectHasNoSrc(IProject project) {
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null) {
        return false;
    }/*from ww  w .  j a va 2 s. c  om*/

    boolean foundSrc = false;
    try {
        IClasspathEntry[] cpEntry = javaProject.getRawClasspath();
        for (int j = 0; j < cpEntry.length; j++) {
            IClasspathEntry entry = cpEntry[j];
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                foundSrc = true;
                if (entry.getPath().equals(javaProject.getPath())) {
                    return true;
                }
            }
        }
        if (!foundSrc)
            return true;
    } catch (JavaModelException e) {
        AspectJTestPlugin.log(e);
    }
    return false;
}

From source file:org.eclipse.ajdt.ui.tests.builder.ProjectDependenciesUtils.java

License:Open Source License

public static String makeFullPath(String jarName, IProject projectToOutputToJarFile) {
    String outJar = jarName;/*from   w ww. j  a  v a 2 s  .  c  om*/
    if (outJar != null) {
        if (!outJar.startsWith(File.separator)) {
            IJavaProject jp = JavaCore.create(projectToOutputToJarFile);
            IPath projectPath = jp.getPath();
            IPath full = AspectJPlugin.getWorkspace().getRoot().getLocation().append(projectPath);
            outJar = full.toOSString() + File.separator + outJar;
        }
    }
    System.out.println("TEST: outJar = " + outJar); //$NON-NLS-1$
    return outJar;
}

From source file:org.eclipse.ajdt.ui.tests.wizards.AspectJProjectWizardTest.java

License:Open Source License

/**
 * Tests the projects which are created by the perform finish method
 *//*  w  w  w  . ja  va  2s  . c  o m*/
public void testProjectWizardPerformFinish() throws Exception {

    IProject testSrcProject = createPredefinedProject("SourceProject1"); //$NON-NLS-1$
    IJavaProject javaProject = JavaCore.create(testSrcProject);
    int ID = 1;
    String pDestinationName = "NotVisible" + ID; //$NON-NLS-1$
    String pSrcName = testSrcProject.getName();
    ID++;

    testDestinationFile = AspectJPlugin.getWorkspace().getRoot().getLocation().append(pDestinationName)
            .toFile();
    testSrcFile = AspectJPlugin.getWorkspace().getRoot().getLocation().append(pSrcName).toFile();

    copyFileStructure(testSrcFile, testDestinationFile);
    IProject wizardCreatedProject = makeNewWizardProject("TestWizardProject"); //$NON-NLS-1$
    runGeneralTests(wizardCreatedProject, "TestWizardProject"); //$NON-NLS-1$
    IJavaProject jp = JavaCore.create(wizardCreatedProject);

    try {
        //Eclipse 3.3: the default is now to create projects with a bin folder
        assertEquals("The wizard created project does not have the correct output folder", //$NON-NLS-1$
                jp.getPath().append("bin"), jp.getOutputLocation()); //$NON-NLS-1$
    } catch (JavaModelException e) {
        fail("Failed attempting to find the output location of the project"); //$NON-NLS-1$
    }

    IProject newlyFoundProject = makeNewWizardProject(pDestinationName); // The wizard should make the project from the one
    runGeneralTests(newlyFoundProject, pDestinationName); // existing in the file structure
    IJavaProject discoveredAJProject = JavaCore.create(newlyFoundProject);

    try {
        assertTrue("The wizard discovered project does not have the correct output folder", //$NON-NLS-1$
                javaProject.getOutputLocation().lastSegment()
                        .equals(discoveredAJProject.getOutputLocation().lastSegment()));

    } catch (JavaModelException e) {
        fail("Failed attempting to find the output location of the project"); //$NON-NLS-1$
    }

    String packagePath = "src" + IPath.SEPARATOR + "TestPackage"; //$NON-NLS-1$ //$NON-NLS-2$
    IResource projectPackage = newlyFoundProject.findMember(packagePath);

    assertTrue("The TestPackage of the discovered project has not been identified correctly", //$NON-NLS-1$
            projectPackage != null);

    String helloPath = packagePath + IPath.SEPARATOR + "Hello.java"; //$NON-NLS-1$
    String aspPath = packagePath + IPath.SEPARATOR + "Asp.aj"; //$NON-NLS-1$
    String wrongFile = packagePath + IPath.SEPARATOR + "wrongFile.imc"; //$NON-NLS-1$

    assertTrue("The Hello.java file has not been correctly discovered", //$NON-NLS-1$
            newlyFoundProject.findMember(helloPath) != null);

    assertTrue("The Asp.aj file has not been correctly discovered", //$NON-NLS-1$
            newlyFoundProject.findMember(aspPath) != null);

    assertTrue("An incorrect file has been created during the discovery of the project", //$NON-NLS-1$
            newlyFoundProject.findMember(wrongFile) == null);
}

From source file:org.eclipse.ant.internal.ui.datatransfer.AntNewJavaProjectPage.java

License:Open Source License

protected void importBuildFile(IProgressMonitor monitor, IJavaProject javaProject, File buildFile,
        boolean link) {
    if (link) {/*  w ww  .j ava 2 s  . c  o m*/
        IProject project = javaProject.getProject();
        IFile iBuildFile = project.getFile(buildFile.getName());
        if (!iBuildFile.exists()) {
            try {
                iBuildFile.createLink(new Path(buildFile.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL,
                        monitor);
            } catch (CoreException e) {
                ErrorDialog.openError(getShell(), DataTransferMessages.AntNewJavaProjectPage_22, null,
                        e.getStatus());
            }
        }
    } else {
        IImportStructureProvider structureProvider = FileSystemStructureProvider.INSTANCE;
        File rootDir = buildFile.getParentFile();
        try {
            ImportOperation op = new ImportOperation(javaProject.getPath(), rootDir, structureProvider,
                    new ImportOverwriteQuery(), Collections.singletonList(buildFile));
            op.setCreateContainerStructure(false);
            op.run(monitor);
        } catch (InterruptedException e) {
            // should not happen
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t instanceof CoreException) {
                ErrorDialog.openError(getShell(), DataTransferMessages.AntNewJavaProjectPage_22, null,
                        ((CoreException) t).getStatus());
            }
        }
    }
}

From source file:org.eclipse.birt.report.designer.internal.ui.ide.adapters.IDEClassPathBlock.java

License:Open Source License

private IDECPListElement[] addProjectDialog() {

    try {/*from   ww  w . ja  v  a2 s.co m*/
        Object[] selectArr = getNotYetRequiredProjects();
        new JavaElementComparator().sort(null, selectArr);

        ListSelectionDialog dialog = new ListSelectionDialog(getShell(), Arrays.asList(selectArr),
                new ArrayContentProvider(), new ProjectLabelProvider(),
                Messages.getString("IDEClassPathBlock.ProjectDialog_message")); //$NON-NLS-1$
        dialog.setTitle(Messages.getString("IDEClassPathBlock.ProjectDialog_title")); //$NON-NLS-1$
        dialog.setHelpAvailable(false);
        if (dialog.open() == Window.OK) {
            Object[] result = dialog.getResult();
            IDECPListElement[] cpElements = new IDECPListElement[result.length];
            for (int i = 0; i < result.length; i++) {
                IJavaProject curr = ((IJavaProject) result[i]);
                cpElements[i] = new IDECPListElement(IClasspathEntry.CPE_PROJECT, curr.getPath(),
                        curr.getResource());
            }
            return cpElements;
        }
    } catch (JavaModelException e) {
        return null;
    }
    return null;
}