Java Code Examples for org.eclipse.jdt.core.dom.ASTParser#setProject()

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#setProject() . 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: XbaseHoverDocumentationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Javadoc getJavaDoc() {
	if (context == null || context.eResource() == null || context.eResource().getResourceSet() == null)
		return null;
	Object classpathURIContext = ((XtextResourceSet) context.eResource().getResourceSet()).getClasspathURIContext();
	if (classpathURIContext instanceof IJavaProject) {
		IJavaProject javaProject = (IJavaProject) classpathURIContext;
		@SuppressWarnings("all")
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setProject(javaProject);
		Map<String, String> options = javaProject.getOptions(true);
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
		parser.setCompilerOptions(options);
		String source = rawJavaDoc + "class C{}"; //$NON-NLS-1$
		parser.setSource(source.toCharArray());
		CompilationUnit root = (CompilationUnit) parser.createAST(null);
		if (root == null)
			return null;
		List<AbstractTypeDeclaration> types = root.types();
		if (types.size() != 1)
			return null;
		AbstractTypeDeclaration type = types.get(0);
		return type.getJavadoc();
	}
	return null;
}
 
Example 2
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses the specified Java source file located in the given Java project.
 * 
 * @param sourceFile
 *            The specified Java source file.
 * @param project
 *            The given Java project.
 * @return The parsed compilation unit.
 * @throws IOException
 *             Thrown when I/O error occurs during reading the file.
 * @throws JavaModelException
 */
public static CompilationUnit parseJavaSource(File sourceFile, IJavaProject project)
		throws IOException, JavaModelException {
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	char[] content = SharedUtils.getFileContents(sourceFile);

	parser.setSource(content);
	parser.setProject(project);

	parser.setResolveBindings(true);
	parser.setBindingsRecovery(true);
	parser.setUnitName(sourceFile.getName());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
	return compilationUnit;
}
 
Example 3
Source File: EclipseASTParserFactory.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ASTParserFactory.ASTParserWrapper createJavaParser(final Object context) {
  if ((context instanceof IJavaElement)) {
    final IJavaProject project = ((IJavaElement)context).getJavaProject();
    final String projlevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
    final ASTParser parser = this.createDefaultJavaParser(projlevel);
    if ((context instanceof IJavaProject)) {
      parser.setProject(project);
      this.tweakOptions(parser, project);
    } else {
      if ((context instanceof ICompilationUnit)) {
        parser.setSource(((ICompilationUnit)context));
        this.tweakOptions(parser, ((ICompilationUnit)context).getJavaProject());
      }
    }
    return new ASTParserFactory.ASTParserWrapper(projlevel, parser);
  }
  return super.createJavaParser(context);
}
 
Example 4
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 5
Source File: JdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private boolean isParameterNamesAvailable() throws Exception {
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setIgnoreMethodBodies(true);
	IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
	parser.setProject(javaProject);
	IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
	IBinding[] bindings = parser.createBindings(new IJavaElement[] { type }, null);
	ITypeBinding typeBinding = (ITypeBinding) bindings[0];
	IMethodBinding[] methods = typeBinding.getDeclaredMethods();
	for(IMethodBinding method: methods) {
		if (method.isConstructor()) {
			IMethod element = (IMethod) method.getJavaElement();
			if (element.exists()) {
				String[] parameterNames = element.getParameterNames();
				if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
					return true;
				}
			} else {
				return false;
			}
		}
	}
	return false;
}
 
Example 6
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static CompilationUnit createAST(IJavaElement element, String cuSource) {
	Assert.isNotNull(element);
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	
	IJavaProject javaProject= element.getJavaProject();
	parser.setProject(javaProject);
	Map<String, String> options= javaProject.getOptions(true);
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
	parser.setCompilerOptions(options);
	
	parser.setSource(cuSource.toCharArray());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 7
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static String getPackageName(IJavaProject javaProject, String fileContent) {
	if (fileContent == null) {
		return "";
	}
	//TODO probably not the most efficient way to get the package name as this reads the whole file;
	char[] source = fileContent.toCharArray();
	ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setProject(javaProject);
	parser.setIgnoreMethodBodies(true);
	parser.setSource(source);
	CompilationUnit ast = (CompilationUnit) parser.createAST(null);
	PackageDeclaration pkg = ast.getPackage();
	return (pkg == null || pkg.getName() == null)?"":pkg.getName().getFullyQualifiedName();
}
 
Example 8
Source File: CompilationUnitParser.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public CompilationUnit parse(ICompilationUnit unit) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(unit);
    parser.setResolveBindings(true);
    parser.setProject(unit.getJavaProject());
    parser.setUnitName(unit.getPath().toString());
    return (CompilationUnit) parser.createAST(null);
}
 
