Example usage for org.eclipse.jdt.core JavaCore newSourceEntry

List of usage examples for org.eclipse.jdt.core JavaCore newSourceEntry

Introduction

In this page you can find the example usage for org.eclipse.jdt.core JavaCore newSourceEntry.

Prototype

public static IClasspathEntry newSourceEntry(IPath path, IPath[] inclusionPatterns, IPath[] exclusionPatterns,
        IPath specificOutputLocation) 

Source Link

Document

Creates and returns a new classpath entry of kind CPE_SOURCE for the project's source folder identified by the given absolute workspace-relative path but excluding all source files with paths matching any of the given patterns, and associated with a specific output location (that is, ".class" files are not going to the project default output location).

Usage

From source file:de.plugins.eclipse.depclipse.testcommons.TestingEnvironment.java

License:Open Source License

/** Adds a package fragment root to the workspace.  If
 * a package fragment root with the same name already
 * exists, it is not replaced.  A workspace must be open.
 * Returns the path of the added package fragment root.
 *///  w w w  .jav a2s. c om
public IPath addPackageFragmentRoot(IPath projectPath, String sourceFolderName, IPath[] inclusionPatterns,
        IPath[] exclusionPatterns, String specificOutputLocation) throws JavaModelException {
    checkAssertion("a workspace must be open", this.isOpen); //$NON-NLS-1$
    IPath path = getPackageFragmentRootPath(projectPath, sourceFolderName);
    createFolder(path);
    IPath outputPath = null;
    if (specificOutputLocation != null) {
        outputPath = getPackageFragmentRootPath(projectPath, specificOutputLocation);
        createFolder(outputPath);
    }
    IClasspathEntry entry = JavaCore.newSourceEntry(path,
            inclusionPatterns == null ? new Path[0] : inclusionPatterns,
            exclusionPatterns == null ? new Path[0] : exclusionPatterns, outputPath);
    addEntry(projectPath, entry);
    return path;
}

From source file:eu.artist.migration.modernization.uml2java.repackaged.gen.java.services.WorkspaceServices.java

License:Open Source License

/**
 * Creates a project from scratch in the workspace.
 * // w w  w  .  j a  va2s . com
 * @param eObject
 *            The model element
 */
