Java Code Examples for org.eclipse.jdt.core.IJavaProject#findPackageFragment()

The following examples show how to use org.eclipse.jdt.core.IJavaProject#findPackageFragment() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateJavaTypeQuickfixes.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void setPackageName(NewTypeWizardPage page, URI contextUri, String packageName) {
	IJavaProject javaProject = getJavaProject(contextUri);
	String path = contextUri.trimSegments(1).toPlatformString(true);
	try {
		if(javaProject != null) {
			IPackageFragment contextPackageFragment = javaProject.findPackageFragment(new Path(path));
			if (contextPackageFragment != null) {
				IPackageFragmentRoot root = (IPackageFragmentRoot) contextPackageFragment
						.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
				IPackageFragment packageFragment;
				if(!isEmpty(packageName)) {
					packageFragment = root.getPackageFragment(packageName);
				} else {
					packageFragment = contextPackageFragment;
				}
				page.setPackageFragment(packageFragment, true);
				page.setPackageFragmentRoot(root, true);
			}
		}
	} catch (JavaModelException e) {
		LOG.error("Could not find package for " + path, e);
	}
}
 
Example 2
Source File: ModuleFile.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Find the Source folder for the src/main/.../client
 *
 * TODO won't work b/c super source could have a client, or some other path before it.
 *
 * @param moduleFolder
 * @return The source package java for client
 */
private IJavaElement findSourceFolderElement(IFolder moduleFolder) {
  // TODO red the source attrbute in the module and find it?
  IFolder folderSourcePackage = findSourcePackage(moduleFolder, "client");
  if (folderSourcePackage == null) {
    return null;
  }

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

  try {
    IPackageFragment clientPackage = javaProject.findPackageFragment(folderSourcePackage.getFullPath());
    return clientPackage;
  } catch (JavaModelException e) {
    e.printStackTrace();
  }

  return null;
}
 
Example 3
Source File: CloneInstanceMapper.java    From JDeodorant with MIT License 6 votes vote down vote up
private IMethod getIMethod(IJavaProject jProject, String typeName, String methodName, String methodSignature, int start, int end)
		throws JavaModelException {
	IType type = jProject.findType(typeName);
	if(type == null) {
		IPath path = new Path("/" + jProject.getElementName() + "/" + typeName.substring(0, typeName.lastIndexOf(".")));
		IPackageFragment packageFragment = jProject.findPackageFragment(path);
		if (packageFragment != null)
			type = jProject.findPackageFragment(path).getCompilationUnit(typeName.substring(typeName.lastIndexOf(".")+1)+".java").findPrimaryType();
		else
			return null;
	}
	IMethod iMethod = null;
	if(!methodSignature.equals("")) {
		iMethod = getIMethodWithSignature(jProject, type, methodName, methodSignature, start, end);
	}

	if(iMethod == null) {
		iMethod = recursiveGetIMethod(type, jProject, methodName, methodSignature, start, end);
	}
	return iMethod;
}
 
Example 4
Source File: SourceFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private void deleteRecursivelyEmptyPackages(final IJavaProject project, IPackageFragment packageFragment)
        throws JavaModelException {
    if (packageFragment != null) {
        while (!packageFragment.hasChildren()) {
            //I don't find another way than passing through IResource, directly using IJavaElement seems not possible.
            final IPath pathOfParentPackageFragment = packageFragment.getResource().getParent().getFullPath();
            final IPackageFragment parent = project.findPackageFragment(pathOfParentPackageFragment);
            packageFragment.delete(true, new NullProgressMonitor());
            if (parent instanceof IPackageFragment && !parent.isDefaultPackage()) {
                packageFragment = parent;
            } else {
                return;
            }
        }
    }
}
 
Example 5
Source File: ResourceNameTemplateVariableResolver.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<String> resolveValues(final TemplateVariable variable, final XtextTemplateContext templateContext) {
  final List<String> result = Lists.newArrayList();
  final IDocument document = templateContext.getDocument();
  final Object obj = variable.getVariableType().getParams().iterator().next();
  if (obj instanceof String) {
    final String variableName = (String) obj;
    final IXtextDocument xtextDocument = (IXtextDocument) document;
    final IFile file = xtextDocument.getAdapter(IFile.class);

    switch (variableName) {
    case "package": //$NON-NLS-1$
      if (document instanceof IXtextDocument && file != null && file.getParent() instanceof IFolder) {
        final IJavaProject javaProject = JavaCore.create(file.getProject());
        try {
          final IPackageFragment packageFragment = javaProject.findPackageFragment(file.getParent().getFullPath());
          result.add(packageFragment.getElementName());
        } catch (final JavaModelException e) {
          LOGGER.error("Could not determine package for file of given document"); //$NON-NLS-1$
        }
      }
      break;
    case "file": //$NON-NLS-1$
      final String fileName = file.getName();
      result.add(fileName.indexOf('.') > 0 ? fileName.substring(0, fileName.lastIndexOf('.')) : fileName);
    }
  }
  return Lists.newArrayList(Iterables.filter(result, Predicates.notNull()));
}
 
