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

项目:gw4e.project    文件:ResourceContext.java   
/**
 * @param containerFullPath
 * @param packageFragmentRoot
 * @param targetPkg
 * @param selectedFilename
 * @param selectedFile
 * @param openEditor
 * @param ce
 * @throws CoreException
 */
public ResourceContext(
        IPath containerFullPath, 
        IPackageFragmentRoot packageFragmentRoot,
        IPackageFragment targetPkg,
        String selectedFilename, 
        String extendedClassname,
        IFile selectedFile,
        GENERATION_MODE mode,
        ClassExtension ce) throws CoreException {
    this.selectedFile=selectedFile;
    this.packageFragmentRoot = packageFragmentRoot;
    this.targetPkg  = targetPkg;
    this.interfaceName = selectedFile.getName().split("\\.")[0] + ".java";
    this.selectedFilename = selectedFilename;
    this.containerFullPath = containerFullPath;
    this.mode=mode;
    this.classExtension=ce;
    this.generateOnlyInterface = false;
    this.openEditor = false;
    this.erase = true;
    this.extendedClassname=extendedClassname; 
}
项目: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   
/**
 * Lets get the path of hat have been selected in the UI - the complete path
 * a path is something like "src/main/resources"
 * 
 * @param receiver
 * @return
 */
public static String getSelectedPathInProject(Object receiver) {
    if (!ResourceManager.isPackageFragmentRoot(receiver)) {
        return null;
    }
    IPackageFragmentRoot pkg = (IPackageFragmentRoot) receiver;

    IJavaProject javaProject = pkg.getJavaProject();
    if (javaProject == null)
        return null;

    IProject project = javaProject.getProject();

    if (!GW4ENature.hasGW4ENature(project))
        return null;

    String projectName = pkg.getJavaProject().getElementName();
    int pos = projectName.length();
    String input = pkg.getPath().toString().substring(pos + 2);
    return input;
}
项目:gw4e.project    文件:AuthorizedFolderForGraphDefinition.java   
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
    if ("isAuthorizedFolderForGraphDefinition".equals(property)) {
        // Only PackageFragmentRoot is allowed to enable the menu
        // Represents a set of package fragments, and maps the fragments to
        // an underlying resource which is either
        // a folder, JAR, or ZIP file. (Child of IJavaProject)
        // See JDT Plug-in Developer Guide > Programmer's Guide > JDT Core
        // for more information on Java Model
        if (!ResourceManager.isPackageFragmentRoot(receiver)) {
            return false;
        }
        // Lets get the path of hat have been selected in the UI - the
        // complete path
        // a path is something like "src/main/resources"
        String input = ResourceManager.getSelectedPathInProject(receiver);
        // Now we have it, check whether it is listed in the Preference
        boolean authorized = PreferenceManager.isAuthorizedFolderForGraphDefinition(((IPackageFragmentRoot)receiver).getJavaProject().getProject().getName(),input);
        // Sounds like we have an answer now !
        return authorized;
    }
    // Boo !
    return false;
}
项目: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    文件:GenerationFactory.java   
public static TestResourceGeneration get (IFile file) throws CoreException, FileNotFoundException {
    String targetFolder = GraphWalkerContextManager.getTargetFolderForTestImplementation(file);
    IPath pkgFragmentRootPath = file.getProject().getFullPath().append(new Path(targetFolder));
    IPackageFragmentRoot implementationFragmentRoot = JDTManager.getPackageFragmentRoot(file.getProject(), pkgFragmentRootPath);
    String classname = file.getName().split("\\.")[0];
    classname = classname + PreferenceManager.suffixForTestImplementation(implementationFragmentRoot.getJavaProject().getProject().getName()) + ".java";

    ClassExtension ce = PreferenceManager.getDefaultClassExtension(file);
    IPath p = ResourceManager.getPathWithinPackageFragment(file).removeLastSegments(1);
    p = implementationFragmentRoot.getPath().append(p);

    ResourceContext context = new ResourceContext(p, classname, file, true, false, false, ce);

    TestResourceGeneration trg = new TestResourceGeneration(context);
    return trg;
}
项目:Hydrograph    文件:BuildExpressionEditorDataSturcture.java   
public void createClassRepo(String jarFileName, String Package) {
    ClassRepo.INSTANCE.flusRepo();
    try {
        IPackageFragmentRoot iPackageFragmentRoot = getIPackageFragment(jarFileName);
        if (iPackageFragmentRoot != null) {
            IPackageFragment fragment = iPackageFragmentRoot.getPackageFragment(Package);
            if (fragment != null) {
                for (IClassFile element : fragment.getClassFiles()) {
                    ClassRepo.INSTANCE.addClass(element,"","",false);
                }
            } else {
                new CustomMessageBox(SWT.ERROR, Package + " Package not found in jar "
                        + iPackageFragmentRoot.getElementName(), "ERROR").open();
            }
        }
    } catch (JavaModelException e) {
        LOGGER.error("Error occurred while loading class from jar {}", jarFileName, e);
    }
    loadClassesFromSettingsFolder();
}
项目:turnus    文件:EcoreUtils.java   
/**
 * Returns the list of source folders of the given project as a list of
 * absolute workspace paths.
 * 
 * @param project
 *            a project
 * @return a list of absolute workspace paths
 */
