Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#getParent()

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getParent() . 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: CorrectPackageDeclarationProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getName() {
	ICompilationUnit cu= getCompilationUnit();
	IPackageFragment parentPack= (IPackageFragment) cu.getParent();
	try {
		IPackageDeclaration[] decls= cu.getPackageDeclarations();
		if (parentPack.isDefaultPackage() && decls.length > 0) {
			return Messages.format(CorrectionMessages.CorrectPackageDeclarationProposal_remove_description, BasicElementLabels.getJavaElementName(decls[0].getElementName()));
		}
		if (!parentPack.isDefaultPackage() && decls.length == 0) {
			return (Messages.format(CorrectionMessages.CorrectPackageDeclarationProposal_add_description,  JavaElementLabels.getElementLabel(parentPack, JavaElementLabels.ALL_DEFAULT)));
		}
	} catch(JavaModelException e) {
		JavaLanguageServerPlugin.log(e);
	}
	return (Messages.format(CorrectionMessages.CorrectPackageDeclarationProposal_change_description, JavaElementLabels.getElementLabel(parentPack, JavaElementLabels.ALL_DEFAULT)));
}
 
Example 2
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Uses the New Java file template from the code template page to generate a
 * compilation unit with the given type content.
 * 
 * @param cu The new created compilation unit
 * @param typeContent The content of the type, including signature and type
 * body.
 * @param lineDelimiter The line delimiter to be used.
 * @return String Returns the result of evaluating the new file template
 * with the given type content.
 * @throws CoreException when fetching the file comment fails or fetching the content for the
 *             new compilation unit fails
 * @since 2.1
 */
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
	String fileComment= getFileComment(cu, lineDelimiter);
	String typeComment= getTypeComment(cu, lineDelimiter);
	IPackageFragment pack= (IPackageFragment) cu.getParent();
	String content= CodeGeneration.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
	if (content != null) {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setProject(cu.getJavaProject());
		parser.setSource(content.toCharArray());
		CompilationUnit unit= (CompilationUnit) parser.createAST(null);
		if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
			return content;
		}
	}
	StringBuffer buf= new StringBuffer();
	if (!pack.isDefaultPackage()) {
		buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
	}
	buf.append(lineDelimiter).append(lineDelimiter);
	if (typeComment != null) {
		buf.append(typeComment).append(lineDelimiter);
	}
	buf.append(typeContent);
	return buf.toString();
}
 
Example 3
Source File: OrganizeImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public TypeReferenceProcessor(Set<String> oldSingleImports, Set<String> oldDemandImports, CompilationUnit root, ImportRewrite impStructure, boolean ignoreLowerCaseNames) {
	fOldSingleImports= oldSingleImports;
	fOldDemandImports= oldDemandImports;
	fImpStructure= impStructure;
	fDoIgnoreLowerCaseNames= ignoreLowerCaseNames;

	ICompilationUnit cu= impStructure.getCompilationUnit();

	fImplicitImports= new HashSet<String>(3);
	fImplicitImports.add(""); //$NON-NLS-1$
	fImplicitImports.add("java.lang"); //$NON-NLS-1$
	fImplicitImports.add(cu.getParent().getElementName());

	fAnalyzer= new ScopeAnalyzer(root);

	fCurrPackage= (IPackageFragment) cu.getParent();

	fAllowDefaultPackageImports= cu.getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true).equals(JavaCore.VERSION_1_3);

	fImportsAdded= new HashSet<String>();
	fUnresolvedTypes= new HashMap<String, UnresolvedTypeData>();
}
 
Example 4
Source File: CompilationUnitRenamedReferenceUpdater.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ICompilationUnit getUpdatedCompilationUnit(
    ICompilationUnit compilationUnit) {
  if (!compilationUnit.getElementName().equals(oldCuName)) {
    return compilationUnit;
  }

  // Sanity check
  if (!(compilationUnit.getParent() instanceof IPackageFragment)) {
    GWTPluginLog.logWarning(String.format(
        "The parent of %s is not a package fragment (it is %s of type %s).",
        compilationUnit.getElementName(),
        compilationUnit.getParent().getElementName(),
        compilationUnit.getParent().getClass().getSimpleName()));
    return compilationUnit;
  }

  IPackageFragment pkgFragment = (IPackageFragment) compilationUnit.getParent();
  ICompilationUnit newCu = pkgFragment.getCompilationUnit(newCuName);
  return newCu;
}
 