public void createDefaultProject(EObject eObject) {
    if (!EMFPlugin.IS_ECLIPSE_RUNNING) {
        return;
    }

    IProgressMonitor monitor = new NullProgressMonitor();
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    try {
        IWorkspaceRoot workspaceRoot = workspace.getRoot();

        String projectName = UML2JavaConfigurationHolder.getDefaultProjectName(eObject);
        IProject project = workspaceRoot.getProject(projectName);

        if (project.exists() && project.isAccessible()) {
            if (!project.isOpen()) {
                project.open(monitor);
            }
        } else {
            project.create(new NullProgressMonitor());
            project.open(new NullProgressMonitor());

            IContainer intputContainer = project;

            String sourceFolderName = UML2JavaConfigurationHolder.getSourceFolderPath(eObject);
            StringTokenizer stringTokenizer = new StringTokenizer(sourceFolderName, "/");
            while (stringTokenizer.hasMoreTokens()) {
                String token = stringTokenizer.nextToken();
                IFolder src = intputContainer.getFolder(new Path(token));
                if (!src.exists()) {
                    src.create(true, true, monitor);
                }

                intputContainer = src;
            }

            IContainer outputContainer = project;

            String outputFolderName = UML2JavaConfigurationHolder.getOutputFolderPath(eObject);
            stringTokenizer = new StringTokenizer(outputFolderName, "/");
            while (stringTokenizer.hasMoreTokens()) {
                String token = stringTokenizer.nextToken();
                IFolder out = outputContainer.getFolder(new Path(token));
                if (!out.exists()) {
                    out.create(true, true, monitor);
                }

                outputContainer = out;
            }

            IProjectDescription description = project.getDescription();
            String[] natures = new String[] {};
            if (IUML2JavaConstants.Default.DEFAULT_COMPONENT_ARTIFACTS_TYPE_OSGI
                    .equals(UML2JavaConfigurationHolder.getComponentBasedArchitecture(eObject))
                    || IUML2JavaConstants.Default.DEFAULT_COMPONENT_ARTIFACTS_TYPE_ECLIPSE
                            .equals(UML2JavaConfigurationHolder.getComponentBasedArchitecture(eObject))) {
                natures = new String[] { JavaCore.NATURE_ID, IUML2JavaConstants.PDE_PLUGIN_NATURE_ID };
            } else {
                natures = new String[] { JavaCore.NATURE_ID, };
            }
            description.setNatureIds(natures);
            project.setDescription(description, monitor);

            IJavaProject javaProject = JavaCore.create(project);

            List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
            IExecutionEnvironmentsManager executionEnvironmentsManager = JavaRuntime
                    .getExecutionEnvironmentsManager();
            IExecutionEnvironment[] executionEnvironments = executionEnvironmentsManager
                    .getExecutionEnvironments();

            String defaultJREExecutionEnvironment = UML2JavaConfigurationHolder
                    .getJREExecutionEnvironment(eObject);
            for (IExecutionEnvironment iExecutionEnvironment : executionEnvironments) {
                if (defaultJREExecutionEnvironment.equals(iExecutionEnvironment.getId())) {
                    entries.add(
                            JavaCore.newContainerEntry(JavaRuntime.newJREContainerPath(iExecutionEnvironment)));
                    break;
                }
            }

            javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

            IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
            System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);

            javaProject.setOutputLocation(outputContainer.getFullPath(), monitor);

            IPackageFragmentRoot packageRoot = javaProject
                    .getPackageFragmentRoot(intputContainer.getFullPath().toString());
            newEntries[oldEntries.length] = JavaCore.newSourceEntry(packageRoot.getPath(), new Path[] {},
                    new Path[] {}, outputContainer.getFullPath());

            javaProject.setRawClasspath(newEntries, null);

            IFile buildPropertiesFile = project.getFile("build.properties");
            if (!buildPropertiesFile.exists()) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(
                        "#################################################################################"
                                + System.getProperty("line.separator"));
                stringBuilder.append("## " + UML2JavaConfigurationHolder.getCopyrightAndLicense(eObject)
                        + System.getProperty("line.separator"));
                stringBuilder.append(
                        "#################################################################################"
                                + System.getProperty("line.separator"));
                stringBuilder.append("source.. = " + UML2JavaConfigurationHolder.getSourceFolderPath(eObject)
                        + System.getProperty("line.separator"));
                stringBuilder.append("output.. = " + UML2JavaConfigurationHolder.getOutputFolderPath(eObject)
                        + System.getProperty("line.separator"));
                stringBuilder.append("" + System.getProperty("line.separator"));
                buildPropertiesFile.create(new ByteArrayInputStream(stringBuilder.toString().getBytes()), true,
                        monitor);
            }
        }
    } catch (CoreException coreException) {
        AcceleoEnginePlugin.log(coreException, true);
    }
}

From source file:fede.workspace.eclipse.composition.copy.composer.SourcesCopyComposer.java

License:Apache License

@Override
protected void postCompose(IBuildingContext context, List<IExportedContent> listExportedContent,
        IExporterTarget target) {/* w w  w. j a  va2s.  c  om*/
    super.postCompose(context, listExportedContent, target);

    if (createSourceEntry) {
        try {
            IJavaProject javaProject = JavaProjectManager.getJavaProject(getItem());
            IFolder fSources = javaProject.getProject().getFolder(getTargetPath());
            IPath path = fSources.getFullPath();
            IClasspathEntry ce = JavaCore.newSourceEntry(path, new IPath[] {}, new IPath[] {}, null);

            JavaProjectManager.addProjectClasspath(javaProject, ce, null, false);
        } catch (JavaModelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:fede.workspace.eclipse.java.JavaProjectManager.java

License:Apache License

/**
 * Adds the source folder associated with the item to the source entries in
 * the classpath of the java project.//from  ww w  .ja v a  2 s. c  o m
 * 
 * @param item
 *            the item
 * @param monitor
 *            the monitor
 * @param sourceFolder
 *            the source folder
 * @param specificOutputFolder
 *            the specific output folder
 * 
 * @throws CoreException
 *             the core exception
 */
public static void createJavaSourceFolder(Item item, IFolder sourceFolder, IFolder specificOutputFolder,
        IProgressMonitor monitor) throws CoreException {

    if (sourceFolder == null) {
        return;
    }

    IProject project = sourceFolder.getProject();

    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null) {
        return;
    }

    if (!sourceFolder.exists()) {
        sourceFolder.create(false, true, monitor);
    }

    IFolder defaultOutputFolder = project
            .getFolder(DEFAULT_OUTPUT_FOLDER_NAME.compute(ContextVariableImpl.DEFAULT, item));
    if (!defaultOutputFolder.exists()) {
        defaultOutputFolder.create(false, true, monitor);
    }

    IPath specificOutputPath = null;
    if (specificOutputFolder != null) {
        specificOutputPath = specificOutputFolder.getFullPath();
        if (!specificOutputFolder.exists()) {
            specificOutputFolder.create(false, true, monitor);
        }
    }

    List<IClasspathEntry> classpath = new ArrayList<IClasspathEntry>(
            Arrays.asList(javaProject.getRawClasspath()));
    IClasspathEntry sourceEntry = JavaCore.newSourceEntry(sourceFolder.getFullPath(),
            ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, specificOutputPath);

    if (!classpath.contains(sourceEntry)) {
        classpath.add(sourceEntry);
        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]),
                defaultOutputFolder.getFullPath(), monitor);
    }

}

