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

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

Introduction

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

Prototype

IClasspathEntry[] readRawClasspath();

Source Link

Document

Returns the raw classpath for the project as defined by its .classpath file from disk, or null if unable to read the file.

Usage

From source file:com.android.ide.eclipse.adt.build.BaseBuilder.java

License:Open Source License

/**
 * Returns an array of external jar files used by the project.
 * @return an array of OS-specific absolute file paths
 *//*from   ww  w .j  a v a 2s.  c o m*/
protected final String[] getExternalJars() {
    // get the current project
    IProject project = getProject();

    // get a java project from it
    IJavaProject javaProject = JavaCore.create(project);

    IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();

    ArrayList<String> oslibraryList = new ArrayList<String>();
    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY
                    || e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                // if this is a classpath variable reference, we resolve it.
                if (e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                    e = JavaCore.getResolvedClasspathEntry(e);
                }

                // get the IPath
                IPath path = e.getPath();

                // check the name ends with .jar
                if (AndroidConstants.EXT_JAR.equalsIgnoreCase(path.getFileExtension())) {
                    boolean local = false;
                    IResource resource = wsRoot.findMember(path);
                    if (resource != null && resource.exists() && resource.getType() == IResource.FILE) {
                        local = true;
                        oslibraryList.add(resource.getLocation().toOSString());
                    }

                    if (local == false) {
                        // if the jar path doesn't match a workspace resource,
                        // then we get an OSString and check if this links to a valid file.
                        String osFullPath = path.toOSString();

                        File f = new File(osFullPath);
                        if (f.exists()) {
                            oslibraryList.add(osFullPath);
                        } else {
                            String message = String.format(Messages.Couldnt_Locate_s_Error, path);
                            AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, message);

                            // Also put a warning marker on the project
                            markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_WARNING);
                        }
                    }
                }
            }
        }
    }

    return oslibraryList.toArray(new String[oslibraryList.size()]);
}

