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:fr.imag.adele.cadse.cadseg.menu.ExportBundlePagesAction.java

License:Apache License

@Override
public void doFinish(UIPlatform uiPlatform, Object monitor) throws Exception {
    super.doFinish(uiPlatform, monitor);
    IProgressMonitor pmo = (IProgressMonitor) monitor;
    try {/*from ww  w  . j  a  v a 2  s . c  o m*/
        EclipsePluginContentManger project = (EclipsePluginContentManger) cadsedef.getContentItem();
        pmo.beginTask("export cadse " + cadsedef.getName(), 1);

        String qname = cadsedef.getQualifiedName();
        String qname_version = "";
        String version = "";
        IJavaProject jp = project.getMainMappingContent(IJavaProject.class);
        IProject eclipseProject = project.getProject();
        IPath eclipseProjectPath = eclipseProject.getFullPath();

        // jp.getProject().build(kind, pmo)
        IPath defaultOutputLocation = jp.getOutputLocation();

        IPath manifestPath = new Path(JarFile.MANIFEST_NAME);
        HashSet<IPath> excludePath = new HashSet<IPath>();
        excludePath.add(eclipseProjectPath.append(manifestPath));
        excludePath.add(eclipseProjectPath.append(".project"));
        excludePath.add(eclipseProjectPath.append(".classpath"));
        excludePath.add(eclipseProjectPath.append("run-cadse-" + cadsedef.getName() + ".launch"));
        excludePath.add(eclipseProjectPath.append(".melusine.ser"));
        excludePath.add(eclipseProjectPath.append(".melusine.xml"));

        Manifest mf = new Manifest(eclipseProject.getFile(manifestPath).getContents());
        File pf = new File(file, qname + ".jar");
        File sourceDir = new File(file, qname + ".Source");

        if (tstamp) {
            Date d = new Date(System.currentTimeMillis());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
            String timeStamp = "v" + formatter.format(d);

            version = mf.getMainAttributes().getValue(OsgiManifest.BUNDLE_VERSION);
            String[] partVersion = version.split("\\.");
            if (partVersion.length == 4) {
                version = version + "-" + timeStamp;
            } else {
                version = version + "." + timeStamp;
            }
            mf.getMainAttributes().putValue(OsgiManifest.BUNDLE_VERSION, version);
            pf = new File(file, qname + "_" + version + ".jar");
            qname_version = qname + "_" + version;
            sourceDir = new File(file, qname + ".Source_" + version);
        }

        JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(pf), mf);
        HashMap<IFile, IPath> files = new HashMap<IFile, IPath>();

        IWorkspaceRoot eclipseRoot = eclipseProject.getWorkspace().getRoot();
        IContainer classesFolder = (IContainer) eclipseRoot.findMember(defaultOutputLocation);
        addFolder(files, excludePath, classesFolder, Path.EMPTY);

        IClasspathEntry[] classpaths = jp.getRawClasspath();
        for (IClasspathEntry entry : classpaths) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                if (entry.getOutputLocation() != null) {
                    classesFolder = (IContainer) eclipseRoot.findMember(entry.getOutputLocation());
                    addFolder(files, excludePath, classesFolder, Path.EMPTY);
                }
                IPath sourcePath = entry.getPath();
                excludePath.add(sourcePath);
                continue;
            }
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {

            }
        }

        addFolder(files, excludePath, eclipseProject, Path.EMPTY);
        pmo.beginTask("export cadse " + cadsedef.getName(), files.size());

        Set<IFile> keySet = new TreeSet<IFile>(new Comparator<IFile>() {
            public int compare(IFile o1, IFile o2) {
                return o1.getFullPath().toPortableString().compareTo(o2.getFullPath().toPortableString());
            }
        });
        keySet.addAll(files.keySet());
        for (IFile f : keySet) {
            IPath entryPath = files.get(f);
            pmo.worked(1);
            try {
                ZipUtil.addEntryZip(outputStream, f.getContents(), entryPath.toPortableString(),
                        f.getLocalTimeStamp());
            } catch (Throwable e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        outputStream.close();
        if (deleteOld) {
            File[] childrenFiles = file.listFiles();
            if (childrenFiles != null) {
                for (File f : childrenFiles) {
                    if (f.equals(pf)) {
                        continue;
                    }

                    String fileName = f.getName();

                    if (!fileName.startsWith(qname)) {
                        continue;
                    }
                    FileUtil.deleteDir(f);
                }
            }
        }
        if (exportSource && tstamp) {
            sourceDir.mkdir();
            File srcDir = new File(sourceDir, "src");
            srcDir.mkdir();
            File mfDir = new File(sourceDir, "META-INF");
            mfDir.mkdir();
            File modelDir = new File(srcDir, qname_version);
            modelDir.mkdir();
            FileUtil.setFile(new File(sourceDir, "plugin.xml"),
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<?eclipse version=\"3.0\"?>\n"
                            + "<plugin>\n" + "<extension point=\"org.eclipse.pde.core.source\">\n"
                            + "<location path=\"src\"/>\n" + "</extension>\n" + "</plugin>\n");
            String vendor_info = CadseDefinitionManager.getVendorNameAttribute(cadsedef);
            FileUtil.setFile(new File(mfDir, "MANIFEST.MF"),
                    "Manifest-Version: 1.0\n" + "Bundle-ManifestVersion: 2\n" + "Bundle-SymbolicName: " + qname
                            + ".Source;singleton:=true\n" + "Bundle-Version: " + version + "\n"
                            + "Bundle-Localization: plugin\n" + "Bundle-Vendor: " + vendor_info + "\n"
                            + "Bundle-Name: " + qname + "\n");

            excludePath.clear();
            files.clear();
            classesFolder = (IContainer) eclipseRoot.findMember(defaultOutputLocation);
            excludePath.add(classesFolder.getFullPath());
            for (IClasspathEntry entry : classpaths) {
                if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    if (entry.getOutputLocation() != null) {
                        classesFolder = (IContainer) eclipseRoot.findMember(entry.getOutputLocation());
                        addFolder(files, excludePath, classesFolder, Path.EMPTY);
                    }
                    IPath sourcePath = entry.getPath();
                    excludePath.add(sourcePath);
                    ZipUtil.zipDirectory(eclipseRoot.findMember(sourcePath).getLocation().toFile(),
                            new File(modelDir, "src.zip"), null);
                    continue;
                }
            }
            addFolder(files, excludePath, eclipseProject, Path.EMPTY);
            keySet = files.keySet();
            for (IFile f : keySet) {
                IPath entryPath = files.get(f);
                try {
                    FileUtil.copy(f.getLocation().toFile(), new File(modelDir, entryPath.toOSString()), false);
                } catch (Throwable e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    } catch (RuntimeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {

    }
}

From source file:fr.inria.diverse.commons.eclipse.pde.wizards.pages.pde.ui.templates.AbstractTemplateSection.java

License:Open Source License

/**
 * Returns the folder with Java files in the target project. The default
 * implementation looks for source folders in the classpath of the target
 * folders and picks the first one encountered. Subclasses may override this
 * behaviour.//from   ww  w. j  a  v a  2s .co  m
 * 
 * @param monitor
 *            progress monitor to use
 * @return source folder that will be used to generate Java files or
 *         <samp>null </samp> if none found.
 */

protected IFolder getSourceFolder(IProgressMonitor monitor) {
    IFolder sourceFolder = null;

    try {
        IJavaProject javaProject = JavaCore.create(project);
        IClasspathEntry[] classpath = javaProject.getRawClasspath();
        for (int i = 0; i < classpath.length; i++) {
            IClasspathEntry entry = classpath[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath path = entry.getPath().removeFirstSegments(1);
                if (path.segmentCount() > 0)
                    sourceFolder = project.getFolder(path);
                break;
            }
        }
    } catch (JavaModelException e) {
        PDEPlugin.logException(e);
    }
    return sourceFolder;
}

From source file:fr.obeo.acceleo.tools.classloaders.AcceleoGenClassLoader.java

License:Open Source License

private static void computeURLs(IProject project, List URLs) {
    IFolder binFolder = Resources.getOutputFolder(project);
    if (binFolder != null) {
        String location = binFolder.getLocation().toString();
        if (location.startsWith("/")) { //$NON-NLS-1$
            location = '/' + location;
        }//from   www.java2 s.co  m
        try {
            URLs.add(new URL("file:/" + location + '/')); //$NON-NLS-1$
        } catch (MalformedURLException e) {
            // continue
        }
    }
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries;
    try {
        entries = javaProject.getResolvedClasspath(true);
    } catch (JavaModelException e1) {
        entries = new IClasspathEntry[] {};
    }
    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            IProject reference = ResourcesPlugin.getWorkspace().getRoot()
                    .getProject(entry.getPath().toString());
            if (reference.exists()) {
                AcceleoGenClassLoader.computeURLs(reference, URLs);
            }
        } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            try {
                IFile reference = ResourcesPlugin.getWorkspace().getRoot().getFile(entry.getPath());
                if (reference.exists()) {
                    URL url = (URL) AcceleoGenClassLoader.cacheURL.get(reference.getLocation().toFile());
                    if (url == null) {
                        url = reference.getLocation().toFile().toURL();
                        AcceleoGenClassLoader.cacheURL.put(reference.getLocation().toFile(), url);
                    }
                    URLs.add(url);
                } else {
                    URL url = (URL) AcceleoGenClassLoader.cacheURL.get(entry.getPath().toFile());
                    if (url == null) {
                        url = entry.getPath().toFile().toURL();
                        AcceleoGenClassLoader.cacheURL.put(entry.getPath().toFile(), url);
                    }
                    URLs.add(url);
                }
            } catch (MalformedURLException e) {
                // continue
            }
        } else {
            try {
                URL url = (URL) AcceleoGenClassLoader.cacheURL.get(entry.getPath().toFile());
                if (url == null) {
                    url = entry.getPath().toFile().toURL();
                    AcceleoGenClassLoader.cacheURL.put(entry.getPath().toFile(), url);
                }
                URLs.add(url);
            } catch (MalformedURLException e) {
                // continue
            }
        }
    }
}