public static List<IFolder> getSourceFolders(IProject project) {
    List<IFolder> srcFolders = new ArrayList<IFolder>();

    try {
        IJavaProject javaProject = JavaCore.create(project);
        if (!javaProject.exists()) {
            return srcFolders;
        }

        // iterate over package roots
        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
            IResource resource = root.getCorrespondingResource();
            if (resource != null && resource.getType() == IResource.FOLDER) {
                srcFolders.add((IFolder) resource);
            }
        }
    } catch (CoreException e) {
        Logger.debug("Get source folder exception: %s", e);
    }

    return srcFolders;
}
项目:pde.source.lookup    文件:ClasspathUtils.java   
public static void attachSource(final IPackageFragmentRoot fragment, final IPath newSourcePath,
    IProgressMonitor monitor) {
  try {
    if (fragment == null || fragment.getKind() != IPackageFragmentRoot.K_BINARY) {
      return;
    }
    if (!Objects.equals(fragment.getSourceAttachmentPath(), newSourcePath)) {
      // would be so cool if it refreshed the UI automatically
      fragment.attachSource(newSourcePath, null, monitor);
      // close the root so that source attachment cache is flushed. Else UI
      // won't update
      fragment.close();
      // we have to manually fire a delta to notify the UI about the source
      // attachment.
      JavaModelManager manager = JavaModelManager.getJavaModelManager();
      JavaElementDelta attachedSourceDelta = new JavaElementDelta(fragment.getJavaModel());
      attachedSourceDelta.sourceAttached(fragment);
      manager.getDeltaProcessor().fire(attachedSourceDelta, ElementChangedEvent.POST_CHANGE);
    }
  } catch (CoreException e) {
    // ignore
  }
}
项目:pde.source.lookup    文件:ClasspathUtils.java   
public static IPackageFragmentRoot[] getPluginContainerEntries(IProject project) {
  if (!ProjectUtils.isPluginProject(project)) {
    return new IPackageFragmentRoot[0];
  }
  IJavaProject javaProject = JavaCore.create(project);

  IClasspathEntry pluginContainer = null;
  try {
    pluginContainer = Stream.of(javaProject.getRawClasspath()).filter(cpe -> isPluginContainer(cpe)).findFirst()
        .orElse(null);
  } catch (JavaModelException e) {
    e.printStackTrace();
  }
  if (pluginContainer == null) {
    return new IPackageFragmentRoot[0];
  }
  IPackageFragmentRoot[] pfr = javaProject.findPackageFragmentRoots(pluginContainer);
  return pfr;
}
项目:pde.source.lookup    文件:AbstractSourceDownloadJob.java   
@Override
protected IStatus run(IProgressMonitor monitor) {
  if (monitor == null) {
    monitor = new NullProgressMonitor();
  }
  Collection<IPackageFragmentRoot> currentQueue;
  synchronized (this.queue) {
    currentQueue = new LinkedHashSet<>(this.queue);
    this.queue.clear();
  }

  for (IPackageFragmentRoot fragment : currentQueue) {
    if (monitor.isCanceled()) {
      break;
    }
    findAndAttachSources(fragment, monitor);
  }
  // schedule remaining requests that were added during this run
  synchronized (this.queue) {
    if (!queue.isEmpty() && !monitor.isCanceled()) {
      schedule();
    }
  }
  return Status.OK_STATUS;
}
项目:pde.source.lookup    文件:DownloadSourcesHandler.java   
private Collection<IPackageFragmentRoot> getSelectedClasspathEntries(ISelection selection) {
  if (!(selection instanceof ITreeSelection)) {
    return Collections.emptyList();
  }
  ITreeSelection structuredSelection = (ITreeSelection) selection;
  Set<IPackageFragmentRoot> fragments = new LinkedHashSet<>(structuredSelection.size());
  for (Object o : structuredSelection.toList()) {
    if (o instanceof IPackageFragmentRoot) {
      IPackageFragmentRoot pfr = (IPackageFragmentRoot) o;
      if (ClasspathUtils.isBinaryFragment(pfr) && belongsToPluginContainer(structuredSelection, pfr)) {
        fragments.add(pfr);
      }
    } else if (isPluginContainer(o)) {
      IAdaptable adaptable = (IAdaptable) o;
      IWorkbenchAdapter wa = adaptable.getAdapter(IWorkbenchAdapter.class);
      if (wa != null) {
        Object[] children = wa.getChildren(o);
        if (children instanceof IAdaptable[]) {
          IAdaptable[] adaptables = (IAdaptable[]) children;
          fragments.addAll(filterPackageFragmentRoots(adaptables));
        }
      }
    }
  }
  return fragments;
}
项目:pde.source.lookup    文件:DownloadSourcesActionDelegate.java   
@Override
public void run(IAction action) {
  if (selection == null || selection.isEmpty()) {
    return;
  }
  Set<IPackageFragmentRoot> queue = new LinkedHashSet<>();
  for(Iterator<?> it = selection.iterator(); it.hasNext();) {
    Object element = it.next();
    if(element instanceof IPackageFragmentRoot) {
      IPackageFragmentRoot fragment = (IPackageFragmentRoot) element;
      try {
        if (canProcess(fragment)) {
          queue.add(fragment);
        }
      } catch (CoreException e) {
        e.printStackTrace();
      }
    }
  }
  findSources(queue);
}
项目:pde.source.lookup    文件:DownloadSourcesActionDelegate.java   
@Override
public void setActiveEditor(IAction action, IEditorPart part) {
  if (part != null && part.getEditorInput() instanceof IClassFileEditorInput) {
    Set<IPackageFragmentRoot> queue = new LinkedHashSet<>();
    try {
      IClassFileEditorInput input = (IClassFileEditorInput) part.getEditorInput();
      IJavaElement element = input.getClassFile();
      while (element.getParent() != null) {
        element = element.getParent();
        if (element instanceof IPackageFragmentRoot) {
          IPackageFragmentRoot fragment = (IPackageFragmentRoot) element;
          if (canProcess(fragment)) {
            queue.add(fragment);
          }
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    findSources(queue);
  }
}
项目:eclemma    文件:JavaProjectKit.java   
public ICompilationUnit createCompilationUnit(
    IPackageFragmentRoot fragmentRoot, String testsrc, String path)
    throws CoreException, IOException {
  IPath typepath = new Path(path);
  String pkgname = typepath.removeLastSegments(1).toString()
      .replace('/', '.');
  IPackageFragment fragment = createPackage(fragmentRoot, pkgname);
  StringBuilder sb = new StringBuilder();
  InputStream source = openTestResource(new Path(testsrc).append(typepath));
  Reader r = new InputStreamReader(source);
  int c;
  while ((c = r.read()) != -1)
    sb.append((char) c);
  r.close();
  return createCompilationUnit(fragment, typepath.lastSegment(),
      sb.toString());
}
项目:eclemma    文件:JavaApplicationLauncherTest.java   
@Test
public void testProjectWithSourceFolders() throws Exception {
  IPackageFragmentRoot rootSrc1 = javaProject1.createSourceFolder("src");
  IPackageFragmentRoot rootSrc2 = javaProject1.createSourceFolder("test");
  JavaProjectKit.waitForBuild();

  ILaunchConfigurationWorkingCopy configuration = getJavaApplicationType()
      .newInstance(javaProject1.project, "test.launch");
  configuration.setAttribute(
      IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "project1");

  final Collection<IPackageFragmentRoot> scope = launcher
      .getOverallScope(configuration);

  assertEquals(set(rootSrc1, rootSrc2), set(scope));
}
项目:eclemma    文件:JavaApplicationLauncherTest.java   
@Test
public void testProjectWithLibrary() throws Exception {
  IPackageFragmentRoot rootBin1 = javaProject1.createJAR(
      "testdata/bin/signatureresolver.jar", "/sample.jar", new Path(
          "/UnitTestProject/sample.jar"), null);
  JavaProjectKit.waitForBuild();

  ILaunchConfigurationWorkingCopy configuration = getJavaApplicationType()
      .newInstance(javaProject1.project, "test.launch");
  configuration.setAttribute(
      IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "project1");

  final Collection<IPackageFragmentRoot> scope = launcher
      .getOverallScope(configuration);

  assertEquals(set(rootBin1), set(scope));
}
项目:eclemma    文件:CellTextConverter.java   
private String getSimpleTextForJavaElement(Object element) {
  if (element instanceof IPackageFragmentRoot) {
    final IPackageFragmentRoot root = (IPackageFragmentRoot) element;
    // tweak label if the package fragment root is the project itself:
    if (root.getElementName().length() == 0) {
      element = root.getJavaProject();
    }
    // shorten JAR references
    try {
      if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
        return root.getPath().lastSegment();
      }
    } catch (JavaModelException e) {
      EclEmmaUIPlugin.log(e);
    }
  }
  return workbenchLabelProvider.getText(element);
}
项目:eclemma    文件:DumpExecutionDataTest.java   
@BeforeClass
public static void setup() throws Exception {
    openCoverageView();

    JavaProjectKit project = new JavaProjectKit();
    project.enableJava5();
    final IPackageFragmentRoot root = project.createSourceFolder();
    final IPackageFragment fragment = project.createPackage(root, "example");
    project.createCompilationUnit(fragment, "Example.java",
            "package example; class Example { public static void main(String[] args) throws Exception { Thread.sleep(30000); } }");

    JavaProjectKit.waitForBuild();

    ILaunchConfiguration launchConfiguration = project.createLaunchConfiguration("example.Example");

    launch1 = launchConfiguration.launch(CoverageTools.LAUNCH_MODE, null);
    launch2 = launchConfiguration.launch(CoverageTools.LAUNCH_MODE, null);
}
项目:eclipse.jdt.ls    文件:JavaElementLabelComposer.java   
/**
 * Appends the label for a package fragment. Considers the P_* flags.
 *
 * @param pack the element to render
 * @param flags the rendering flags. Flags with names starting with P_' are considered.
 */
public void appendPackageFragmentLabel(IPackageFragment pack, long flags) {
    if (getFlag(flags, JavaElementLabels.P_QUALIFIED)) {
        appendPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), JavaElementLabels.ROOT_QUALIFIED);
        fBuilder.append('/');
    }
    if (pack.isDefaultPackage()) {
        fBuilder.append(JavaElementLabels.DEFAULT_PACKAGE);
    } else if (getFlag(flags, JavaElementLabels.P_COMPRESSED)) {
        appendCompressedPackageFragment(pack);
    } else {
        fBuilder.append(getElementName(pack));
    }
    if (getFlag(flags, JavaElementLabels.P_POST_QUALIFIED)) {
        fBuilder.append(JavaElementLabels.CONCAT_STRING);
        appendPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), JavaElementLabels.ROOT_QUALIFIED);
    }
}
项目:EclipsePlugins    文件:FileTemplateWizardMainPage.java   
public String getDefaultPackage() {
    WPILibJavaPlugin.logInfo("Project: "+project);
    String defaultPackage = null;
    if (project != null) {
        try {
            IPackageFragmentRoot root = JavaCore.create(project)
                    .getPackageFragmentRoot(project.getFolder("src"));
            String backupPackage = "";
            for (IJavaElement child : root.getChildren()) {
                if (child.getElementType()==IJavaElement.PACKAGE_FRAGMENT
                        && child.getElementName().endsWith("."+ending)) {
                    defaultPackage = child.getElementName();
                }
                backupPackage =  child.getElementName();
            }
            if (defaultPackage == null) defaultPackage = backupPackage;
        } catch (JavaModelException e) {
               WPILibJavaPlugin.logError("Error getting default package.", e);
        }
    }
    if (defaultPackage != null) return defaultPackage;
    else return "";
}
项目:o3smeasures-tool    文件:PackageBuilder.java   
/**
 * @see IBuilder#build
 */
