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

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

Introduction

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

Prototype

IPath getPath();

Source Link

Document

Returns the path of this classpath entry.

Usage

From source file:com.javadude.antxr.eclipse.core.AntxrNature.java

License:Open Source License

public void deconfigure() throws CoreException {
    if (AntxrNature.DEBUG) {
        System.out.println("deconfiguring ANTXR nature");
    }/*from w w  w.  j  a v  a2 s.c  o m*/
    IProject project = getProject();
    IProjectDescription desc = project.getDescription();
    List<ICommand> commands = new ArrayList<ICommand>(Arrays.asList(desc.getBuildSpec()));
    for (Iterator i = commands.iterator(); i.hasNext();) {
        ICommand command = (ICommand) i.next();
        if (command.getBuilderName().equals(AntxrBuilder.BUILDER_ID)
                || command.getBuilderName().equals(SMapInstallerBuilder.BUILDER_ID)
                || command.getBuilderName().equals(WarningCleanerBuilder.BUILDER_ID)) {
            i.remove();
        }
    }

    // Commit the spec change into the project
    desc.setBuildSpec(commands.toArray(new ICommand[commands.size()]));
    project.setDescription(desc, null);

    // remove the jar from the classpath if present
    // delete the jar from the lib dir
    // if the lib dir is empty, delete it
    //        String jarPath = "/" + getProject().getName() + "/lib/antxr.jar";
    String generatedSourcePath = "/" + getProject().getName() + "/antxr-generated";
    final IJavaProject javaProject = JavaCore.create(getProject());
    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
    final List<IClasspathEntry> newEntries = new ArrayList<IClasspathEntry>();
    for (IClasspathEntry entry : rawClasspath) {
        //            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
        //                if (entry.getPath().toString().equals(jarPath)) {
        //                    found = i;
        //                    break;
        //                }
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            if (entry.getPath().toString().equals(generatedSourcePath)) {
                continue; // skip the antxr-generated source folder
            }
        }
        newEntries.add(entry);
    }

    JavaCore.run(new IWorkspaceRunnable() {
        public void run(IProgressMonitor monitor) throws CoreException {
            IClasspathEntry entries[] = newEntries.toArray(new IClasspathEntry[newEntries.size()]);
            javaProject.setRawClasspath(entries, null);
            IFolder folder = getProject().getFolder("antxr-generated");
            if (folder.exists() && !hasNonAntxrGeneratedFile(folder)) {
                folder.delete(true, null);
            } else {
                AntxrCorePlugin.getUtil().warning(4211,
                        "Did not delete antxr-generated source directory; it contains non-generated source. You should move that source to another source dir; it really doesn't belong there...");
            }
        }
    }, null);
}

From source file:com.javadude.antxr.eclipse.core.builder.AntxrBuilder.java

License:Open Source License

/**
 * Compile a grammar/* ww  w .java 2 s .com*/
 *
 * @param aFile
 *            The grammar file to compile
 * @param aMonitor
 *            A progress monitor
 */