Example 5
Source File: FileEventHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static ICompilationUnit createCompilationUnit(ICompilationUnit unit) {
	try {
		unit.getResource().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
		if (unit.getResource().exists()) {
			IJavaElement parent = unit.getParent();
			if (parent instanceof IPackageFragment) {
				IPackageFragment pkg = (IPackageFragment) parent;
				if (JavaModelManager.determineIfOnClasspath(unit.getResource(), unit.getJavaProject()) != null) {
					unit = pkg.createCompilationUnit(unit.getElementName(), unit.getSource(), true, new NullProgressMonitor());
				}
			}
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException(e.getMessage(), e);
	}
	return unit;
}
 
Example 6
Source File: CorrectPackageDeclarationProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

	ICompilationUnit cu= getCompilationUnit();

	IPackageFragment parentPack= (IPackageFragment) cu.getParent();
	IPackageDeclaration[] decls= cu.getPackageDeclarations();

	if (parentPack.isDefaultPackage() && decls.length > 0) {
		for (int i= 0; i < decls.length; i++) {
			ISourceRange range= decls[i].getSourceRange();
			root.addChild(new DeleteEdit(range.getOffset(), range.getLength()));
		}
		return;
	}
	if (!parentPack.isDefaultPackage() && decls.length == 0) {
		String lineDelim = "\n";
		String str= "package " + parentPack.getElementName() + ';' + lineDelim + lineDelim; //$NON-NLS-1$
		root.addChild(new InsertEdit(0, str));
		return;
	}

	root.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), parentPack.getElementName()));
}
 
Example 7
Source File: JavaElementLabelComposer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Appends the label for a compilation unit. Considers the CU_* flags.
 *
 * @param cu the element to render
 * @param flags the rendering flags. Flags with names starting with 'CU_' are considered.
 */
public void appendCompilationUnitLabel(ICompilationUnit cu, long flags) {
	if (getFlag(flags, JavaElementLabels.CU_QUALIFIED)) {
		IPackageFragment pack= (IPackageFragment) cu.getParent();
		if (!pack.isDefaultPackage()) {
			appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
			fBuilder.append('.');
		}
	}
	fBuilder.append(cu.getElementName());

	if (getFlag(flags, JavaElementLabels.CU_POST_QUALIFIED)) {
		fBuilder.append(JavaElementLabels.CONCAT_STRING);
		appendPackageFragmentLabel((IPackageFragment) cu.getParent(), flags & QUALIFIER_FLAGS);
	}
}
 
Example 8
Source File: JavaElementLabelComposer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Appends the label for a compilation unit. Considers the CU_* flags.
 *
 * @param cu the element to render
 * @param flags the rendering flags. Flags with names starting with 'CU_' are considered.
 */
public void appendCompilationUnitLabel(ICompilationUnit cu, long flags) {
	if (getFlag(flags, JavaElementLabels.CU_QUALIFIED)) {
		IPackageFragment pack= (IPackageFragment) cu.getParent();
		if (!pack.isDefaultPackage()) {
			appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
			fBuffer.append('.');
		}
	}
	fBuffer.append(cu.getElementName());

	if (getFlag(flags, JavaElementLabels.CU_POST_QUALIFIED)) {
		int offset= fBuffer.length();
		fBuffer.append(JavaElementLabels.CONCAT_STRING);
		appendPackageFragmentLabel((IPackageFragment) cu.getParent(), flags & QUALIFIER_FLAGS);
		if (getFlag(flags, JavaElementLabels.COLORIZE)) {
			fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
		}
	}
}
 
Example 9
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @return search scope with
 * <p>- fPackage and
 * <p>- all CUs from fOccurrences which are not in a namesake package
 */
