Java 类org.eclipse.jdt.core.JavaCore 实例源码

项目:gw4e.project    文件:InvalidAnnotationPathGeneratorMarkerResolution.java   
private void fix(IMarker marker, IProgressMonitor monitor) {
    MarkerResolutionGenerator.printAttributes (marker);
    try {
        String filepath  = (String) marker.getAttribute(BuildPolicyConfigurationException.JAVAFILENAME);
        int start = (int) marker.getAttribute(IMarker.CHAR_START);
        int end =  (int) marker.getAttribute(IMarker.CHAR_END);
        IFile ifile = (IFile) ResourceManager.toResource(new Path(filepath));
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(ifile);
        String source = cu.getBuffer().getContents();
        String part1 =  source.substring(0,start);
        String part2 =  source.substring(end);
        source = part1 + "value=\"" + resolutionMarkerDescription.getGenerator() + "\"" + part2;
        final Document document = new Document(source);
        cu.getBuffer().setContents(document.get());
        cu.save(monitor, false);
    } catch (Exception e) {
        ResourceManager.logException(e);
    }
}
项目:ContentAssist    文件:WorkspaceUtilities.java   
/**
 * Collects all compilation units within the project.
 * @return the collection of the compilation units
 */
public static List<ICompilationUnit> collectAllCompilationUnits() {
    List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();

    try {
        IProject[] projects =  getWorkspace().getRoot().getProjects();
        for (int i = 0; i < projects.length; i++) {
            IJavaProject project = (IJavaProject)JavaCore.create((IProject)projects[i]);

            IPackageFragment[] packages = project.getPackageFragments();
            for (int j = 0; j < packages.length; j++) {

                ICompilationUnit[] cus = packages[j].getCompilationUnits();
                for (int k = 0; k < cus.length; k++) {
                    IResource res = cus[k].getResource();
                    if (res.getType() == IResource.FILE) {
                        String name = cus[k].getPath().toString();
                        if (name.endsWith(".java")) { 
                            units.add(cus[k]);
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }

    return units;
}
项目:vertigo-chroma-kspplugin    文件:ResourceUtils.java   
/**
 * Obtient la map Project vers Projet Java du workspace courant.
 * 
 * @return Map des projets.
 */
public static JavaProjectMap getProjectMap() {
    JavaProjectMap projects = new JavaProjectMap();

    /* Racine du workspace courant. */
    IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();

    /* Parcourt les projets de la racine. */
    for (IProject project : wsRoot.getProjects()) {

        /* Vérication que le projet est un projet Java accessible. */
        if (!project.isAccessible() || !JdtUtils.isJavaProject(project)) {
            continue;
        }

        /* Obtient l'AST du projet. */
        IJavaProject javaProject = JavaCore.create(project);
        projects.put(project, javaProject);
    }
    return projects;
}
项目:Equella    文件:JarPluginModelImpl.java   
@Override
public List<IClasspathEntry> createClasspathEntries()
{
    IPath srcJar = null;
    if( underlyingResource.getFileExtension().equals("jar") )
    {
        String name = underlyingResource.getName();
        IFile srcJarFile = underlyingResource.getProject().getFile(
            "lib-src/" + name.substring(0, name.length() - 4) + "-sources.jar");
        if( srcJarFile.exists() )
        {
            srcJar = srcJarFile.getFullPath();
        }
    }
    return Arrays.asList(JavaCore.newLibraryEntry(underlyingResource.getFullPath(), srcJar, null));
}
项目:gw4e.project    文件:ClasspathManager.java   
/**
 * Add GraphWalker libraries to the passed project
 * 
 * @param project
 * @throws JavaModelException
 */
public static void addGW4EClassPathContainer(IProject project) throws JavaModelException {
    if (hasGW4EClassPathContainer(project)) {
        return;
    }
    IJavaProject javaProject = JavaCore.create(project); 
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
    System.arraycopy(entries, 0, newEntries, 0, entries.length);
    Path lcp = new Path(GW4ELibrariesContainer.ID);
    IClasspathEntry libEntry = JavaCore.newContainerEntry(lcp, true);
    newEntries[entries.length] = JavaCore.newContainerEntry(libEntry.getPath(), true);
    javaProject.setRawClasspath(newEntries, null);

    addJunit4Libraries(project);
}
项目:gw4e.project    文件:ClasspathManager.java   
/**
 * Add JUnit libraries to the passed project
 * 
 * @param project
 * @throws JavaModelException
 */
private static void addJunit4Libraries(IProject project) throws JavaModelException {
    IClasspathEntry entry = JavaCore.newContainerEntry(JUnitCore.JUNIT4_CONTAINER_PATH);
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    boolean junitFound = false;
    String s = entry.getPath().toString();
    for (int i = 0; i < entries.length; i++) {
        if (entries[i].getPath().toString().indexOf(s) != -1) {
            junitFound = true;
            break;
        }
    }
    if (!junitFound) {
        IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
        System.arraycopy(entries, 0, newEntries, 0, entries.length);
        newEntries[entries.length] = entry;
        javaProject.setRawClasspath(newEntries, null);
    }
}
项目:gw4e.project    文件:ClasspathManager.java   
/**
 * Remove the passed folder from ClassPath
 * 
 * @param project
 * @param folderPath
 * @param monitor
 * @throws JavaModelException
 */
public static void removeFolderFromClasspath(IProject project, String folderPath, IProgressMonitor monitor)
        throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    List<IClasspathEntry> newEntries = new ArrayList<IClasspathEntry>();
    IPath folder = project.getFolder(folderPath).getFullPath();
    for (int i = 0; i < entries.length; i++) {
        if (!entries[i].getPath().equals(folder)) {
            newEntries.add(entries[i]);
        }
    }
    entries = new IClasspathEntry[newEntries.size()];
    newEntries.toArray(entries);
    javaProject.setRawClasspath(entries, monitor);

}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param projectName
 * @return
 * @throws JavaModelException
 */
private static List<IType> findClassesWithAnnotation(String projectName, Class annotationClass, String attributName,
        boolean valued) throws JavaModelException {
    List<IType> classList = new ArrayList<IType>();
    IProject project = ResourceManager.getProject(projectName);
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragment[] packages = javaProject.getPackageFragments();
    for (IPackageFragment packageFragment : packages) {
        for (final ICompilationUnit compilationUnit : packageFragment.getCompilationUnits()) {
            if (compilationUnit.exists()) {
                IType type = getClassesWithAnnotation(compilationUnit, annotationClass, attributName, valued);
                if (type != null)
                    classList.add(type);
            }
        }
    }
    return classList;
}
项目:gw4e.project    文件:GraphWalkerContextManager.java   
public static IJavaProject[] getGW4EProjects() {
    IJavaProject[] projects;
    try {
        projects = JavaCore.create(ResourceManager.getWorkspaceRoot()).getJavaProjects();
    } catch (JavaModelException e) {
        ResourceManager.logException(e);
        projects = new IJavaProject[0];
    }
    List<IJavaProject> gwps = new ArrayList<IJavaProject>();
    for (int i = 0; i < projects.length; i++) {
        if (GW4ENature.hasGW4ENature(projects[i].getProject())) {
            gwps.add(projects[i]);
        }
    }

    IJavaProject[] gwprojects = new IJavaProject[gwps.size()];
    gwps.toArray(gwprojects);
    return gwprojects;
}
项目:gw4e.project    文件:ResourceManager.java   
/**
 * @param project
 * @param qualifiedName
 * @return
 * @throws CoreException
 */
public static IFile getIFileFromQualifiedName(String projectname, String qualifiedName) throws CoreException {
    IProject project = getProject(projectname);
    IJavaProject jproject = JavaCore.create(project);
    IPackageFragment[] pkgs = jproject.getPackageFragments();
    String spath = qualifiedName.replace(".", "/");
    for (int i = 0; i < pkgs.length; i++) {
        if (pkgs[i].getKind() != IPackageFragmentRoot.K_SOURCE)
            continue;
        IPath path = pkgs[i].getPath().append(spath);
        IFile iFile = (IFile) ResourceManager.getResource(path.toString() + ".java");
        if (iFile != null && iFile.exists())
            return iFile;
    }
    return null;
}
项目:gw4e.project    文件:ResourceManager.java   
/**
 * Return whether the resource is in of the passed folders
 * 
 * @param resource
 * @param folders
 * @return
 */
public static boolean isFileInFolders(IFile resource, String[] folders) {
    if (resource == null)
        return false;
    IProject p = resource.getProject();
    IJavaProject javaProject = JavaCore.create(p);
    for (int i = 0; i < folders.length; i++) {
        IPath folderPath = javaProject.getPath().append(folders[i]);
        String allowedPAth = folderPath.toString();
        String resourcePath = resource.getFullPath().toString();
        if (resourcePath.startsWith(allowedPAth)) {
            return true;
        }
    }
    return false;
}
项目:gw4e.project    文件:GW4EFixesTestCase.java   
@Test
public void testUpdatePathGeneratorInSourceFile () throws CoreException, FileNotFoundException {
    System.out.println("XXXXXXXXXXXXXXXXXXXX testUpdatePathGeneratorInSourceFile");
    String expectedNewGenerator = "random(vertex_coverage(50))";

        PetClinicProject.create (bot,gwproject); // At this step the generator is "random(edge_coverage(100))"

        IFile veterinarien = PetClinicProject.getVeterinariensSharedStateImplFile(gwproject);
    ICompilationUnit cu = JavaCore.createCompilationUnitFrom(veterinarien);
    String oldGenerator = JDTManager.findPathGeneratorInGraphWalkerAnnotation(cu);
        SourceHelper.updatePathGenerator(veterinarien, oldGenerator, expectedNewGenerator);
        cu = JavaCore.createCompilationUnitFrom(veterinarien);
        String newGenerator = JDTManager.findPathGeneratorInGraphWalkerAnnotation(cu);
        assertEquals(newGenerator,expectedNewGenerator);

        String location = JDTManager.getGW4EGeneratedAnnotationValue(cu,"value");
        IPath path = new Path (gwproject).append(location);
        IFile graphModel =  (IFile)ResourceManager.getResource(path.toString());
        IPath buildPolicyPath = ResourceManager.getBuildPoliciesPathForGraphModel(graphModel);
        IFile buildPolicyFile =  (IFile)ResourceManager.getResource(buildPolicyPath.toString());

    PropertyValueCondition condition = new PropertyValueCondition(buildPolicyFile,graphModel.getName(),"random(edge_coverage(100));I;random(vertex_coverage(50));I;");
    bot.waitUntil(condition);
    }
项目:gw4e.project    文件:GW4EProject.java   
public void assertHasSourceFolders(String[] folders) throws JavaModelException {
    IProject project = getRoot().getProject(this.projectName);
    IJavaProject jproject = JavaCore.create(project);
    IPackageFragmentRoot[] pkgs = jproject.getPackageFragmentRoots();

    for (int i = 0; i < folders.length; i++) {
        String folder = folders[i];
        boolean found = false;
        for (int j = 0; j < pkgs.length; j++) {
            IPackageFragmentRoot pkg = pkgs[j];
            IPath path = new Path("/").append(this.projectName).append(folder);
            if (pkg.getPath().toString().equalsIgnoreCase(path.toString())) {
                found = true;
            }
            ;
        }
        assertTrue("Expected folder: " + folder, found);
    }
}
项目:gw4e.project    文件:JDTHelper.java   
public static boolean containsMethod (String path, String[] requiredMethods) throws JavaModelException {
    IResource resource = ResourceManager.getResource(path);
    IFile file = (IFile) resource;
    ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
    IType[] types = cu.getAllTypes();
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < types.length; i++) {
        IMethod[] methods = types[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            list.add(methods[j].getElementName());
        }
    } 
    for (int i = 0; i < requiredMethods.length; i++) {
        String method = requiredMethods[i];
        if (!list.contains(method)) return false;
    }     
    return true;
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testFindAnnotationParsingInGeneratedAnnotation() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
    IFile impl = (IFile) ResourceManager
            .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString());
    ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl);

    AnnotationParsing annoParsing = JDTManager.findAnnotationParsingInGeneratedAnnotation(compilationUnit, "value");
    Location location = annoParsing.getLocation();
    assertNotNull(location);

    int line = IOHelper.findLocationLineInFile(impl, "@Generated");
    assertEquals(line,location.getLineNumber());

    Location loc = IOHelper.findLocationInFile(impl, line, "value = \"src/test/resources/Simple.json\"");
    assertEquals(location,loc);

    String value = annoParsing.getValue ( );
    assertEquals("src/test/resources/Simple.json", value);
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testFindAnnotationParsingInGraphWalkerAnnotation() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
    IFile impl = (IFile) ResourceManager
            .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString());
    ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl);
    AnnotationParsing annoParsing = JDTManager.findAnnotationParsingInGraphWalkerAnnotation(compilationUnit, "value");
    Location location = annoParsing.getLocation();
    assertNotNull(location);
    int line = IOHelper.findLocationLineInFile(impl, "@GraphWalker");
    assertEquals(line,location.getLineNumber());
    Location loc = IOHelper.findLocationInFile(impl, line, "value = \"random(edge_coverage(100))\"");
    assertEquals(location,loc);

    String value = annoParsing.getValue ( );
    assertEquals("random(edge_coverage(100))", value);
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testEnrichClass() throws Exception {
    IJavaProject pj = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME,true,false);

    IFile impl = ProjectHelper.createDummyClass (pj);
    ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl);
    IMethod m = compilationUnit.getTypes() [0].getMethod("runFunctionalTest",new String[0]);
    assertFalse (m.exists());

    IFile file = (IFile) ResourceManager.getResource(pj.getProject().getFullPath().append("src/test/resources/Simple.json").toString());
    ResourceContext context =  GenerationFactory.getResourceContext(file);
    ClassExtension ce = context.getClassExtension();
    ce.setGenerateRunFunctionalTest(true);
    ce.setStartElementForJunitTest("start_app");    
    TestResourceGeneration trg = new TestResourceGeneration(context);    
    JDTManager.enrichClass(impl, trg, new NullProgressMonitor());

    m = compilationUnit.getTypes() [0].getMethod("runFunctionalTest",new String[0]);
    assertTrue (m.exists());

}
项目:bayou    文件:Parser.java   
public void parse() throws ParseException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    Map<String, String> options = JavaCore.getOptions();
    options.put("org.eclipse.jdt.core.compiler.source", "1.8");
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setUnitName("Program.java");
    parser.setEnvironment(new String[] { classpath != null? classpath : "" },
            new String[] { "" }, new String[] { "UTF-8" }, true);
    parser.setResolveBindings(true);
    cu = (CompilationUnit) parser.createAST(null);

    List<IProblem> problems = Arrays.stream(cu.getProblems()).filter(p ->
                                        p.isError() &&
                                        p.getID() != IProblem.PublicClassMustMatchFileName && // we use "Program.java"
                                        p.getID() != IProblem.ParameterMismatch // Evidence varargs
                                    ).collect(Collectors.toList());
    if (problems.size() > 0)
        throw new ParseException(problems);
}
项目:Hydrograph    文件:ValidatorUtility.java   
private IJavaProject createJavaProjectThroughActiveEditor() {

    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
            if(page.getActiveEditor().getEditorInput() instanceof IFileEditorInput)
            {   
            IFileEditorInput input = (IFileEditorInput) page.getActiveEditor().getEditorInput();
            IFile file = input.getFile();
            IProject activeProject = file.getProject();
            IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(activeProject.getName());
            return JavaCore.create(project);
            }
            else if(page.getActiveEditor().getEditorInput() instanceof IClassFileEditorInput)
            {
      IClassFileEditorInput classFileEditorInput=(InternalClassFileEditorInput)page.getActiveEditor().getEditorInput() ;
      IClassFile classFile=classFileEditorInput.getClassFile();
      return classFile.getJavaProject();
            }
            return null;
}
项目:BUILD_file_generator    文件:ReferencedClassesParser.java   
private static ASTParser createCompilationUnitParser() {
  ASTParser parser = ASTParser.newParser(AST.JLS8);
  Map options = JavaCore.getOptions();
  JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
  parser.setCompilerOptions(options);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  return parser;
}
项目:RefDiff    文件:LSDiffRunner.java   
private static Set<ICompilationUnit> getFiles(String projname) throws CoreException {
    IWorkspaceRoot ws = ResourcesPlugin.getWorkspace().getRoot();
    IProject proj = ws.getProject(projname);
    IJavaProject javaProject = JavaCore.create(proj);
    Set<ICompilationUnit> files = new HashSet<ICompilationUnit>();
    javaProject.open(new NullProgressMonitor());
    for( IPackageFragment packFrag : javaProject.getPackageFragments()) {
        for (ICompilationUnit icu : packFrag.getCompilationUnits()) {
            files.add(icu);
        }
    }
    javaProject.close();
    return files;
}
项目:Equella    文件:JPFClasspathContainer.java   
public static void addToProject(IJavaProject javaProject)
{
    try
    {
        Set<IClasspathEntry> entries = new LinkedHashSet<>();
        entries.addAll(Arrays.asList(javaProject.getRawClasspath()));
        entries.add(JavaCore.newContainerEntry(JPFClasspathPlugin.CONTAINER_PATH));
        javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
    }
    catch( JavaModelException e )
    {
        JPFClasspathLog.logError(e);
    }

}
项目:Equella    文件:JPFClasspathContainerInitializer.java   
@Override
public void initialize(IPath containerPath, IJavaProject javaProject) throws CoreException
{
    IProject project = javaProject.getProject();
    IPluginModel model = JPFPluginModelManager.instance().findModel(project);
    JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { javaProject },
        new IClasspathContainer[] { new JPFClasspathContainer(model) }, null);
}
项目:visuflow-plugin    文件:JimpleBuilder.java   
protected void fullBuild(IProgressMonitor monitor) throws CoreException{
    Visuflow.getDefault().getLogger().info("Build Start");
    String targetFolder = "sootOutput";
    IJavaProject project = JavaCore.create(getProject());
    IResourceDelta delta = getDelta(project.getProject());
    if (delta == null || !delta.getAffectedChildren()[0].getProjectRelativePath().toString().equals(targetFolder)) {
        classpath = getSootCP(project);
        String location = GlobalSettings.get("Target_Path");
        IFolder folder = project.getProject().getFolder(targetFolder);

        // at this point, no resources have been created
        if (!folder.exists()) {
            // Changed to force because of bug id vis-119
            folder.create(IResource.FORCE, true, monitor);

        } else {
            for (IResource resource : folder.members()) {
                resource.delete(IResource.FORCE, monitor);
            }
        }
        classpath = location + classpath;
        String[] sootString = new String[] { "-cp", classpath, "-exclude", "javax", "-allow-phantom-refs", "-no-bodies-for-excluded", "-process-dir",
                location, "-src-prec", "only-class", "-w", "-output-format", "J", "-keep-line-number", "-output-dir",
                folder.getLocation().toOSString()/* , "tag.ln","on" */ };
        ICFGStructure icfg = new ICFGStructure();
        JimpleModelAnalysis analysis = new JimpleModelAnalysis();
        analysis.setSootString(sootString);
        List<VFClass> jimpleClasses = new ArrayList<>();
        try {
            analysis.createICFG(icfg, jimpleClasses);
            fillDataModel(icfg, jimpleClasses);
        } catch(Exception e) {
            logger.error("Couldn't execute analysis", e);
        }

        folder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }
}
项目:Equella    文件:JPFPluginModelManager.java   
@Override
protected IStatus run(IProgressMonitor monitor)
{
    try
    {
        boolean more = false;
        do
        {
            IJavaProject[] projects = null;
            IClasspathContainer[] containers = null;
            synchronized( fProjects )
            {
                projects = fProjects.toArray(new IJavaProject[fProjects.size()]);
                containers = fContainers.toArray(new IClasspathContainer[fContainers.size()]);
                fProjects.clear();
                fContainers.clear();
            }
            JavaCore.setClasspathContainer(JPFClasspathPlugin.CONTAINER_PATH, projects, containers, monitor);
            synchronized( fProjects )
            {
                more = !fProjects.isEmpty();
            }
        }
        while( more );

    }
    catch( JavaModelException e )
    {
        return e.getStatus();
    }
    return Status.OK_STATUS;
}
项目:Equella    文件:WorkspacePluginModelManager.java   
@Override
protected void addListeners()
{
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    workspace.addResourceChangeListener(this, IResourceChangeEvent.PRE_CLOSE);
    JavaCore.addPreProcessingResourceChangedListener(this, IResourceChangeEvent.POST_CHANGE);

}
项目:Equella    文件:WorkspacePluginModelManager.java   
@Override
protected void removeListeners()
{
    ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
    JavaCore.removePreProcessingResourceChangedListener(this);
    super.removeListeners();
}
项目:Hydrograph    文件:ProjectStructureCreator.java   
/**
 * Sets the <b>src</b> folder as the source folder in project
 * @param project
 * @param javaProject
 * @return IClasspathEntry[]
 * @throws JavaModelException
 */