Example 9
Source File: TypeEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private StandardType createStandardType(String fullyQualifiedName, IJavaProject focus) {
	try {
		IType javaElementType= focus.findType(fullyQualifiedName);
		StandardType result= fStandardTypes.get(javaElementType);
		if (result != null)
			return result;
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setProject(focus);
		IBinding[] bindings= parser.createBindings(new IJavaElement[] {javaElementType} , null);
		return createStandardType((ITypeBinding)bindings[0]);
	} catch (JavaModelException e) {
		// fall through
	}
	return null;
}
 
Example 10
Source File: JavadocContentAccess2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static CompilationUnit createAST(IJavaElement element, String cuSource) {
	Assert.isNotNull(element);
	ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);

	IJavaProject javaProject = element.getJavaProject();
	parser.setProject(javaProject);
	Map<String, String> options = javaProject.getOptions(true);
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
	parser.setCompilerOptions(options);

	parser.setSource(cuSource.toCharArray());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 11
Source File: LazyGenericTypeProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the type binding of the expected type as it is contained in the
 * code completion context.
 *
 * @return the binding of the expected type
 */
private ITypeBinding getExpectedType() {
	char[][] chKeys= fInvocationContext.getCoreContext().getExpectedTypesKeys();
	if (chKeys == null || chKeys.length == 0)
		return null;

	String[] keys= new String[chKeys.length];
	for (int i= 0; i < keys.length; i++) {
		keys[i]= String.valueOf(chKeys[0]);
	}

	final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setProject(fCompilationUnit.getJavaProject());
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);

	final Map<String, IBinding> bindings= new HashMap<String, IBinding>();
	ASTRequestor requestor= new ASTRequestor() {
		@Override
		public void acceptBinding(String bindingKey, IBinding binding) {
			bindings.put(bindingKey, binding);
		}
	};
	parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

	if (bindings.size() > 0)
		return (ITypeBinding) bindings.get(keys[0]);

	return null;
}
 
Example 12
Source File: JavaCompilationParticipantTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode parseTestClass() {
  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setResolveBindings(false);
  parser.setSource(testClass.getCompilationUnit());
  return parser.createAST(null);
}
 
Example 13
Source File: JavaValidationVisitorTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setResolveBindings(false);
  parser.setSource(testClass.getCompilationUnit());
  ast = parser.createAST(null);
}
 
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: UseSuperTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the text change manager for this processor.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the refactoring status
 * @return the created text change manager
 * @throws JavaModelException
 *             if the method declaration could not be found
 * @throws CoreException
 *             if the changes could not be generated
 */
protected final TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException, CoreException {
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 300); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.UseSuperTypeProcessor_creating);
		final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
		final IJavaProject project= fSubType.getJavaProject();
		final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setWorkingCopyOwner(fOwner);
		parser.setResolveBindings(true);
		parser.setProject(project);
		parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
		if (fSubType.isBinary() || fSubType.isReadOnly()) {
			final IBinding[] bindings= parser.createBindings(new IJavaElement[] { fSubType, fSuperType }, new SubProgressMonitor(monitor, 50));
			if (bindings != null && bindings.length == 2 && bindings[0] instanceof ITypeBinding && bindings[1] instanceof ITypeBinding) {
				solveSuperTypeConstraints(null, null, fSubType, (ITypeBinding) bindings[0], (ITypeBinding) bindings[1], new SubProgressMonitor(monitor, 100), status);
				if (!status.hasFatalError())
					rewriteTypeOccurrences(manager, null, null, null, null, new HashSet<String>(), status, new SubProgressMonitor(monitor, 150));
			}
		} else {
			parser.createASTs(new ICompilationUnit[] { fSubType.getCompilationUnit() }, new String[0], new ASTRequestor() {

				@Override
				public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
					try {
						final CompilationUnitRewrite subRewrite= new CompilationUnitRewrite(fOwner, unit, node);
						final AbstractTypeDeclaration subDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fSubType, subRewrite.getRoot());
						if (subDeclaration != null) {
							final ITypeBinding subBinding= subDeclaration.resolveBinding();
							if (subBinding != null) {
								final ITypeBinding superBinding= findTypeInHierarchy(subBinding, fSuperType.getFullyQualifiedName('.'));
								if (superBinding != null) {
									solveSuperTypeConstraints(subRewrite.getCu(), subRewrite.getRoot(), fSubType, subBinding, superBinding, new SubProgressMonitor(monitor, 100), status);
									if (!status.hasFatalError()) {
										rewriteTypeOccurrences(manager, this, subRewrite, subRewrite.getCu(), subRewrite.getRoot(), new HashSet<String>(), status, new SubProgressMonitor(monitor, 200));
										final TextChange change= subRewrite.createChange(true);
										if (change != null)
											manager.manage(subRewrite.getCu(), change);
									}
								}
							}
						}
					} catch (CoreException exception) {
						JavaPlugin.log(exception);
						status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.UseSuperTypeProcessor_internal_error));
					}
				}

				@Override
				public final void acceptBinding(final String key, final IBinding binding) {
					// Do nothing
				}
			}, new NullProgressMonitor());
		}
		return manager;
	} finally {
		monitor.done();
	}
}
 