From source file:com.android.ide.eclipse.adt.build.ResourceManagerBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//w  w  w.  j  a va 2  s. co  m
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
    // Get the project.
    IProject project = getProject();

    // Clear the project of the generic markers
    BaseBuilder.removeMarkersFromProject(project, AdtConstants.MARKER_ADT);

    // check for existing target marker, in which case we abort.
    // (this means: no SDK, no target, or unresolvable target.)
    abortOnBadSetup(project);

    // Check the compiler compliance level, displaying the error message
    // since this is the first builder.
    int res = ProjectHelper.checkCompilerCompliance(project);
    String errorMessage = null;
    switch (res) {
    case ProjectHelper.COMPILER_COMPLIANCE_LEVEL:
        errorMessage = Messages.Requires_Compiler_Compliance_5;
    case ProjectHelper.COMPILER_COMPLIANCE_SOURCE:
        errorMessage = Messages.Requires_Source_Compatibility_5;
    case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET:
        errorMessage = Messages.Requires_Class_Compatibility_5;
    }

    if (errorMessage != null) {
        BaseProjectHelper.addMarker(project, AdtConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR);
        AdtPlugin.printErrorToConsole(project, errorMessage);

        // interrupt the build. The next builders will not run.
        stopBuild(errorMessage);
    }

    // Check that the SDK directory has been setup.
    String osSdkFolder = AdtPlugin.getOsSdkFolder();

    if (osSdkFolder == null || osSdkFolder.length() == 0) {
        AdtPlugin.printErrorToConsole(project, Messages.No_SDK_Setup_Error);
        markProject(AdtConstants.MARKER_ADT, Messages.No_SDK_Setup_Error, IMarker.SEVERITY_ERROR);

        // This interrupts the build. The next builders will not run.
        stopBuild(Messages.No_SDK_Setup_Error);
    }

    // check the project has a target
    IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project);
    if (projectTarget == null) {
        // no target. marker has been set by the container initializer: exit silently.
        // This interrupts the build. The next builders will not run.
        stopBuild("Project has no target");
    }

    // check the 'gen' source folder is present
    boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup
    IJavaProject javaProject = JavaCore.create(project);

    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath path = e.getPath();
                if (path.segmentCount() == 2 && path.segment(1).equals(SdkConstants.FD_GEN_SOURCES)) {
                    hasGenSrcFolder = true;
                    break;
                }
            }
        }
    }

    boolean genFolderPresent = false; // whether the gen folder actually exists
    IResource resource = project.findMember(SdkConstants.FD_GEN_SOURCES);
    genFolderPresent = resource != null && resource.exists();

    if (hasGenSrcFolder == false && genFolderPresent) {
        // No source folder setup for 'gen' in the project, but there's already a
        // 'gen' resource (file or folder).
        String message;
        if (resource.getType() == IResource.FOLDER) {
            // folder exists already! This is an error. If the folder had been created
            // by the NewProjectWizard, it'd be a source folder.
            message = String.format(
                    "%1$s already exists but is not a source folder. Convert to a source folder or rename it.",
                    resource.getFullPath().toString());
        } else {
            // resource exists but is not a folder.
            message = String.format(
                    "Resource %1$s is in the way. ADT needs a source folder called 'gen' to work. Rename or delete resource.",
                    resource.getFullPath().toString());
        }

        AdtPlugin.printErrorToConsole(project, message);
        markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);

        // This interrupts the build. The next builders will not run.
        stopBuild(message);
    } else if (hasGenSrcFolder == false || genFolderPresent == false) {
        // either there is no 'gen' source folder in the project (older SDK),
        // or the folder does not exist (was deleted, or was a fresh svn checkout maybe.)

        // In case we are migrating from an older SDK, we go through the current source
        // folders and delete the generated Java files.
        ArrayList<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(javaProject);
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        for (IPath path : sourceFolders) {
            IResource member = root.findMember(path);
            if (member != null) {
                removeDerivedResources(member, monitor);
            }
        }

        // create the new source folder, if needed
        IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
        if (genFolderPresent == false) {
            AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
                    "Creating 'gen' source folder for generated Java files");
            genFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
            genFolder.setDerived(true);
        }

        // add it to the source folder list, if needed only (or it will throw)
        if (hasGenSrcFolder == false) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            entries = ProjectHelper.addEntryToClasspath(entries,
                    JavaCore.newSourceEntry(genFolder.getFullPath()));
            javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
        }

        // refresh the whole project
        project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));
    }

    // Check the preference to be sure we are supposed to refresh
    // the folders.
    if (AdtPlugin.getAutoResRefresh()) {
        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Refreshing_Res);

        // refresh the res folder.
        IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES);
        resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

        // Also refresh the assets folder to make sure the ApkBuilder
        // will now it's changed and will force a new resource packaging.
        IFolder assetsFolder = project.getFolder(AndroidConstants.WS_ASSETS);
        assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.build.builders.ResourceManagerBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// w w  w .  j  a  va  2 s  .  c  o m
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
    // Get the project.
    final IProject project = getProject();
    IJavaProject javaProject = JavaCore.create(project);

    // Clear the project of the generic markers
    removeMarkersFromContainer(project, AdtConstants.MARKER_ADT);

    // check for existing target marker, in which case we abort.
    // (this means: no SDK, no target, or unresolvable target.)
    try {
        abortOnBadSetup(javaProject, null);
    } catch (AbortBuildException e) {
        return null;
    }

    // Check the compiler compliance level, displaying the error message
    // since this is the first builder.
    Pair<Integer, String> result = ProjectHelper.checkCompilerCompliance(project);
    String errorMessage = null;
    switch (result.getFirst().intValue()) {
    case ProjectHelper.COMPILER_COMPLIANCE_LEVEL:
        errorMessage = Messages.Requires_Compiler_Compliance_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_SOURCE:
        errorMessage = Messages.Requires_Source_Compatibility_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET:
        errorMessage = Messages.Requires_Class_Compatibility_s;
        break;
    }

    if (errorMessage != null) {
        errorMessage = String.format(errorMessage,
                result.getSecond() == null ? "(no value)" : result.getSecond());

        if (JavaCore.VERSION_1_7.equals(result.getSecond())) {
            // If the user is trying to target 1.7 but compiling with something older,
            // the error message can be a bit misleading; instead point them in the
            // direction of updating the project's build target.
            Sdk currentSdk = Sdk.getCurrent();
            if (currentSdk != null) {
                IAndroidTarget target = currentSdk.getTarget(project.getProject());
                if (target != null && target.getVersion().getApiLevel() < 19) {
                    errorMessage = "Using 1.7 requires compiling with Android 4.4 "
                            + "(KitKat); currently using " + target.getVersion();
                }

                ProjectState projectState = Sdk.getProjectState(project);
                if (projectState != null) {
                    BuildToolInfo buildToolInfo = projectState.getBuildToolInfo();
                    if (buildToolInfo == null) {
                        buildToolInfo = currentSdk.getLatestBuildTool();
                    }
                    if (buildToolInfo != null && buildToolInfo.getRevision().getMajor() < 19) {
                        errorMessage = "Using 1.7 requires using Android Build Tools "
                                + "version 19 or later; currently using " + buildToolInfo.getRevision();
                    }
                }
            }
        }

        markProject(AdtConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR);
        AdtPlugin.printErrorToConsole(project, errorMessage);

        return null;
    }

    // Check that the SDK directory has been setup.
    String osSdkFolder = AdtPlugin.getOsSdkFolder();

    if (osSdkFolder == null || osSdkFolder.length() == 0) {
        AdtPlugin.printErrorToConsole(project, Messages.No_SDK_Setup_Error);
        markProject(AdtConstants.MARKER_ADT, Messages.No_SDK_Setup_Error, IMarker.SEVERITY_ERROR);

        return null;
    }

    // check the 'gen' source folder is present
    boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup

    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath path = e.getPath();
                if (path.segmentCount() == 2 && path.segment(1).equals(SdkConstants.FD_GEN_SOURCES)) {
                    hasGenSrcFolder = true;
                    break;
                }
            }
        }
    }

    boolean genFolderPresent = false; // whether the gen folder actually exists
    IResource resource = project.findMember(SdkConstants.FD_GEN_SOURCES);
    genFolderPresent = resource != null && resource.exists();

    if (hasGenSrcFolder == false && genFolderPresent) {
        // No source folder setup for 'gen' in the project, but there's already a
        // 'gen' resource (file or folder).
        String message;
        if (resource.getType() == IResource.FOLDER) {
            // folder exists already! This is an error. If the folder had been created
            // by the NewProjectWizard, it'd be a source folder.
            message = String.format(
                    "%1$s already exists but is not a source folder. Convert to a source folder or rename it.",
                    resource.getFullPath().toString());
        } else {
            // resource exists but is not a folder.
            message = String.format(
                    "Resource %1$s is in the way. ADT needs a source folder called 'gen' to work. Rename or delete resource.",
                    resource.getFullPath().toString());
        }

        AdtPlugin.printErrorToConsole(project, message);
        markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);

        return null;
    } else if (hasGenSrcFolder == false || genFolderPresent == false) {
        // either there is no 'gen' source folder in the project (older SDK),
        // or the folder does not exist (was deleted, or was a fresh svn checkout maybe.)

        // In case we are migrating from an older SDK, we go through the current source
        // folders and delete the generated Java files.
        List<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(javaProject);
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        for (IPath path : sourceFolders) {
            IResource member = root.findMember(path);
            if (member != null) {
                removeDerivedResources(member, monitor);
            }
        }

        // create the new source folder, if needed
        IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
        if (genFolderPresent == false) {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
                    "Creating 'gen' source folder for generated Java files");
            genFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        }

        // add it to the source folder list, if needed only (or it will throw)
        if (hasGenSrcFolder == false) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            entries = ProjectHelper.addEntryToClasspath(entries,
                    JavaCore.newSourceEntry(genFolder.getFullPath()));
            javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
        }

        // refresh specifically the gen folder first, as it may break the build
        // if it doesn't arrive in time then refresh the whole project as usual.
        genFolder.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));

        // it seems like doing this fails to properly rebuild the project. the Java builder
        // running right after this builder will not see the gen folder, and will not be
        // restarted after this build. Therefore in this particular case, we start another
        // build asynchronously so that it's rebuilt after this build.
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor m) {
                try {
                    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, m);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });

    }

    // convert older projects which use bin as the eclipse output folder into projects
    // using bin/classes
    IFolder androidOutput = BaseProjectHelper.getAndroidOutputFolder(project);
    IFolder javaOutput = BaseProjectHelper.getJavaOutputFolder(project);
    if (androidOutput.exists() == false || javaOutput == null
            || javaOutput.getParent().equals(androidOutput) == false) {
        // get what we want as the new java output.
        IFolder newJavaOutput = androidOutput.getFolder(SdkConstants.FD_CLASSES_OUTPUT);

        if (androidOutput.exists() == false) {
            androidOutput.create(true /*force*/, true /*local*/, monitor);
        }

        if (newJavaOutput.exists() == false) {
            newJavaOutput.create(true /*force*/, true /*local*/, monitor);
        }

        // set the java output to this project.
        javaProject.setOutputLocation(newJavaOutput.getFullPath(), monitor);

        // need to do a full build. Can't build while we're already building, so launch a
        // job to build it right after this build
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor jobMonitor) {
                try {
                    project.build(IncrementalProjectBuilder.CLEAN_BUILD, jobMonitor);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });
    }

    // check that we have bin/res/
    IFolder binResFolder = androidOutput.getFolder(SdkConstants.FD_RESOURCES);
    if (binResFolder.exists() == false) {
        binResFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 10));
    }

    // Check the preference to be sure we are supposed to refresh
    // the folders.
    if (AdtPrefs.getPrefs().getBuildForceResResfresh()) {
        AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Refreshing_Res);

        // refresh the res folder.
        IFolder resFolder = project.getFolder(AdtConstants.WS_RESOURCES);
        resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

        // Also refresh the assets folder to make sure the ApkBuilder
        // will now it's changed and will force a new resource packaging.
        IFolder assetsFolder = project.getFolder(AdtConstants.WS_ASSETS);
        assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.build.BuildHelper.java