private IClasspathEntry[] setSourceFolderInClassPath(IProject project,  IJavaProject javaProject) throws JavaModelException {
    IFolder sourceFolder = project.getFolder(Constants.ProjectSupport_SRC); //$NON-NLS-1$
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder);
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
    return newEntries;
}
项目:dacapobench    文件:TestingEnvironment.java   
public IPath addProject(String projectName, String compliance) {
  checkAssertion("a workspace must be open", this.isOpen); //$NON-NLS-1$
  IProject project = createProject(projectName);
  int requiredComplianceFlag = 0;
  String compilerVersion = null;
  if ("1.5".equals(compliance)) {
    requiredComplianceFlag = AbstractCompilerTest.F_1_5;
    compilerVersion = CompilerOptions.VERSION_1_5;
  } else if ("1.6".equals(compliance)) {
    requiredComplianceFlag = AbstractCompilerTest.F_1_6;
    compilerVersion = CompilerOptions.VERSION_1_6;
  } else if ("1.7".equals(compliance)) {
    requiredComplianceFlag = AbstractCompilerTest.F_1_7;
    compilerVersion = CompilerOptions.VERSION_1_7;
  } else if (!"1.4".equals(compliance) && !"1.3".equals(compliance)) {
    throw new UnsupportedOperationException("Test framework doesn't support compliance level: " + compliance);
  }
  if (requiredComplianceFlag != 0) {
    if ((AbstractCompilerTest.getPossibleComplianceLevels() & requiredComplianceFlag) == 0)
      throw new RuntimeException("This test requires a " + compliance + " JRE");
    IJavaProject javaProject = JavaCore.create(project);
    Map options = new HashMap();
    options.put(CompilerOptions.OPTION_Compliance, compilerVersion);
    options.put(CompilerOptions.OPTION_Source, compilerVersion);
    options.put(CompilerOptions.OPTION_TargetPlatform, compilerVersion);
    javaProject.setOptions(options);
  }
  return project.getFullPath();
}
项目:Equella    文件:NewJPFPluginWizardPageOne.java   
@Override
public IClasspathEntry[] getDefaultClasspathEntries()
{
    List<IClasspathEntry> entries = new ArrayList<>();
    entries.addAll(Arrays.asList(PreferenceConstants.getDefaultJRELibrary()));
    entries.add(JavaCore.newContainerEntry(JPFClasspathPlugin.CONTAINER_PATH));
    return entries.toArray(new IClasspathEntry[entries.size()]);
}
项目:dacapobench    文件:TestingEnvironment.java   
private synchronized IProject createProject(String projectName) {
  final IProject project = this.workspace.getRoot().getProject(projectName);

  Object cmpl = JavaCore.getOption(CompilerOptions.OPTION_Compliance);
  Object src  = JavaCore.getOption(CompilerOptions.OPTION_Source);
  Object tgt  = JavaCore.getOption(CompilerOptions.OPTION_TargetPlatform);

  try {
    IWorkspaceRunnable create = new IWorkspaceRunnable() {
      public void run(IProgressMonitor monitor) throws CoreException {
        project.create(null, null);
        project.open(null);
      }
    };
    this.workspace.run(create, null);
    this.projects.put(projectName, project);
    addBuilderSpecs(projectName);
  } catch (CoreException e) {
    handle(e);
  } finally {
    // restore workspace settings
    Hashtable options = JavaCore.getOptions();
    options.put(CompilerOptions.OPTION_Compliance,cmpl);
    options.put(CompilerOptions.OPTION_Source,src);
    options.put(CompilerOptions.OPTION_TargetPlatform,tgt);
    JavaCore.setOptions(options);
  }
  return project;
}
项目:Equella    文件:JPFProjectNature.java   
@Override
public void deconfigure() throws CoreException
{
    IProjectDescription description = project.getDescription();
    JPFManifestBuilder.removeBuilderFromProject(description);
    JPFClasspathContainer.removeFromProject(JavaCore.create(project));
    project.setDescription(description, null);
    JPFManifestBuilder.deleteMarkers(project);
}
项目:RefDiff    文件:SDModelBuilder.java   
private static ASTParser buildAstParser(String[] sourceFolders) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setEnvironment(new String[0], sourceFolders, null, true);
    // parser.setEnvironment(new String[0], new String[]{"tmp\\refactoring-toy-example\\src"}, null, false);
    return parser;
}
项目:gw4e.project    文件:GW4ENature.java   
public static IClasspathEntry[] getSourceClasspathEntries(String project) {
    IPath path1 = new Path(project).append(Constant.SOURCE_MAIN_JAVA).makeAbsolute();
    IPath path2 = new Path(project).append(Constant.SOURCE_MAIN_RESOURCES).makeAbsolute();
    IPath path3 = new Path(project).append(Constant.SOURCE_TEST_JAVA).makeAbsolute();
    IPath path4 = new Path(project).append(Constant.SOURCE_TEST_RESOURCES).makeAbsolute();
    IPath path5 = new Path(project).append(Constant.SOURCE_GENERATED_INTERFACE).makeAbsolute();
    IPath path6 = new Path(project).append(Constant.TEST_GENERATED_INTERFACE).makeAbsolute();
    return new IClasspathEntry[] { JavaCore.newSourceEntry(path1), JavaCore.newSourceEntry(path2),
            JavaCore.newSourceEntry(path3), JavaCore.newSourceEntry(path4),
            JavaCore.newSourceEntry(path5) , JavaCore.newSourceEntry(path6)};
}
项目:gw4e.project    文件:ExecutionContextSelectionUIPage.java   
private void setupAncestor(ComboViewer comboViewer) {
    comboViewer.setContentProvider(new IStructuredContentProvider() {
        @Override
        public Object[] getElements(Object inputElement) {
            List<IFile> files = (List<IFile>) inputElement;
            Object[] ret = new Object[files.size()];
            int index = 0;
            for (IFile file : files) {
                ret[index++] = JavaCore.create(file);
            }
            return ret;
        }
    });
    comboViewer.setLabelProvider(new JavaElementLabelProvider(
            JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT));
    comboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            if (selection.size() > 0) {
                ancestor = (ICompilationUnit) selection.getFirstElement();
            }
        }
    });
    comboViewer.getCombo().setData(GW4E_CONVERSION_WIDGET_ID, GW4E_CONVERSION_COMBO_ANCESTOR_EXTEND_TEST);

    comboViewer.setInput(ancestors);
    if (hasItems()) {
        comboViewer.setSelection(new StructuredSelection(JavaCore.create(ancestors.get(0))));
    }
}
项目:gw4e.project    文件:FolderSelectionGroup.java   
@Override
public Image getImage(Object element) {
    IResource resource = (IResource) element;
    IJavaElement javaElement = JavaCore.create(resource);

    if (javaElement instanceof IJavaProject) {
        return PlatformUI.getWorkbench().getSharedImages().getImage(org.eclipse.ui.ide.IDE.SharedImages.IMG_OBJ_PROJECT);
    }

    org.eclipse.ui.ISharedImages sharedImages= PlatformUI.getWorkbench().getSharedImages();

    Image image = sharedImages.getImage(org.eclipse.ui.ISharedImages.IMG_OBJ_FOLDER);
    return image;

}
项目:Hydrograph    文件:BuildExpressionEditorDataSturcture.java   
/**
 * Returns packages of given jar file
 * 
 * @param jarFileName
 * @return IPackageFragmentRoot
 *          packages of given jar file
 */
