public void testRemoveFromBuildpath01() throws Exception {
    fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME);
    IPackageFragmentRoot src1 = JavaProjectHelper.addSourceContainer(fJavaProject, "src1");
    IPackageFragmentRoot src2 = JavaProjectHelper.addSourceContainer(fJavaProject, "src2");

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    CPListElement[] toRemove = new CPListElement[2];
    toRemove[0] = CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject);
    toRemove[1] = CPListElement.createFromExisting(src2.getRawClasspathEntry(), fJavaProject);

    BuildpathDelta delta = ClasspathModifier.removeFromBuildpath(toRemove, cpProject);
    assertDeltaResources(
        delta,
        new IPath[0],
        new IPath[] {src1.getPath(), src2.getPath()},
        new IPath[0],
        new IPath[0]);
    assertDeltaDefaultOutputFolder(
        delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME));
    assertDeltaRemovedEntries(delta, new IPath[] {src1.getPath(), src2.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 1);
  }
Exemplo n.º 2
0
 private Bundle getBundle(JdtTypeMirror mirror) {
   IType mirroredType = mirror.getMirroredType();
   IPackageFragmentRoot fragmentRoot = getPackageFragmentRoot(mirroredType);
   if (fragmentRoot == null || fragmentRoot.getPath() == null) return null;
   File file = fragmentRoot.getPath().toFile();
   String bundleName;
   if (file.isFile()) bundleName = getBundleNameFromJar(file);
   else if (file.isDirectory()) bundleName = getBundleNameFromDir(file);
   else return null;
   if (bundleName == null) return null;
   return Platform.getBundle(bundleName);
 }
 /** @since 2.4 */
 @Override
 public Pair<URI, URI> getURIMapping(IPackageFragmentRoot root) throws JavaModelException {
   PackageFragmentRootData data = getData(root);
   if (data.uriPrefix == null) return null;
   IPath path = root.isExternal() ? root.getPath() : root.getUnderlyingResource().getLocation();
   URI physical = null;
   if (root.isArchive()) {
     String archiveScheme =
         "zip".equalsIgnoreCase(root.getPath().getFileExtension()) ? "zip" : "jar";
     physical = URI.createURI(archiveScheme + ":file:" + path.toFile().getPath() + "!/");
   } else {
     physical = URI.createFileURI(path.toFile().getPath() + "/");
   }
   return Tuples.create(data.uriPrefix, physical);
 }
  public void testRemoveFromBuildpathBug153299Lib() throws Exception {
    fJavaProject = createProject(null);
    IPackageFragmentRoot p01 =
        JavaProjectHelper.addSourceContainer(fJavaProject, null, new IPath[] {new Path("src1/")});

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    IPath[] jarPaths = new IPath[] {JavaProjectHelper.MYLIB.makeAbsolute()};

    ClasspathModifier.addExternalJars(jarPaths, cpProject);
    ClasspathModifier.commitClassPath(cpProject, null);

    cpProject = CPJavaProject.createFromExisting(fJavaProject);

    BuildpathDelta delta =
        ClasspathModifier.removeFromBuildpath(
            new CPListElement[] {
              CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject)
            },
            cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(delta, fJavaProject.getPath());
    assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 2);
  }
 private long getContainerTimestamp(TypeNameMatch match) {
   try {
     IType type = match.getType();
     IResource resource = type.getResource();
     if (resource != null) {
       URI location = resource.getLocationURI();
       if (location != null) {
         IFileInfo info = EFS.getStore(location).fetchInfo();
         if (info.exists()) {
           // The element could be removed from the build path. So check
           // if the Java element still exists.
           IJavaElement element = JavaCore.create(resource);
           if (element != null && element.exists()) return info.getLastModified();
         }
       }
     } else { // external JAR
       IPackageFragmentRoot root = match.getPackageFragmentRoot();
       if (root.exists()) {
         IFileInfo info = EFS.getLocalFileSystem().getStore(root.getPath()).fetchInfo();
         if (info.exists()) {
           return info.getLastModified();
         }
       }
     }
   } catch (CoreException e) {
     // Fall through
   }
   return IResource.NULL_STAMP;
 }
