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

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

Introduction

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

Prototype

IClasspathEntry[] getRawClasspath() throws JavaModelException;

Source Link

Document

Returns the raw classpath for the project, as a list of classpath entries.

Usage

From source file:com.redhat.ceylon.eclipse.core.model.JDTModule.java

License:Open Source License

public synchronized List<IPackageFragmentRoot> getPackageFragmentRoots() {
    if (packageFragmentRoots.isEmpty() && !moduleManager.isExternalModuleLoadedFromSource(getNameAsString())) {
        IJavaProject javaProject = moduleManager.getJavaProject();
        if (javaProject != null) {
            if (this.equals(getLanguageModule())) {
                IClasspathEntry runtimeClasspathEntry = null;

                try {
                    for (IClasspathEntry entry : javaProject.getRawClasspath()) {
                        if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER && entry.getPath().segment(0)
                                .equals(CeylonLanguageModuleContainer.CONTAINER_ID)) {
                            runtimeClasspathEntry = entry;
                            break;
                        }//from   ww  w  .  j  a v  a2 s  .c  om
                    }

                    if (runtimeClasspathEntry != null) {
                        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
                            if (root.exists() && javaProject.isOnClasspath(root)
                                    && root.getRawClasspathEntry().equals(runtimeClasspathEntry)) {
                                packageFragmentRoots.add(root);
                            }
                        }
                    }
                } catch (JavaModelException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                File jarToSearch = null;
                try {
                    jarToSearch = returnCarFile();
                    if (jarToSearch == null) {
                        RepositoryManager repoMgr = CeylonBuilder
                                .getProjectRepositoryManager(javaProject.getProject());
                        if (repoMgr != null) {
                            jarToSearch = CeylonProjectModulesContainer.getModuleArtifact(repoMgr, this);
                        }
                    }

                    if (jarToSearch != null) {
                        IPackageFragmentRoot root = moduleManager.getJavaProject()
                                .getPackageFragmentRoot(jarToSearch.toString());
                        if (root instanceof JarPackageFragmentRoot) {
                            JarPackageFragmentRoot jarRoot = (JarPackageFragmentRoot) root;
                            if (jarRoot.getJar().getName().equals(jarToSearch.getPath())) {
                                packageFragmentRoots.add(root);
                            }
                        }
                    }
                } catch (CoreException e) {
                    if (jarToSearch != null) {
                        System.err.println("Exception trying to get Jar file '" + jarToSearch + "' :");
                    }
                    e.printStackTrace();
                }
            }
        }
    }
    return packageFragmentRoots;
}

From source file:com.redhat.ceylon.eclipse.ui.test.CeylonEditorTest.java

License:Open Source License

private IProject createJavaProject(String name) throws CoreException, JavaModelException {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(name);
    project.create(null);/*from ww w . j  a  v a  2 s  .co  m*/
    project.open(null);

    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID });
    project.setDescription(description, null);

    IJavaProject javaProject = JavaCore.create(project);

    IFolder binFolder = project.getFolder("bin");
    binFolder.create(false, true, null);
    javaProject.setOutputLocation(binFolder.getFullPath(), null);

    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
    LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
    for (LibraryLocation element : locations) {
        entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
    }
    //add libs to project class path
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

    IFolder sourceFolder = project.getFolder("src");
    sourceFolder.create(false, true, null);

    IPackageFragmentRoot packageroot = javaProject.getPackageFragmentRoot(sourceFolder);
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(packageroot.getPath());
    javaProject.setRawClasspath(newEntries, null);
    return project;
}

From source file:com.siteview.mde.internal.core.builders.BuildErrorReporter.java

License:Open Source License

