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

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

Introduction

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

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:org.datanucleus.ide.eclipse.jobs.LaunchUtilities.java

License:Open Source License

/**
 * Utility method to obtain the classpath entries for the given <code>IJavaProject</code>
 * @param javaProject The <code>IJavaProject</code> the classpath should be obtained for
 * @return A <code>List</code> of valid classpath entries as <code>String</code> values
 * @throws CoreException//from  w w w  . j ava  2 s .  c om
 */
public static List getDefaultClasspath(IJavaProject javaProject) throws CoreException {
    List classpath = new ArrayList();

    IRuntimeClasspathEntry outputEntry = JavaRuntime.newDefaultProjectClasspathEntry(javaProject);
    classpath.add(outputEntry.getMemento());

    IPath systemLibsPath = new Path(JavaRuntime.JRE_CONTAINER);
    IRuntimeClasspathEntry systemLibsEntry = JavaRuntime.newRuntimeContainerClasspathEntry(systemLibsPath,
            IRuntimeClasspathEntry.STANDARD_CLASSES);
    classpath.add(systemLibsEntry.getMemento());

    String useProjectSettingsStr = javaProject.getResource().getPersistentProperty(
            new QualifiedName("org.datanucleus.ide.eclipse.preferences.general", "useProjectSettings"));
    boolean useProjectSettings = useProjectSettingsStr != null ? Boolean.parseBoolean(useProjectSettingsStr)
            : false;

    boolean useProjectClasspath = Plugin.getDefault().getPreferenceStore()
            .getBoolean(PreferenceConstants.USE_PROJECT_CLASSPATH);
    if (useProjectSettings) {
        String useProjCPStr = javaProject.getResource().getPersistentProperty(new QualifiedName(
                "org.datanucleus.ide.eclipse.preferences.general", PreferenceConstants.USE_PROJECT_CLASSPATH));
        useProjectClasspath = (useProjCPStr != null ? Boolean.parseBoolean(useProjCPStr) : false);
    }

    if (!useProjectClasspath) {
        // Add on user-defined classpath jars if required
        String classpathEntries = useProjectSettings ? javaProject.getResource()
                .getPersistentProperty(new QualifiedName("org.datanucleus.ide.eclipse.preferences.general",
                        PreferenceConstants.CLASSPATH_ENTRIES))
                : Plugin.getDefault().getPreferenceStore().getString(PreferenceConstants.CLASSPATH_ENTRIES);
        IRuntimeClasspathEntry preferenceEntry = JavaRuntime.newStringVariableClasspathEntry(classpathEntries);
        classpath.add(preferenceEntry.getMemento());
    }

    return classpath;
}

From source file:org.ebayopensource.vjet.eclipse.core.ClassPathUtils.java

License:Open Source License

public static URL[] getProjectDependencyUrls(List<IJavaProject> javaProjectList, List<URL> currentUrlList,
        HashMap<String, String> projectMap) throws JavaModelException, MalformedURLException {

    List<URL> projectDependencyUrlList = currentUrlList;

    if (projectDependencyUrlList == null) {
        projectDependencyUrlList = new ArrayList<URL>();
    }/*ww w  .j a va  2s.c om*/

    for (IJavaProject project : javaProjectList) {

        if (projectMap.containsKey(project.getElementName()) == true) {
            continue;
        } else {
            projectMap.put(project.getElementName(), project.getElementName());
        }

        // Add the dependencies to the URL list
        IClasspathEntry[] entries;
        entries = project.getResolvedClasspath(true);

        for (IClasspathEntry entry : entries) {

            IPath path = entry.getPath();
            File f = path.toFile();
            URL entryUrl;
            entryUrl = f.toURI().toURL();
            switch (entry.getEntryKind()) {

            case IClasspathEntry.CPE_LIBRARY:
                if (projectDependencyUrlList.contains(entryUrl) == false) {
                    projectDependencyUrlList.add(entryUrl);
                }
                break;

            case IClasspathEntry.CPE_PROJECT:
                List<IJavaProject> subjavaProjectList = new ArrayList<IJavaProject>();
                IResource subResource = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());
                if (subResource == null) {
                    // String projectName = entry.getPath().toString();
                    // String parentProjectName = project.getElementName();
                    // throw new EclipseProjectNotFoundException(
                    // projectName,
                    // MessageFormat
                    // .format(
                    // "The dependent project {0} of project {1} is not
                    // available.\nPlease update your workspace to include
                    // this project",
                    // projectName, parentProjectName));
                }
                if (subResource != null && subResource.getType() == IResource.PROJECT) {
                    IProject subProject = (IProject) subResource;
                    IJavaProject subJavaProject = JavaCore.create(subProject);
                    if (subJavaProject != null && subJavaProject.exists()) {
                        subjavaProjectList.add(subJavaProject);

                        // Recursively call our selves to populate the
                        // project
                        // dependency's for the sub projects.
                        getProjectDependencyUrls(subjavaProjectList, projectDependencyUrlList, projectMap);
                    }

                }
                break;

            default:
                break;
            }
        }

        IPath path = project.getOutputLocation();
        IPath projectResourceLocation = project.getResource().getLocation();
        File projectFilePath = projectResourceLocation.append(path.removeFirstSegments(1)).toFile();
        URL projectOutputUrl;
        projectOutputUrl = projectFilePath.toURI().toURL();

        if (projectDependencyUrlList.contains(projectOutputUrl) == false) {
            projectDependencyUrlList.add(projectOutputUrl);
        }
    }

    URL[] arrayList = new URL[projectDependencyUrlList.size()];
    URL[] returnURLArray = projectDependencyUrlList.toArray(arrayList);

    return returnURLArray;

}