Exemplo n.º 6
0
 /* (non-Javadoc)
  * @see IJavaSearchScope#encloses(IJavaElement)
  */
 public boolean encloses(IJavaElement element) {
   if (this.elements != null) {
     for (int i = 0, length = this.elements.size(); i < length; i++) {
       IJavaElement scopeElement = (IJavaElement) this.elements.get(i);
       IJavaElement searchedElement = element;
       while (searchedElement != null) {
         if (searchedElement.equals(scopeElement)) return true;
         searchedElement = searchedElement.getParent();
       }
     }
     return false;
   }
   IPackageFragmentRoot root =
       (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
   if (root != null && root.isArchive()) {
     // external or internal jar
     IPath rootPath = root.getPath();
     String rootPathToString =
         rootPath.getDevice() == null ? rootPath.toString() : rootPath.toOSString();
     IPath relativePath = getPath(element, true /*relative path*/);
     return indexOf(rootPathToString, relativePath.toString()) >= 0;
   }
   // resource in workspace
   String fullResourcePathString = getPath(element, false /*full path*/).toString();
   return indexOf(fullResourcePathString) >= 0;
 }
  /**
   * Adds a source container to a IJavaProject.
   *
   * @param jproject The parent project
   * @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;
  }
  protected List<String> getSourceFolders(IProject project) {
    List<String> result = new ArrayList<String>();
    IJavaProject javaProject = JavaCore.create(project);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    try {
      for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) {
        if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
          IPath path = packageFragmentRoot.getPath();
          IFolder folder = root.getFolder(path);
          String location = folder.getLocation().toString();

          if (!location.contains("src-gen")) {
            result.add(location);
          }
        }
      }

      for (IProject referencedProject : javaProject.getProject().getReferencedProjects()) {
        if (referencedProject.isAccessible() && referencedProject.hasNature(JavaCore.NATURE_ID)) {
          result.addAll(getSourceFolders(referencedProject));
        }
      }

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

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

    return result;
  }
  public void testRemoveFromBuildpathBug153299Src() throws Exception {
    fJavaProject = createProject(null);

    // Use the old behavior in order to test the fallback code. Set to ERROR since 3.8.
    fJavaProject.setOption(
        JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.IGNORE);

    IPackageFragmentRoot p01 =
        JavaProjectHelper.addSourceContainer(fJavaProject, null, new IPath[] {new Path("src1/")});
    JavaProjectHelper.addSourceContainer(fJavaProject, "src1");

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);

    BuildpathDelta delta =
        ClasspathModifier.removeFromBuildpath(
            new CPListElement[] {
              CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject)
            },
            cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(
        delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME));
    assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 2);
  }
Exemplo n.º 10
0
 /**
  * Adds a new source container specified by the container name to the source path of the specified
  * project
  *
  * @param jproject
  * @param containerName
  * @return the package fragment root of the container name
  * @throws CoreException
  */
 public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName)
     throws CoreException {
   IProject project = jproject.getProject();
   IPackageFragmentRoot root =
       jproject.getPackageFragmentRoot(addFolderToProject(project, containerName));
   IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath());
   addToClasspath(jproject, cpe);
   return root;
 }
 /**
  * Returns the path for this fragment in a OS friendly string. Note that in windows, the method
  * for getting the absolute path varies for source folders and jars
  *
  * @param fragmentRoot The fragment containing classes
  * @return The path of this fragment root, os-friendly
  */
 private String getPathFor(final IPackageFragmentRoot fragmentRoot) {
   final IResource resource = fragmentRoot.getResource();
   final IPath path;
   if (resource != null) {
     path = resource.getRawLocation();
   } else {
     path = fragmentRoot.getPath().makeAbsolute();
   }
   return path.toOSString();
 }