public void compileFile(IFile aFile, IProgressMonitor aMonitor) {
    String grammarFileName = aFile.getProjectRelativePath().toString();
    try {
        // delete the old generated files for this grammar
        aFile.getProject().accept(new CleaningVisitor(aMonitor, grammarFileName));

        // if it's in a java project, only build it if it's in a source dir
        if (AntxrCorePlugin.getUtil().hasNature(aFile.getProject(), AntxrNature.NATURE_ID)) {
            IProject project = aFile.getProject();
            IJavaProject javaProject = JavaCore.create(project);
            IPath path = aFile.getFullPath();
            boolean ok = false;
            IClasspathEntry[] resolvedClasspath = javaProject.getResolvedClasspath(true);
            for (int i = 0; i < resolvedClasspath.length; i++) {
                IClasspathEntry entry = resolvedClasspath[i];

                if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
                    continue;
                }

                IPath entryPath = entry.getPath();
                if (entryPath.isPrefixOf(path)) {
                    ok = true;
                    break;
                }
            }
            if (!ok) {
                return;
            }
        }
    } catch (CoreException e1) {
        e1.printStackTrace();
    }

    fFile = aFile;

    aMonitor.beginTask(
            AntxrCorePlugin.getFormattedMessage("AntxrBuilder.compiling", aFile.getFullPath().toString()), 4);

    // Remove all markers from this file
    try {
        aFile.deleteMarkers(null, true, IResource.DEPTH_INFINITE);
    } catch (CoreException e) {
        AntxrCorePlugin.log(e);
    }

    // Prepare arguments for ANTXR compiler
    // read the settings for this grammar
    Map<String, Map<String, String>> map = SettingsPersister.readSettings(aFile.getProject());

    List<String> args = createArguments(map, aFile);
    if (AntxrBuilder.DEBUG) {
        System.out.println("Compiling ANTXR grammar '" + aFile.getName() + "': arguments=" + args);
    }

    // Monitor system out and err
    fOriginalOut = System.out;
    fOriginalErr = System.err;
    System.setOut(new PrintStream(new MonitoredOutputStream(this)));
    System.setErr(new PrintStream(new MonitoredOutputStream(this)));

    try {
        // Compile ANTXR grammar file
        AntxrTool tool = new AntxrTool();
        if (!tool.preprocess(args.toArray(new String[args.size()]))) {
            try {
                aMonitor.worked(1);
                if (!tool.parse()) {
                    aMonitor.worked(1);
                    if (!tool.generate()) {
                        aMonitor.worked(1);
                        refreshFolder(map, tool, args, aFile, grammarFileName,
                                ResourcesPlugin.getWorkspace().getRoot().findMember(fOutput), aMonitor,
                                tool.getSourceMaps());
                    } else {

                        // If errors during generate then delete all
                        // generated files
                        deleteFiles(tool, aFile.getParent(), aMonitor);
                    }
                    aMonitor.worked(1);
                }
            } catch (CoreException e) {
                AntxrCorePlugin.log(e);
            }
        }

    } catch (Throwable e) {
        if (!(e instanceof SecurityException)) {
            AntxrCorePlugin.log(e);
        }
    } finally {
        System.setOut(fOriginalOut);
        System.setErr(fOriginalErr);
        aMonitor.done();
    }
}

From source file:com.javadude.antxr.eclipse.core.builder.AntxrBuilder.java

License:Open Source License

/**
 * Returns list of commandline arguments for ANTXR compiler.
 *
 * @param map/*www .  j a va 2  s  .c  o m*/
 *            the saved antxr-eclipse settings for this project
 * @param file
 *            The grammar file to parse
 * @return a list of command-line arguments
 */