From source file:org.autorefactor.refactoring.rules.JavaCoreHelper.java

License:Open Source License

private static List<IClasspathEntry> getClasspathEntries(final IPackageFragmentRoot root) throws Exception {
    final List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    final IClasspathEntry srcEntry = JavaCore.newSourceEntry(root.getPath(), EMPTY_PATHS, EMPTY_PATHS, null);
    final IClasspathEntry rtJarEntry = JavaCore.newLibraryEntry(getPathToRtJar(), null, null);
    entries.add(srcEntry);//from www.j  a va 2s .  c  o m
    entries.add(rtJarEntry);

    extractClasspathEntries(entries, "../samples/pom.xml");
    return entries;
}

From source file:org.autorefactor.refactoring.rules.JavaCoreHelper.java

License:Open Source License

private static IPackageFragmentRoot addSourceContainer(IJavaProject javaProject, String containerName)
        throws Exception {
    final IProject project = javaProject.getProject();
    final IFolder folder = project.getFolder(containerName);
    createFolder(folder);//  w  w w  .java  2s  .  c  o m

    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);
    IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath(), EMPTY_PATHS, EMPTY_PATHS, null);
    addToClasspath(javaProject, Arrays.asList(cpe));
    return root;
}

From source file:org.ebayopensource.turmeric.eclipse.maven.core.m2eclipse.MavenProjectConfigurator.java

License:Open Source License

@Override
public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException {
    if (request == null) {
        return;//  w ww  .  j a va2s.c  o  m
    }

    if (request.isProjectImport() == true) {
        IProject project = request.getProject();
        SupportedProjectType projectType = null;
        if (isValidInterfaceProject(project) && TurmericServiceUtils.isSOAInterfaceProject(project) == false) {
            projectType = SupportedProjectType.INTERFACE;
        } else if (isValidImplementationProject(project)
                && TurmericServiceUtils.isSOAImplProject(project) == false) {
            projectType = SupportedProjectType.IMPL;
        } else if (isValidConsumerProject(project)
                && TurmericServiceUtils.isSOAConsumerProject(project) == false) {
            projectType = SupportedProjectType.CONSUMER;
        } else if (isValidTypeLibraryProject(project)
                && TurmericServiceUtils.isSOATypeLibraryProject(project) == false) {
            projectType = SupportedProjectType.TYPE_LIBRARY;
        } else if (isValidErrorLibraryProject(project)
                && TurmericServiceUtils.isSOAErrorLibraryProject(project) == false) {
            projectType = SupportedProjectType.ERROR_LIBRARY;
        } else {
            //OK this is not a Turmeric project after all.
            return;
        }

        String natureId = GlobalRepositorySystem.instanceOf().getActiveRepositorySystem()
                .getProjectNatureId(projectType);

        if (StringUtils.isNotBlank(natureId)) {
            //it is a SOA project
            JDTUtil.addNatures(project, monitor, natureId);
            InputStream input = null;
            try {
                input = request.getPom().getContents();
                Model model = MavenCoreUtils.mavenEclipseAPI().parsePom(input);
                Build build = model.getBuild();
                final IJavaProject javaProject = JavaCore.create(project);
                List<IPath> srcDirs = JDTUtil.getSourceDirectories(project);
                List<IPath> additionalSrcDirs = new ArrayList<IPath>();
                Plugin: for (Plugin plugin : build.getPlugins()) {
                    if (plugin.getArtifactId().equals("build-helper-maven-plugin")) {
                        for (PluginExecution exec : plugin.getExecutions()) {
                            if ("add-source".equals(exec.getId()) && exec.getConfiguration() != null) {
                                String xml = exec.getConfiguration().toString();
                                InputStream ins = null;
                                try {
                                    ins = new ByteArrayInputStream(xml.getBytes());
                                    Document doc = JDOMUtil.readXML(ins);
                                    Element elem = doc.getRootElement().getChild("sources");
                                    if (elem != null) {
                                        for (Object obj : elem.getChildren("source")) {
                                            if (obj instanceof Element) {
                                                IPath src = new Path(((Element) obj).getTextTrim());
                                                if (srcDirs.contains(src) == false) {
                                                    additionalSrcDirs.add(src);
                                                }
                                            }
                                        }
                                    }

                                } finally {
                                    IOUtils.closeQuietly(ins);
                                }
                                break Plugin;
                            }
                        }
                    }
                }

                if (additionalSrcDirs.isEmpty() == false) {
                    final List<IClasspathEntry> entries = ListUtil.arrayList(javaProject.readRawClasspath());
                    IPath outputDir = project.getFolder(build.getOutputDirectory()).getFullPath();
                    List<String> missingDirs = new ArrayList<String>();
                    for (IPath path : additionalSrcDirs) {
                        IFolder folder = project.getFolder(path);
                        if (folder.exists() == false) {
                            missingDirs.add(path.toString());
                        }
                        IPath srcPath = project.getFolder(path).getFullPath();
                        if (containsSourcePath(entries, srcPath) == false) {
                            entries.add(JavaCore.newSourceEntry(srcPath, new IPath[0], new IPath[0],
                                    outputDir.makeAbsolute()));
                        }
                    }
                    if (missingDirs.isEmpty() == false) {
                        WorkspaceUtil.createFolders(project, missingDirs, monitor);
                    }

                    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]), monitor);
                }
            } catch (Exception e) {
                throw new CoreException(EclipseMessageUtils.createErrorStatus(e));
            } finally {
                IOUtils.closeQuietly(input);
            }
        }
    }
}