Exemplo n.º 12
0
  private IPackageFragmentRoot createSourceFolder() throws CoreException {
    IFolder folder = project.getFolder("src");
    folder.create(false, true, null);
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);

    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());
    javaProject.setRawClasspath(newEntries, null);
    return root;
  }
Exemplo n.º 13
0
 public static ISourceLocation findLocation(IPackageFragmentRoot root) throws JavaModelException {
   if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
     IPath path = EclEmmaCorePlugin.getAbsolutePath(root.getPath());
     return new SourceLocation(path, new Path(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH));
   } else {
     IPath path = root.getSourceAttachmentPath();
     if (path != null) {
       path = EclEmmaCorePlugin.getAbsolutePath(path);
       return new SourceLocation(path, root.getSourceAttachmentRootPath());
     } else {
       return null;
     }
   }
 }
 private Object computeModificationStamp(IPackageFragmentRoot root) {
   try {
     if (root.exists()) {
       IResource resource = root.getUnderlyingResource();
       if (resource != null) {
         Object result = getLastModified(resource);
         if (result != null) {
           return result;
         }
       }
       return root.getPath().toFile().lastModified();
     }
   } catch (CoreException e) {
     log.error(e.getMessage(), e);
   }
   return new Object();
 }
 /**
  * Creates and adds a class folder to the class path and imports all files contained in the given
  * ZIP file.
  *
  * @param jproject The parent project
  * @param containerName
  * @param sourceAttachPath The source attachment path
  * @param sourceAttachRoot The source attachment root path
  * @param zipFile
  * @return The handle of the created root
  * @throws IOException
  * @throws CoreException
  * @throws InvocationTargetException
  */
 public static IPackageFragmentRoot addClassFolderWithImport(
     IJavaProject jproject,
     String containerName,
     IPath sourceAttachPath,
     IPath sourceAttachRoot,
     File zipFile)
     throws IOException, CoreException, InvocationTargetException {
   ZipFile file = new ZipFile(zipFile);
   try {
     IPackageFragmentRoot root =
         addClassFolder(jproject, containerName, sourceAttachPath, sourceAttachRoot);
     importFilesFromZip(file, root.getPath(), null);
     return root;
   } finally {
     file.close();
   }
 }
 protected IBinaryType createInfoFromClassFileInJar(Openable classFile) {
   String filePath =
       (((ClassFile) classFile).getType().getFullyQualifiedName('$')).replace('.', '/')
           + SuffixConstants.SUFFIX_STRING_class;
   IPackageFragmentRoot root = classFile.getPackageFragmentRoot();
   IPath path = root.getPath();
   // take the OS path for external jars, and the forward slash path for internal jars
   String rootPath = path.getDevice() == null ? path.toString() : path.toOSString();
   String documentPath = rootPath + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + filePath;
   IBinaryType binaryType = (IBinaryType) this.binariesFromIndexMatches.get(documentPath);
   if (binaryType != null) {
     this.infoToHandle.put(binaryType, classFile);
     return binaryType;
   } else {
     return super.createInfoFromClassFileInJar(classFile);
   }
 }
 /**
  * Adds a source container to a IJavaProject and imports all files contained in the given ZIP
  * file.
  *
  * @param jproject The parent project
  * @param containerName Name of the source container
  * @param zipFile Archive to import
  * @param containerEncoding encoding for the generated source container
  * @param exclusionFilters Exclusion filters to set
  * @return The handle to the new source container
  * @throws InvocationTargetException Creation failed
  * @throws CoreException Creation failed
  * @throws IOException Creation failed
  */
 public static IPackageFragmentRoot addSourceContainerWithImport(
     IJavaProject jproject,
     String containerName,
     File zipFile,
     String containerEncoding,
     IPath[] exclusionFilters)
     throws InvocationTargetException, CoreException, IOException {
   ZipFile file = new ZipFile(zipFile);
   try {
     IPackageFragmentRoot root = addSourceContainer(jproject, containerName, exclusionFilters);
     ((IContainer) root.getCorrespondingResource()).setDefaultCharset(containerEncoding, null);
     importFilesFromZip(file, root.getPath(), null);
     return root;
   } finally {
     file.close();
   }
 }
 private PackageFragmentRootData getCachedData(IPackageFragmentRoot root) {
   final String path = root.getPath().toString();
   synchronized (cachedPackageFragmentRootData) {
     if (cachedPackageFragmentRootData.containsKey(path)) {
       final PackageFragmentRootData data = cachedPackageFragmentRootData.get(path);
       if (isUpToDate(data, root)) {
         data.addRoot(root);
         return data;
       } else {
         cachedPackageFragmentRootData.remove(path);
       }
     }
   }
   PackageFragmentRootData data = initializeData(root);
   synchronized (cachedPackageFragmentRootData) {
     cachedPackageFragmentRootData.put(path, data);
   }
   return data;
 }
  public void testRemoveFromBuildpath01RemoveProject() throws Exception {
    fJavaProject = createProject(null);
    IPackageFragmentRoot p01 = JavaProjectHelper.addSourceContainer(fJavaProject, null);

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);

    BuildpathDelta delta =
        ClasspathModifier.removeFromBuildpath(
            new CPListElement[] {
              CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject)
            },
            cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(delta, fJavaProject.getPath());
    assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()});
    assertDeltaAddedEntries(delta, new IPath[0]);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 1);
  }
  private static boolean isRootAt(IPackageFragmentRoot root, IPath entry) {
    try {
      IClasspathEntry cpe = root.getRawClasspathEntry();
      if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
        IPath outputLocation = cpe.getOutputLocation();
        if (outputLocation == null) outputLocation = root.getJavaProject().getOutputLocation();

        IPath location =
            ResourcesPlugin.getWorkspace().getRoot().findMember(outputLocation).getLocation();
        if (entry.equals(location)) return true;
      }
    } catch (JavaModelException e) {
      JavaPlugin.log(e);
    }

    IResource resource = root.getResource();
    if (resource != null && entry.equals(resource.getLocation())) return true;

    IPath path = root.getPath();
    if (path != null && entry.equals(path)) return true;

    return false;
  }
 /** @since 2.5 */
 @Override
 public URI getUri(/* @NonNull */ IStorage storage) {
   if (storage instanceof IJarEntryResource) {
     final IJarEntryResource casted = (IJarEntryResource) storage;
     IPackageFragmentRoot packageFragmentRoot = casted.getPackageFragmentRoot();
     Map<URI, IStorage> data = getAllEntries(packageFragmentRoot);
     for (Map.Entry<URI, IStorage> entry : data.entrySet()) {
       if (entry.getValue().equals(casted)) return entry.getKey();
     }
     if (packageFragmentRoot.exists() && packageFragmentRoot.isArchive()) {
       IPath jarPath = packageFragmentRoot.getPath();
       URI jarURI;
       if (packageFragmentRoot.isExternal()) {
         jarURI = URI.createFileURI(jarPath.toOSString());
       } else {
         jarURI = URI.createPlatformResourceURI(jarPath.toString(), true);
       }
       URI result = URI.createURI("archive:" + jarURI + "!" + storage.getFullPath());
       return result;
     }
   }
   return null;
 }
  Text createFolderField(Composite composite) {
    Label folderLabel = new Label(composite, SWT.LEFT | SWT.WRAP);
    folderLabel.setText("Source folder: ");
    GridData flgd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    flgd.horizontalSpan = 1;
    folderLabel.setLayoutData(flgd);

    final Text folder = new Text(composite, SWT.SINGLE | SWT.BORDER);
    GridData fgd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    fgd.horizontalSpan = 2;
    fgd.grabExcessHorizontalSpace = true;
    folder.setLayoutData(fgd);
    if (sourceDir != null) {
      String folderName = sourceDir.getPath().toPortableString();
      folder.setText(folderName);
    }
    folder.addModifyListener(
        new ModifyListener() {
          @Override
          public void modifyText(ModifyEvent e) {
            setSourceDir(folder.getText());
            if (sourceDir != null && packageNameIsLegal()) {
              packageFragment = sourceDir.getPackageFragment(packageName);
            }
            if (sourceDir == null) {
              setErrorMessage(getSelectSourceFolderMessage());
            } else if (!packageNameIsLegal()) {
              setErrorMessage(getIllegalPackageNameMessage());
            } else if (!unitNameIsLegal()) {
              setErrorMessage(getIllegalUnitNameMessage());
            } else {
              setErrorMessage(null);
            }
            setPageComplete(isComplete());
          }

          private void setSourceDir(String folderName) {
            try {
              sourceDir = null;
              for (IJavaProject jp :
                  JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects()) {
                for (IPackageFragmentRoot pfr : jp.getPackageFragmentRoots()) {
                  if (pfr.getPath().toPortableString().equals(folderName)) {
                    sourceDir = pfr;
                    return;
                  }
                }
              }
            } catch (JavaModelException jme) {
              jme.printStackTrace();
            }
          }
        });

    Button selectFolder = new Button(composite, SWT.PUSH);
    selectFolder.setText("Browse...");
    GridData sfgd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    sfgd.horizontalSpan = 1;
    selectFolder.setLayoutData(sfgd);
    selectFolder.addSelectionListener(
        new SelectionListener() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            IPackageFragmentRoot pfr =
                getSourceContainer(getShell(), ResourcesPlugin.getWorkspace().getRoot(), sourceDir);
            if (pfr != null) {
              sourceDir = pfr;
              String folderName = sourceDir.getPath().toPortableString();
              folder.setText(folderName);
              packageFragment = sourceDir.getPackageFragment(packageName);
              setPageComplete(isComplete());
            }
            if (sourceDir == null) {
              setErrorMessage(getSelectSourceFolderMessage());
            } else if (!packageNameIsLegal()) {
              setErrorMessage(getIllegalPackageNameMessage());
            } else if (!unitNameIsLegal()) {
              setErrorMessage(getIllegalUnitNameMessage());
            } else {
              setErrorMessage(null);
            }
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {}
        });

    new Label(composite, SWT.NONE);

    Link link = new Link(composite, SWT.NONE);
    link.setText("<a>Create new source folder...</a>");
    GridData kgd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    kgd.horizontalSpan = 3;
    kgd.grabExcessHorizontalSpace = true;
    link.setLayoutData(kgd);
    link.addSelectionListener(
        new SelectionListener() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            IPackageFragmentRoot pfr = (IPackageFragmentRoot) openSourceFolderWizard();
            if (pfr != null) {
              sourceDir = pfr;
              String folderName = sourceDir.getPath().toPortableString();
              folder.setText(folderName);
              packageFragment = sourceDir.getPackageFragment(packageName);
              setPageComplete(isComplete());
            }
            if (sourceDir == null) {
              setErrorMessage(getSelectSourceFolderMessage());
            } else if (!packageNameIsLegal()) {
              setErrorMessage(getIllegalPackageNameMessage());
            } else if (!unitNameIsLegal()) {
              setErrorMessage(getIllegalUnitNameMessage());
            } else {
              setErrorMessage(null);
            }
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {}
        });

    return folder;
  }
  private void collectProposals(
      IJavaProject project, String name, Collection<DefaultClasspathFixProposal> proposals)
      throws CoreException {
    int idx = name.lastIndexOf('.');
    char[] packageName =
        idx != -1 ? name.substring(0, idx).toCharArray() : null; // no package provided
    char[] typeName = name.substring(idx + 1).toCharArray();

    if (typeName.length == 1 && typeName[0] == '*') {
      typeName = null;
    }

    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    ArrayList<TypeNameMatch> res = new ArrayList<TypeNameMatch>();
    TypeNameMatchCollector requestor = new TypeNameMatchCollector(res);
    int matchMode = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    new SearchEngine()
        .searchAllTypeNames(
            packageName,
            matchMode,
            typeName,
            matchMode,
            IJavaSearchConstants.TYPE,
            scope,
            requestor,
            IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
            null);

    if (res.isEmpty()) {
      return;
    }
    HashSet<Object> addedClaspaths = new HashSet<Object>();
    for (int i = 0; i < res.size(); i++) {
      TypeNameMatch curr = res.get(i);
      IType type = curr.getType();
      if (type != null) {
        IPackageFragmentRoot root =
            (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        try {
          IClasspathEntry entry = root.getRawClasspathEntry();
          if (entry == null) {
            continue;
          }
          IJavaProject other = root.getJavaProject();
          int entryKind = entry.getEntryKind();
          if ((entry.isExported() || entryKind == IClasspathEntry.CPE_SOURCE)
              && addedClaspaths.add(other)) {
            IClasspathEntry newEntry = JavaCore.newProjectEntry(other.getPath());
            Change change = ClasspathFixProposal.newAddClasspathChange(project, newEntry);
            if (change != null) {
              String[] args = {
                BasicElementLabels.getResourceName(other.getElementName()),
                BasicElementLabels.getResourceName(project.getElementName())
              };
              String label =
                  Messages.format(
                      CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_project_description,
                      args);
              String desc = label;
              DefaultClasspathFixProposal proposal =
                  new DefaultClasspathFixProposal(
                      label, change, desc, IProposalRelevance.ADD_PROJECT_TO_BUILDPATH);
              proposals.add(proposal);
            }
          }
          if (entryKind == IClasspathEntry.CPE_CONTAINER) {
            IPath entryPath = entry.getPath();
            if (isNonProjectSpecificContainer(entryPath)) {
              addLibraryProposal(project, root, entry, addedClaspaths, proposals);
            } else {
              try {
                IClasspathContainer classpathContainer =
                    JavaCore.getClasspathContainer(entryPath, root.getJavaProject());
                if (classpathContainer != null) {
                  IClasspathEntry entryInContainer =
                      JavaModelUtil.findEntryInContainer(classpathContainer, root.getPath());
                  if (entryInContainer != null) {
                    addLibraryProposal(project, root, entryInContainer, addedClaspaths, proposals);
                  }
                }
              } catch (CoreException e) {
                // ignore
              }
            }
          } else if ((entryKind == IClasspathEntry.CPE_LIBRARY
              || entryKind == IClasspathEntry.CPE_VARIABLE)) {
            addLibraryProposal(project, root, entry, addedClaspaths, proposals);
          }
        } catch (JavaModelException e) {
          // ignore
        }
      }
    }
  }
Exemplo n.º 24
0
  /**
   * Convert the empty project to an Acceleo project.
   *
   * @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);
    }
  }
 /** {@inheritDoc} */
 public IFolder getOutputFolder() {
   IPath outputPath = root.getPath().append(pathMapper.getBaseResourceFolder().getPathString());
   return root.getJavaModel().getWorkspace().getRoot().getFolder(outputPath);
 }
 /** {@inheritDoc} */
 public IPath getPath() {
   return root.getPath().append(CALSourcePathMapper.SCRIPTS_BASE_FOLDER);
 }
 /**
  * Sets the current source folder (model and text field) to the given package fragment root.
  *
  * @param root The new root.
  * @param canBeModified if <code>false</code> the source folder field can not be changed by the
  *     user. If <code>true</code> the field is editable
  */
 public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean canBeModified) {
   fCurrRoot = root;
   String str = (root == null) ? "" : root.getPath().makeRelative().toString(); // $NON-NLS-1$
   fContainerDialogField.setText(str);
   fContainerDialogField.setEnabled(canBeModified);
 }