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

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

Introduction

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

Prototype

IPath getOutputLocation() throws JavaModelException;

Source Link

Document

Returns the default output location for this project as a workspace- relative absolute path.

Usage

From source file:org.drools.eclipse.util.ProjectClassLoader.java

License:Apache License

public static List<URL> getProjectClassPathURLs(IJavaProject project, List<String> alreadyLoadedProjects) {
    List<URL> pathElements = new ArrayList<URL>();
    try {/*from   w ww. j a va 2  s . c  o  m*/
        IClasspathEntry[] paths = project.getResolvedClasspath(true);
        Set<IPath> outputPaths = new HashSet<IPath>();
        if (paths != null) {
            for (int i = 0; i < paths.length; i++) {
                IClasspathEntry path = paths[i];
                if (path.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    URL url = getRawLocationURL(path.getPath());
                    pathElements.add(url);
                } else if (path.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    IPath output = path.getOutputLocation();
                    if (path.getOutputLocation() != null) {
                        outputPaths.add(output);
                    }
                }
            }
        }
        IPath location = getProjectLocation(project.getProject());
        IPath outputPath = location.append(project.getOutputLocation().removeFirstSegments(1));
        pathElements.add(0, outputPath.toFile().toURI().toURL());
        for (IPath path : outputPaths) {
            outputPath = location.append(path.removeFirstSegments(1));
            pathElements.add(0, outputPath.toFile().toURI().toURL());
        }

        // also add classpath of required projects
        for (String projectName : project.getRequiredProjectNames()) {
            if (!alreadyLoadedProjects.contains(projectName)) {
                alreadyLoadedProjects.add(projectName);
                IProject reqProject = project.getProject().getWorkspace().getRoot().getProject(projectName);
                if (reqProject != null) {
                    IJavaProject reqJavaProject = JavaCore.create(reqProject);
                    pathElements.addAll(getProjectClassPathURLs(reqJavaProject, alreadyLoadedProjects));
                }
            }
        }
    } catch (JavaModelException e) {
        DroolsEclipsePlugin.log(e);
    } catch (MalformedURLException e) {
        DroolsEclipsePlugin.log(e);
    } catch (Throwable t) {
        DroolsEclipsePlugin.log(t);
    }
    return pathElements;
}

From source file:org.ebayopensource.turmeric.eclipse.errorlibrary.buildsystem.core.ErrorLibraryBuildSystemConfigurer.java

License:Open Source License

/**
 * Adds the java support.//from   w w w.  ja v a 2s.c  om
 *
 * @param errorLibraryProject the error library project
 * @param outputLocation the output location
 * @param monitor the monitor
 * @throws CoreException the core exception
 */