From source file:org.eclim.plugin.jdt.project.JavaProjectManager.java

License:Open Source License

@Override
public List<Error> update(IProject project, CommandLine commandLine) throws Exception {
    String buildfile = commandLine.getValue(Options.BUILD_FILE_OPTION);

    IJavaProject javaProject = JavaUtils.getJavaProject(project);
    javaProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);

    // validate that .classpath xml is well formed and valid.
    PluginResources resources = (PluginResources) Services.getPluginResources(PluginResources.NAME);
    List<Error> errors = XmlUtils.validateXml(javaProject.getProject().getName(), CLASSPATH,
            resources.getResource(CLASSPATH_XSD).toString());
    if (errors.size() > 0) {
        return errors;
    }/*w  ww  .j  a v a2  s  .  c o  m*/

    String dotclasspath = javaProject.getProject().getFile(CLASSPATH).getRawLocation().toOSString();

    // ivy.xml, pom.xml, etc updated.
    if (buildfile != null) {
        try {
            IClasspathEntry[] entries = mergeWithBuildfile(javaProject, buildfile);
            errors = setClasspath(javaProject, entries, dotclasspath);
        } catch (IllegalStateException ise) {
            errors.add(new Error(ise.getMessage(), buildfile, 1, 1, false));
        }

        // .classpath updated.
    } else {
        // if an exception occurs reading the classpath then eclipse will return a
        // default classpath which we would otherwise then write back into the
        // .classpath file. This hack prevents that and will return a relevent
        // error message as a validation error.
        try {
            ((JavaProject) javaProject).readFileEntriesWithException(null);
        } catch (Exception e) {
            errors.add(new Error(e.getMessage(), dotclasspath, 1, 1, false));
            return errors;
        }

        IClasspathEntry[] entries = javaProject.readRawClasspath();
        errors = setClasspath(javaProject, entries, dotclasspath);
    }

    if (errors.size() > 0) {
        return errors;
    }
    return null;
}

From source file:org.eclipse.ajdt.core.tests.builder.AJBuilderTest.java

License:Open Source License

