Example usage for org.eclipse.jdt.core IClasspathEntry getEntryKind

List of usage examples for org.eclipse.jdt.core IClasspathEntry getEntryKind

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IClasspathEntry getEntryKind.

Prototype

int getEntryKind();

Source Link

Document

Returns the kind of this classpath entry.

Usage

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

License:Open Source License

private List<String> getAllClassPathFromEntries(List<IClasspathEntry> list) {
    List<String> retValue = new ArrayList();
    IWorkspace space = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = space.getRoot();

    for (int i = 0; i < list.size(); i++) {
        IClasspathEntry curr = list.get(i);
        boolean inWorkSpace = true;

        if (space == null || space.getRoot() == null) {
            inWorkSpace = false;/*w  w w.j  av a 2  s  .  c om*/
        }

        IPath path = curr.getPath();
        if (curr.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
            path = JavaCore.getClasspathVariable(path.segment(0));
        } else {
            path = JavaCore.getResolvedClasspathEntry(curr).getPath();
        }

        if (curr.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            if (root.findMember(path) instanceof IProject) {
                List<String> strs = getProjectClasspath((IProject) root.findMember(path), false, true);
                for (int j = 0; j < strs.size(); j++) {
                    addToList(retValue, strs.get(j));
                }
            }
        } else {
            if (root.findMember(path) == null) {
                inWorkSpace = false;
            }

            if (inWorkSpace) {
                String absPath = getFullPath(path, root.findMember(path).getProject());

                //retValue.add( absPath );
                addToList(retValue, absPath);
            } else {
                //retValue.add( path.toFile( ).getAbsolutePath( ));
                addToList(retValue, path.toFile().getAbsolutePath());
            }
        }

        //strs.add( JavaCore.getResolvedClasspathEntry( entry ).getPath( ).toFile( ).getAbsolutePath( ) );
    }
    return retValue;
}

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

License:Open Source License

private List<String> resolveClasspathEntries(IClasspathEntry[] classpathEntries, boolean needExported,
        IJavaProject project) {//  w  ww .  ja v a  2  s.  co  m
    ArrayList<String> newClassPath = new ArrayList<String>();
    IWorkspace space = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = space.getRoot();
    for (int i = 0; i < classpathEntries.length; i++) {
        IClasspathEntry curr = classpathEntries[i];
        if (!needExported && !curr.isExported() && curr.getEntryKind() != IClasspathEntry.CPE_VARIABLE) {
            continue;
        }
        IPath path = curr.getPath();
        //         if (curr.getEntryKind( ) == IClasspathEntry.CPE_VARIABLE)
        //         {
        //            path = JavaCore.getClasspathVariable( path.segment( 0 ) );
        //         }
        //         else
        //         {
        path = JavaCore.getResolvedClasspathEntry(curr).getPath();
        //         }

        if (project != null && curr.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            try {
                IClasspathContainer contianer = JavaCore.getClasspathContainer(path, project);
                if (contianer != null && contianer.getKind() == IClasspathContainer.K_APPLICATION) {
                    IClasspathEntry[] entrys = contianer.getClasspathEntries();
                    List<String> list = resolveClasspathEntries(entrys, needExported, project);
                    for (int j = 0; j < list.size(); j++) {
                        addToList(newClassPath, list.get(j));
                    }
                }
            } catch (JavaModelException e) {
                //do nothing
            }
            continue;
        }
        if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            path = curr.getOutputLocation();
        }
        if (path == null) {
            continue;
        }
        if (curr.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            if (root.findMember(path) instanceof IProject) {
                List<String> strs = getProjectClasspath((IProject) root.findMember(path), false, false);
                for (int j = 0; j < strs.size(); j++) {
                    addToList(newClassPath, strs.get(j));
                }
            }
        } else if (curr.getEntryKind() == IClasspathEntry.CPE_LIBRARY
                || curr.getEntryKind() == IClasspathEntry.CPE_VARIABLE
                || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {

            boolean inWorkSpace = true;
            if (space == null || space.getRoot() == null) {
                inWorkSpace = false;
            }

            if (root.findMember(path) == null) {
                inWorkSpace = false;
            }

            if (inWorkSpace) {
                String absPath = getFullPath(path, root.findMember(path).getProject());

                //URL url = new URL( "file:///" + absPath );//$NON-NLS-1$//file:/
                //newClassPath.add( url.getPath( ) );
                newClassPath.add(absPath);
            } else {
                //                  newClassPath.add( curr.getPath( )
                //                        .toFile( )
                //                        .toURI( )
                //                        .toURL( ) );
                newClassPath.add(path.toFile().getAbsolutePath());
            }

        }

    }
    return newClassPath;
}

From source file:org.eclipse.buckminster.jdt.internal.BMClasspathInitializer.java

License:Open Source License