public IPackageFragmentRoot getIPackageFragment(String jarFileName) {
    IProject iProject = getCurrentProject();
    IJavaProject javaProject = JavaCore.create(iProject);
    try {
        if(StringUtils.equals(jarFileName, hydrograph.ui.common.util.Constants.ProjectSupport_SRC)){
            return getSrcPackageFragment(javaProject);
        }

        IPackageFragmentRoot[] fragmentRoot = javaProject.getAllPackageFragmentRoots();
        for (IPackageFragmentRoot iPackageFragmentRoot : fragmentRoot) {
            if (StringUtils.contains(iPackageFragmentRoot.getElementName(), jarFileName))
                return iPackageFragmentRoot;
        }
    } catch (JavaModelException javaModelException) {
        LOGGER.error("Error occurred while loading engines-transform jar", javaModelException);
    }
    finally{
        if(javaProject!=null){
            try {
                javaProject.close();
            } catch (JavaModelException modelException) {
                LOGGER.warn("JavaModelException occurred while closing java-project"+modelException);
            }
        }
    }
    if(StringUtils.equals(jarFileName, ConfigFileReader.INSTANCE.getConfigurationValueFromCommon(Constants.KEY_TRANSFORMATION_JAR)))
        new CustomMessageBox(SWT.ERROR, "Error occurred while loading " + jarFileName + " file", "ERROR").open();
    return null;
}
项目:gw4e.project    文件:GeneratorChoiceComposite.java   
public void initialize(String widgetid, boolean active) {
    setEnabled(active);
    setContentProvider(new IStructuredContentProvider() {
        @Override
        public Object[] getElements(Object inputElement) {
            List<IFile> files = (List<IFile>) inputElement;
            Object[] ret = new Object[files.size()];
            int index = 0;
            for (IFile file : files) {
                ret[index++] = JavaCore.create(file);
            }
            return ret;
        }
    });
    setLabelProvider(new JavaElementLabelProvider(
            JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT));
    addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            if (selection.size() > 0) {
                ICompilationUnit element = (ICompilationUnit) selection.getFirstElement();
                GeneratorChoiceComposite.this.pkgf = (IPackageFragment) element.getParent();
                listener.handleEvent(null);
            }
        }
    });
    setData(GW4E_CONVERSION_WIDGET_ID, widgetid);

    setInput(ancestors);
    if (active && hasItems()) {
        setSelection(new StructuredSelection(JavaCore.create(ancestors.get(0))));
    }
}
项目:gw4e.project    文件:ClasspathManager.java   
/**
 * 
 * @param project
 * @return whether the project has the GW4E ClassPathContainer
 * @throws JavaModelException
 */