private boolean outputDirContainsFile(IProject project, String packageName, String fileName)
        throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IPath workspaceRelativeOutputPath = javaProject.getOutputLocation();

    String realOutputLocation = null;
    if (workspaceRelativeOutputPath.segmentCount() == 1) { // project
        // root/*w  ww . ja v  a  2s. c  om*/
        realOutputLocation = javaProject.getResource().getLocation().toOSString();
    } else {
        IFolder out = ResourcesPlugin.getWorkspace().getRoot().getFolder(workspaceRelativeOutputPath);
        realOutputLocation = out.getLocation().toOSString();
    }

    File outputDir = new File(realOutputLocation + File.separator + packageName);
    if (outputDir.exists()) {
        File[] outputFiles = outputDir.listFiles();
        for (int i = 0; i < outputFiles.length; i++) {
            if (outputFiles[i].getName().equals(fileName)) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.eclipse.ajdt.core.tests.builder.AJBuilderTest2.java

License:Open Source License

private boolean outputDirContainsFile(IProject project, String packageName, String fileName)
        throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IPath workspaceRelativeOutputPath = javaProject.getOutputLocation();

    String realOutputLocation = null;
    if (workspaceRelativeOutputPath.segmentCount() == 1) { // project
        // root/*from  www  .  j  a va  2s  . c o m*/
        realOutputLocation = javaProject.getResource().getLocation().toOSString();
    } else {
        IFolder out = ResourcesPlugin.getWorkspace().getRoot().getFolder(workspaceRelativeOutputPath);
        realOutputLocation = out.getLocation().toOSString();
    }

    File outputDir = new File(realOutputLocation + File.separator + packageName);
    File[] outputFiles = outputDir.listFiles();
    for (int i = 0; i < outputFiles.length; i++) {
        if (outputFiles[i].getName().equals(fileName)) {
            return true;
        }
    }
    return false;
}

From source file:org.eclipse.ajdt.internal.core.ajde.CoreOutputLocationManager.java

License:Open Source License

/**
 * Record the 'common output directory', namely the one where all the output
 * goes//  w ww  .  j  a  va 2  s .  c o  m
 */
private void setCommonOutputDir() {
    IJavaProject jProject = JavaCore.create(project);
    IPath workspaceRelativeOutputPath;
    try {
        workspaceRelativeOutputPath = jProject.getOutputLocation();
    } catch (JavaModelException e) {
        commonOutputDir = project.getLocation().toFile();
        outputIsRoot = true;
        return;
    }
    if (workspaceRelativeOutputPath.segmentCount() == 1) {
        commonOutputDir = jProject.getResource().getLocation().toFile();
        outputIsRoot = true;
        return;
    }
    IFolder out = ResourcesPlugin.getWorkspace().getRoot().getFolder(workspaceRelativeOutputPath);
    commonOutputDir = out.getLocation().toFile();
}

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

License:Open Source License

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

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

License:Open Source License

/**
 * Searches for all main methods in the given scope. Also searches 
 * for Aspects that have main methods./*from   w w w. j a va2  s  . co m*/
 */
public IType[] searchMainMethodsIncludingAspects(IProgressMonitor pm, IJavaSearchScope scope,
        boolean includeSubtypes) throws JavaModelException {

    pm.beginTask(LauncherMessages.MainMethodSearchEngine_1, 100);
    IProgressMonitor javaSearchMonitor = new SubProgressMonitor(pm, 100);
    IType[] mainTypes = super.searchMainMethods(javaSearchMonitor, scope, includeSubtypes);
    IProject[] projects = AspectJPlugin.getWorkspace().getRoot().getProjects();

    Set<IType> mainSet = new HashSet<IType>();
    for (int i = 0; i < mainTypes.length; i++) {
        mainSet.add(mainTypes[i]);
    }

    // Bug 261745 --- must search for aspect types in Java files.  
    // these are not found through JDT Weaving
    IProgressMonitor ajSearchMonitor = new SubProgressMonitor(pm, 100);
    ajSearchMonitor.beginTask(LauncherMessages.MainMethodSearchEngine_1, 100);
    double ticksPerProject = Math.floor(100F / (float) projects.length);
    if (ticksPerProject < 1) {
        ticksPerProject = 1;
    }
    IPath[] paths = scope.enclosingProjectsAndJars();
    Set<IPath> pathsSet = new HashSet<IPath>(paths.length * 2);
    for (int i = 0; i < paths.length; i++) {
        pathsSet.add(paths[i]);
    }

    for (int i = 0; i < projects.length; i++) {
        try {
            if (projects[i].hasNature("org.eclipse.ajdt.ui.ajnature")) { //$NON-NLS-1$ 
                IJavaProject jp = JavaCore.create(projects[i]);
                if (jp != null) {
                    if (pathsSet.contains(jp.getResource().getFullPath())) {
                        Set<IFile> includedFiles = BuildConfig.getIncludedSourceFiles(projects[i]);
                        Set<IType> mains = getAllAspectsWithMain(scope, includedFiles);
                        mainSet.addAll(mains);
                    }
                }
            }
        } catch (Exception e) {
        }
        ajSearchMonitor.internalWorked(ticksPerProject);
        ajSearchMonitor.done();
    }
    pm.done();
    return mainSet.toArray(new IType[mainSet.size()]);
}

From source file:org.eclipse.andmore.internal.wizards.exportgradle.ExportGradleTest.java

License:Open Source License

@Test
public void testSimpleAndroidApp() throws Throwable {
    IProject project = getProject("simple-app");
    final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);

    final ProjectSetupBuilder builder = new ProjectSetupBuilder();
    builder.setProject(Collections.singletonList(javaProject));

    Job job = new Job("Validate project") {
        @Override//  w w  w  .  ja  v a 2  s.  com
        protected IStatus run(IProgressMonitor monitor) {
            try {
                BuildFileCreator.createBuildFiles(builder, null, monitor);
                File buildfile = new File(javaProject.getResource().getLocation().toString(),
                        BuildFileCreator.BUILD_FILE);
                assertTrue(buildfile.exists());
                String contents = Files.toString(buildfile, Charsets.UTF_8);
                String expectedContents = "buildscript {\n" + "    repositories {\n" + "        "
                        + BuildFileCreator.MAVEN_REPOSITORY + "\n" + "    }\n" + "    dependencies {\n"
                        + "        " + BuildFileCreator.PLUGIN_CLASSPATH + "\n" + "    }\n" + "}\n"
                        + "apply plugin: 'android'\n" + "\n" + "dependencies {\n" + "}\n" + "\n" + "android {\n"
                        + "    compileSdkVersion 16\n" + "    buildToolsVersion \"16\"\n" + "\n"
                        + "    defaultConfig {\n" + "        minSdkVersion 1\n" + "        targetSdkVersion 1\n"
                        + "    }\n" + "    sourceSets {\n" + "        main {\n"
                        + "            manifest.srcFile 'AndroidManifest.xml'\n"
                        + "            java.srcDirs = ['src']\n" + "            resources.srcDirs = ['src']\n"
                        + "            aidl.srcDirs = ['src']\n"
                        + "            renderscript.srcDirs = ['src']\n" + "            res.srcDirs = ['res']\n"
                        + "            assets.srcDirs = ['assets']\n" + "        }\n"
                        + "        instrumentTest.setRoot('tests')\n" + "    }\n" + "}";

                assertEqualsWhitespaceInsensitive(expectedContents, contents);
            } catch (Throwable t) {
                mLastThrown = t;
            }
            return null;
        }
    };
    job.schedule(1000);
    job.join();
    Object property = job.getProperty(ERROR_KEY);
    assertNull(property);
    if (mLastThrown != null) {
        throw mLastThrown;
    }
}