Example 6
Source File: CheckResourceUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the name of containing package.
 *
 * @param xtextDocument
 *          the xtext document
 * @return the name of containing package
 */
public String getNameOfContainingPackage(final IXtextDocument xtextDocument) {
  IFile file = xtextDocument.getAdapter(IFile.class);
  if (file != null && file.getParent() instanceof IFolder) {
    IJavaProject javaProject = JavaCore.create(file.getProject());
    try {
      IPackageFragment myFragment = javaProject.findPackageFragment(file.getParent().getFullPath());
      return myFragment.getElementName();
    } catch (JavaModelException e) {
      LOGGER.error("Could not determine package for file of given document");
    }
  }
  return null;
}
 
Example 7
Source File: CheckProjectHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the catalog plugin path.
 *
 * @param catalog
 *          the catalog
 * @return the catalog plugin path
 */
public String getCatalogPluginPath(final CheckCatalog catalog) {
  final URI uri = EcoreUtil.getURI(catalog);
  IFile file = RuntimeProjectUtil.findFileStorage(uri, mapper);
  IJavaProject project = JavaCore.create(file.getProject());
  try {
    IPackageFragment packageFragment = project.findPackageFragment(file.getParent().getFullPath());
    String result = packageFragment.getElementName().replace('.', '/');
    return result + '/' + file.getName();
  } catch (JavaModelException e) {
    LOGGER.error("Could not determine plugin path for catalog " + catalog.getName(), e);
  }
  return null;
}
 
Example 8
Source File: CheckProjectHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the catalog qualified name. Instead of using the qualified name provider, which is based
 * on the object attribute values, this method uses the resource properties for determining the
 * fully qualified name. This is legitimate, because the check catalog FQN consists of the Java
 * package name concatenated with the file name (which must be equal to the model name).
 *
 * @param catalog
 *          the catalog
 * @return the catalog qualified name
 */
public String getCatalogQualifiedName(final CheckCatalog catalog) {
  final URI uri = EcoreUtil.getURI(catalog);
  IFile file = RuntimeProjectUtil.findFileStorage(uri, mapper);
  IJavaProject project = JavaCore.create(file.getProject());
  try {
    IPackageFragment packageFragment = project.findPackageFragment(file.getParent().getFullPath());
    final String fileNameWithoutExtension = file.getName().substring(0, file.getName().length() - (file.getFileExtension().length() + 1));
    return packageFragment.getElementName() + '.' + fileNameWithoutExtension;
  } catch (JavaModelException e) {
    LOGGER.error("Could not determine plugin path for catalog " + catalog.getName(), e);
  }
  return null;
}
 
Example 9
Source File: ModuleFile.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the GWT Maven Module package from GWT plugin 2 module.gwt.xml.
 *
 * @param project
 * @return the module path
 */
private IJavaElement getGwtMavenModuleNameForGwtMavenPlugin2(IProject project) {
  if (project == null) {
    return null;
  }

  IFolder moduleFolder = (IFolder) getFile().getParent();

  // For GWT maven plugin 2, its module is in src/main
  if (!moduleFolder.toString().contains("src/main")) {
    return null;
  }

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

  String moduleName = WebAppProjectProperties.getGwtMavenModuleName(project);
  if (moduleName == null || !moduleName.contains(".")) {
    return null;
  }

  String[] moduleNameParts = moduleName.split("\\.");

  IPath path = moduleFolder.getFullPath().append("java");
  for (int i = 0; i < moduleNameParts.length - 1; i++) {
    path = path.append(moduleNameParts[i]);
  }

  try {
    return javaProject.findPackageFragment(path);
  } catch (JavaModelException e) {
    return null;
  }
}
 
Example 10
Source File: ClientBundleResource.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private String getSourceAnnotationValue(IType clientBundle) throws JavaModelException {
  IJavaProject javaProject = clientBundle.getJavaProject();
  assert (javaProject.isOnClasspath(file));

  IPackageFragment resourcePckg = javaProject.findPackageFragment(file.getParent().getFullPath());

  // If the resource is not in the same package as our ClientBundle, we need
  // an @Source with the full classpath-relative path to the resource.
  if (!clientBundle.getPackageFragment().equals(resourcePckg)) {
    return ResourceUtils.getClasspathRelativePath(resourcePckg, file.getName()).toString();
  }

  // If the resource has a different name than the method, we need an @Source,
  // although in this case we don't need the full path.
  String fileNameWithoutExt = ResourceUtils.filenameWithoutExtension(file);
  if (!ResourceUtils.areFilenamesEqual(fileNameWithoutExt, methodName)) {
    return file.getName();
  }

  // If resource doesn't have one of the default extensions, we need @Source.
  IType resourceType = JavaModelSearch.findType(javaProject, resourceTypeName);
  if (!hasDefaultExtension(file, resourceType)) {
    return file.getName();
  }

  // If the resource is in ClientBundle package and its name (without file
  // extension) matches the method name, no need for @Source
  return null;
}
 