private void validateBuild(IBuild build) {

    IBuildEntry binIncludes = null;//from w w  w  .  ja  v  a  2s  .c om
    IBuildEntry binExcludes = null;
    IBuildEntry srcIncludes = null;
    IBuildEntry srcExcludes = null;
    IBuildEntry jarsExtra = null;
    IBuildEntry bundleList = null;
    IBuildEntry javacSource = null;
    IBuildEntry javacTarget = null;
    IBuildEntry jreCompilationProfile = null;
    IBuildEntry javaProjectWarnings = null;
    ArrayList javacWarnings = new ArrayList();
    ArrayList javacErrors = new ArrayList();
    ArrayList sourceEntries = new ArrayList(1);
    ArrayList sourceEntryKeys = new ArrayList(1);
    ArrayList outputEntries = new ArrayList(1);
    Map encodingEntries = new HashMap();
    IBuildEntry[] entries = build.getBuildEntries();
    for (int i = 0; i < entries.length; i++) {
        String name = entries[i].getName();
        if (entries[i].getTokens().length == 0)
            prepareError(name, null, MDECoreMessages.BuildErrorReporter_emptyEntry, MDEMarkerFactory.B_REMOVAL,
                    MDEMarkerFactory.CAT_FATAL);
        else if (name.equals(PROPERTY_BIN_INCLUDES))
            binIncludes = entries[i];
        else if (name.equals(PROPERTY_BIN_EXCLUDES))
            binExcludes = entries[i];
        else if (name.equals(PROPERTY_SRC_INCLUDES))
            srcIncludes = entries[i];
        else if (name.equals(PROPERTY_SRC_EXCLUDES))
            srcExcludes = entries[i];
        else if (name.equals(PROPERTY_JAVAC_SOURCE))
            javacSource = entries[i];
        else if (name.equals(PROPERTY_JAVAC_TARGET))
            javacTarget = entries[i];
        else if (name.equals(PROPERTY_PROJECT_SETTINGS))
            javaProjectWarnings = entries[i];
        else if (name.equals(PROPERTY_JRE_COMPILATION_PROFILE))
            jreCompilationProfile = entries[i];
        else if (name.startsWith(PROPERTY_JAVAC_WARNINGS_PREFIX))
            javacWarnings.add(entries[i]);
        else if (name.startsWith(PROPERTY_JAVAC_ERRORS_PREFIX))
            javacErrors.add(entries[i]);
        else if (name.startsWith(PROPERTY_SOURCE_PREFIX))
            sourceEntries.add(entries[i]);
        else if (name.startsWith(PROPERTY_OUTPUT_PREFIX))
            outputEntries.add(entries[i]);
        else if (name.startsWith(PROPERTY_JAVAC_DEFAULT_ENCODING_PREFIX))
            encodingEntries.put(entries[i].getName(), entries[i].getTokens()[0]);
        else if (name.equals(PROPERTY_JAR_EXTRA_CLASSPATH))
            jarsExtra = entries[i];
        else if (name.equals(IBuildEntry.SECONDARY_DEPENDENCIES))
            bundleList = entries[i];
        else if (name.equals(PROPERTY_CUSTOM)) {
            String[] tokens = entries[i].getTokens();
            if (tokens.length == 1 && tokens[0].equalsIgnoreCase("true")) //$NON-NLS-1$
                // nothing to validate in custom builds
                return;
        }

        // non else if statement to catch all names
        if (name.startsWith(PROPERTY_SOURCE_PREFIX))
            sourceEntryKeys.add(entries[i].getName());
    }

    // validation not relying on build flag
    if (fClasspathSeverity != CompilerFlags.IGNORE) {
        if (bundleList != null)
            validateDependencyManagement(bundleList);
    }

    if (jarsExtra != null)
        validateJarsExtraClasspath(jarsExtra);
    validateIncludes(binIncludes, sourceEntryKeys, fBinInclSeverity);
    validateIncludes(binExcludes, sourceEntryKeys, fBinInclSeverity);
    validateIncludes(srcIncludes, sourceEntryKeys, fSrcInclSeverity);
    validateIncludes(srcExcludes, sourceEntryKeys, fSrcInclSeverity);
    validateSourceFoldersInSrcIncludes(srcIncludes);

    try {
        IJavaProject jp = JavaCore.create(fProject);
        if (jp.exists()) {
            IClasspathEntry[] cpes = jp.getRawClasspath();
            validateMissingLibraries(sourceEntryKeys, cpes);
            validateSourceEntries(sourceEntries, srcExcludes, cpes);
            SourceEntryErrorReporter srcEntryErrReporter = new SourceEntryErrorReporter(fFile, build);
            srcEntryErrReporter.initialize(sourceEntries, outputEntries, cpes, fProject);
            srcEntryErrReporter.validate();
            ArrayList problems = srcEntryErrReporter.getProblemList();
            for (int i = 0; i < problems.size(); i++) {
                if (!fProblemList.contains(problems.get(i))) {
                    fProblemList.add(problems.get(i));
                }
            }

        }
    } catch (JavaModelException e) {
    }

    validateMissingSourceInBinIncludes(binIncludes, sourceEntryKeys, build);
    validateBinIncludes(binIncludes);
    validateExecutionEnvironment(javacSource, javacTarget, jreCompilationProfile, javacWarnings, javacErrors,
            getSourceLibraries(sourceEntries));
    validateJavaCompilerSettings(javaProjectWarnings);
}