From source file:fr.obeo.ariadne.ide.connector.java.internal.explorer.JavaExplorer.java

License:Open Source License

/**
 * Launches the exploration of the given Java project.
 * //w w w . j  a v  a2s.com
 * @param project
 *            The Java project to explore
 * @param monitor
 *            The progress monitor
 * @return The Component representing the Java project.
 */
public Component doExplore(IProject project, IProgressMonitor monitor) {
    Component ariadneComponent = this.getOrCreateComponent(project);
    IJavaProject iJavaProject = JavaCore.create(project);
    try {
        IClasspathEntry[] rawClasspath = iJavaProject.getRawClasspath();
        for (IClasspathEntry iClasspathEntry : rawClasspath) {
            // We have the source folders of the project.
            IPath inputFolderPath = iClasspathEntry.getPath();
            IPath outputFolderPath = iClasspathEntry.getOutputLocation();

            if (outputFolderPath == null) {
                outputFolderPath = iJavaProject.getOutputLocation();
            }

            // Create the classpath entry
            ClasspathEntry classpathEntry = CodeFactory.eINSTANCE.createClasspathEntry();
            classpathEntry.setInputFolder(inputFolderPath.toString());
            classpathEntry.setOutputFolder(outputFolderPath.toString());
            ariadneComponent.getClasspathEntries().add(classpathEntry);

            int entryKind = iClasspathEntry.getEntryKind();
            if (IClasspathEntry.CPE_SOURCE == entryKind) {
                // Explore its content located in its input folder
                this.exploreClasspathEntry(iJavaProject, iClasspathEntry, classpathEntry, monitor);
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }

    return ariadneComponent;
}

From source file:gov.redhawk.ide.codegen.java.AbstractJavaCodeGenerator.java

License:Open Source License

@Override
public IStatus cleanupSourceFolders(final IProject project, final IProgressMonitor monitor) {
    final IJavaProject jp = JavaCore.create(project);
    final HashSet<IClasspathEntry> paths = new HashSet<IClasspathEntry>();
    try {//from  w w w. ja va  2  s  .  co m
        for (final IClasspathEntry path : jp.getRawClasspath()) {
            IPath p = path.getPath();
            if (path.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                if (p.segment(0).equals(project.getFullPath().segment(0))) {
                    p = p.removeFirstSegments(1);
                    if (project.getFolder(p).exists()) {
                        paths.add(path);
                    }
                }
            } else {
                paths.add(path);
            }
        }
        jp.setRawClasspath(paths.toArray(new IClasspathEntry[paths.size()]), monitor);
    } catch (final JavaModelException e) {
        return new Status(IStatus.WARNING, JavaGeneratorPlugin.PLUGIN_ID,
                "Unable to adjust the list of source code folders for the project");
    }
    return new Status(IStatus.OK, JavaGeneratorPlugin.PLUGIN_ID, "Cleaned up source folders");
}

From source file:gov.redhawk.ide.codegen.java.JavaGeneratorUtils.java

License:Open Source License

public static void addSourceClassPaths(final IJavaProject jproject, final IPath srcPath, final IPath binPath,
        final IProgressMonitor monitor) throws CoreException {
    final SubMonitor progress = SubMonitor.convert(monitor, 1);
    final Set<IClasspathEntry> entries = new LinkedHashSet<IClasspathEntry>(
            Arrays.asList(jproject.getRawClasspath()));

    // Add source code to the java project classpath
    for (final IClasspathEntry path : entries) {
        if ((path.getEntryKind() == IClasspathEntry.CPE_SOURCE)
                && path.getPath().equals(jproject.getProject().getFullPath())) {
            continue;
        }/*from   ww w . j a  v a  2 s  .c om*/
        entries.add(path);
    }

    final IClasspathEntry e = JavaCore.newSourceEntry(srcPath, new Path[0], binPath);
    entries.add(e);

    jproject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), progress.newChild(1));
}