@Override
public void resourceChanged(IResourceChangeEvent event) {
    IPath path = BMClasspathContainer.PATH;
    try {//ww  w .  j ava  2  s .co m
        IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
        for (IJavaProject javaProject : model.getJavaProjects()) {
            for (IClasspathEntry rawEntry : javaProject.readRawClasspath()) {
                if (rawEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                    IPath entryPath = rawEntry.getPath();
                    if (path.isPrefixOf(entryPath)) {
                        this.initialize(entryPath, javaProject);
                        return;
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    } catch (CoreException e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.buckminster.jdt.internal.ClasspathEmitter.java

License:Open Source License

private static void appendPaths(IJavaModel model, IProject project, String target, List<IPath> path,
        HashSet<IPath> seenPaths, HashSet<String> seenProjects, boolean atTop) throws CoreException {
    Logger log = Buckminster.getLogger();
    String projectName = project.getName();
    if (seenProjects.contains(projectName))
        return;/*from  w w  w  . j  av  a2  s .co  m*/
    seenProjects.add(projectName);
    log.debug("Emitting classpath for project %s...", projectName); //$NON-NLS-1$

    IJavaProject javaProject = model.getJavaProject(projectName);
    IClasspathEntry[] entries;
    if (javaProject == null || !javaProject.exists()) {
        // The project may still be a component that exports jar files.
        //
        BMClasspathContainer container = new BMClasspathContainer(project, target);
        entries = container.getClasspathEntries();
        log.debug(" not a java project, contains %d entries", Integer.valueOf(entries.length)); //$NON-NLS-1$
    } else {
        entries = (atTop && target != null) ? changeClasspathForTarget(javaProject, target)
                : javaProject.getResolvedClasspath(false);
        log.debug(" java project, contains %d entries", Integer.valueOf(entries.length)); //$NON-NLS-1$
    }

    for (IClasspathEntry entry : entries) {
        IPath entryPath;
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
            log.debug(" found library with path: %s", entry.getPath()); //$NON-NLS-1$
            if (!(atTop || entry.isExported())) {
                log.debug(" skipping path %s. It's neither at top nor exported", entry.getPath()); //$NON-NLS-1$
                continue;
            }

            entryPath = entry.getPath();
            break;
        case IClasspathEntry.CPE_SOURCE:
            entryPath = entry.getOutputLocation();
            if (entryPath == null) {
                // Uses default output location
                //
                IJavaProject proj = model.getJavaProject(entry.getPath().segment(0));
                if (proj == null)
                    continue;
                entryPath = proj.getOutputLocation();
            }
            log.debug(" found source with path: %s", entryPath); //$NON-NLS-1$
            break;
        case IClasspathEntry.CPE_PROJECT:
            projectName = entry.getPath().segment(0);
            log.debug(" found project: %s", projectName); //$NON-NLS-1$
            if (!(atTop || entry.isExported())) {
                log.debug(" skipping project %s. It's neither at top nor exported", projectName); //$NON-NLS-1$
                continue;
            }

            IProject conProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
            appendPaths(model, conProject, null, path, seenPaths, seenProjects, false);
            continue;
        default:
            throw BuckminsterException.fromMessage(Messages.unexpected_classpath_entry_kind);
        }

        IResource folder = ResourcesPlugin.getWorkspace().getRoot().findMember(entryPath);
        if (folder != null) {
            log.debug(" path %s is inside workspace, switching to %s", entryPath, folder.getLocation()); //$NON-NLS-1$
            entryPath = folder.getLocation();
        }

        if (!seenPaths.contains(entryPath)) {
            seenPaths.add(entryPath);
            path.add(entryPath);
            log.debug(" path %s added", entryPath); //$NON-NLS-1$
        }
    }
}

From source file:org.eclipse.buckminster.jdt.internal.ClasspathEmitter.java

License:Open Source License

/**
 * This method obtains the raw classpath from the javaProject and scans it
 * for BMClasspathContainer. The first one found is either kept if it
 * corresponds to the target or replaced if not. All other
 * BMClasspathContainers are removed. If no BMClasspathContainer was found,
 * a new one that represents the target is added first in the list. All
 * IClasspathEntry instances are then resolved.
 * //  w  ww  .j  a  v a 2 s .  co  m
 * @param javaProject
 * @param target
 * @return
 * @throws JavaModelException
 */
private static IClasspathEntry[] changeClasspathForTarget(IJavaProject javaProject, String target)
        throws CoreException {
    boolean entriesChanged = false;
    boolean haveOtherBMCPs = false;
    boolean targetContainerInstalled = false;

    Logger log = Buckminster.getLogger();
    log.debug("Changing classpath for project %s into %s", javaProject.getProject().getName(), target); //$NON-NLS-1$
    IPath desiredContainer = BMClasspathContainer.PATH.append(target);
    IClasspathEntry[] rawEntries = javaProject.readRawClasspath();
    int top = rawEntries.length;
    for (int idx = 0; idx < top; ++idx) {
        IClasspathEntry rawEntry = rawEntries[idx];
        if (rawEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            IPath entryPath = rawEntry.getPath();
            if (BMClasspathContainer.PATH.isPrefixOf(entryPath)) {
                if (!targetContainerInstalled) {
                    if (!desiredContainer.equals(entryPath)) {
                        // This is not the desired container. Replace it.
                        //
                        rawEntries[idx] = JavaCore.newContainerEntry(desiredContainer);
                        entriesChanged = true;
                    }
                    targetContainerInstalled = true;
                } else
                    haveOtherBMCPs = true;
            }
        }
    }

    if (targetContainerInstalled) {
        if (haveOtherBMCPs) {
            // Remove other Buckminster containers
            //
            ArrayList<IClasspathEntry> newEntries = new ArrayList<IClasspathEntry>(top);
            for (int idx = 0; idx < top; ++idx) {
                IClasspathEntry rawEntry = rawEntries[idx];
                if (rawEntry.getEntryKind() != IClasspathEntry.CPE_CONTAINER
                        || rawEntry.getPath().equals(desiredContainer))
                    newEntries.add(rawEntry);
            }
            rawEntries = newEntries.toArray(new IClasspathEntry[newEntries.size()]);
            entriesChanged = true;
        }
    } else {
        rawEntries = ArrayUtils.appendFirst(rawEntries,
                new IClasspathEntry[] { JavaCore.newContainerEntry(desiredContainer) });
        entriesChanged = true;
    }

    log.debug(entriesChanged ? " changes detected" : " no changes detected"); //$NON-NLS-1$ //$NON-NLS-2$

    return entriesChanged ? getResolvedClasspath(javaProject, rawEntries)
            : javaProject.getResolvedClasspath(false);
}

From source file:org.eclipse.buckminster.jdt.internal.ClasspathEmitter.java

License:Open Source License

private static IClasspathEntry[] getResolvedClasspath(IJavaProject project, IClasspathEntry[] entries)
        throws CoreException {
    ArrayList<IClasspathEntry> resolvedEntries = new ArrayList<IClasspathEntry>();
    for (IClasspathEntry rawEntry : entries) {
        switch (rawEntry.getEntryKind()) {
        case IClasspathEntry.CPE_VARIABLE:

            IClasspathEntry resolvedEntry = null;
            try {
                resolvedEntry = JavaCore.getResolvedClasspathEntry(rawEntry);
            } catch (AssertionFailedException e) {
            }//from w  w w  .  j  a v a 2s  .co  m
            if (resolvedEntry == null)
                throw new JavaModelException(
                        ClasspathEntry.validateClasspathEntry(project, rawEntry, false, false));
            break;

        case IClasspathEntry.CPE_CONTAINER:
            IPath entryPath = rawEntry.getPath();
            IClasspathContainer container;
            if (BMClasspathContainer.PATH.isPrefixOf(entryPath))
                //
                // This one is probably not in the project classpath
                //
                container = new BMClasspathContainer(project.getProject(),
                        entryPath.segmentCount() > 1 ? entryPath.lastSegment() : null);
            else
                container = JavaCore.getClasspathContainer(entryPath, project);

            if (container == null)
                throw new JavaModelException(
                        ClasspathEntry.validateClasspathEntry(project, rawEntry, false, false));

            IClasspathEntry[] containerEntries = container.getClasspathEntries();
            if (containerEntries == null)
                continue;

            for (IClasspathEntry cEntry : containerEntries) {
                // if container is exported or restricted, then its
                // nested
                // entries must in turn be exported
                //
                cEntry = ((ClasspathEntry) cEntry).combineWith((ClasspathEntry) rawEntry);
                resolvedEntries.add(cEntry);
            }
            continue;
        }
        resolvedEntries.add(rawEntry);
    }
    return resolvedEntries.toArray(new IClasspathEntry[resolvedEntries.size()]);
}

From source file:org.eclipse.buckminster.pde.cspecgen.bundle.CSpecFromSource.java

License:Open Source License

@Override
public void generate(IProgressMonitor monitor) throws CoreException {
    monitor.beginTask(null, 100);/*from  ww w.jav  a  2s . c o  m*/

    CSpecBuilder cspec = getCSpec();
    GroupBuilder classpath = cspec.addGroup(ATTRIBUTE_JAVA_BINARIES, true);
    GroupBuilder fullClean = cspec.addGroup(ATTRIBUTE_FULL_CLEAN, true);
    GroupBuilder bundleJars = cspec.addGroup(ATTRIBUTE_BUNDLE_JARS, true);
    cspec.addGroup(ATTRIBUTE_PRODUCT_CONFIG_EXPORTS, true);

    if (getReader().isFileSystemReader())
        projectDesc = ProjectDescReader.getProjectDescription(getReader(),
                MonitorUtils.subMonitor(monitor, 15));
    else {
        projectDesc = null;
        MonitorUtils.worked(monitor, 15);
    }

    addImports();
    MonitorUtils.worked(monitor, 5);

    IClasspathEntry[] classPath;
    try {
        classPath = ClasspathReader.getClasspath(getReader(), MonitorUtils.subMonitor(monitor, 45));
    } catch (CoreException e) {
        classPath = null;
    }
    if (classPath == null)
        classPath = new IClasspathEntry[0];

    fullClean.addLocalPrerequisite(generateRemoveDirAction("build", OUTPUT_DIR, false)); //$NON-NLS-1$
    fullClean.addLocalPrerequisite(cspec.addInternalAction(ATTRIBUTE_ECLIPSE_CLEAN, false));

    boolean simpleBundle = false;
    IBuild build = buildModel.getBuild();
    ArrayList<String> jarsToCompile = null;
    Map<IPath, IPath> outputMap = new HashMap<IPath, IPath>();
    for (IBuildEntry entry : build.getBuildEntries()) {
        String name = entry.getName();
        if (name.startsWith("source.")) //$NON-NLS-1$
        {
            if (name.length() == 8 && name.charAt(7) == '.') {
                simpleBundle = true;
            } else if (name.endsWith(".jar") && name.length() > 11) { //$NON-NLS-1$
                if (jarsToCompile == null)
                    jarsToCompile = new ArrayList<String>();
                jarsToCompile.add(name.substring(7));
            }
        } else if (name.startsWith("output.") && name.length() > 7) { //$NON-NLS-1$
            String[] tokens = entry.getTokens();
            if (tokens.length == 1)
                outputMap.put(Path.fromPortableString(tokens[0]), Path.fromPortableString(name.substring(7)));
        }
    }

    // Exported entries in the classpath must be added to the
    // java.binaries export
    //
    ActionBuilder eclipseBuild = getAttributeEclipseBuild();
    Set<IPath> derivedArtifacts = new HashSet<IPath>();

    IPath[] projectRootReplacement = new IPath[1];
    HashMap<IPath, AttributeBuilder> eclipseBuildProducts = new HashMap<IPath, AttributeBuilder>();
    IPath componentHome = Path.fromPortableString(KeyConstants.ACTION_HOME_REF);
    IPath defaultOutputLocation = null;
    GroupBuilder ebSrcBld = null;
    int cnt = 0;
    for (IClasspathEntry cpe : classPath) {
        if (cpe.getEntryKind() != IClasspathEntry.CPE_SOURCE)
            continue;

        // add the class path entry to build sources
        IPath cpePath = asProjectRelativeFolder(cpe.getPath(), projectRootReplacement);
        ArtifactBuilder ab = cspec.addArtifact(ATTRIBUTE_ECLIPSE_BUILD_SOURCE + '_' + cnt++, false,
                projectRootReplacement[0]);
        ab.setBase(cpePath);
        if (ebSrcBld == null)
            ebSrcBld = getGroupEclipseBuildSource(true);
        ebSrcBld.addLocalPrerequisite(ab);

        // The output declared in the source entry is a product of the
        // Eclipse build. If there's no output declared, we use the
        // default.
        //
        IPath output = cpe.getOutputLocation();
        if (output == null) {
            if (defaultOutputLocation == null)
                defaultOutputLocation = getDefaultOutputLocation(classPath, projectRootReplacement);
            output = defaultOutputLocation;
        } else
            output = asProjectRelativeFolder(output, projectRootReplacement);

        if (output == null)
            continue;

        // Several source may contribute to the same output directory.
        // Make sure we only add it once.
        //
        if (eclipseBuildProducts.containsKey(output))
            continue;

        // Products use ${buckminster.output} as the default base so we
        // need
        // to prefix the project relative output here
        //
        IPath base;
        IPath relPath = null;
        if (output.isAbsolute()) {
            base = output;
        } else {
            base = projectRootReplacement[0];
            if (base == null)
                base = componentHome;
            base = base.append(output);

            // Find the expected location in the
            // bundle jar. We don't care about
            // '.' since that is handled elsewhere
            relPath = outputMap.get(output);
            if (relPath != null && relPath.segmentCount() == 1 && ".".equals(relPath.segment(0))) //$NON-NLS-1$
                relPath = null;

            if (relPath != null)
                derivedArtifacts.add(relPath);
        }

        GroupBuilder productRebase = null;
        String artifactName = getArtifactName(output);
        if (relPath != null && base.segmentCount() > relPath.segmentCount()) {
            // Rebase if possible. relPath must be a suffix of base
            IPath cmp = base.removeFirstSegments(base.segmentCount() - relPath.segmentCount());
            if (cmp.equals(relPath)) {
                productRebase = cspec.addGroup(artifactName, false);
                productRebase.setName(artifactName);

                // Change the name of the actual product and use
                // it as a prerequisite to this group
                artifactName += ".raw"; //$NON-NLS-1$
                productRebase.addLocalPrerequisite(artifactName);
                productRebase.setPrerequisiteRebase(base.removeLastSegments(relPath.segmentCount()));
            }
        }

        ArtifactBuilder ab2 = eclipseBuild.addProductArtifact(artifactName, false, base);

        // Add either the rebased group or the product as the
        // built product for later perusal
        eclipseBuildProducts.put(output, productRebase == null ? ab2 : productRebase);
    }

    AttributeBuilder buildSource = null;
    if (ebSrcBld != null)
        buildSource = normalizeGroup(ebSrcBld);

    // The classpath already contains all the re-exported stuff (it was
    // added when the imports were added). Only thing missing is the
    // output from the Eclipse build and the optional extra jar files.
    // TODO: We want to limit the 'eclipseBuild' prerequisite to
    // what this bundle actually exports
    //
    classpath.addLocalPrerequisite(eclipseBuild);

    // The bundle classpath can contain artifacts that can stem from three
    // different locations:
    // 1. The bundle itself, i.e. a simpleBundle containing .class files
    // rooted
    // at the bundle root
    // 2. Jars compiled from .class files produced by the eclipse build
    // (build entries)
    // 3. Pre-built extra jar files present in the bundle.
    //
    List<String> binIncludes;
    List<String> srcIncludes;
    if (getReader().isFileSystemReader()) {
        File baseDir = getReader().getLocation();
        binIncludes = expandBinFiles(baseDir, build);
        srcIncludes = expandSrcFiles(baseDir, build);
    } else {
        binIncludes = Collections.emptyList();
        srcIncludes = Collections.emptyList();
    }

    String bundleClassPath = null;
    if (plugin instanceof BundlePlugin) {
        IBundle bundle = ((BundlePlugin) plugin).getBundle();
        setFilter(bundle.getHeader(ICoreConstants.PLATFORM_FILTER));

        cspec.setShortDesc(expand(bundle.getHeader(Constants.BUNDLE_NAME)));
        bundleClassPath = bundle.getHeader(Constants.BUNDLE_CLASSPATH);
        if (bundleClassPath != null) {
            cnt = 0;
            GroupBuilder eaBld = null;
            StringTokenizer tokens = new StringTokenizer(bundleClassPath, ","); //$NON-NLS-1$
            while (tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim();
                if (simpleBundle && token.equals(".") || token.equals("./")) //$NON-NLS-1$ //$NON-NLS-2$
                    continue;

                if (jarsToCompile != null && jarsToCompile.contains(token))
                    //
                    // Assume that this jar is produced by the eclipse build
                    // and thus covered by inclusion from the project
                    // classpath above.
                    //
                    continue;

                if (binIncludes.contains(token))
                    // This one is covered by bin.includes so don't add it
                    // here
                    continue;

                // We don't know how this entry came about. Chances are it
                // has been checked in with the source.
                //
                ArtifactBuilder ab = cspec.addArtifact(ATTRIBUTE_BUNDLE_EXTRAJARS + '_' + cnt++, false, null);
                IPath eaPath = resolveLink(Path.fromPortableString(token), projectRootReplacement);
                ab.setBase(projectRootReplacement[0]);
                ab.addPath(eaPath);
                if (eaBld == null)
                    eaBld = getGroupExtraJars();
                eaBld.addLocalPrerequisite(ab);
            }

            if (eaBld != null)
                normalizeGroup(eaBld);
        }
    }

    IBuildEntry secondaryDeps = build.getEntry(IBuildEntry.SECONDARY_DEPENDENCIES);
    if (secondaryDeps != null) {
        // Add dependencies unless they have been added as imports already
        //
        for (String depName : secondaryDeps.getTokens()) {
            ComponentRequestBuilder dep = cspec.createDependencyBuilder();
            dep.setName(depName);
            dep.setComponentTypeID(IComponentType.OSGI_BUNDLE);
            addDependency(dep);
        }
    }

    // The manifest version may end with "qualifier" in which case it needs
    // to be expanded.
    // The expansion will create a new copy in a different location. In case
    // there is no
    // expansion, we can use the original file.
    //
    IPath manifestFolder = resolveLink(new Path(IPDEBuildConstants.MANIFEST_FOLDER).append(MANIFEST), null)
            .removeLastSegments(1).addTrailingSeparator();
    AttributeBuilder manifest = null;
    boolean versionExpansion = false;
    Version version = cspec.getVersion();
    if (version != null) {
        String versionQualifier = VersionHelper.getQualifier(version);
        if (versionQualifier != null)
            versionExpansion = versionQualifier.endsWith(VersionQualifierTask.QUALIFIER_SUFFIX);
    }

    // Add the build.properties artifact. We want to manage that separately
    // since it
    // is one of the requirements for expanding the bundle version
    //
    cspec.addArtifact(ATTRIBUTE_BUILD_PROPERTIES, true, null).addPath(new Path(BUILD_PROPERTIES_FILE));

    if (versionExpansion) {
        // Add the action that will create the manifest copy with the
        // version expanded
        // Another action that will do the same for the manifest used for
        // the source bundle
        //
        IPath manifestPath = new Path(MANIFEST);
        ArtifactBuilder rawManifest = cspec.addArtifact(ATTRIBUTE_RAW_MANIFEST, false, manifestFolder);
        rawManifest.addPath(manifestPath);

        ActionBuilder versionExpansionAction = addAntAction(ATTRIBUTE_MANIFEST, TASK_EXPAND_BUNDLE_VERSION,
                false);

        versionExpansionAction.addLocalPrerequisite(ATTRIBUTE_RAW_MANIFEST, ALIAS_MANIFEST);
        versionExpansionAction.addLocalPrerequisite(ATTRIBUTE_BUILD_PROPERTIES, ALIAS_PROPERTIES);

        versionExpansionAction.setProductAlias(ALIAS_OUTPUT);
        versionExpansionAction.setProductBase(OUTPUT_DIR_TEMP);
        versionExpansionAction.addProductPath(manifestPath);
        manifest = versionExpansionAction;
    } else {
        // No expansion needed, use original file.
        //
        ArtifactBuilder rawManifest = cspec.addArtifact(ATTRIBUTE_MANIFEST, true, manifestFolder);
        rawManifest.addPath(new Path(MANIFEST));
        manifest = rawManifest;
    }

    // Create an action for building each jar.
    //
    if (jarsToCompile != null) {
        for (String jarName : jarsToCompile)
            derivedArtifacts.add(createJarAction(jarName, classPath, build, outputMap,
                    simpleBundle ? eclipseBuildProducts : null));
    }

    if (simpleBundle) {
        derivedArtifacts.add(new Path(".")); //$NON-NLS-1$
        derivedArtifacts.add(new Path("./")); // Uncertain which one is used //$NON-NLS-1$
    }

    // The jar contents group represents all contents of the final jar
    // except the
    // manifest
    //
    GroupBuilder jarContents = getAttributeJarContents();

    // Add additional artifacts to be included in the bundle
    //
    boolean includeBuildProps = false;
    boolean considerAboutMappings = VersionConsolidator.getBooleanProperty(
            getReader().getNodeQuery().getProperties(), PROP_PDE_CONSIDER_ABOUT_MAPPINGS, true);
    if (!binIncludes.isEmpty()) {
        GroupBuilder binIncludesSource = null;
        cnt = 0;
        for (String token : binIncludes) {
            if (BUNDLE_FILE.equalsIgnoreCase(token))
                //
                // Handled separately (might be derived)
                //
                continue;

            if (versionExpansion && BUILD_PROPERTIES_FILE.equals(token)) {
                includeBuildProps = true;
                continue;
            }

            IPath binInclude = new Path(token);
            if (derivedArtifacts.contains(binInclude))
                //
                // Not an artifact. This is produced by some action
                //
                continue;

            if (binIncludesSource == null)
                binIncludesSource = cspec.addGroup(ATTRIBUTE_BIN_INCLUDES, false);

            if (considerAboutMappings && ABOUT_MAPPINGS_FILE.equalsIgnoreCase(token)) {
                AttributeBuilder aboutMappings = addAboutMappingsAction(binInclude, projectRootReplacement[0]);
                binIncludesSource.addLocalPrerequisite(aboutMappings);
            } else {
                IPath biPath = resolveLink(binInclude, projectRootReplacement);
                ArtifactBuilder ab = cspec.addArtifact(ATTRIBUTE_BIN_INCLUDES + '_' + cnt++, false,
                        projectRootReplacement[0]);
                ab.addPath(biPath);
                binIncludesSource.addLocalPrerequisite(ab);
            }
        }

        if (binIncludesSource != null) {
            normalizeGroup(binIncludesSource);
            jarContents.addLocalPrerequisite(ATTRIBUTE_BIN_INCLUDES);
        }
        if (includeBuildProps)
            jarContents.addLocalPrerequisite(ATTRIBUTE_BUILD_PROPERTIES);
    }

    GroupBuilder srcIncludesSource = null;
    if (!srcIncludes.isEmpty()) {
        cnt = 0;
        for (String token : srcIncludes) {
            IPath srcInclude = new Path(token);

            if (srcIncludesSource == null)
                srcIncludesSource = cspec.addGroup(ATTRIBUTE_SRC_INCLUDES, false);

            IPath biPath = resolveLink(srcInclude, projectRootReplacement);
            ArtifactBuilder ab = cspec.addArtifact(ATTRIBUTE_SRC_INCLUDES + '_' + cnt++, false,
                    projectRootReplacement[0]);
            ab.addPath(biPath);
            srcIncludesSource.addLocalPrerequisite(ab);
        }
    }

    if (buildSource != null) {
        if (srcIncludesSource == null)
            srcIncludesSource = cspec.addGroup(IBuildEntry.SRC_INCLUDES, false);
        srcIncludesSource.addLocalPrerequisite(buildSource);
    }

    if (simpleBundle && !binIncludes.isEmpty()) {
        // These products from the eclipse.build will contain the .class
        // files for the bundle
        //
        String excludesStr = null;
        IBuildEntry excludes = build.getEntry(PROPERTY_EXCLUDE_PREFIX + '.');
        if (excludes != null)
            excludesStr = TextUtils.concat(excludes.getTokens(), ","); //$NON-NLS-1$

        for (AttributeBuilder product : eclipseBuildProducts.values()) {
            if (excludesStr == null)
                jarContents.addLocalPrerequisite(product);
            else {
                String pruneName = product.getName() + ".pruned"; //$NON-NLS-1$
                ActionBuilder prune = cspec.addAction(pruneName, false, CopyActor.ID, false);
                prune.addLocalPrerequisite(product);
                prune.addProperty(CopyActor.PROP_EXCLUDES, excludesStr, false);
                prune.setProductBase(OUTPUT_DIR_TEMP.append(pruneName));
                jarContents.addLocalPrerequisite(prune);
            }
        }
    }

    ActionBuilder buildPlugin;
    String jarName = plugin.getId() + '_' + plugin.getVersion() + ".jar"; //$NON-NLS-1$
    IPath jarPath = Path.fromPortableString(jarName);
    if (getReader().isFileSystemReader() && (getReader().exists(jarName, new NullProgressMonitor())
            || getLinkDescriptions().containsKey(jarPath))) {
        buildPlugin = addAntAction(ATTRIBUTE_BUNDLE_JAR, TASK_COPY_GROUP, true);
        buildPlugin.setPrerequisitesAlias(ALIAS_REQUIREMENTS);
        IPath resolvedJarPath = resolveLink(jarPath, projectRootReplacement);
        ArtifactBuilder importedJar = cspec.addArtifact(ATTRIBUTE_IMPORTED_JAR, false,
                projectRootReplacement[0]);
        importedJar.addPath(resolvedJarPath);
        buildPlugin.getPrerequisitesBuilder().addLocalPrerequisite(importedJar);
    } else {
        buildPlugin = addAntAction(ATTRIBUTE_BUNDLE_JAR, TASK_CREATE_BUNDLE_JAR, true);
        buildPlugin.addLocalPrerequisite(manifest.getName(), ALIAS_MANIFEST);
        buildPlugin.addLocalPrerequisite(jarContents.getName(), ALIAS_REQUIREMENTS);
    }
    addGenerateApiDescription(build);

    buildPlugin.setProductAlias(ALIAS_OUTPUT);
    buildPlugin.setProductBase(OUTPUT_DIR_JAR);
    buildPlugin.setUpToDatePolicy(UpToDatePolicy.COUNT);
    buildPlugin.setProductFileCount(1);

    GroupBuilder bundleAndFragments = cspec.addGroup(ATTRIBUTE_BUNDLE_AND_FRAGMENTS, true);
    IPluginModelBase model = plugin.getPluginModel();
    if (model instanceof IFragmentModel)
        addBundleHostDependency((IFragmentModel) model);
    else {
        ActionBuilder copyTargetFragments = cspec.addAction(ATTRIBUTE_TARGET_FRAGMENTS, false,
                ACTOR_COPY_TARGET_FRAGMENTS, false);
        copyTargetFragments.setProductAlias(ALIAS_OUTPUT);
        copyTargetFragments.setProductBase(OUTPUT_DIR_FRAGMENTS);
        copyTargetFragments.addLocalPrerequisite(getAttributeEclipseBuild());
        copyTargetFragments.setUpToDatePolicy(UpToDatePolicy.ACTOR);
        copyTargetFragments.addProperty(FragmentsActor.PROP_FRAGMENT_ATTRIBUTE, ATTRIBUTE_BUNDLE_JAR, false);
        bundleAndFragments.addLocalPrerequisite(copyTargetFragments);
    }
    bundleAndFragments.addLocalPrerequisite(buildPlugin);
    bundleJars.addLocalPrerequisite(bundleAndFragments);

    GroupBuilder bundleAndFragmentsSource = cspec.addGroup(ATTRIBUTE_BUNDLE_AND_FRAGMENTS_SOURCE, true);
    if (!(model instanceof IFragmentModel)) {
        ActionBuilder copyTargetFragmentsSource = cspec.addAction(ATTRIBUTE_TARGET_FRAGMENTS_SOURCE, false,
                ACTOR_COPY_TARGET_FRAGMENTS, false);
        copyTargetFragmentsSource.setProductAlias(ALIAS_OUTPUT);
        copyTargetFragmentsSource.setProductBase(OUTPUT_DIR_FRAGMENTS_SOURCE);
        copyTargetFragmentsSource.setUpToDatePolicy(UpToDatePolicy.ACTOR);
        copyTargetFragmentsSource.addProperty(FragmentsActor.PROP_FRAGMENT_ATTRIBUTE,
                ATTRIBUTE_SOURCE_BUNDLE_JAR, false);
        bundleAndFragmentsSource.addLocalPrerequisite(copyTargetFragmentsSource);
    }

    if (srcIncludesSource != null) {
        // Add Actions to create a source bundle jar

        // this is for the source manifest
        ActionBuilder sourceManifestAction = addAntAction(ATTRIBUTE_SOURCE_MANIFEST,
                TASK_CREATE_SOURCE_MANIFEST, false);
        sourceManifestAction.addLocalPrerequisite(ATTRIBUTE_MANIFEST, ALIAS_MANIFEST);
        sourceManifestAction.addLocalPrerequisite(ATTRIBUTE_BUILD_PROPERTIES, ALIAS_PROPERTIES);

        sourceManifestAction.setProductAlias(ALIAS_OUTPUT);
        sourceManifestAction.setProductBase(OUTPUT_DIR_TEMP);
        IPath sourceManifestPath = new Path(SOURCE_MANIFEST);
        sourceManifestAction.addProductPath(sourceManifestPath);

        // this is for the source bundle
        ActionBuilder sourceBundleAction = addAntAction(ATTRIBUTE_SOURCE_BUNDLE_JAR, TASK_CREATE_BUNDLE_JAR,
                true);
        sourceBundleAction.addLocalPrerequisite(IBuildEntry.SRC_INCLUDES, ALIAS_REQUIREMENTS);
        sourceBundleAction.addLocalPrerequisite(ATTRIBUTE_SOURCE_MANIFEST, ALIAS_MANIFEST);
        sourceBundleAction.setProductAlias(ALIAS_OUTPUT);
        sourceBundleAction.setProductBase(OUTPUT_DIR_SOURCE_JAR);
        bundleAndFragmentsSource.addLocalPrerequisite(sourceBundleAction);

        GeneratorBuilder genBld = cspec.createGeneratorBuilder();
        genBld.setAttribute(ATTRIBUTE_SOURCE_BUNDLE_JAR);
        genBld.setGeneratesType(IComponentType.OSGI_BUNDLE);
        genBld.setName(cspec.getName() + ".source"); //$NON-NLS-1$
        cspec.addGenerator(genBld);
    } else {
        // Add an empty group so that it can be referenced
        cspec.addGroup(ATTRIBUTE_SOURCE_BUNDLE_JAR, true);
    }

    addProducts(MonitorUtils.subMonitor(monitor, 20));
    monitor.done();
}

From source file:org.eclipse.buckminster.pde.cspecgen.bundle.CSpecFromSource.java

License:Open Source License

private IClasspathEntry[] getSourceEntries(IClasspathEntry[] classPath, String jarName, IBuild build,
        IPath[][] notFound) {/*from   w  w w.  j a v a  2s  . c  o  m*/
    IBuildEntry srcIncl = build.getEntry(IBuildEntry.JAR_PREFIX + jarName);
    if (srcIncl == null) {
        notFound[0] = Trivial.EMPTY_PATH_ARRAY;
        return emptyClasspath;
    }

    List<IClasspathEntry> cpEntries = null;
    List<IPath> missingEntries = null;
    if (classPath == null) {
        for (String src : srcIncl.getTokens()) {
            if (missingEntries == null)
                missingEntries = new ArrayList<IPath>();
            missingEntries.add(resolveLink(Path.fromPortableString(src).addTrailingSeparator(), null));
        }
    } else {
        for (String src : srcIncl.getTokens()) {
            boolean found = false;
            IPath srcPath = resolveLink(Path.fromPortableString(src), null).addTrailingSeparator();
            for (IClasspathEntry ce : classPath) {
                if (ce.getEntryKind() != IClasspathEntry.CPE_SOURCE)
                    continue;

                IPath cePath = asProjectRelativeFolder(ce.getPath(), null);
                if (cePath.equals(srcPath)) {
                    found = true;
                    if (cpEntries == null)
                        cpEntries = new ArrayList<IClasspathEntry>();
                    cpEntries.add(ce);
                    break;
                }
            }
            if (!found) {
                if (missingEntries == null)
                    missingEntries = new ArrayList<IPath>();
                missingEntries.add(srcPath);
            }
        }
    }
    notFound[0] = missingEntries == null ? Trivial.EMPTY_PATH_ARRAY
            : missingEntries.toArray(new IPath[missingEntries.size()]);
    return cpEntries == null ? emptyClasspath : cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
}

From source file:org.eclipse.buildship.core.launch.internal.GradleClasspathProvider.java

License:Open Source License

private static IRuntimeClasspathEntry[] resolveOutputLocations(IRuntimeClasspathEntry projectEntry,
        IJavaProject project, LaunchConfigurationScope configurationScopes) throws CoreException {
    List<IPath> outputLocations = Lists.newArrayList();
    boolean hasSourceFolderWithoutCustomOutput = false;

    if (project.exists() && project.getProject().isOpen()) {
        for (IClasspathEntry entry : project.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {

                // only add the output location if it's in the same source set
                if (configurationScopes.isEntryIncluded(entry)) {
                    IPath path = entry.getOutputLocation();
                    if (path != null) {
                        outputLocations.add(path);
                    } else {
                        // only use the default output if there's at least one source folder that doesn't have a custom output location
                        hasSourceFolderWithoutCustomOutput = true;
                    }/*from   ww  w .j a  v  a2 s. com*/
                }
            }
        }
    }

    if (outputLocations.isEmpty()) {
        return new IRuntimeClasspathEntry[] { projectEntry };
    }

    IPath defaultOutputLocation = project.getOutputLocation();
    if (!outputLocations.contains(defaultOutputLocation) && hasSourceFolderWithoutCustomOutput) {
        outputLocations.add(defaultOutputLocation);
    }

    IRuntimeClasspathEntry[] result = new IRuntimeClasspathEntry[outputLocations.size()];
    for (int i = 0; i < result.length; i++) {
        result[i] = new RuntimeClasspathEntry(JavaCore.newLibraryEntry(outputLocations.get(i), null, null));
        result[i].setClasspathProperty(projectEntry.getClasspathProperty());
    }
    return result;
}

From source file:org.eclipse.buildship.core.workspace.internal.GradleClasspathContainerRuntimeClasspathEntryResolver.java

License:Open Source License

private void collectContainerRuntimeClasspath(IClasspathContainer container,
        List<IRuntimeClasspathEntry> result, boolean includeExportedEntriesOnly,
        LaunchConfigurationScope configurationScopes) throws CoreException {
    for (final IClasspathEntry cpe : container.getClasspathEntries()) {
        if (!includeExportedEntriesOnly || cpe.isExported()) {
            if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY && configurationScopes.isEntryIncluded(cpe)) {
                result.add(JavaRuntime.newArchiveRuntimeClasspathEntry(cpe.getPath()));
            } else if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                Optional<IProject> candidate = findAccessibleJavaProject(cpe.getPath().segment(0));
                if (candidate.isPresent()) {
                    IJavaProject dependencyProject = JavaCore.create(candidate.get());
                    IRuntimeClasspathEntry projectRuntimeEntry = JavaRuntime
                            .newProjectRuntimeClasspathEntry(dependencyProject);
                    // add the project entry itself so that the source lookup can find the classes
                    // see https://github.com/eclipse/buildship/issues/383
                    result.add(projectRuntimeEntry);
                    Collections.addAll(result,
                            JavaRuntime.resolveRuntimeClasspathEntry(projectRuntimeEntry, dependencyProject));
                    collectContainerRuntimeClasspathIfPresent(dependencyProject, result, true,
                            configurationScopes);
                }//  w ww  .j  a  v a 2s  .c om
            }
        }
    }
}