License:Open Source License

/**
 * Computes all the project output and dependencies that must go into building the apk.
 *
 * @param resMarker//w ww . j  av  a 2s .  c o  m
 * @throws CoreException
 */
private void gatherPaths(ResourceMarker resMarker) throws CoreException {
    IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();

    // get a java project for the project.
    IJavaProject javaProject = JavaCore.create(mProject);

    // get the output of the main project
    IPath path = javaProject.getOutputLocation();
    IResource outputResource = wsRoot.findMember(path);
    if (outputResource != null && outputResource.getType() == IResource.FOLDER) {
        mCompiledCodePaths.add(outputResource.getLocation().toOSString());
    }

    // we could use IJavaProject.getResolvedClasspath directly, but we actually
    // want to see the containers themselves.
    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            // ignore non exported entries, unless they're in the DEPEDENCIES container,
            // in which case we always want it (there may be some older projects that
            // have it as non exported).
            if (e.isExported() || (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER
                    && e.getPath().toString().equals(AdtConstants.CONTAINER_DEPENDENCIES))) {
                handleCPE(e, javaProject, wsRoot, resMarker);
            }
        }
    }
}

From source file:com.android.ide.eclipse.adt.internal.build.PostCompilerHelper.java

License:Open Source License

/**
 * Returns an array of external jar files used by the project.
 * @return an array of OS-specific absolute file paths
 *///from w w w  . j  a  v a 2 s  . c  o  m