From source file:com.siteview.mde.internal.core.builders.BuildErrorReporter.java

License:Open Source License

/**
 * Matches the javacSource, javacTarget, javacWarnings, javacErrors and jre.compilation.prile entries in build.properties with the 
 * project specific Java Compiler properties and reports the errors found.
 * //from  ww  w  .  ja va2  s  .  co  m
 * @param javacSourceEntry
 * @param javacTargetEntry
 * @param jreCompilationProfileEntry
 * @param javacWarningsEntries
 * @param javacErrorsEntries 
 * @param libraryNames list of library names (javacWarnings/javacErrors require an entry for each source library)
 */
private void validateExecutionEnvironment(IBuildEntry javacSourceEntry, IBuildEntry javacTargetEntry,
        IBuildEntry jreCompilationProfileEntry, ArrayList javacWarningsEntries, ArrayList javacErrorsEntries,
        List libraryNames) {
    // if there is no source to compile, don't worry about compiler settings
    IJavaProject project = JavaCore.create(fProject);
    if (project.exists()) {
        IClasspathEntry[] classpath = null;
        try {
            classpath = project.getRawClasspath();
        } catch (JavaModelException e) {
            MDECore.log(e);
            return;
        }
        boolean source = false;
        for (int i = 0; i < classpath.length; i++) {
            IClasspathEntry cpe = classpath[i];
            if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                source = true;
            }
        }
        if (!source) {
            return;
        }

        String projectComplianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, false);

        if (projectComplianceLevel != null) {

            IMonitorModelBase model = MonitorRegistry.findModel(fProject);
            String[] execEnvs = null;
            if (model != null) {
                BundleDescription bundleDesc = model.getBundleDescription();
                if (bundleDesc != null) {
                    execEnvs = bundleDesc.getExecutionEnvironments();
                }
            }

            if (execEnvs == null || execEnvs.length == 0) {
                return;
            }

            //PDE Build uses top most entry to build the plug-in
            String execEnv = execEnvs[0];

            String projectSourceCompatibility = project.getOption(JavaCore.COMPILER_SOURCE, true);
            String projectClassCompatibility = project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
                    true);
            if (projectComplianceLevel
                    .equals(findMatchingEE(projectSourceCompatibility, projectClassCompatibility, false))
                    && execEnv.equals(
                            findMatchingEE(projectSourceCompatibility, projectClassCompatibility, true))) {
                return; //The project compliance settings matches the BREE
            }

            Map defaultComplianceOptions = new HashMap();
            JavaCore.setComplianceOptions(projectComplianceLevel, defaultComplianceOptions);

            //project compliance does not match the BREE
            String projectJavaCompatibility = findMatchingEE(projectSourceCompatibility,
                    projectClassCompatibility, true);
            String message = null;
            if (projectJavaCompatibility != null) {
                if (jreCompilationProfileEntry == null) {
                    message = NLS.bind(
                            MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                            PROPERTY_JRE_COMPILATION_PROFILE,
                            MDECoreMessages.BuildErrorReporter_CompilercomplianceLevel);
                    prepareError(PROPERTY_JRE_COMPILATION_PROFILE, projectJavaCompatibility, message,
                            MDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                            MDEMarkerFactory.CAT_EE);
                } else {
                    if (!projectJavaCompatibility.equalsIgnoreCase(jreCompilationProfileEntry.getTokens()[0])) {
                        message = NLS.bind(
                                MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                PROPERTY_JRE_COMPILATION_PROFILE,
                                MDECoreMessages.BuildErrorReporter_CompilercomplianceLevel);
                        prepareError(PROPERTY_JRE_COMPILATION_PROFILE, projectJavaCompatibility, message,
                                MDEMarkerFactory.B_REPLACE, fJavaComplianceSeverity, MDEMarkerFactory.CAT_EE);
                    }
                }
            } else {
                // Check source level setting
                if (projectSourceCompatibility.equals(defaultComplianceOptions.get(JavaCore.COMPILER_SOURCE))) {
                    if (javacSourceEntry != null) {
                        message = NLS.bind(
                                MDECoreMessages.BuildErrorReporter_BuildEntryNotRequiredMatchesDefault,
                                PROPERTY_JAVAC_SOURCE, MDECoreMessages.BuildErrorReporter_SourceCompatibility);
                        prepareError(PROPERTY_JAVAC_SOURCE, null, message, MDEMarkerFactory.B_REMOVAL,
                                fJavaComplianceSeverity, MDEMarkerFactory.CAT_EE);
                    }
                } else {
                    if (javacSourceEntry == null) {
                        message = NLS.bind(
                                MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                                PROPERTY_JAVAC_SOURCE, MDECoreMessages.BuildErrorReporter_SourceCompatibility);
                        prepareError(PROPERTY_JAVAC_SOURCE, projectSourceCompatibility, message,
                                MDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                MDEMarkerFactory.CAT_EE);
                    } else {
                        if (!projectSourceCompatibility.equalsIgnoreCase(javacSourceEntry.getTokens()[0])) {
                            message = NLS.bind(
                                    MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                    PROPERTY_JAVAC_SOURCE,
                                    MDECoreMessages.BuildErrorReporter_SourceCompatibility);
                            prepareError(PROPERTY_JAVAC_SOURCE, projectSourceCompatibility, message,
                                    MDEMarkerFactory.B_REPLACE, fJavaComplianceSeverity,
                                    MDEMarkerFactory.CAT_EE);
                        }
                    }
                }

                // Check target level setting
                if (projectClassCompatibility
                        .equals(defaultComplianceOptions.get(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM))) {
                    if (javacTargetEntry != null) {
                        message = NLS.bind(
                                MDECoreMessages.BuildErrorReporter_BuildEntryNotRequiredMatchesDefault,
                                PROPERTY_JAVAC_TARGET,
                                MDECoreMessages.BuildErrorReporter_GeneratedClassFilesCompatibility);
                        prepareError(PROPERTY_JAVAC_TARGET, null, message, MDEMarkerFactory.B_REMOVAL,
                                fJavaComplianceSeverity, MDEMarkerFactory.CAT_EE);
                    }
                } else {
                    if (javacTargetEntry == null) {
                        message = NLS.bind(
                                MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                                PROPERTY_JAVAC_TARGET,
                                MDECoreMessages.BuildErrorReporter_GeneratedClassFilesCompatibility);
                        prepareError(PROPERTY_JAVAC_TARGET, projectClassCompatibility, message,
                                MDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                MDEMarkerFactory.CAT_EE);
                    } else {
                        if (!projectClassCompatibility.equalsIgnoreCase(javacTargetEntry.getTokens()[0])) {
                            message = NLS.bind(
                                    MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                    PROPERTY_JAVAC_TARGET,
                                    MDECoreMessages.BuildErrorReporter_GeneratedClassFilesCompatibility);
                            prepareError(PROPERTY_JAVAC_TARGET, projectClassCompatibility, message,
                                    MDEMarkerFactory.B_REPLACE, fJavaComplianceSeverity,
                                    MDEMarkerFactory.CAT_EE);
                        }
                    }
                }
            }

            boolean warnForJavacWarnings = message != null || javacSourceEntry != null
                    || javacTargetEntry != null || jreCompilationProfileEntry != null;
            if (warnForJavacWarnings == false) {
                return;
            }

            checkJavaComplianceSettings(projectComplianceLevel, javacWarningsEntries, javacErrorsEntries,
                    libraryNames);
        }
    }
}