@Override
public void build(Measure measure, ItemMeasured item) {
    IPackageFragment[] packages;
    ItemMeasured packageMeasured; 
    String packageName = "";
    try {
        packages = project.getPackageFragments();
        for (IPackageFragment myPackage : packages) {
            if ((myPackage.getKind() == IPackageFragmentRoot.K_SOURCE) && myPackage.hasChildren()) {

                packageName = myPackage.isDefaultPackage() ? "(default)" : myPackage.getElementName();
                packageMeasured = new ItemMeasured(packageName, item);
                addClassBuilder(measure, myPackage, packageMeasured);
                item.addChild(packageMeasured);
                item.setMax(packageMeasured.getMax());
                item.setClassWithMax(packageMeasured.getClassWithMax());
                item.addValue(packageMeasured.getValue());
                item.addMean(packageMeasured.getMean());
            }
        }
    } catch (JavaModelException exception) {
        logger.error(exception);
    }
}
项目:eclemma    文件:ScopeUtils.java   
/**
 * Returns the scope configured with the given configuration. If no scope has
 * been explicitly defined, the default filter settings are applied to the
 * overall scope.
 *
 * @param configuration
 *          launch configuration to read scope from
 *
 * @return configured scope
 */
public static Set<IPackageFragmentRoot> getConfiguredScope(
    final ILaunchConfiguration configuration) throws CoreException {
  final Set<IPackageFragmentRoot> all = getOverallScope(configuration);
  @SuppressWarnings("rawtypes")
  final List<?> selection = configuration.getAttribute(
      ICoverageLaunchConfigurationConstants.ATTR_SCOPE_IDS, (List) null);
  if (selection == null) {
    final DefaultScopeFilter filter = new DefaultScopeFilter(
        EclEmmaCorePlugin.getInstance().getPreferences());
    return filter.filter(all, configuration);
  } else {
    all.retainAll(readScope(selection));
    return all;
  }
}
项目:eclemma    文件:ScopeUtils.java   
/**
 * Remove all JRE runtime entries from the given set
 *
 * @param scope
 *          set to filter
 * @return filtered set without JRE runtime entries
 */