private final String[] getExternalJars() {
    // get a java project from it
    IJavaProject javaProject = JavaCore.create(mProject);

    IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();

    ArrayList<String> oslibraryList = new ArrayList<String>();
    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY
                    || e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                // if this is a classpath variable reference, we resolve it.
                if (e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                    e = JavaCore.getResolvedClasspathEntry(e);
                }

                // get the IPath
                IPath path = e.getPath();

                // check the name ends with .jar
                if (AndroidConstants.EXT_JAR.equalsIgnoreCase(path.getFileExtension())) {
                    IResource resource = wsRoot.findMember(path);
                    if (resource != null && resource.exists() && resource.getType() == IResource.FILE) {
                        oslibraryList.add(resource.getLocation().toOSString());
                    } else {
                        // if the jar path doesn't match a workspace resource,
                        // then we get an OSString and check if this links to a valid file.
                        String osFullPath = path.toOSString();

                        File f = new File(osFullPath);
                        if (f.exists()) {
                            oslibraryList.add(osFullPath);
                        } else {
                            String message = String.format(Messages.Couldnt_Locate_s_Error, path);
                            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, mProject, message);

                            // Also put a warning marker on the project
                            BaseProjectHelper.markResource(mProject, AndroidConstants.MARKER_PACKAGING, message,
                                    IMarker.SEVERITY_WARNING);
                        }
                    }
                }
            }
        }
    }

    return oslibraryList.toArray(new String[oslibraryList.size()]);
}

