Java Code Examples for org.eclipse.jdt.core.IPackageFragment#getElementName()

The following examples show how to use org.eclipse.jdt.core.IPackageFragment#getElementName() . 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: ResourceMacro.java    From ContentAssist with MIT License 6 votes vote down vote up
/**
 * Obtains the name of the specified element.
 * @param elem the element
 * @param type the type of the element
 * @return the name string
 */
public static String getName(IJavaElement elem) {
    int type = elem.getElementType();
    if (type == IJavaElement.JAVA_PROJECT) {
        return elem.getResource().getName();
        
    } else if (type == IJavaElement.PACKAGE_DECLARATION) {
        IPackageFragment jpackage = (IPackageFragment)elem;
        return jpackage.getElementName();
        
    } else if (type == IJavaElement.COMPILATION_UNIT) {
        return elem.getResource().getName();
    }
    
    return "";
}
 
Example 2
Source File: NewModuleWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
protected void initModulePage(IStructuredSelection selection) {
  IJavaElement jelem = getInitialJavaElement(selection);

  initContainerPage(jelem);

  String pName = "";
  if (jelem != null) {
    IPackageFragment pf = (IPackageFragment) jelem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
    if (pf != null) {
      pName = pf.getElementName();
    }
  }

  modulePackageField.setText(pName);

  modulePackageCompletionProcessor.setPackageFragmentRoot(getPackageFragmentRoot());

  moduleCreateElementsCheckboxes.setSelection(
      CLIENT_PACKAGE_CHECKBOX_GROUP_INDEX, true);
  moduleCreateElementsCheckboxes.setSelection(
      PUBLIC_PATH_CHECKBOX_GROUP_INDEX, true);

  doFieldChange(CONTAINER, null);
}
 
Example 3
Source File: XtendTypeCreatorUtil.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public static String createPackageDeclaration(String typeName, IPackageFragment packageFragment, @SuppressWarnings("rawtypes") List superInterfaces, String lineSeparator) {
	StringBuffer sb = new StringBuffer();
	if(packageFragment.getElementName() != null && !packageFragment.getElementName().equals("")){
		sb.append("package ");
		sb.append(packageFragment.getElementName());
	}
	int size = superInterfaces.size();
	if(size > 0) {
		sb.append(lineSeparator);
		sb.append(lineSeparator);
	}
	for (int index = 0; index < size; index++) {
		Object superInterface = superInterfaces.get(index);
		addImport(sb, superInterface, index + 1 != size ? lineSeparator : null);
	}
	return sb.toString();
}
 