From source file:com.siteview.mde.internal.core.builders.BundleErrorReporter.java

License:Open Source License

private void validateRequiredExecutionEnvironment() {
    int sev = CompilerFlags.getFlag(fProject, CompilerFlags.P_INCOMPATIBLE_ENV);
    if (sev == CompilerFlags.IGNORE)
        return;//from   w  w w .j ava2 s.c  o m
    BundleDescription desc = fModel.getBundleDescription();
    if (desc == null)
        return;

    // if we aren't a java project, let's not check for a BREE
    try {
        if (!fProject.hasNature(JavaCore.NATURE_ID))
            return;
    } catch (CoreException e) {
        return;
    }

    String[] bundleEnvs = desc.getExecutionEnvironments();
    if (bundleEnvs == null || bundleEnvs.length == 0) {
        // No EE specified
        IJavaProject javaProject = JavaCore.create(fProject);

        // See if the project has an EE classpath entry
        if (javaProject.exists()) {
            try {
                IClasspathEntry[] entries = javaProject.getRawClasspath();

                for (int i = 0; i < entries.length; i++) {
                    if (entries[i].getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                        IPath currentPath = entries[i].getPath();
                        if (JavaRuntime.newDefaultJREContainerPath().matchingFirstSegments(currentPath) > 0) {
                            String eeId = JavaRuntime.getExecutionEnvironmentId(currentPath);
                            if (eeId != null) {
                                IMarker marker = report(
                                        MDECoreMessages.BundleErrorReporter_noExecutionEnvironmentSet, 1, sev,
                                        MDEMarkerFactory.M_EXECUTION_ENVIRONMENT_NOT_SET,
                                        MDEMarkerFactory.CAT_EE);
                                addMarkerAttribute(marker, "ee_id", eeId); //$NON-NLS-1$
                                return;
                            }
                        }
                    }
                }
            } catch (JavaModelException e) {
                MDECore.log(e);
            }
        }

        // If no EE classpath entry, get a matching EE for the project JRE (or the default JRE)
        IExecutionEnvironment[] systemEnvs = JavaRuntime.getExecutionEnvironmentsManager()
                .getExecutionEnvironments();
        IVMInstall vm = JavaRuntime.getDefaultVMInstall();
        if (javaProject.exists()) {
            try {
                vm = JavaRuntime.getVMInstall(javaProject);
            } catch (CoreException e) {
                MDECore.log(e);
            }
        }

        if (vm != null) {
            for (int i = 0; i < systemEnvs.length; i++) {
                // Get strictly compatible EE for the default VM
                if (systemEnvs[i].isStrictlyCompatible(vm)) {
                    IMarker marker = report(MDECoreMessages.BundleErrorReporter_noExecutionEnvironmentSet, 1,
                            sev, MDEMarkerFactory.M_EXECUTION_ENVIRONMENT_NOT_SET, MDEMarkerFactory.CAT_EE);
                    addMarkerAttribute(marker, "ee_id", systemEnvs[i].getId()); //$NON-NLS-1$
                    break;
                }
            }
        }
        return;
    }

    IHeader header = getHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT);
    if (header == null)
        return;

    IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(bundleEnvs[0]);
    if (env != null) {
        IJavaProject jproject = JavaCore.create(fProject);
        IClasspathEntry[] entries;
        try {
            entries = jproject.getRawClasspath();
            for (int i = 0; i < entries.length; i++) {
                if (entries[i].getEntryKind() != IClasspathEntry.CPE_CONTAINER)
                    continue;
                IPath currentPath = entries[i].getPath();
                if (JavaRuntime.newDefaultJREContainerPath().matchingFirstSegments(currentPath) == 0)
                    continue;

                IPath validPath = JavaRuntime.newJREContainerPath(env);
                if (!validPath.equals(currentPath)) {
                    // Check if the user is using a perfect match JRE
                    IVMInstall vm = JavaRuntime.getVMInstall(currentPath);
                    if (vm == null || !env.isStrictlyCompatible(vm)) {
                        report(NLS.bind(MDECoreMessages.BundleErrorReporter_reqExecEnv_conflict, bundleEnvs[0]),
                                getLine(header, bundleEnvs[0]), sev, MDEMarkerFactory.M_MISMATCHED_EXEC_ENV,
                                MDEMarkerFactory.CAT_EE);
                    }
                }
            }
        } catch (JavaModelException e) {
        }
    }
    IExecutionEnvironment[] systemEnvs = JavaRuntime.getExecutionEnvironmentsManager()
            .getExecutionEnvironments();
    for (int i = 0; i < bundleEnvs.length; i++) {
        boolean found = false;
        for (int j = 0; j < systemEnvs.length; j++) {
            if (bundleEnvs[i].equals(systemEnvs[j].getId())) {
                found = true;
                break;
            }
        }
        if (!found) {
            report(NLS.bind(MDECoreMessages.BundleErrorReporter_reqExecEnv_unknown, bundleEnvs[i]),
                    getLine(header, bundleEnvs[i]), sev, MDEMarkerFactory.M_UNKNOW_EXEC_ENV,
                    MDEMarkerFactory.CAT_EE);
            break;
        }
    }
}