Example 16
Source File: CreateTypeMemberOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
	if (this.createdNode == null) {
		this.source = removeIndentAndNewLines(this.source, cu);
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(this.source.toCharArray());
		parser.setProject(getCompilationUnit().getJavaProject());
		parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
		ASTNode node = parser.createAST(this.progressMonitor);
		String createdNodeSource;
		if (node.getNodeType() != ASTNode.TYPE_DECLARATION) {
			createdNodeSource = generateSyntaxIncorrectAST();
			if (this.createdNode == null)
				throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
		} else {
			TypeDeclaration typeDeclaration = (TypeDeclaration) node;
			if ((typeDeclaration.getFlags() & ASTNode.MALFORMED) != 0) {
				createdNodeSource = generateSyntaxIncorrectAST();
				if (this.createdNode == null)
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
			} else {
				List bodyDeclarations = typeDeclaration.bodyDeclarations();
				if (bodyDeclarations.size() == 0) {
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
				}
				this.createdNode = (ASTNode) bodyDeclarations.iterator().next();
				createdNodeSource = this.source;
			}
		}
		if (this.alteredName != null) {
			SimpleName newName = this.createdNode.getAST().newSimpleName(this.alteredName);
			SimpleName oldName = rename(this.createdNode, newName);
			int nameStart = oldName.getStartPosition();
			int nameEnd = nameStart + oldName.getLength();
			StringBuffer newSource = new StringBuffer();
			if (this.source.equals(createdNodeSource)) {
				newSource.append(createdNodeSource.substring(0, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd));
			} else {
				// syntactically incorrect source
				int createdNodeStart = this.createdNode.getStartPosition();
				int createdNodeEnd = createdNodeStart + this.createdNode.getLength();
				newSource.append(createdNodeSource.substring(createdNodeStart, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd, createdNodeEnd));

			}
			this.source = newSource.toString();
		}
	}
	if (rewriter == null) return this.createdNode;
	// return a string place holder (instead of the created node) so has to not lose comments and formatting
	return rewriter.createStringPlaceholder(this.source, this.createdNode.getNodeType());
}
 
Example 17
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final CompilationUnitRewrite sourceRewrite, final ICompilationUnit copy, final Set<String> replacements, final RefactoringStatus status, final IProgressMonitor monitor) {
	try {
		monitor.beginTask("", 100); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.PullUpRefactoring_checking);
		final IType declaring= getDeclaringType();
		final IJavaProject project= declaring.getJavaProject();
		final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setWorkingCopyOwner(fOwner);
		parser.setResolveBindings(true);
		parser.setProject(project);
		parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
		parser.createASTs(new ICompilationUnit[] { copy}, new String[0], new ASTRequestor() {

			@Override
			public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
				try {
					final IType subType= (IType) JavaModelUtil.findInCompilationUnit(unit, declaring);
					final AbstractTypeDeclaration subDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(subType, node);
					if (subDeclaration != null) {
						final ITypeBinding subBinding= subDeclaration.resolveBinding();
						if (subBinding != null) {
							String name= null;
							ITypeBinding superBinding= null;
							final ITypeBinding[] superBindings= Bindings.getAllSuperTypes(subBinding);
							for (int index= 0; index < superBindings.length; index++) {
								name= superBindings[index].getName();
								if (name.startsWith(fDestinationType.getElementName()))
									superBinding= superBindings[index];
							}
							if (superBinding != null) {
								solveSuperTypeConstraints(unit, node, subType, subBinding, superBinding, new SubProgressMonitor(monitor, 80), status);
								if (!status.hasFatalError())
									rewriteTypeOccurrences(manager, this, sourceRewrite, unit, node, replacements, status, new SubProgressMonitor(monitor, 120));
							}
						}
					}
				} catch (JavaModelException exception) {
					JavaPlugin.log(exception);
					status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
				}
			}

			@Override
			public final void acceptBinding(final String key, final IBinding binding) {
				// Do nothing
			}
		}, new NullProgressMonitor());
	} finally {
		monitor.done();
	}
}
 