From source file:org.eclipse.andmore.internal.wizards.exportgradle.ExportGradleTest.java

License:Open Source License

@Test
public void testSimpleAndroidLib() throws Throwable {
    final IProject project = getProject("simple-library");
    ProjectState projectState = Sdk.getProjectState(project.getProject());
    ProjectPropertiesWorkingCopy propertiesWorkingCopy = projectState.getProperties().makeWorkingCopy();
    propertiesWorkingCopy.setProperty(PROPERTY_LIBRARY, "true");
    propertiesWorkingCopy.save();/*from  ww  w .j  av a2  s  .  c  o  m*/
    IResource projectProp = project.findMember(SdkConstants.FN_PROJECT_PROPERTIES);
    if (projectProp != null) {
        projectProp.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
    }

    Job job = new Job("Validate project") {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);

                final ProjectSetupBuilder builder = new ProjectSetupBuilder();
                builder.setProject(Collections.singletonList(javaProject));

                BuildFileCreator.createBuildFiles(builder, null, monitor);
                File buildfile = new File(javaProject.getResource().getLocation().toString(),
                        BuildFileCreator.BUILD_FILE);
                assertTrue(buildfile.exists());
                String contents = Files.toString(buildfile, Charsets.UTF_8);
                String expectedContents = "buildscript {\n" + "    repositories {\n" + "        "
                        + BuildFileCreator.MAVEN_REPOSITORY + "\n" + "    }\n" + "    dependencies {\n"
                        + "        " + BuildFileCreator.PLUGIN_CLASSPATH + "\n" + "    }\n" + "}\n"
                        + "apply plugin: 'android-library'\n" + "\n" + "dependencies {\n" + "}\n" + "\n"
                        + "android {\n" + "    compileSdkVersion 16\n" + "    buildToolsVersion \"16\"\n" + "\n"
                        + "    defaultConfig {\n" + "        minSdkVersion 1\n" + "        targetSdkVersion 1\n"
                        + "    }\n" + "    sourceSets {\n" + "        main {\n"
                        + "            manifest.srcFile 'AndroidManifest.xml'\n"
                        + "            java.srcDirs = ['src']\n" + "            resources.srcDirs = ['src']\n"
                        + "            aidl.srcDirs = ['src']\n"
                        + "            renderscript.srcDirs = ['src']\n" + "            res.srcDirs = ['res']\n"
                        + "            assets.srcDirs = ['assets']\n" + "        }\n"
                        + "        instrumentTest.setRoot('tests')\n" + "    }\n" + "}";

                assertEqualsWhitespaceInsensitive(expectedContents, contents);
            } catch (Throwable t) {
                mLastThrown = t;
            }
            return null;
        }
    };
    job.schedule(1000);
    job.join();
    Object property = job.getProperty(ERROR_KEY);
    assertNull(property);
    if (mLastThrown != null) {
        throw mLastThrown;
    }
}