public static Set<IPackageFragmentRoot> filterJREEntries(
    Collection<IPackageFragmentRoot> scope) throws JavaModelException {
  final Set<IPackageFragmentRoot> filtered = new HashSet<IPackageFragmentRoot>();
  for (final IPackageFragmentRoot root : scope) {
    final IClasspathEntry entry = root.getRawClasspathEntry();
    switch (entry.getEntryKind()) {
    case IClasspathEntry.CPE_SOURCE:
    case IClasspathEntry.CPE_LIBRARY:
    case IClasspathEntry.CPE_VARIABLE:
      filtered.add(root);
      break;
    case IClasspathEntry.CPE_CONTAINER:
      IClasspathContainer container = JavaCore.getClasspathContainer(
          entry.getPath(), root.getJavaProject());
      if (container != null
          && container.getKind() == IClasspathContainer.K_APPLICATION) {
        filtered.add(root);
      }
      break;
    }
  }
  return filtered;
}
项目:gemoc-studio-modeldebugging    文件:PlainK3ExecutionEngine.java   
/**
 * Return a bundle containing 'aspectClassName'.
 * 
 * Return null if not found.
 */
private Bundle findBundle(final IExecutionContext executionContext, String aspectClassName) {

    // Look using JavaWorkspaceScope as this is safer and will look in
    // dependencies
    IType mainIType = getITypeMainByWorkspaceScope(aspectClassName);

    Bundle bundle = null;
    String bundleName = null;
    if (mainIType != null) {
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) mainIType.getPackageFragment()
                .getParent();

        bundleName = packageFragmentRoot.getPath().removeLastSegments(1).lastSegment().toString();
        if (bundleName != null) {

            // We try to look into an already loaded bundle
            bundle = Platform.getBundle(bundleName);
        }
    } else {
        // the main isn't visible directly from the workspace, try another
        // method
        bundle = _executionContext.getMelangeBundle();
    }

    return bundle;
}
项目:gw4e.project    文件:GeneratorChoiceComposite.java   
public IPackageFragmentRoot getRoot() {
    IFile file = (IFile) selection.getFirstElement();
    IPackageFragmentRoot root = null;
    try {
        root = JDTManager.findPackageFragmentRoot(file.getProject(), pkgf.getPath());
    } catch (JavaModelException e) {
        ResourceManager.logException(e);
    }

    return root;
}
项目:gw4e.project    文件:GeneratorChoiceComposite.java   
public void setTarget(IPath p, String name) {
    IFolder folder = (IFolder) ResourceManager.getResource(p.toString());
    IJavaElement element = JavaCore.create(folder);
    if (element instanceof IPackageFragmentRoot) {
        this.pkgf = ((IPackageFragmentRoot) element).getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
    } else {
        this.pkgf = (IPackageFragment) element;
    }
    String value = name.split(Pattern.quote(".")) [0];
    newClassnameText.setText(value);
    extendingClassnameText.setText(value);
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param elt
 * @return
 * @throws JavaModelException
 */
public static String getFullyQualifiedName(IJavaElement elt) throws JavaModelException {
    IPackageFragmentRoot[] roots = elt.getJavaProject().getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].getPath().isPrefixOf(elt.getPath())) {
            IPath p = elt.getPath().makeRelativeTo(roots[i].getPath());
            return p.toString();
        }
    }
    return elt.getElementName();
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * Return a package fragment with the passed path
 * 
 * @param project
 * @param path
 * @return
 * @throws JavaModelException
 */