Example 4
Source File: JavaPackageFragmentRootCompletionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ICompletionProposal[] createPackagesProposals(int documentOffset, String input) {
	ArrayList<JavaCompletionProposal> proposals= new ArrayList<JavaCompletionProposal>();
	String prefix= input.substring(0, documentOffset);
	try {
		IJavaElement[] packageFragments= fPackageFragmentRoot.getChildren();
		for (int i= 0; i < packageFragments.length; i++) {
			IPackageFragment pack= (IPackageFragment) packageFragments[i];
			String packName= pack.getElementName();
			if (packName.length() == 0 || ! packName.startsWith(prefix))
				continue;
			Image image= getImage(JavaPluginImages.DESC_OBJS_PACKAGE);
			JavaCompletionProposal proposal= new JavaCompletionProposal(packName, 0, input.length(), image, packName, 0);
			proposals.add(proposal);
		}
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}
	return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
 
Example 5
Source File: MoveCompilationUnitChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IPackageFragment[] createDestination(IPackageFragmentRoot root, IPackageFragment destination, IProgressMonitor pm) throws JavaModelException {
	String packageName= destination.getElementName();
	String[] split= packageName.split("\\."); //$NON-NLS-1$

	ArrayList<IPackageFragment> created= new ArrayList<>();

	StringBuilder name= new StringBuilder();
	name.append(split[0]);
	for (int i= 0; i < split.length; i++) {
		IPackageFragment fragment= root.getPackageFragment(name.toString());
		if (!fragment.exists()) {
			created.add(fragment);
		}

		if (fragment.equals(destination)) {
			root.createPackageFragment(name.toString(), true, pm);
			return created.toArray(new IPackageFragment[created.size()]);
		}

		name.append("."); //$NON-NLS-1$
		name.append(split[i + 1]);
	}

	return null;
}
 
Example 6
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static PackageNode createPackageNode(IPackageFragment fragment) {
	if (fragment == null) {
		return null;
	}

	String projectName = fragment.getJavaProject().getProject().getName();
	String uri = null;
	if (fragment.getResource() != null) {
		uri = JDTUtils.getFileURI(fragment.getResource());
	}

	if (fragment.isDefaultPackage()) {
		return new PackageNode(DEFAULT_PACKAGE_DISPLAYNAME, uri, fragment.getPath().toPortableString(), projectName, true);
	}

	return new PackageNode(fragment.getElementName(), uri, fragment.getPath().toPortableString(), projectName, false);
}
 
Example 7
Source File: PackagesViewHierarchicalContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Object findNextLevelParentByElementName(IPackageFragment child) {
	String name= child.getElementName();

	int index= name.lastIndexOf('.');
	if (index != -1) {
		String realParentName= name.substring(0, index);
		IPackageFragment element= ((IPackageFragmentRoot) child.getParent()).getPackageFragment(realParentName);
		if (element.exists()) {
			return element;
		}
	}
	return child.getParent();
}
 
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: 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 10
Source File: AccessorClassCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getResourceBundleName() throws CoreException {
	IResource res= ResourcesPlugin.getWorkspace().getRoot().findMember(fResourceBundlePath.removeLastSegments(1));
	if (res != null && res.exists()) {
		IJavaElement el= JavaCore.create(res);
		if (el instanceof IPackageFragment) {
			IPackageFragment p= (IPackageFragment) el;
			return p.getElementName() + '.' + getPropertyFileNameWithoutExtension();
		} else
			if ((el instanceof IPackageFragmentRoot) || (el instanceof IJavaProject)) {
				return getPropertyFileNameWithoutExtension();
			}
	}
	throw new CoreException(new StatusInfo(IStatus.ERROR, "Resourcebundle not specified")); //$NON-NLS-1$
}
 
Example 11
Source File: XtendTypeCreatorUtil.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public static String createPackageDeclaration(String typeName, IPackageFragment packageFragment, String lineSeparator) {
	StringBuffer sb = new StringBuffer();
	if(packageFragment.getElementName() != null && !packageFragment.getElementName().equals("")){
		sb.append("package ");
		sb.append(packageFragment.getElementName());
	}
	return sb.toString();
}
 
Example 12
Source File: PropPageTitleProvider.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
String getTitle(IPackageFragment pack) {
    if (pack == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder("Package: ");
    String name = pack.getElementName();
    if (name == null || name.length() == 0) {
        sb.append("default package");
    } else {
        sb.append(name);
    }
    return sb.toString();
}
 
Example 13
Source File: PackagesViewLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String calculateName(IPackageFragment fragment) {

		String name= fragment.getElementName();
		if (name.indexOf(".") != -1) //$NON-NLS-1$
			name= name.substring(name.lastIndexOf(".") + 1); //$NON-NLS-1$
		return name;

	}
 
Example 14
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the package field has to be pre-filled in this page and returns the package
 * fragment to be used for that. The package fragment has the name of the project if the source
 * folder does not contain any package and if the project name is a valid package name. If the
 * source folder contains exactly one package then the name of that package is used as the
 * package fragment's name. <code>null</code> is returned if none of the above is applicable.
 * 
 * @param javaProject the containing Java project of the selection used to initialize this page
 * 
 * @return the package fragment to be pre-filled in this page or <code>null</code> if no
 *         suitable package can be suggested for the given project
 * 
 * @since 3.9
 */
private IPackageFragment getPackage(IJavaProject javaProject) {
	String packName= null;
	final IPackageFragmentRoot pkgFragmentRoot= getPackageFragmentRoot();
	IJavaElement[] packages= null;
	try {
		if (pkgFragmentRoot != null && pkgFragmentRoot.exists()) {
			packages= pkgFragmentRoot.getChildren();
			if (packages.length == 1) { // only default package -> use Project name
				packName= javaProject.getElementName();
				// validate package name
				IStatus status= validatePackageName(packName, javaProject);
				if (status.getSeverity() == IStatus.OK) {
					return pkgFragmentRoot.getPackageFragment(packName);
				}
			} else {
				int noOfPackages= 0;
				IPackageFragment thePackage= null;
				for (final IJavaElement pack : packages) {
					IPackageFragment pkg= (IPackageFragment) pack;
					// ignoring empty parent packages and default package
					if ((!pkg.hasSubpackages() || pkg.hasChildren()) && !pkg.isDefaultPackage()) {
						noOfPackages++;
						thePackage= pkg;
						if (noOfPackages > 1) {
							return null;
						}
					}
				}
				if (noOfPackages == 1) { // use package name
					packName= thePackage.getElementName();
					return pkgFragmentRoot.getPackageFragment(packName);
				}
			}
		}
	} catch (JavaModelException e) {
		// fall through
	}
	return null;
}
 
Example 15
Source File: DeltaConverter.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.3
 * @deprecated This method is not used anymore.
 */
@Deprecated
protected String getExpectedPrimaryTypeNameFor(ICompilationUnit cu) {
	String fileName = cu.getElementName();
	String typeName = fileName.substring(0, fileName.lastIndexOf('.'));
	IPackageFragment pkg = (IPackageFragment) cu.getParent();
	if (!pkg.isDefaultPackage()) {
		typeName = pkg.getElementName() + '.' + typeName;
	}
	return typeName;
}
 
Example 16
Source File: RenamePackageChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public RenamePackageChange(IPackageFragment pack, String newName, boolean renameSubpackages) {
	this(pack.getPath(), pack.getElementName(), newName, IResource.NULL_STAMP, null, renameSubpackages);
	Assert.isTrue(!pack.isReadOnly(), "package must not be read only"); //$NON-NLS-1$
}
 
Example 17
Source File: RenameModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private String getNewPackageName(IPackageFragment rootPackage, String newPackageName, String oldSubPackageName) {
	String oldPackageName= rootPackage.getElementName();
	return newPackageName + oldSubPackageName.substring(oldPackageName.length());
}
 
Example 18
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static String getCompilationUnitContent(ICompilationUnit cu, String fileComment, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
	IPackageFragment pack= (IPackageFragment)cu.getParent();
	String packDecl= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$
	return getCompilationUnitContent(cu, packDecl, fileComment, typeComment, typeContent, lineDelimiter);
}
 
Example 19
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * The wizard owning this page is responsible for calling this method with the
 * current selection. The selection is used to initialize the fields of the wizard
 * page.
 *
 * @param selection used to initialize the fields
 */
public void init(IStructuredSelection selection) {
	IJavaElement jelem= getInitialJavaElement(selection);

	initContainerPage(jelem);
	String pName= ""; //$NON-NLS-1$
	if (jelem != null) {
		IPackageFragment pf= (IPackageFragment) jelem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
		if (pf != null && !pf.isDefaultPackage()) {
			pName= pf.getElementName();
		} else {
			if (jelem.getJavaProject() != null) {
				final IPackageFragmentRoot pkgFragmentRoot= getPackageFragmentRoot();
				if (pkgFragmentRoot != null && pkgFragmentRoot.exists()) {
					try {
						IJavaElement[] packages= pkgFragmentRoot.getChildren();
						if (packages.length == 1) { // only default package
							String prName= jelem.getJavaProject().getElementName();
							IStatus status= getPackageStatus(prName);
							if (status.getSeverity() == IStatus.OK) {
								pName= prName;
							}
						}
					} catch (JavaModelException e) {
						// fall through
					}
				}
			}
		}
	}
	setPackageText(pName, true);

	IDialogSettings dialogSettings= getDialogSettings();
	if (dialogSettings != null) {
		IDialogSettings section= dialogSettings.getSection(PAGE_NAME);
		if (section != null) {
			boolean createPackageDocumentation= section.getBoolean(SETTINGS_CREATEPACKAGE_INFO_JAVA);
			fCreatePackageInfoJavaDialogField.setSelection(createPackageDocumentation);
		}
	}

	updateStatus(new IStatus[] { fContainerStatus, fPackageStatus });
}
 
Example 20
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Sets the package fragment to the given value. The method updates the model
 * and the text of the control.
 *
 * @param pack the package fragment to be set
 * @param canBeModified if <code>true</code> the package fragment is
 * editable; otherwise it is read-only.
 */
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
	fCurrPackage= pack;
	fCanModifyPackage= canBeModified;
	String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
	fPackageDialogField.setText(str);
	updateEnableState();
}