From source file:org.eclipse.acceleo.internal.ide.ui.wizards.project.AcceleoProjectWizard.java

License:Open Source License

/**
 * Convert the empty project to an Acceleo project.
 * /* w  w  w  .  j a  v a2  s .c  o  m*/
 * @param project
 *            The newly created project.
 * @param selectedJVM
 *            The name of the selected JVM (J2SE-1.5 or JavaSE-1.6 recommended).
 * @param allModules
 *            The description of the module that need to be created.
 * @param shouldGenerateModules
 *            Indicates if we should generate the modules in the project or not. The wizard container to
 *            display the progress monitor
 * @param monitor
 *            The monitor.
 */
public static void convert(IProject project, String selectedJVM, List<AcceleoModule> allModules,
        boolean shouldGenerateModules, IProgressMonitor monitor) {
    String generatorName = computeGeneratorName(project.getName());
    AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE.createAcceleoProject();
    acceleoProject.setName(project.getName());
    acceleoProject.setGeneratorName(generatorName);

    // Default JRE value
    acceleoProject.setJre(selectedJVM);
    if (acceleoProject.getJre() == null || acceleoProject.getJre().length() == 0) {
        acceleoProject.setJre("J2SE-1.5"); //$NON-NLS-1$         
    }

    if (shouldGenerateModules) {
        for (AcceleoModule acceleoModule : allModules) {
            String parentFolder = acceleoModule.getParentFolder();
            IProject moduleProject = ResourcesPlugin.getWorkspace().getRoot()
                    .getProject(acceleoModule.getProjectName());
            if (moduleProject.exists() && moduleProject.isAccessible()
                    && acceleoModule.getModuleElement() != null
                    && acceleoModule.getModuleElement().isIsMain()) {
                IPath parentFolderPath = new Path(parentFolder);
                IFolder folder = moduleProject.getFolder(parentFolderPath.removeFirstSegments(1));
                acceleoProject.getExportedPackages()
                        .add(folder.getProjectRelativePath().removeFirstSegments(1).toString().replaceAll("/", //$NON-NLS-1$
                                "\\.")); //$NON-NLS-1$
            }
            // Calculate project dependencies
            List<String> metamodelURIs = acceleoModule.getMetamodelURIs();
            for (String metamodelURI : metamodelURIs) {
                // Find the project containing this metamodel and add a dependency to it.
                EPackage ePackage = AcceleoPackageRegistry.INSTANCE.getEPackage(metamodelURI);
                if (ePackage != null && !(ePackage instanceof EcorePackage)) {
                    Bundle bundle = AcceleoWorkspaceUtil.getBundle(ePackage.getClass());
                    acceleoProject.getPluginDependencies().add(bundle.getSymbolicName());
                }
            }
        }
    }

    try {
        IProjectDescription description = project.getDescription();
        description.setNatureIds(new String[] { JavaCore.NATURE_ID, IBundleProjectDescription.PLUGIN_NATURE,
                IAcceleoConstants.ACCELEO_NATURE_ID, });
        project.setDescription(description, monitor);

        IJavaProject iJavaProject = JavaCore.create(project);

        // Compute the JRE
        List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
        IExecutionEnvironmentsManager executionEnvironmentsManager = JavaRuntime
                .getExecutionEnvironmentsManager();
        IExecutionEnvironment[] executionEnvironments = executionEnvironmentsManager.getExecutionEnvironments();
        for (IExecutionEnvironment iExecutionEnvironment : executionEnvironments) {
            if (acceleoProject.getJre().equals(iExecutionEnvironment.getId())) {
                entries.add(JavaCore.newContainerEntry(JavaRuntime.newJREContainerPath(iExecutionEnvironment)));
                break;
            }
        }

        // PDE Entry (will not be generated anymore)
        entries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); //$NON-NLS-1$

        // Sets the input / output folders
        IFolder target = project.getFolder("src"); //$NON-NLS-1$
        if (!target.exists()) {
            target.create(true, true, monitor);
        }

        IFolder classes = project.getFolder("bin"); //$NON-NLS-1$
        if (!classes.exists()) {
            classes.create(true, true, monitor);
        }

        iJavaProject.setOutputLocation(classes.getFullPath(), monitor);
        IPackageFragmentRoot packageRoot = iJavaProject.getPackageFragmentRoot(target);
        entries.add(JavaCore.newSourceEntry(packageRoot.getPath(), new Path[] {}, new Path[] {},
                classes.getFullPath()));

        iJavaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
        iJavaProject.open(monitor);

        AcceleoProjectUtils.generateFiles(acceleoProject, allModules, project, shouldGenerateModules, monitor);

        // Default settings
        AcceleoBuilderSettings settings = new AcceleoBuilderSettings(project);
        settings.setCompilationKind(AcceleoBuilderSettings.COMPILATION_PLATFORM_RESOURCE);
        settings.setResourceKind(AcceleoBuilderSettings.BUILD_XMI_RESOURCE);
        settings.save();
    } catch (CoreException e) {
        AcceleoUIActivator.log(e, true);
    }
}