private List<String> createArguments(Map<String, Map<String, String>> map, IFile file) {
    List<String> args = new ArrayList<String>();

    AntxrCorePlugin.getDefault().upgradeOldSettings(file, map);

    fOutput = SettingsPersister.get(map, file, SettingsPersister.OUTPUT_PROPERTY);
    // Prepare absolute output path (-o)
    String outputPath = null;
    if (fOutput != null && fOutput.trim().length() > 0) {
        outputPath = convertRootRelatedPath(fOutput);
    }
    if (outputPath == null) {
        try {
            IJavaProject javaProject = JavaCore.create(file.getProject());
            IClasspathEntry rawClasspath[] = javaProject.getRawClasspath();
            String longestSourceDirPrefix = "";
            String grammarFilePath = file.getFullPath().toString();
            for (IClasspathEntry entry : rawClasspath) {
                if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    String sourceDirString = entry.getPath().toString();
                    if (grammarFilePath.startsWith(sourceDirString)
                            && sourceDirString.length() > longestSourceDirPrefix.length()) {
                        longestSourceDirPrefix = sourceDirString;
                    }
                }
            }

            if ("".equals(longestSourceDirPrefix)) {
                return null;
            }
            String basePath = file.getFullPath().removeLastSegments(1).toString();
            String packageName = basePath.substring(longestSourceDirPrefix.length());
            IFolder targetDirFolder = file.getProject().getFolder("antxr-generated/" + packageName);
            if (!targetDirFolder.exists()) {
                targetDirFolder.getRawLocation().toFile().mkdirs();
                file.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
            }
            fOutput = targetDirFolder.getFullPath().toString();
            outputPath = targetDirFolder.getLocation().toString();
        } catch (Exception e) {
            throw new RuntimeException("Could not set up antxr-generated as output dir", e);
        }
    }

    args.add("-o");
    args.add(outputPath);

    // Get boolean options from grammar properties
    addBooleanGrammarProperty(map, file, SettingsPersister.DEBUG_PROPERTY, "-debug", null, args, false);
    addBooleanGrammarProperty(map, file, SettingsPersister.HTML_PROPERTY, "-html", null, args, false);
    addBooleanGrammarProperty(map, file, SettingsPersister.DOCBOOK_PROPERTY, "-docbook", null, args, false);
    addBooleanGrammarProperty(map, file, SettingsPersister.DIAGNOSTIC_PROPERTY, "-diagnostic", null, args,
            false);
    addBooleanGrammarProperty(map, file, SettingsPersister.TRACE_PROPERTY, "-trace", null, args, false);
    addBooleanGrammarProperty(map, file, SettingsPersister.TRACE_PARSER_PROPERTY, "-traceParser", null, args,
            false);
    addBooleanGrammarProperty(map, file, SettingsPersister.TRACE_LEXER_PROPERTY, "-traceLexer", null, args,
            false);
    addBooleanGrammarProperty(map, file, SettingsPersister.TRACE_TREE_PARSER_PROPERTY, "-traceTreeParser", null,
            args, false);
    addBooleanGrammarProperty(map, file, SettingsPersister.SMAP_PROPERTY, "-smap", null, args, true);

    // Get super grammars from grammar properties
    String superGrammars = SettingsPersister.get(map, file, SettingsPersister.SUPER_GRAMMARS_PROPERTY);

    // Prepare optional super grammar(s) (-glib)
    // Can be defined in two ways : in a property dialog OR
    // inside the grammar using a comment "// -glib <file in same folder>"
    if (superGrammars != null && superGrammars.trim().length() > 0) {
        superGrammars = convertRootRelatedPathList(superGrammars);
        if (superGrammars != null) {
            args.add("-glib");
            args.add(superGrammars);
        }
    } else {
        // Try to get // -glib parameter from comment in .g file. This
        // enables sharing in a team project without local reconfiguration
        String localSuperGrammar = extractGlibComment(fFile);
        if (localSuperGrammar != null) {
            localSuperGrammar = convertFolderRelatedPath(localSuperGrammar);
            if (localSuperGrammar != null) {
                args.add("-glib");
                args.add(localSuperGrammar);
            }
        }
    }

    // Prepare ANTXR grammar file which needs to be compiled
    args.add(fFile.getLocation().toOSString());
    return args;
}

From source file:com.javadude.antxr.eclipse.smapinstaller.SMapInstallerBuilder.java

License:Open Source License

/**
 * Installs the modified smap into a generated classfile
 * @param resource/*  w w  w.j  av a 2s.co m*/
 * @throws JavaModelException
 */