From source file:gov.redhawk.ide.codegen.jet.java.template.StartJavaShTemplate.java

License:Open Source License

/**
* {@inheritDoc}//ww w .  ja  v  a  2  s  .  c  om
*/

public String generate(Object argument) {
    final StringBuffer stringBuffer = new StringBuffer();

    JavaTemplateParameter template = (JavaTemplateParameter) argument;
    ImplementationSettings implSettings = template.getImplSettings();
    Implementation impl = template.getImpl();
    SoftPkg softPkg = (SoftPkg) impl.eContainer();
    IResource resource = ModelUtil.getResource(implSettings);
    IProject project = resource.getProject();
    IJavaProject javaProject = JavaCore.create(project);
    String implName = gov.redhawk.ide.codegen.util.CodegenFileHelper.safeGetImplementationName(impl,
            implSettings);
    String jarPrefix = gov.redhawk.ide.codegen.util.CodegenFileHelper.getPreferredFilePrefix(softPkg,
            implSettings);
    String pkg = template.getPackage();
    String mainClass = gov.redhawk.ide.codegen.jet.java.JavaGeneratorProperties.getMainClass(impl,
            implSettings);

    String projDir = "/" + project.getName() + "/" + implSettings.getOutputDir();
    String libs = "";
    String vars = "";
    try {
        for (final IClasspathEntry path : javaProject.getRawClasspath()) {
            if (path.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                final String lib = path.getPath().toString();
                libs += lib.replaceAll(projDir, "\\$myDir") + ":";
            } else if (path.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                vars += "$" + path.getPath().toString() + ":";
            }
        }
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    stringBuffer.append(TEXT_1);
    stringBuffer.append(libs);
    stringBuffer.append(TEXT_2);
    stringBuffer.append(vars);
    stringBuffer.append(TEXT_3);
    stringBuffer.append(jarPrefix);
    stringBuffer.append(TEXT_4);
    stringBuffer.append(mainClass);
    stringBuffer.append(TEXT_5);
    stringBuffer.append(libs);
    stringBuffer.append(TEXT_6);
    stringBuffer.append(vars);
    stringBuffer.append(TEXT_7);
    stringBuffer.append(jarPrefix);
    stringBuffer.append(TEXT_8);
    stringBuffer.append(mainClass);
    stringBuffer.append(TEXT_9);
    stringBuffer.append(TEXT_10);
    return stringBuffer.toString();
}

From source file:hydrograph.ui.expression.editor.composites.CategoriesDialogSourceComposite.java

License:Apache License

private void createDelButton(Composite headerComposite) {
    deleteButton = new Button(headerComposite, SWT.NONE);
    deleteButton.setBounds(0, 0, 75, 25);
    deleteButton.setToolTipText(Messages.EXTERNAL_JAR_DIALOG_DELETE_BUTTON_TOOLTIP);
    try {/*  ww w  . j a  v a  2  s  .c om*/
        deleteButton.setImage(ImagePathConstant.DELETE_BUTTON.getImageFromRegistry());
    } catch (Exception exception) {
        LOGGER.error("Exception occurred while attaching image to button", exception);
        deleteButton.setText("Delete");
    }

    deleteButton.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (comboJarList.getSelectionIndex() > -1) {
                String jarName = comboJarList.getItem(comboJarList.getSelectionIndex());
                if (userIsSure(jarName)) {
                    try {
                        removeJarFromBuildPath(jarName);
                        comboJarList.remove(jarName);
                        sourcePackageList.removeAll();
                        refresh(jarName);
                        enableOrDisableAddLabelsOnComboSelection();
                    } catch (CoreException e1) {
                        LOGGER.error(
                                "Exception occurred while removing jar file" + jarName + "from build Path");
                    }
                }
            }
        }

        private boolean userIsSure(String jarName) {
            MessageBox messageBox = new MessageBox(Display.getCurrent().getActiveShell(),
                    SWT.ICON_QUESTION | SWT.YES | SWT.NO);
            messageBox.setMessage("Do you really want to remove " + jarName + " file?\nCannot be undone.");
            messageBox.setText("Remove Resource");
            int response = messageBox.open();
            if (response == SWT.YES)
                return true;
            return false;
        }

        private void refresh(String jarName) {
            boolean isAnyItemRemovedFromTargetList = false;
            String[] items = targetComposite.getTargetList().getItems();
            targetComposite.getTargetList().removeAll();
            for (String item : items) {
                String jarFileName = StringUtils.trim(StringUtils.substringAfter(item, Constants.DASH));
                if (!StringUtils.equalsIgnoreCase(jarFileName, jarName)) {
                    targetComposite.getTargetList().add(item);
                } else
                    isAnyItemRemovedFromTargetList = true;
            }
            if (isAnyItemRemovedFromTargetList) {
                addCategoreisDialog.createPropertyFileForSavingData();
            }
        }

        private void removeJarFromBuildPath(String jarName) throws CoreException {
            LOGGER.debug("Removing jar file" + jarName + "from build Path");
            IJavaProject javaProject = JavaCore
                    .create(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject());
            IFile jarFile = javaProject.getProject().getFolder(PathConstant.PROJECT_LIB_FOLDER)
                    .getFile(jarName);
            IClasspathEntry[] oldClasspathEntry = javaProject.getRawClasspath();
            IClasspathEntry[] newClasspathEntry = new IClasspathEntry[oldClasspathEntry.length - 1];
            if (jarFile.exists()) {
                int index = 0;
                for (IClasspathEntry classpathEntry : oldClasspathEntry) {
                    if (classpathEntry.getPath().equals(jarFile.getFullPath())) {
                        continue;
                    }
                    newClasspathEntry[index] = classpathEntry;
                    index++;
                }
                javaProject.setRawClasspath(newClasspathEntry, new NullProgressMonitor());
                jarFile.delete(true, new NullProgressMonitor());
            }
            javaProject.close();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {/* Do-Nothing */
        }
    });
}