From source file:com.siteview.mde.internal.core.ClasspathComputer.java

License:Open Source License

/**
 * Returns a new classpath container entry for the given execution environment.  If the given java project
 * has an existing JRE/EE classpath entry, the access rules, extra attributes and isExported settings of
 * the existing entry will be added to the new execution entry.
 *  /*from   www.jav  a 2s.c o m*/
 * @param javaProject project to check for existing classpath entries
 * @param ee id of the execution environment to create an entry for
 * @param path id of the container to create an entry for
 * 
 * @return new classpath container entry
 * @throws CoreException if there is a problem accessing the classpath entries of the project
 */
public static IClasspathEntry createEntryUsingPreviousEntry(IJavaProject javaProject, String ee, IPath path)
        throws CoreException {
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    for (int i = 0; i < entries.length; i++) {
        if (entries[i].getPath().equals(path)) {
            if (path.equals(MDECore.JRE_CONTAINER_PATH))
                return JavaCore.newContainerEntry(getEEPath(ee), entries[i].getAccessRules(),
                        entries[i].getExtraAttributes(), entries[i].isExported());

            return JavaCore.newContainerEntry(path, entries[i].getAccessRules(),
                    entries[i].getExtraAttributes(), entries[i].isExported());
        }
    }

    if (path.equals(MDECore.JRE_CONTAINER_PATH))
        return createJREEntry(ee);

    return JavaCore.newContainerEntry(path);
}