public static void addJavaSupport(SOAErrorLibraryProject errorLibraryProject, String outputLocation,
        IProgressMonitor monitor) throws CoreException {
    final IProject project = errorLibraryProject.getProject();
    boolean changedClasspath = false;
    if (JDTUtil.addJavaNature(project, monitor)) {
        changedClasspath = true;
    }
    // Configuring the Java Project
    final IJavaProject javaProject = JavaCore.create(project);
    final List<IClasspathEntry> classpath = JDTUtil.rawClasspath(javaProject, true);
    final List<IClasspathEntry> classpathContainers = new ArrayList<IClasspathEntry>();
    // TODO Lets see if we need this
    if (outputLocation.equals(javaProject.getOutputLocation()) == false) {
        final IFolder outputDirClasses = project.getFolder(outputLocation);
        javaProject.setOutputLocation(outputDirClasses.getFullPath(), monitor);
        changedClasspath = true;
    }

    // Dealing with the case where the root of the project is set to be the
    // src and bin destinations... bad... bad...
    for (final Iterator<IClasspathEntry> iterator = classpath.iterator(); iterator.hasNext();) {
        final IClasspathEntry entry = iterator.next();
        if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            classpathContainers.add(entry);
        }
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE
                || !entry.getPath().equals(new Path("/" + project.getName())))
            continue;
        iterator.remove();
        changedClasspath |= true;
    }
    for (final SOAProjectSourceDirectory dir : errorLibraryProject.getSourceDirectories()) {
        if (!WorkspaceUtil.isDotDirectory(dir.getLocation())) {
            final IFolder source = project.getFolder(dir.getLocation());
            // If the Java project existed previously, checking if
            // directories
            // already exist in
            // its classpath.
            boolean found = false;
            for (final IClasspathEntry entry : classpath) {
                if (!entry.getPath().equals(source.getFullPath()))
                    continue;
                found = true;
                break;
            }
            if (found)
                continue;
            changedClasspath |= true;
            IPath[] excludePatterns = ClasspathEntry.EXCLUDE_NONE;
            if (dir.getExcludePatterns() != null) {
                int length = dir.getExcludePatterns().length;
                excludePatterns = new Path[length];
                for (int i = 0; i < length; i++) {
                    excludePatterns[i] = new Path(dir.getExcludePatterns()[i]);
                }
            }
            IPath outputPath = dir.getOutputLocation() != null
                    ? project.getFolder(dir.getOutputLocation()).getFullPath()
                    : null;
            final IClasspathEntry entry = JavaCore.newSourceEntry(source.getFullPath(), excludePatterns,
                    outputPath);
            classpath.add(entry);
        }
    }
    ProgressUtil.progressOneStep(monitor);
    // Adding the runtime library
    boolean found = false;
    for (final IClasspathEntry entry : classpath) {
        // All JRE Containers should have a prefix of
        // org.eclipse.jdt.launching.JRE_CONTAINER
        if (JavaRuntime.newDefaultJREContainerPath().isPrefixOf(entry.getPath())
                && JavaRuntime.newDefaultJREContainerPath().equals(entry.getPath())) {
            found = true;
            break;
        }
    }
    if (!found) {
        changedClasspath = true;
        classpath.add(JavaRuntime.getDefaultJREContainerEntry());
    }
    // we want all classpath containers to be the end of .classpath file
    classpath.removeAll(classpathContainers);
    classpath.addAll(classpathContainers);

    ProgressUtil.progressOneStep(monitor);
    // Configuring the classpath of the Java Project
    if (changedClasspath) {
        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[0]), null);
    }
}

From source file:org.ebayopensource.turmeric.eclipse.utils.plugin.JDTUtil.java

License:Open Source License

/**
 * Adds the java support to eclipse project.
 * ie soa nature is added here.//ww  w .  ja  v a2s  .  co m
 * Class Path container related linking etc..
 *
 * @param project the project
 * @param sourceDirectories the source directories
 * @param defaultCompilerLevel the default compiler level
 * @param outputLocation the output location
 * @param monitor the monitor
 * @throws CoreException the core exception
 */