protected void installSmap(IResource resource) throws JavaModelException {
    // We only work on smap files -- skip everything else
    if (!(resource instanceof IFile)) {
        return;
    }
    IFile smapIFile = (IFile) resource;
    if (!"smap".equalsIgnoreCase(smapIFile.getFileExtension())) {
        return;
    }
    IJavaProject javaProject = JavaCore.create(smapIFile.getProject());

    // get the name of the corresponding java source file
    IPath smapPath = smapIFile.getFullPath();

    IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);
    for (IClasspathEntry entry : classpathEntries) {
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
            continue;
        }
        if (!entry.getPath().isPrefixOf(smapPath)) {
            continue;
        }

        // found the right source container
        IPath outputLocation = entry.getOutputLocation();
        if (outputLocation == null) {
            outputLocation = javaProject.getOutputLocation();
        }
        // strip the source dir and .smap suffix
        String sourceDir = entry.getPath().toString();
        String smapName = smapPath.toString();
        String javaSourceName = smapName.substring(0, smapName.length() - 5) + ".java";
        String className = smapName.substring(sourceDir.length(), smapName.length() - 5) + ".class";
        IPath path = outputLocation.append(className);
        IPath workspaceLoc = ResourcesPlugin.getWorkspace().getRoot().getLocation();
        IPath classFileLocation = workspaceLoc.append(path);
        IResource classResource = ResourcesPlugin.getWorkspace().getRoot().findMember(javaSourceName);

        File classFile = classFileLocation.toFile();
        File smapFile = smapIFile.getLocation().toFile();
        try {
            String installSmap = classResource.getPersistentProperty(AntxrBuilder.INSTALL_SMAP);
            if ("true".equals(installSmap)) {
                SDEInstaller.install(classFile, smapFile);
            }
        } catch (CoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.javadude.dependencies.actions.DOTReportAction.java

License:Open Source License

public void run(IAction action) {
    // create DOT definition
    String NL = System.getProperty("line.separator");
    String dot = "digraph dependencies {" + NL;
    try {/*  www.ja va  2  s. c  o m*/
        for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
            if (project.isOpen() && project.hasNature(JavaCore.NATURE_ID)) {
                IJavaProject javaProject = JavaCore.create(project);
                for (IClasspathEntry entry : javaProject.getRawClasspath()) {
                    if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                        dot += '\t' + fixName(project.getName()) + " -> "
                                + fixName(entry.getPath().lastSegment()) + ';' + NL;
                    }
                }
            }
        }
        dot += "}";
        try {
            FileWriter fileWriter = new FileWriter("/dependencies.dot");
            fileWriter.write(dot);
            fileWriter.close();
        } catch (IOException e) {
            DependenciesPlugin.error(111, "Error writing dot file /dependencies.dot", e);
        }
    } catch (CoreException e) {
        DependenciesPlugin.error(222, "Error determining dependencies", e);
    }
}

From source file:com.javadude.dependencies.commands.DeleteCommand.java

License:Open Source License

@Override
public void execute() {
    // delete the target dep from the project
    try {//from  w  w w  .  j  av a  2 s .  co  m
        IClasspathEntry[] rawClasspath = getDependency().getSource().getRawClasspath();
        List<IClasspathEntry> newClasspath = new ArrayList<IClasspathEntry>();
        for (IClasspathEntry entry : rawClasspath) {
            if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT
                    || !entry.getPath().equals(getDependency().getTarget().getPath())) {
                newClasspath.add(entry);
            } else {
                setDeletedPosition(newClasspath.size());
                setDeletedEntry(entry);
            }
        }
        rawClasspath = newClasspath.toArray(new IClasspathEntry[rawClasspath.length - 1]);
        getDependency().getSource().setRawClasspath(rawClasspath, null);
    } catch (JavaModelException e) {
        throw new RuntimeException("Trouble deleting!", e);
    }
}

From source file:com.javadude.dependencies.editparts.WorkspaceRootEditPart.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/* w  ww  .  j  av  a2s.  c om*/
protected List getModelChildren() {
    List<String> geronimoLibs = new ArrayList<String>();

    // return the java projects
    IWorkspaceRoot root = (IWorkspaceRoot) getModel();
    List<IJavaProject> javaProjects = new ArrayList<IJavaProject>();
    Map<IPath, IJavaProject> projectFinder = new HashMap<IPath, IJavaProject>();
    for (int i = 0; i < root.getProjects().length; i++) {
        IProject project = root.getProjects()[i];
        try {
            if (project.isOpen() && project.hasNature(JavaCore.NATURE_ID)) {
                IJavaProject javaProject = JavaCore.create(project);
                javaProjects.add(javaProject);
                projectFinder.put(javaProject.getPath(), javaProject);
            }
        } catch (CoreException e) {
            DependenciesPlugin.error(142, "Could not check project nature", e);
        }
    }

    // need to make this more efficient -- should only process deltas
    // set up dependencies
    DependencyManager.clear();

    for (Iterator iter = javaProjects.iterator(); iter.hasNext();) {
        IJavaProject project = (IJavaProject) iter.next();
        try {
            IClasspathEntry[] rawClasspath = project.getRawClasspath();
            for (int i = 0; i < rawClasspath.length; i++) {
                IClasspathEntry entry = rawClasspath[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                    IPath path = entry.getPath();
                    IJavaProject targetProject = projectFinder.get(path);
                    Dependency dependency = new Dependency(project, targetProject, entry.isExported());
                    DependencyManager.add(dependency);
                }
            }
        } catch (JavaModelException e) {
            DependenciesPlugin.error(342, "Could not get classpath", e);
        }
    }

    List<Object> results = new ArrayList<Object>(javaProjects);
    results.addAll(geronimoLibs);
    return results;
}