From source file:com.android.ide.eclipse.adt.internal.project.BaseProjectHelper.java

License:Open Source License

/**
 * returns a list of source classpath for a specified project
 * @param javaProject/*  w  w  w .  j a v  a 2 s  .  c  o m*/
 * @return a list of path relative to the workspace root.
 */
@NonNull
public static List<IPath> getSourceClasspaths(IJavaProject javaProject) {
    List<IPath> sourceList = Lists.newArrayList();
    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                sourceList.add(e.getPath());
            }
        }
    }

    return sourceList;
}

From source file:com.android.ide.eclipse.adt.internal.project.LibraryClasspathContainerInitializer.java

License:Open Source License

/**
 * Finds all the dependencies of a given project and add them to a project list and
 * a jar list./*ww w.j  a  v  a 2s .c  om*/
 * Only classpath entries that are exported are added, and only Java project (not Android
 * project) are added.
 *
 * @param project the project to query
 * @param projects the referenced project list to add to
 * @param jarFiles the jar list to add to
 * @param includeJarFiles whether to include jar files or just projects. This is useful when
 *           calling on an Android project (value should be <code>false</code>)
 */
private static void getDependencyListFromClasspath(IProject project, Set<IProject> projects, Set<File> jarFiles,
        boolean includeJarFiles) {
    IJavaProject javaProject = JavaCore.create(project);
    IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();

    // we could use IJavaProject.getResolvedClasspath directly, but we actually
    // want to see the containers themselves.
    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            // ignore entries that are not exported
            if (!e.getPath().toString().equals(CONTAINER_DEPENDENCIES) && e.isExported()) {
                processCPE(e, javaProject, wsRoot, projects, jarFiles, includeJarFiles);
            }
        }
    }
}

From source file:com.android.ide.eclipse.adt.internal.resources.manager.ProjectClassLoader.java

License:Open Source License

/**
 * Returns an array of external jar files used by the project.
 * @return an array of OS-specific absolute file paths
 *//*from ww w  .  j  a  v  a2 s  .  com*/
private final URL[] getExternalJars() {
    // get a java project from it
    IJavaProject javaProject = JavaCore.create(mJavaProject.getProject());

    ArrayList<URL> oslibraryList = new ArrayList<URL>();
    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY
                    || e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                // if this is a classpath variable reference, we resolve it.
                if (e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                    e = JavaCore.getResolvedClasspathEntry(e);
                }

                handleClassPathEntry(e, oslibraryList);
            } else if (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                // get the container.
                try {
                    IClasspathContainer container = JavaCore.getClasspathContainer(e.getPath(), javaProject);
                    // ignore the system and default_system types as they represent
                    // libraries that are part of the runtime.
                    if (container != null && container.getKind() == IClasspathContainer.K_APPLICATION) {
                        IClasspathEntry[] entries = container.getClasspathEntries();
                        for (IClasspathEntry entry : entries) {
                            // TODO: Xav -- is this necessary?
                            if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                                entry = JavaCore.getResolvedClasspathEntry(entry);
                            }

                            handleClassPathEntry(entry, oslibraryList);
                        }
                    }
                } catch (JavaModelException jme) {
                    // can't resolve the container? ignore it.
                    AdtPlugin.log(jme, "Failed to resolve ClasspathContainer: %s", e.getPath());
                }
            }
        }
    }

    return oslibraryList.toArray(new URL[oslibraryList.size()]);
}