public static IPackageFragmentRoot getPackageFragmentRoot(IProject project, IPath path) throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].getPath().equals(path))
            return roots[i];
    }
    return null;
}
项目:gw4e.project    文件:JDTManager.java   
public static IPackageFragmentRoot findPackageFragmentRoot(IProject project, IPath path) throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].getPath().isPrefixOf(path))
            return roots[i];
    }
    return null;
}
项目:gw4e.project    文件:JDTManager.java   
public static IPath removePackageFragmentRoot(IProject project, IPath path) throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].getPath().isPrefixOf(path))
            return path.makeRelativeTo(roots[i].getPath());
    }
    return null;
}
项目:gw4e.project    文件:GraphWalkerContextManager.java   
/**
 * @param file
 * @return
 * @throws CoreException
 */
public static AbstractPostConversion getDefaultGraphConversion(IFile file,boolean generateOnlyInterface) throws CoreException {
    AbstractPostConversion converter = null;
    boolean canBeConverted = PreferenceManager.isGraphModelFile(file);
    if (canBeConverted) {
        String targetFolder = GraphWalkerContextManager.getTargetFolderForTestImplementation(file);
        IPath pkgFragmentRootPath = file.getProject().getFullPath().append(new Path(targetFolder));
        IPackageFragmentRoot implementationFragmentRoot = JDTManager.getPackageFragmentRoot(file.getProject(),
                pkgFragmentRootPath);
        String classname = file.getName().split("\\.")[0];
        classname = classname + PreferenceManager.suffixForTestImplementation(
                implementationFragmentRoot.getJavaProject().getProject().getName()) + ".java";

        ClassExtension ce = PreferenceManager.getDefaultClassExtension(file);
        IPath p = ResourceManager.getPathWithinPackageFragment(file).removeLastSegments(1);
        p = implementationFragmentRoot.getPath().append(p);
        ResourceContext context = new ResourceContext(p, classname, file, true, false, generateOnlyInterface, ce);
        converter = new JavaTestBasedPostConversionImpl(context);
    }
    return converter;
}
项目:gw4e.project    文件:ResourceManager.java   
/**
 * Return package fragment of the passed resource
 * 
 * @param project
 * @param path
 * @return
 * @throws JavaModelException
 */