Example 18
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the type name has changed. The method validates the
 * type name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
	StatusInfo status= new StatusInfo();
	fCurrType= null;
	String typeNameWithParameters= getTypeName();
	// must not be empty
	if (typeNameWithParameters.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
		return status;
	}

	String typeName= getTypeNameWithoutParameters();
	if (typeName.indexOf('.') != -1) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
		return status;
	}

	IJavaProject project= getJavaProject();
	IStatus val= validateJavaTypeName(typeName, project);
	if (val.getSeverity() == IStatus.ERROR) {
		status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
		return status;
	} else if (val.getSeverity() == IStatus.WARNING) {
		status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
		// continue checking
	}

	// must not exist
	if (!isEnclosingTypeSelected()) {
		IPackageFragment pack= getPackageFragment();
		if (pack != null) {
			ICompilationUnit cu= pack.getCompilationUnit(getCompilationUnitName(typeName));
			fCurrType= cu.getType(typeName);
			IResource resource= cu.getResource();

			if (resource.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
				return status;
			}
			URI location= resource.getLocationURI();
			if (location != null) {
				try {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
						return status;
					}
				} catch (CoreException e) {
					status.setError(Messages.format(
						NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
						BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
				}
			}
		}
	} else {
		IType type= getEnclosingType();
		if (type != null) {
			fCurrType= type.getType(typeName);
			if (fCurrType.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
		}
	}

	if (!typeNameWithParameters.equals(typeName) && project != null) {
		if (!JavaModelUtil.is50OrHigher(project)) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
			return status;
		}
		String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(typeDeclaration.toCharArray());
		parser.setProject(project);
		CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null);
		IProblem[] problems= compilationUnit.getProblems();
		if (problems.length > 0) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
			return status;
		}
	}
	return status;
}
 
Example 19
Source File: CleanUpRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void next(IProgressMonitor monitor) throws CoreException {
	List<ICompilationUnit> parseList= new ArrayList<ICompilationUnit>();
	List<ICompilationUnit> sourceList= new ArrayList<ICompilationUnit>();

	try {
		for (Iterator<ParseListElement> iter= fParseList.iterator(); iter.hasNext();) {
			ParseListElement element= iter.next();

			ICompilationUnit compilationUnit= element.getTarget().getCompilationUnit();
			if (fSolutions.containsKey(compilationUnit)) {
				if (fWorkingCopies.containsKey(compilationUnit)) {
					compilationUnit= fWorkingCopies.get(compilationUnit);
				} else {
					compilationUnit= compilationUnit.getWorkingCopy(new WorkingCopyOwner() {}, null);
					fWorkingCopies.put(compilationUnit.getPrimary(), compilationUnit);
				}
				applyChange(compilationUnit, fSolutions.get(compilationUnit.getPrimary()));
			}

			if (requiresAST(element.getCleanUps())) {
				parseList.add(compilationUnit);
			} else {
				sourceList.add(compilationUnit);
			}
		}

		CleanUpRefactoringProgressMonitor cuMonitor= new CleanUpRefactoringProgressMonitor(monitor, parseList.size() + sourceList.size(), fSize, fIndex);
		CleanUpASTRequestor requestor= new CleanUpASTRequestor(fParseList, fSolutions, cuMonitor);
		if (parseList.size() > 0) {
			ASTBatchParser parser= new ASTBatchParser() {
				@Override
				protected ASTParser createParser(IJavaProject project) {
					ASTParser result= createCleanUpASTParser();
					result.setProject(project);

					Map<String, String> options= RefactoringASTParser.getCompilerOptions(project);
					options.putAll(fCleanUpOptions);
					result.setCompilerOptions(options);
					return result;
				}
			};
			try {
				ICompilationUnit[] units= parseList.toArray(new ICompilationUnit[parseList.size()]);
				parser.createASTs(units, new String[0], requestor, cuMonitor);
			} catch (FixCalculationException e) {
				throw e.getException();
			}
		}

		for (Iterator<ICompilationUnit> iterator= sourceList.iterator(); iterator.hasNext();) {
			ICompilationUnit cu= iterator.next();

			monitor.worked(1);

			requestor.acceptSource(cu);

			if (monitor.isCanceled())
				throw new OperationCanceledException();
		}

		fParseList= requestor.getUndoneElements();
		fIndex= cuMonitor.getIndex();
	} finally {
	}
}
 
Example 20
Source File: ASTBatchParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a new parser which can be used to create ASTs
 * for compilation units in <code>project</code>
 * <p>
 * Subclasses may override
 * </p>
 *
 * @param project the project for which ASTs are been generated
 * @return an AST parser capable of creating ASTs of compilation units in project
 */
protected ASTParser createParser(IJavaProject project) {
	ASTParser result= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	result.setResolveBindings(true);
	result.setProject(project);

	return result;
}