From source file:com.android.ide.eclipse.auidt.internal.build.builders.ResourceManagerBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  w  w  w.  j a va2  s. co  m
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
    // Get the project.
    final IProject project = getProject();
    IJavaProject javaProject = JavaCore.create(project);

    // Clear the project of the generic markers
    removeMarkersFromContainer(project, AdtConstants.MARKER_ADT);

    // check for existing target marker, in which case we abort.
    // (this means: no SDK, no target, or unresolvable target.)
    try {
        abortOnBadSetup(javaProject);
    } catch (AbortBuildException e) {
        return null;
    }

    // Check the compiler compliance level, displaying the error message
    // since this is the first builder.
    Pair<Integer, String> result = ProjectHelper.checkCompilerCompliance(project);
    String errorMessage = null;
    switch (result.getFirst().intValue()) {
    case ProjectHelper.COMPILER_COMPLIANCE_LEVEL:
        errorMessage = Messages.Requires_Compiler_Compliance_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_SOURCE:
        errorMessage = Messages.Requires_Source_Compatibility_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET:
        errorMessage = Messages.Requires_Class_Compatibility_s;
        break;
    }

    if (errorMessage != null) {
        errorMessage = String.format(errorMessage,
                result.getSecond() == null ? "(no value)" : result.getSecond());

        markProject(AdtConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR);
        AdtPlugin.printErrorToConsole(project, errorMessage);

        return null;
    }

    // Check that the SDK directory has been setup.
    String osSdkFolder = AdtPlugin.getOsSdkFolder();

    if (osSdkFolder == null || osSdkFolder.length() == 0) {
        AdtPlugin.printErrorToConsole(project, Messages.No_SDK_Setup_Error);
        markProject(AdtConstants.MARKER_ADT, Messages.No_SDK_Setup_Error, IMarker.SEVERITY_ERROR);

        return null;
    }

    // check the project has a target
    IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project);
    if (projectTarget == null) {
        // no target. marker has been set by the container initializer: exit silently.
        return null;
    }

    // check the 'gen' source folder is present
    boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup

    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath path = e.getPath();
                if (path.segmentCount() == 2 && path.segment(1).equals(SdkConstants.FD_GEN_SOURCES)) {
                    hasGenSrcFolder = true;
                    break;
                }
            }
        }
    }

    boolean genFolderPresent = false; // whether the gen folder actually exists
    IResource resource = project.findMember(SdkConstants.FD_GEN_SOURCES);
    genFolderPresent = resource != null && resource.exists();

    if (hasGenSrcFolder == false && genFolderPresent) {
        // No source folder setup for 'gen' in the project, but there's already a
        // 'gen' resource (file or folder).
        String message;
        if (resource.getType() == IResource.FOLDER) {
            // folder exists already! This is an error. If the folder had been created
            // by the NewProjectWizard, it'd be a source folder.
            message = String.format(
                    "%1$s already exists but is not a source folder. Convert to a source folder or rename it.",
                    resource.getFullPath().toString());
        } else {
            // resource exists but is not a folder.
            message = String.format(
                    "Resource %1$s is in the way. ADT needs a source folder called 'gen' to work. Rename or delete resource.",
                    resource.getFullPath().toString());
        }

        AdtPlugin.printErrorToConsole(project, message);
        markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);

        return null;
    } else if (hasGenSrcFolder == false || genFolderPresent == false) {
        // either there is no 'gen' source folder in the project (older SDK),
        // or the folder does not exist (was deleted, or was a fresh svn checkout maybe.)

        // In case we are migrating from an older SDK, we go through the current source
        // folders and delete the generated Java files.
        List<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(javaProject);
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        for (IPath path : sourceFolders) {
            IResource member = root.findMember(path);
            if (member != null) {
                removeDerivedResources(member, monitor);
            }
        }

        // create the new source folder, if needed
        IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
        if (genFolderPresent == false) {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
                    "Creating 'gen' source folder for generated Java files");
            genFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        }

        // add it to the source folder list, if needed only (or it will throw)
        if (hasGenSrcFolder == false) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            entries = ProjectHelper.addEntryToClasspath(entries,
                    JavaCore.newSourceEntry(genFolder.getFullPath()));
            javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
        }

        // refresh specifically the gen folder first, as it may break the build
        // if it doesn't arrive in time then refresh the whole project as usual.
        genFolder.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));

        // it seems like doing this fails to properly rebuild the project. the Java builder
        // running right after this builder will not see the gen folder, and will not be
        // restarted after this build. Therefore in this particular case, we start another
        // build asynchronously so that it's rebuilt after this build.
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor m) {
                try {
                    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, m);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });

    }

    // convert older projects which use bin as the eclipse output folder into projects
    // using bin/classes
    IFolder androidOutput = BaseProjectHelper.getAndroidOutputFolder(project);
    IFolder javaOutput = BaseProjectHelper.getJavaOutputFolder(project);
    if (androidOutput.exists() == false || javaOutput == null
            || javaOutput.getParent().equals(androidOutput) == false) {
        // get what we want as the new java output.
        IFolder newJavaOutput = androidOutput.getFolder(SdkConstants.FD_CLASSES_OUTPUT);

        if (androidOutput.exists() == false) {
            androidOutput.create(true /*force*/, true /*local*/, monitor);
        }

        if (newJavaOutput.exists() == false) {
            newJavaOutput.create(true /*force*/, true /*local*/, monitor);
        }

        // set the java output to this project.
        javaProject.setOutputLocation(newJavaOutput.getFullPath(), monitor);

        // need to do a full build. Can't build while we're already building, so launch a
        // job to build it right after this build
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor jobMonitor) {
                try {
                    project.build(IncrementalProjectBuilder.CLEAN_BUILD, jobMonitor);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });
    }

    // check that we have bin/res/
    IFolder binResFolder = androidOutput.getFolder(SdkConstants.FD_RESOURCES);
    if (binResFolder.exists() == false) {
        binResFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 10));
    }

    // Check the preference to be sure we are supposed to refresh
    // the folders.
    if (AdtPrefs.getPrefs().getBuildForceResResfresh()) {
        AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Refreshing_Res);

        // refresh the res folder.
        IFolder resFolder = project.getFolder(AdtConstants.WS_RESOURCES);
        resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

        // Also refresh the assets folder to make sure the ApkBuilder
        // will now it's changed and will force a new resource packaging.
        IFolder assetsFolder = project.getFolder(AdtConstants.WS_ASSETS);
        assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }

    return null;
}

From source file:com.android.ide.eclipse.auidt.internal.build.BuildHelper.java

License:Open Source License

/**
 * Computes all the project output and dependencies that must go into building the apk.
 *
 * @param resMarker//from w  ww.  ja  va 2  s.c o m
 * @throws CoreException
 */
private void gatherPaths(ResourceMarker resMarker) throws CoreException {
    IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();

    // get a java project for the project.
    IJavaProject javaProject = JavaCore.create(mProject);

    // get the output of the main project
    IPath path = javaProject.getOutputLocation();
    IResource outputResource = wsRoot.findMember(path);
    if (outputResource != null && outputResource.getType() == IResource.FOLDER) {
        mCompiledCodePaths.add(outputResource.getLocation().toOSString());
    }

    // we could use IJavaProject.getResolvedClasspath directly, but we actually
    // want to see the containers themselves.
    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            // ignore non exported entries, unless it's the LIBRARIES container,
            // in which case we always want it (there may be some older projects that
            // have it as non exported).
            if (e.isExported() || (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER
                    && e.getPath().toString().equals(AdtConstants.CONTAINER_LIBRARIES))) {
                handleCPE(e, javaProject, wsRoot, resMarker);
            }
        }
    }
}