public static void addJavaSupport(IProject project, List<String> sourceDirectories, String defaultCompilerLevel,
        String outputLocation, IProgressMonitor monitor) throws CoreException {

    boolean changedClasspath = false;
    if (addJavaNature(project, monitor)) {
        changedClasspath = true;
    }
    // Configuring the Java Project
    final IJavaProject javaProject = JavaCore.create(project);
    final List<IClasspathEntry> classpath = JDTUtil.rawClasspath(javaProject, true);
    if (outputLocation.equals(javaProject.getOutputLocation()) == false) {
        final IFolder outputDirClasses = project.getFolder(outputLocation);
        javaProject.setOutputLocation(outputDirClasses.getFullPath(), monitor);
        changedClasspath = true;
    }

    // Dealing with the case where the root of the project is set to be the
    // src and bin destinations... bad... bad...
    for (final Iterator<IClasspathEntry> iterator = classpath.iterator(); iterator.hasNext();) {
        final IClasspathEntry entry = iterator.next();
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE
                || !entry.getPath().equals(new Path("/" + project.getName())))
            continue;
        iterator.remove();
        changedClasspath |= true;
    }
    for (final String dir : sourceDirectories) {

        final IFolder source = project.getFolder(dir);
        // If the Java project existed previously, checking if directories
        // already exist in
        // its classpath.
        boolean found = false;
        for (final IClasspathEntry entry : classpath) {
            if (!entry.getPath().equals(source.getFullPath()))
                continue;
            found = true;
            break;
        }
        if (found)
            continue;
        changedClasspath |= true;
        classpath.add(JavaCore.newSourceEntry(source.getFullPath()));
    }
    ProgressUtil.progressOneStep(monitor, 10);
    // Adding the runtime library
    boolean found = false;
    for (final IClasspathEntry entry : classpath) {
        // All JRE Containers should have a prefix of
        // org.eclipse.jdt.launching.JRE_CONTAINER
        if (JavaRuntime.newDefaultJREContainerPath().isPrefixOf(entry.getPath())
                && JavaRuntime.newDefaultJREContainerPath().equals(entry.getPath())) {
            found = true;
            break;
        }
    }
    if (!found) {
        changedClasspath = true;
        classpath.add(JavaRuntime.getDefaultJREContainerEntry());
    }
    ProgressUtil.progressOneStep(monitor);
    // Configuring the classpath of the Java Project
    if (changedClasspath) {
        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[0]), null);
    }

    IProjectFacetVersion projectFacetVersion = JavaFacetUtils.JAVA_60;
    if (StringUtils.isNotBlank(defaultCompilerLevel)) {
        try {
            projectFacetVersion = JavaFacetUtils.compilerLevelToFacet(defaultCompilerLevel);
        } catch (Exception e) {
            Logger.getLogger(JDTUtil.class.getName()).throwing(JDTUtil.class.getName(), "addJavaSupport", e);
        }
    }

    JavaFacetUtils.setCompilerLevel(project, projectFacetVersion);
}

From source file:org.ebayopensource.turmeric.eclipse.utils.plugin.JDTUtil.java

License:Open Source License

private static void resolveClasspathToURLs(final IJavaProject javaProject, final Set<URL> resolvedEntries,
        final Set<String> visited) throws JavaModelException, IOException {
    if (javaProject == null || !javaProject.exists())
        return;//  w w  w .  j  a  v a2  s. co m
    final String projectName = javaProject.getProject().getName();
    if (visited.contains(projectName))
        return;
    visited.add(projectName);
    for (final IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            resolveClasspathToURLs(JavaCore.create(WorkspaceUtil.getProject(entry.getPath())), resolvedEntries,
                    visited);
        } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            resolvedEntries.add(WorkspaceUtil.getLocation(entry.getPath()).toFile().toURI().toURL());

        } else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath location = entry.getOutputLocation() != null ? entry.getOutputLocation()
                    : javaProject.getOutputLocation();
            if (location.toString().startsWith(WorkspaceUtil.PATH_SEPERATOR + projectName)) {
                //it happens that the path is not absolute
                location = javaProject.getProject().getFolder(location.removeFirstSegments(1)).getLocation();
            }

            resolvedEntries.add(location.toFile().toURI().toURL());
        }
    }
}

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>();
    }/*from   w  w  w .  j av  a 2 s.c o  m*/

    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.command.src.JavacCommand.java

License:Open Source License

/**
 * {@inheritDoc}/*from  www .j  av a 2  s. c  o  m*/
 * @see org.eclim.command.Command#execute(CommandLine)
 */