From source file:com.siteview.mde.internal.core.ClasspathHelper.java

License:Open Source License

private static Map getClasspathMap(IProject project, boolean checkExcluded, boolean onlyJarsIfLinked,
        boolean absolutePaths) throws JavaModelException {
    List excluded = getFoldersToExclude(project, checkExcluded);
    IJavaProject jProject = JavaCore.create(project);
    HashMap map = new HashMap();
    IClasspathEntry[] entries = jProject.getRawClasspath();
    for (int i = 0; i < entries.length; i++) {
        // most of the paths we get will be project relative, so we need to make the paths relative
        // we will have problems adding an "absolute" path that is workspace relative
        IPath output = null, source = null;
        if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            source = entries[i].getPath();
            output = entries[i].getOutputLocation();
            if (output == null)
                output = jProject.getOutputLocation();
        } else if (entries[i].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            source = entries[i].getPath();
            output = entries[i].getPath();
            if (source.segmentCount() == 1)
                source = new Path(DOT);
        }/* w w w  .  ja va 2 s .c  o m*/
        if (output != null && !excluded.contains(output)) {
            IResource file = project.findMember(output.removeFirstSegments(1));
            // make the path either relative or absolute
            if (file != null) {
                boolean isLinked = file.isLinked(IResource.CHECK_ANCESTORS);
                if (entries[i].getEntryKind() != IClasspathEntry.CPE_SOURCE && !isLinked && onlyJarsIfLinked)
                    continue;
                output = (isLinked || absolutePaths) ? file.getLocation().makeAbsolute()
                        : output.makeRelative();
            } else
                continue;
            ArrayList list = (ArrayList) map.get(source);
            if (list == null)
                list = new ArrayList();
            list.add(output);
            map.put(source, list);
        }
    }
    return map;
}

From source file:com.siteview.mde.internal.core.exports.WorkspaceExportHelper.java

License:Open Source License