private IJavaSearchScope getPackageAndOccurrencesWithoutNamesakesScope() {
	List<IJavaElement> scopeList= new ArrayList<>();
	scopeList.add(fPackage);
	for (int i= 0; i < fOccurrences.length; i++) {
		ICompilationUnit cu= fOccurrences[i].getCompilationUnit();
		if (cu == null) {
			continue;
		}
		IPackageFragment pack= (IPackageFragment) cu.getParent();
		if (! pack.getElementName().equals(fPackage.getElementName())) {
			scopeList.add(cu);
		}
	}
	return SearchEngine.createJavaSearchScope(scopeList.toArray(new IJavaElement[scopeList.size()]));
}
 
Example 10
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isReferenceInAnotherFragmentOfSamePackage(ICompilationUnit referencingCu, ICompilationUnit movedUnit) {
	if (referencingCu == null)
		return false;
	if (! (referencingCu.getParent() instanceof IPackageFragment))
		return false;
	IPackageFragment pack= (IPackageFragment) referencingCu.getParent();
	return isInAnotherFragmentOfSamePackage(movedUnit, pack);
}
 
Example 11
Source File: NLSHintHelper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IPackageFragment getPackageOfAccessorClass(IJavaProject javaProject, ITypeBinding accessorBinding) throws JavaModelException {
	if (accessorBinding != null) {
		ICompilationUnit unit= Bindings.findCompilationUnit(accessorBinding, javaProject);
		if (unit != null) {
			return (IPackageFragment) unit.getParent();
		}
	}
	return null;
}
 
Example 12
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SearchResultGroup[] getReferences(ICompilationUnit unit, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	final SearchPattern pattern= RefactoringSearchEngine.createOrPattern(unit.getTypes(), IJavaSearchConstants.REFERENCES);
	if (pattern != null) {
		String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getFileName(unit));
		ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
		Collector requestor= new Collector(((IPackageFragment) unit.getParent()), binaryRefs);
		IJavaSearchScope scope= RefactoringScopeFactory.create(unit, true, false);

		SearchResultGroup[] result= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
		binaryRefs.addErrorIfNecessary(status);
		return result;
	}
	return new SearchResultGroup[] {};
}
 
Example 13
Source File: ReorgUtils.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isParentInWorkspaceOrOnDisk(ICompilationUnit cu, IPackageFragment dest){
	if (cu == null)
		return false;
	IJavaElement cuParent= cu.getParent();
	if (cuParent == null)
		return false;
	if (cuParent.equals(dest))
		return true;
	IResource cuResource= cu.getResource();
	IResource packageResource= ResourceUtil.getResource(dest);
	return isParentInWorkspaceOrOnDisk(cuResource, packageResource);
}
 