public String execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    IProject project = ProjectUtils.getProject(projectName);
    IJavaProject javaProject = JavaUtils.getJavaProject(project);

    Project antProject = new Project();
    BuildLogger buildLogger = new DefaultLogger();
    buildLogger.setMessageOutputLevel(Project.MSG_INFO);
    buildLogger.setOutputPrintStream(getContext().out);
    buildLogger.setErrorPrintStream(getContext().err);
    antProject.addBuildListener(buildLogger);
    antProject.setBasedir(ProjectUtils.getPath(project));
    //antProject.setProperty(
    //    "build.compiler", "org.eclipse.jdt.core.JDTCompilerAdapter");

    Javac javac = new Javac();
    javac.setTaskName("javac");
    javac.setProject(antProject);
    javac.setFork(true);
    File outputDir = new File(ProjectUtils.getFilePath(project, javaProject.getOutputLocation().toOSString()));
    outputDir.mkdirs();
    javac.setDestdir(outputDir);

    // construct classpath
    Path classpath = new Path(antProject);
    String[] paths = ClasspathUtils.getClasspath(javaProject);
    for (String path : paths) {
        Path.PathElement pe = classpath.createPathElement();
        pe.setPath(path);
    }
    javac.setClasspath(classpath);

    // construct sourcepath
    String sourcepath = ProjectUtils.getSetting(project, "org.eclim.java.compile.sourcepath");
    if (sourcepath != null && !sourcepath.trim().equals(StringUtils.EMPTY)) {
        paths = StringUtils.split(sourcepath, " ");
    } else {
        paths = ClasspathUtils.getSrcPaths(javaProject);
    }
    for (String path : paths) {
        Path src = javac.createSrc();
        src.setPath(path);
    }
    javac.setIncludes("**/*.java");

    try {
        javac.execute();
    } catch (BuildException be) {
        // just print the message: should just indicate that something didn't compile.
        println(be.getMessage());
    }

    return StringUtils.EMPTY;
}

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

License:Open Source License

/**
 * Sets the classpath for the supplied project.
 *
 * @param javaProject The project./*w  w  w .j  av  a2s . com*/
 * @param entries The classpath entries.
 * @param classpath The file path of the .classpath file.
 * @return Array of Error or null if no errors reported.
 */
protected List<Error> setClasspath(IJavaProject javaProject, IClasspathEntry[] entries, String classpath)
        throws Exception {
    FileOffsets offsets = FileOffsets.compile(classpath);
    String classpathValue = IOUtils.toString(new FileInputStream(classpath));
    ArrayList<Error> errors = new ArrayList<Error>();
    for (IClasspathEntry entry : entries) {
        IJavaModelStatus status = JavaConventions.validateClasspathEntry(javaProject, entry, true);
        if (!status.isOK()) {
            errors.add(createErrorForEntry(javaProject, entry, status, offsets, classpath, classpathValue));
        }
    }

    IJavaModelStatus status = JavaConventions.validateClasspath(javaProject, entries,
            javaProject.getOutputLocation());

    // always set the classpathValue anyways, so that the user can correct the
    // file.
    //if(status.isOK() && errors.isEmpty()){
    javaProject.setRawClasspath(entries, null);
    javaProject.makeConsistent(null);
    //}

    if (!status.isOK()) {
        errors.add(new Error(status.getMessage(), classpath, 1, 1, false));
    }
    return errors;
}

From source file:org.eclim.plugin.jdt.util.ClasspathUtils.java

License:Open Source License

/**
 * Recursively collects classpath entries from the current and dependent
 * projects./*from  w  ww  . ja  v a  2 s .c  om*/
 */