private Map getPluginOutputFolders(IBuildModel buildModel, IJavaProject javaProject) throws JavaModelException {
    Map outputEntries = new HashMap();

    IBuildEntry[] buildEntries = buildModel.getBuild().getBuildEntries();
    for (int i = 0; i < buildEntries.length; i++) {
        String name = buildEntries[i].getName();
        if (name.startsWith(IBuildPropertiesConstants.PROPERTY_SOURCE_PREFIX)) {
            Set outputPaths = new HashSet();

            String[] sourceFolders = buildEntries[i].getTokens();
            for (int j = 0; j < sourceFolders.length; j++) {

                IClasspathEntry[] classpathEntries = javaProject.getRawClasspath();
                for (int k = 0; k < classpathEntries.length; k++) {
                    if (classpathEntries[k].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                        IPath sourcePath = classpathEntries[k].getPath().removeFirstSegments(1); // Entries include project as first segment
                        if (sourcePath.equals(new Path(sourceFolders[j]))) {
                            IPath outputPath = classpathEntries[k].getOutputLocation();
                            if (outputPath == null) {
                                outputPath = javaProject.getOutputLocation();
                            }/*from ww  w.  ja v  a2s. co  m*/
                            outputPaths.add(outputPath.removeFirstSegments(1)); // Entries include project as first segment
                        }
                    }
                }
            }
            if (!outputPaths.isEmpty()) {
                outputEntries.put(name.substring(IBuildPropertiesConstants.PROPERTY_SOURCE_PREFIX.length()),
                        outputPaths);
            }
        }
    }
    return outputEntries;
}

From source file:com.siteview.mde.internal.core.project.BundleProjectDescription.java

License:Open Source License

/**
 * Creates and returns a bundle claspath specifications for the given source.<library> build
 * entry//from   w w w.  ja  v  a2s .co m
 * 
 * @param project
 * @param entry
 * @param binary whether a binary folder (<code>true</code>) or source folder (<code>false</code>)
 * @return associated bundle classpath specifications or <code>null</code> if a malformed entry
 * @throws CoreException if unable to access Java build path
 */
private IBundleClasspathEntry[] getClasspathEntries(IProject project, IBuildEntry entry, boolean binary)
        throws CoreException {
    String[] tokens = entry.getTokens();
    IPath lib = null;
    if (binary) {
        lib = new Path(entry.getName().substring(IBuildEntry.OUTPUT_PREFIX.length()));
    } else {
        lib = new Path(entry.getName().substring(IBuildEntry.JAR_PREFIX.length()));
    }
    if (tokens != null && tokens.length > 0) {
        IBundleClasspathEntry[] bces = new IBundleClasspathEntry[tokens.length];
        for (int i = 0; i < tokens.length; i++) {
            IPath path = new Path(tokens[i]);
            IBundleClasspathEntry spec = null;
            if (binary) {
                spec = getBundleProjectService().newBundleClasspathEntry(null, path, lib);
            } else {
                IJavaProject jp = JavaCore.create(project);
                IPath output = null;
                if (jp.exists()) {
                    IClasspathEntry[] rawClasspath = jp.getRawClasspath();
                    for (int j = 0; j < rawClasspath.length; j++) {
                        IClasspathEntry cpe = rawClasspath[j];
                        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                            if (cpe.getPath().removeFirstSegments(1).equals(path)) {
                                output = cpe.getOutputLocation();
                                if (output != null) {
                                    output = output.removeFirstSegments(1);
                                }
                                break;
                            }
                        }
                    }
                }
                spec = getBundleProjectService().newBundleClasspathEntry(path, output, lib);
            }
            bces[i] = spec;
        }
        return bces;
    }
    return null;
}

From source file:com.siteview.mde.internal.core.project.ProjectModifyOperation.java

License:Open Source License

/**
 * Creates or modifies a project based on the given description.
 * //from ww  w  .  j a  v  a 2 s .  c o m
 * @param monitor progress monitor or <code>null</code>
 * @param description project description
 * @throws CoreException if project creation fails
 */