public static boolean hasGW4EClassPathContainer(IProject project) throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    for (int i = 0; i < entries.length; i++) {
        if (entries[i].getPath().toString().startsWith(GW4ELibrariesContainer.ID)) {
            return true;
        }
    }
    return false;
}
项目:gw4e.project    文件:ClasspathManager.java   
/**
 * Manage source folders exclusion
 * 
 * @param project
 * @param rootSrcEntry
 * @param relative
 * @return
 * @throws JavaModelException
 */
private static IClasspathEntry ensureExcludedPath(IProject project, IClasspathEntry rootSrcEntry,
        String relative) throws JavaModelException {
    if (rootSrcEntry == null)
        return rootSrcEntry;
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    IPath[] excluded = rootSrcEntry.getExclusionPatterns();
    boolean entryFound = false;
    for (int i = 0; i < excluded.length; i++) {
        if (excluded[i].toString().equalsIgnoreCase(relative)) {
            entryFound = true;
            break;
        }
    }
    if (!entryFound) {
        IPath rootSrcPath = javaProject.getPath().append("src");
        IPath[] newEntries = new IPath[excluded.length + 1];
        System.arraycopy(excluded, 0, newEntries, 0, excluded.length);
        newEntries[excluded.length] = new Path(relative);
        rootSrcEntry = JavaCore.newSourceEntry(rootSrcPath, newEntries);
        entries = javaProject.getRawClasspath();
        List<IClasspathEntry> temp = new ArrayList<IClasspathEntry>();
        temp.add(rootSrcEntry);
        for (int i = 0; i < entries.length; i++) {
            if (!(entries[i].getPath().equals(rootSrcPath))) {
                temp.add(entries[i]);
            }
        }
        IClasspathEntry[] array = new IClasspathEntry[temp.size()];
        temp.toArray(array);
        javaProject.setRawClasspath(array, null);
    }
    return rootSrcEntry;
}