private static void collect(IJavaProject javaProject, List<String> paths, Set<IJavaProject> visited,
        boolean isFirstProject) throws Exception {
    if (visited.contains(javaProject)) {
        return;
    }
    visited.add(javaProject);

    try {
        IPath out = javaProject.getOutputLocation();
        paths.add(ProjectUtils.getFilePath(javaProject.getProject(), out.addTrailingSeparator().toOSString()));
    } catch (JavaModelException ignore) {
        // ignore... just signals that no output dir was configured.
    }

    IProject project = javaProject.getProject();
    String name = project.getName();

    IClasspathEntry[] entries = null;
    try {
        entries = javaProject.getResolvedClasspath(true);
    } catch (JavaModelException jme) {
        // this may or may not be a problem.
        logger.warn("Unable to retrieve resolved classpath for project: " + name, jme);
        return;
    }

    final List<IJavaProject> nextProjects = new ArrayList<IJavaProject>();
    for (IClasspathEntry entry : entries) {
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_CONTAINER:
        case IClasspathEntry.CPE_VARIABLE:
            String path = entry.getPath().toOSString().replace('\\', '/');
            if (path.startsWith("/" + name + "/")) {
                path = ProjectUtils.getFilePath(project, path);
            }
            paths.add(path);
            break;
        case IClasspathEntry.CPE_PROJECT:
            if (isFirstProject || entry.isExported()) {
                javaProject = JavaUtils.getJavaProject(entry.getPath().segment(0));
                if (javaProject != null) {
                    // breadth first, not depth first, to preserve dependency ordering
                    nextProjects.add(javaProject);
                }
            }
            break;
        case IClasspathEntry.CPE_SOURCE:
            IPath out = entry.getOutputLocation();
            if (out != null) {
                paths.add(ProjectUtils.getFilePath(javaProject.getProject(),
                        out.addTrailingSeparator().toOSString()));
            }
            break;
        }
    }
    // depth second
    for (final IJavaProject nextProject : nextProjects) {
        collect(nextProject, paths, visited, false);
    }
}

From source file:org.eclipse.acceleo.common.internal.utils.workspace.AcceleoWorkspaceUtil.java

License:Open Source License

/**
 * This will return the set of output folders name for the given (java) project.
 * <p>/*from w w  w  .  j a v a2 s. c o m*/
 * For example, if a project has a source folder "src" with its output folder set as "bin" and a source
 * folder "src-gen" with its output folder set as "bin-gen", this will return a LinkedHashSet containing
 * both "bin" and "bin-gen".
 * </p>
 * 
 * @param project
 *            The project we seek the output folders of.
 * @return The set of output folders name for the given (java) project.
 */
private static Set<String> getOutputFolders(IProject project) {
    final Set<String> classpathEntries = new CompactLinkedHashSet<String>();
    final IJavaProject javaProject = JavaCore.create(project);
    try {
        for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                final IPath output = entry.getOutputLocation();
                if (output != null) {
                    classpathEntries.add(output.removeFirstSegments(1).toString());
                }
            }
        }
        /*
         * Add the default output location to the classpath anyway since source folders are not required
         * to have their own
         */
        final IPath output = javaProject.getOutputLocation();
        classpathEntries.add(output.removeFirstSegments(1).toString());
    } catch (JavaModelException e) {
        AcceleoCommonPlugin.log(e, false);
    }
    return classpathEntries;
}

From source file:org.eclipse.acceleo.ide.ui.resources.AcceleoProject.java

License:Open Source License

/**
 * Gets the output folder of the project. For example : '/MyProject/bin'.
 * //from w  ww.  j  ava  2  s.  co m
 * @param aProject
 *            is a project of the workspace
 * @return the output folder of the project, or null if it doesn't exist
 * @see org.eclipse.acceleo.internal.ide.ui.editors.template.actions.refactor.AcceleoRefactoringUtils#getOutputFolder(IProject
 *      aProject)
 */
private static IFolder getOutputFolder(IProject aProject) {
    final IJavaProject javaProject = JavaCore.create(aProject);
    try {
        IPath output = javaProject.getOutputLocation();
        if (output != null && output.segmentCount() > 1) {
            IFolder folder = aProject.getWorkspace().getRoot().getFolder(output);
            if (folder.isAccessible()) {
                return folder;
            }
        }
    } catch (JavaModelException e) {
        // continue
        AcceleoUIActivator.getDefault().getLog().log(e.getStatus());
    }
    return null;
}