public void execute(IProgressMonitor monitor, IBundleProjectDescription description) throws CoreException {
    // retrieve current description of the project to detect differences
    IProject project = description.getProject();
    IBundleProjectService service = (IBundleProjectService) MDECore.getDefault()
            .acquireService(IBundleProjectService.class.getName());
    IBundleProjectDescription before = service.getDescription(project);
    boolean considerRoot = !project.exists();
    String taskName = null;
    boolean jpExisted = false;
    if (project.exists()) {
        taskName = Messages.ProjectModifyOperation_0;
        jpExisted = before.hasNature(JavaCore.NATURE_ID);
    } else {
        taskName = Messages.ProjectModifyOperation_1;
        // new bundle projects get Java and Plug-in natures
        if (description.getNatureIds().length == 0) {
            description
                    .setNatureIds(new String[] { IBundleProjectDescription.PLUGIN_NATURE, JavaCore.NATURE_ID });
        }
    }
    boolean becomeBundle = !before.hasNature(IBundleProjectDescription.PLUGIN_NATURE)
            && description.hasNature(IBundleProjectDescription.PLUGIN_NATURE);

    // set default values when migrating from Java project to bundle project
    if (jpExisted && becomeBundle) {
        if (description.getExecutionEnvironments() == null) {
            // use EE from Java project when unspecified in the description, and a bundle nature is being added
            IJavaProject jp = JavaCore.create(project);
            if (jp.exists()) {
                IClasspathEntry[] classpath = jp.getRawClasspath();
                for (int i = 0; i < classpath.length; i++) {
                    IClasspathEntry entry = classpath[i];
                    if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                        String id = JavaRuntime.getExecutionEnvironmentId(entry.getPath());
                        if (id != null) {
                            description.setExecutionEnvironments(new String[] { id });
                            break;
                        }
                    }
                }
            }
        }
    }
    // other default values when becoming a bundle
    if (becomeBundle) {
        // set default values for where unspecified
        if (description.getBundleVersion() == null) {
            description.setBundleVersion(new Version(1, 0, 0, "qualifier")); //$NON-NLS-1$
        }
    }

    SubMonitor sub = SubMonitor.convert(monitor, taskName, 6);
    // create and open project
    createProject(description);
    // set bundle root for new projects
    if (considerRoot) {
        IFolder folder = null;
        IPath root = description.getBundleRoot();
        if (root != null && !root.isEmpty()) {
            folder = project.getFolder(root);
            CoreUtility.createFolder(folder);
        }
        PDEProject.setBundleRoot(project, folder);
    }
    sub.worked(1);
    configureNatures(description);
    sub.worked(1);
    if (project.hasNature(JavaCore.NATURE_ID)) {
        configureJavaProject(description, before, jpExisted);
    }
    sub.worked(1);
    configureManifest(description, before);
    sub.worked(1);
    configureBuildPropertiesFile(description, before);
    sub.worked(1);

    // project settings for Equinox, Extension Registry, Automated dependency policy,
    // manifest editor launch shortcuts and export wizard
    IEclipsePreferences pref = new ProjectScope(project).getNode(MDECore.PLUGIN_ID);
    if (pref != null) {
        // best guess for automated dependency management: Equinox + Extensions = use required bundle
        if (description.isEquinox() && description.isExtensionRegistry()) {
            pref.remove(ICoreConstants.RESOLVE_WITH_REQUIRE_BUNDLE); // i.e. use required bundle
        } else {
            pref.putBoolean(ICoreConstants.RESOLVE_WITH_REQUIRE_BUNDLE, false);
        }
        if (description.isExtensionRegistry()) {
            pref.remove(ICoreConstants.EXTENSIONS_PROPERTY); // i.e. support extensions
        } else {
            pref.putBoolean(ICoreConstants.EXTENSIONS_PROPERTY, false);
        }
        if (description.isEquinox()) {
            pref.remove(ICoreConstants.EQUINOX_PROPERTY); // i.e. using Equinox
        } else {
            pref.putBoolean(ICoreConstants.EQUINOX_PROPERTY, false);
        }
        String[] shorts = description.getLaunchShortcuts();
        if (shorts == null || shorts.length == 0) {
            pref.remove(ICoreConstants.MANIFEST_LAUNCH_SHORTCUTS); // use defaults
        } else {
            StringBuffer value = new StringBuffer();
            for (int i = 0; i < shorts.length; i++) {
                if (i > 0) {
                    value.append(',');
                }
                value.append(shorts[i]);
            }
            pref.put(ICoreConstants.MANIFEST_LAUNCH_SHORTCUTS, value.toString());
        }
        if (description.getExportWizardId() == null) {
            pref.remove(ICoreConstants.MANIFEST_EXPORT_WIZARD);
        } else {
            pref.put(ICoreConstants.MANIFEST_EXPORT_WIZARD, description.getExportWizardId());
        }
        try {
            pref.flush();
        } catch (BackingStoreException e) {
            throw new CoreException(
                    new Status(IStatus.ERROR, MDECore.PLUGIN_ID, Messages.ProjectModifyOperation_2, e));
        }
    }

    if (fModel.isDirty()) {
        fModel.save();
    }
    sub.worked(1);
    sub.done();
    if (monitor != null) {
        monitor.done();
    }
}