From source file:icy.icy4eclipse.core.IcyProject.java

License:Open Source License

void fixBuildpath() {
    try {/*from w  ww . java  2  s .c  o m*/
        IClasspathEntry[] entries = javaProject.getRawClasspath();

        for (int i = 0; i < entries.length; i++) {
            IClasspathEntry entry = entries[i];
            String path = entry.getPath().toOSString();
            if ((entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE)
                    && (path.startsWith(Icy4EclipsePlugin.getIcyHomeDir()))) {
                String npath = path.substring(Icy4EclipsePlugin.getIcyHomeDir().length());
                IPath ipath = new Path(ICY4ECLIPSE_HOME_VARIABLE + npath);
                entries[i] = JavaCore.newVariableEntry(ipath, null, null);
                Icy4EclipsePlugin.logInfo("fixBuildpath : " + path + " -> " + ipath.toOSString());
            }
        }

        javaProject.setRawClasspath(entries, null);
    } catch (JavaModelException e) {
        Icy4EclipsePlugin.logException(e);
    }
}

From source file:in.cypal.studio.gwt.core.facet.InstallDelegate.java

License:Apache License

public static void addUserLibToClassPath(IProject project, IProgressMonitor monitor) {

    monitor = Util.getNonNullMonitor(monitor);
    try {//from  www.ja va  2  s .  c  o  m

        IJavaProject javaProject = JavaCore.create(project);
        IClasspathEntry[] oldClasspath = javaProject.getRawClasspath();
        IClasspathEntry[] newClasspath = new IClasspathEntry[oldClasspath.length + 1];
        System.arraycopy(oldClasspath, 0, newClasspath, 0, oldClasspath.length);
        IClasspathEntry gwtuserJarEntry = JavaCore.newVariableEntry(Util.getGwtUserLibPath(), null, null);
        gwtuserJarEntry = JavaCore.newVariableEntry(gwtuserJarEntry.getPath(), null, null, new IAccessRule[0],
                new IClasspathAttribute[0], false);
        newClasspath[oldClasspath.length] = gwtuserJarEntry;
        javaProject.setRawClasspath(newClasspath, monitor);

    } catch (CoreException e) {
        // the jar is already in the classpath.
        Activator.logException(e);
    } finally {
        monitor.done();
    }

}