Example 11
Source File: EclipseResourceTypeDetector.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the given resource is a test resource according to the Java or Maven standard.
 *
 * @param resource the resource to test.
 * @return {@link Boolean#TRUE} if the resource is a test resource. {@link Boolean#FALSE}
 *     if the resource is not a test resource. {@code null} if the detector cannot determine
 *     the type of the resource.
 */
@SuppressWarnings("checkstyle:nestedifdepth")
protected static Boolean isJavaOrMavenTestResource(Resource resource) {
	final URI uri = resource.getURI();
	if (uri.isPlatformResource()) {
		final String platformString = uri.toPlatformString(true);
		final IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
		if (iresource != null) {
			final IProject project = iresource.getProject();
			final IJavaProject javaProject = JavaCore.create(project);
			try {
				final IPackageFragment packageFragment = javaProject.findPackageFragment(iresource.getParent().getFullPath());
				final IPackageFragmentRoot root = (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
				if (root != null) {
					final IPath rootPath = root.getPath();
					String name = null;
					if (root.isExternal()) {
						name = rootPath.toOSString();
					} else if (javaProject.getElementName().equals(rootPath.segment(0))) {
					    if (rootPath.segmentCount() != 1) {
							name = rootPath.removeFirstSegments(1).makeRelative().toString();
					    }
					} else {
						name = rootPath.toString();
					}
					if (name != null && name.startsWith(SARLConfig.FOLDER_MAVEN_TEST_PREFIX)) {
						return Boolean.TRUE;
					}
				}
			} catch (JavaModelException e) {
				//
			}
		}
	}
	return null;
}
 
Example 12
Source File: SourceFileStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void renameLegacy(final String newQualifiedClassName) {
    final IJavaProject project = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();
    String packageName = "";
    String className = newQualifiedClassName;

    if (newQualifiedClassName.indexOf(".") != -1) {
        packageName = newQualifiedClassName.substring(0, newQualifiedClassName.lastIndexOf("."));
        className = newQualifiedClassName.substring(newQualifiedClassName.lastIndexOf(".") + 1,
                newQualifiedClassName.length());
    }

    try {
        final IRepositoryStore<?> store = getParentStore();
        final IPackageFragmentRoot root = project.findPackageFragmentRoot(store.getResource().getFullPath());
        root.createPackageFragment(packageName, true, Repository.NULL_PROGRESS_MONITOR);
        final IPackageFragment targetContainer = project
                .findPackageFragment(store.getResource().getFullPath().append(packageName.replace(".", "/")));
        final IType type = project.findType(qualifiedClassName);
        if (type != null) {
            type.getCompilationUnit().move(targetContainer, null, className + ".java", true,
                    Repository.NULL_PROGRESS_MONITOR);
            qualifiedClassName = newQualifiedClassName;
        }
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
}
 
Example 13
Source File: PackageFileStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public IPackageFragment getPackageFragment() {
    final IJavaProject project = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();
    try {
        return project.findPackageFragment(getParentStore().getResource().getFullPath().append(packageName.replace(".", "/")));
    } catch (final JavaModelException e) {
        BonitaStudioLog.error(e);
    }
    return null;
}
 
Example 14
Source File: SourceRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T getChild(final String fileName, boolean force) {
    if (fileName == null) {
        return null;
    }
    if (fileName.endsWith(".java") || fileName.endsWith(".groovy")) {
        final T fileStore = super.getChild(fileName, force);
        if (fileStore != null) {
            return fileStore;
        }
    }
    try {
        final IJavaProject javaProject = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();
        if (javaProject != null) {
            final IType javaType = javaProject.findType(fileName);
            if (javaType != null) {
                if (javaType instanceof SourceType || isSourceType(fileName, javaProject)) {
                    return (T) new SourceFileStore(fileName, this);
                }
                return null;
            } else { // package name
                final IPackageFragment packageFragment = javaProject
                        .findPackageFragment(getResource().getFullPath().append(fileName.replace(".", "/")));
                if (packageFragment != null) {
                    return (T) new PackageFileStore(fileName, this);
                }
            }
        }
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
    return null;
}
 
Example 15
Source File: PackageFileStore.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
private IPackageFragment retrieveParentPackageFragment(final IJavaProject project,
        final IPackageFragment packageFragment) throws JavaModelException {
    final IPath pathOfParentPackageFragment = packageFragment.getResource().getParent().getFullPath();
    final IPackageFragment parent = project.findPackageFragment(pathOfParentPackageFragment);
    return parent;
}