From source file:com.javapathfinder.vjp.DefaultProperties.java

License:Open Source License

/**
 * append all relevant paths from the target project settings to the vm.classpath 
 *///from w  ww  . j a  v a 2s  .  co  m
private static void appendProjectClassPaths(IJavaProject project, StringBuilder cp) {
    try {
        // we need to maintain order
        LinkedHashSet<IPath> paths = new LinkedHashSet<IPath>();

        // append the default output folder
        IPath defOutputFolder = project.getOutputLocation();
        if (defOutputFolder != null) {
            paths.add(defOutputFolder);
        }
        // look for libraries and source root specific output folders
        for (IClasspathEntry e : project.getResolvedClasspath(true)) {
            IPath ePath = null;

            switch (e.getContentKind()) {
            case IClasspathEntry.CPE_LIBRARY:
                ePath = e.getPath();
                break;
            case IClasspathEntry.CPE_SOURCE:
                ePath = e.getOutputLocation();
                break;
            }

            if (ePath != null && !paths.contains(ePath)) {

                paths.add(ePath);
            }
        }

        for (IPath path : paths) {
            String absPath = getAbsolutePath(project, path).toOSString();

            //        if (cp.length() > 0) {
            //          cp.append(Config.LIST_SEPARATOR);
            //        }
            // only add classes that are found in bin
            if (absPath.contains("/bin"))
                cp.append(absPath);
        }
        System.out.println("cp is" + cp);
    } catch (JavaModelException jme) {
        VJP.logError("Could not append Project classpath", jme);
    }
}

From source file:com.javapathfinder.vjp.DefaultProperties.java

License:Open Source License

private static String getSourcepathEntry(IJavaProject project) {

    StringBuilder sourcepath = new StringBuilder();
    IClasspathEntry[] paths;//from  w ww.  j  a  va  2 s. c  o  m

    try {
        paths = project.getResolvedClasspath(true);
    } catch (JavaModelException e) {
        VJP.logError("Could not retrieve project classpaths.", e);
        return "";
    }

    for (IClasspathEntry entry : paths) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            sourcepath.append(getAbsolutePath(project, entry.getPath()));
            sourcepath.append(Config.LIST_SEPARATOR);
        } else if (entry.getSourceAttachmentPath() != null) {
            IPath path = entry.getSourceAttachmentPath();
            if (path.getFileExtension() == null) { //null for a directory
                sourcepath.append(path);
                sourcepath.append(Config.LIST_SEPARATOR);
            }
        }
    }
    if (sourcepath.length() > 0)
        sourcepath.setLength(sourcepath.length() - 1); //remove that trailing separator
    // VJP.logInfo(sourcepath.toString());
    return sourcepath.toString();
}

From source file:com.jstar.eclipse.objects.JavaFile.java

License:BSD License

public String getProjectClasspath() {
    StringBuilder projectClassPath = new StringBuilder();

    try {//  w w  w  . j av  a2 s.  c o m
        for (IClasspathEntry entry : getJavaProject().getProject().getResolvedClasspath(true)) {
            final int entryKind = entry.getEntryKind();
            if (entryKind == IClasspathEntry.CPE_SOURCE) {
                projectClassPath
                        .append(getJavaProject().getWorkspaceLocation().append(entry.getPath()).toOSString());
                projectClassPath.append(File.pathSeparator);
            }

            if (entryKind == IClasspathEntry.CPE_LIBRARY) {
                projectClassPath.append(getAbsolutePath(entry));
                projectClassPath.append(File.pathSeparator);

            }

            //TODO: IClasspathEntry.CPE_PROJECT
        }

        return projectClassPath.toString();
    } catch (CoreException ce) {
        ce.printStackTrace(ConsoleService.getInstance().getConsoleStream());
        return "";
    }
}