From source file:org.eclipse.che.jdt.testplugin.JavaProjectHelper.java

License:Open Source License

/**
 * Adds a source container to a IJavaProject.
 * @param jproject The parent project//from  w ww  . j  a va2 s.c om
 * @param containerName The name of the new source container
 * @param inclusionFilters Inclusion filters to set
 * @param exclusionFilters Exclusion filters to set
 * @param outputLocation The location where class files are written to, <b>null</b> for project output folder
 * @return The handle to the new source container
 * @throws CoreException Creation failed
 */
public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName,
        IPath[] inclusionFilters, IPath[] exclusionFilters, String outputLocation) throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (containerName == null || containerName.length() == 0) {
        container = project;
    } else {
        IFolder folder = project.getFolder(containerName);
        if (!folder.exists()) {
            CoreUtility.createFolder(folder, false, true, null);
        }
        container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(container);

    IPath outputPath = null;
    if (outputLocation != null) {
        IFolder folder = project.getFolder(outputLocation);
        if (!folder.exists()) {
            CoreUtility.createFolder(folder, false, true, null);
        }
        outputPath = folder.getFullPath();
    }
    IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath(), inclusionFilters, exclusionFilters,
            outputPath);
    addToClasspath(jproject, cpe);
    return root;
}

From source file:org.eclipse.edt.ide.ui.wizards.EGLProjectUtility.java

License:Open Source License

/**
 * Return a list with classpath/container entries for the default
 * Java source folder and the JRE.//ww  w.  jav  a 2 s .  c o  m
 * 
 * @param project
 * @return
 * @throws CoreException
 */
public static List<IClasspathEntry> getDefaultJavaClassPathEntryList(IProject project) throws CoreException {
    List<IClasspathEntry> list = new ArrayList<IClasspathEntry>();

    // Get the default Java source folder name from Java workspace
    // preferences
    String sourceFolderName;
    IPreferenceStore prefs = PreferenceConstants.getPreferenceStore();
    if (prefs.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) {
        sourceFolderName = prefs.getString(PreferenceConstants.SRCBIN_SRCNAME);
    } else {
        sourceFolderName = JAVA_DEFAULT_SOURCE_FOLDER;
    }
    IResource srcFolder = project.getFolder(sourceFolderName);

    if ((srcFolder instanceof IFolder) && !srcFolder.exists())
        CoreUtility.createFolder((IFolder) srcFolder, true, true, null);

    IClasspathEntry javaClasspathEntry = JavaCore.newSourceEntry(srcFolder.getFullPath(), new Path[0],
            new Path[0], null);
    list.add(javaClasspathEntry);

    list.add(JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER"))); //$NON-NLS-1$

    return list;
}