Example 14
Source File: TypeCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private String createCuContent(ICompilationUnit cu, String typeContent) throws CoreException {
  String fileComment = getFileComment(cu);
  String typeComment = getTypeComment(cu);
  IPackageFragment cuPckg = (IPackageFragment) cu.getParent();

  // Use the 'New Java File' code template specified by workspace preferences
  String content = CodeGeneration.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
  if (content != null) {
    // Parse the generated source to make sure it's error-free
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setProject(cu.getJavaProject());
    parser.setSource(content.toCharArray());
    CompilationUnit unit = (CompilationUnit) parser.createAST(null);
    if ((cuPckg.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
      return content;
    }
  }

  // If we didn't have a template to use, just generate the source by hand
  StringBuffer buf = new StringBuffer();
  if (!cuPckg.isDefaultPackage()) {
    buf.append("package ").append(cuPckg.getElementName()).append(';');
  }
  buf.append(lineDelimiter).append(lineDelimiter);
  if (typeComment != null) {
    buf.append(typeComment).append(lineDelimiter);
  }
  buf.append(typeContent);
  return buf.toString();
}
 
Example 15
Source File: ReorgUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean isParentInWorkspaceOrOnDisk(ICompilationUnit cu, IPackageFragment dest){
	if (cu == null) {
		return false;
	}
	IJavaElement cuParent= cu.getParent();
	if (cuParent == null) {
		return false;
	}
	if (cuParent.equals(dest)) {
		return true;
	}
	IResource cuResource= cu.getResource();
	IResource packageResource= ResourceUtil.getResource(dest);
	return isParentInWorkspaceOrOnDisk(cuResource, packageResource);
}
 
Example 16
Source File: ReplaceTypeCodeWithStateStrategyInputPage.java    From JDeodorant with MIT License 4 votes vote down vote up
public ReplaceTypeCodeWithStateStrategyInputPage(ReplaceTypeCodeWithStateStrategy refactoring) {
	super("State/Strategy Type Names");
	this.refactoring = refactoring;
	ICompilationUnit sourceCompilationUnit = (ICompilationUnit)refactoring.getSourceCompilationUnit().getJavaElement();
	this.parentPackage = (IPackageFragment)sourceCompilationUnit.getParent();
	this.parentPackageClassNames = new ArrayList<String>();
	try {
		for(ICompilationUnit compilationUnit : parentPackage.getCompilationUnits()) {
			String className = compilationUnit.getElementName();
			parentPackageClassNames.add(className.substring(0, className.indexOf(".java")));
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	TypeVisitor typeVisitor = new TypeVisitor();
	refactoring.getSourceCompilationUnit().accept(typeVisitor);
	Set<ITypeBinding> typeBindings = typeVisitor.getTypeBindings();
	for(ITypeBinding typeBinding : typeBindings) {
		if(!parentPackageClassNames.contains(typeBinding.getName()) && !typeBinding.isNested()) {
			parentPackageClassNames.add(typeBinding.getName());
		}
	}
	this.javaLangClassNames = new ArrayList<String>();
	this.javaLangClassNames.add("Boolean");
	this.javaLangClassNames.add("Byte");
	this.javaLangClassNames.add("Character");
	this.javaLangClassNames.add("Class");
	this.javaLangClassNames.add("Double");
	this.javaLangClassNames.add("Enum");
	this.javaLangClassNames.add("Error");
	this.javaLangClassNames.add("Exception");
	this.javaLangClassNames.add("Float");
	this.javaLangClassNames.add("Integer");
	this.javaLangClassNames.add("Long");
	this.javaLangClassNames.add("Math");
	this.javaLangClassNames.add("Number");
	this.javaLangClassNames.add("Object");
	this.javaLangClassNames.add("Package");
	this.javaLangClassNames.add("Process");
	this.javaLangClassNames.add("Runtime");
	this.javaLangClassNames.add("Short");
	this.javaLangClassNames.add("String");
	this.javaLangClassNames.add("StringBuffer");
	this.javaLangClassNames.add("StringBuilder");
	this.javaLangClassNames.add("System");
	this.javaLangClassNames.add("Thread");
	this.javaLangClassNames.add("Void");
	this.textMap = new LinkedHashMap<Text, SimpleName>();
	this.defaultNamingMap = new LinkedHashMap<Text, String>();
}
 
Example 17
Source File: AssistCompilationUnit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public AssistCompilationUnit(ICompilationUnit compilationUnit, WorkingCopyOwner owner, Map bindingCache, Map infoCache) {
	super((PackageFragment)compilationUnit.getParent(), compilationUnit.getElementName(), owner);
	this.bindingCache = bindingCache;
	this.infoCache = infoCache;
}
 
Example 18
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the classpath of the package containing the compilation unit being validated.
 */
private static IPath getPackagePath(ASTNode node) {
  ICompilationUnit cu = JavaASTUtils.getCompilationUnit(node);
  IPackageFragment pckg = (IPackageFragment) cu.getParent();
  return new Path(pckg.getElementName().replace('.', '/'));
}
 
Example 19
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 20
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean isInAnotherFragmentOfSamePackage(ICompilationUnit cu, IPackageFragment pack) {
	if (! (cu.getParent() instanceof IPackageFragment))
		return false;
	IPackageFragment cuPack= (IPackageFragment) cu.getParent();
	return ! cuPack.equals(pack) && JavaModelUtil.isSamePackage(cuPack, pack);
}