public static IPackageFragmentRoot getPackageFragmentRoot(IProject project, IPackageFragment pkg)
        throws JavaModelException {
    IJavaProject jproject = JavaCore.create(project);
    IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        IPackageFragmentRoot root = roots[i];
        IPackageFragment pf = root.getPackageFragment(pkg.getElementName());
        if (pf.equals(pkg))
            return root;
    }
    return null;
}
项目:gw4e.project    文件:ResourceManager.java   
/**
 * Return package fragment of the passed resource
 * 
 * @param project
 * @param path
 * @return
 * @throws CoreException
 */
public static IPackageFragment getPackageFragment(IProject project, IPath path) throws CoreException {
    IFolder folder = ResourceManager.ensureFolder(project, path.toString(), new NullProgressMonitor());
    IJavaElement element = JavaCore.create(folder);
    if (element instanceof IPackageFragment) {
        return (IPackageFragment) element;
    }
    if (element instanceof IPackageFragmentRoot) {
        IPackageFragmentRoot root = (IPackageFragmentRoot) element;
        element = root.getPackageFragment("");
        return (IPackageFragment) element;
    }
    return null;
}
项目:gw4e.project    文件:TestConvertor.java   
private void findOldGraphFile(IProgressMonitor monitor) throws JavaModelException, FileNotFoundException {
    AnnotationParsing ap = JDTManager.findAnnotationParsingInModelAnnotation(testInterface, "file");
    this.model = ap.getValue("file");
    IPackageFragmentRoot[] roots = testInterface.getJavaProject().getPackageFragmentRoots();
    for (int j = 0; j < roots.length; j++) {
        IPackageFragmentRoot root = roots[j];
        IFolder resource = (IFolder) root.getResource();
        if (resource==null) throw new FileNotFoundException (model);
        IFile graphFile = resource.getFile(model);
        if (graphFile.exists()) {
            oldGraphFile = graphFile;
            break;
        }
    }
}
项目:gw4e.project    文件:SynchronizeBuildPoliciesEnabled.java   
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
    IProject project = null;
    boolean authorized = false; 
    if (receiver instanceof IJavaProject) {
        project =  ((IJavaProject)receiver).getProject();
        authorized = true;
    } else {
        if (receiver instanceof IPackageFragmentRoot) {
            IPackageFragmentRoot pfr = ((IPackageFragmentRoot)receiver);
            project = pfr.getJavaProject().getProject();
            try {
                authorized =  (pfr.getKind() == IPackageFragmentRoot.K_SOURCE);
            } catch (JavaModelException ignore) {
            }
        } else {
            if (receiver instanceof IPackageFragment) {
                IPackageFragment  pf = (IPackageFragment)receiver;
                project = pf.getJavaProject().getProject();
                authorized = true;
            }
        }
    }
    if (authorized && project!= null) {
        if (GW4ENature.hasGW4ENature(project)) 
            return true;
    }

    return false; 
}
项目:gw4e.project    文件:ResourceManagerTest.java   
@Test
public void testGetPackageFragmentRoot() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true, false);
    ResourceManager.createFile(project.getProject().getName(), "src/test/resources", "mypkg/subpkg", "test.java",
            "");
    IPackageFragment frag = (IPackageFragment) project.findElement(new Path("mypkg/subpkg"));

    IPackageFragmentRoot pfr = ResourceManager.getPackageFragmentRoot(project.getProject(), frag);
    assertNotNull(pfr);
}
项目:gw4e.project    文件:ResourceManagerTest.java   
@Test
public void testGetPackageFragment() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true, false);
    ResourceManager.createFile(project.getProject().getName(), "src/test/resources", "mypkg/subpkg", "test.java",
            "");
    IPackageFragment pf = ResourceManager.getPackageFragment(project.getProject(),
            new Path("src/test/resources/mypkg/subpkg"));
    assertNotNull(pf);

    IPackageFragment frag = (IPackageFragment) project.findElement(new Path("mypkg/subpkg"));
    IPackageFragmentRoot pfr = ResourceManager.getPackageFragmentRoot(project.getProject(), frag);
    pf = ResourceManager.getPackageFragment(project.getProject(), pfr.getPath().removeFirstSegments(1));
    assertNotNull(pf);
}
项目:gw4e.project    文件:ResourceManagerTest.java   
@Test
public void testGetSelectedPathInProject() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true, false);
    ResourceManager.createFile(project.getProject().getName(), "src/test/resources", "mypkg/subpkg", "test.java",
            "");

    IPackageFragment frag = (IPackageFragment) project.findElement(new Path("mypkg/subpkg"));
    IPackageFragmentRoot pfr = ResourceManager.getPackageFragmentRoot(project.getProject(), frag);
    String s = ResourceManager.getSelectedPathInProject(pfr);
    assertEquals("src/test/resources", s);
}
项目:gw4e.project    文件:ResourceManagerTest.java   
@Test
public void testIsPackageFragmentRoot() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true, false);
    ResourceManager.createFile(project.getProject().getName(), "src/test/resources", "mypkg/subpkg", "test.java",
            "");

    IPackageFragment frag = (IPackageFragment) project.findElement(new Path("mypkg/subpkg"));
    IPackageFragmentRoot pfr = ResourceManager.getPackageFragmentRoot(project.getProject(), frag);

    boolean b = ResourceManager.isPackageFragmentRoot(pfr);
    assertTrue(b);

    b = ResourceManager.isPackageFragmentRoot(project);
    assertFalse(b);
}