Java Code Examples for org.eclipse.jdt.core.dom.CompilationUnit#getProblems()

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit#getProblems() . 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
/**
 * {@inheritDoc}
 */
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
	try {
		ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement();
		if (!cu.isStructureKnown())
			return 0; //[clean up] 'Remove unnecessary $NLS-TAGS$' removes necessary ones in case of syntax errors: https://bugs.eclipse.org/bugs/show_bug.cgi?id=285814 : 
	} catch (JavaModelException e) {
		return 0;
	}
	
	int result= 0;
	IProblem[] problems= compilationUnit.getProblems();
	if (isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS))
		result+= getNumberOfProblems(problems, IProblem.NonExternalizedStringLiteral);

	if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS))
		result+= getNumberOfProblems(problems, IProblem.UnnecessaryNLSTag);

	return result;
}
 
Example 2
protected List<Either<Command, CodeAction>> getCodeActions(ICompilationUnit cu) throws JavaModelException {

		CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null);
		IProblem[] problems = astRoot.getProblems();

		Range range = getRange(cu, problems);

		CodeActionParams parms = new CodeActionParams();

		TextDocumentIdentifier textDocument = new TextDocumentIdentifier();
		textDocument.setUri(JDTUtils.toURI(cu));
		parms.setTextDocument(textDocument);
		parms.setRange(range);
		CodeActionContext context = new CodeActionContext();
		context.setDiagnostics(DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true));
		context.setOnly(Arrays.asList(CodeActionKind.QuickFix));
		parms.setContext(context);

		return new CodeActionHandler(this.preferenceManager).getCodeActionCommands(parms, new NullProgressMonitor());
	}
 
Example 3
@Test
public void testUnnecessary() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("import java.security.*;\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	CompilationUnit asRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, monitor);
	IProblem[] problems = asRoot.getProblems();
	List<Diagnostic> diagnostics = DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true);
	assertEquals(1, diagnostics.size());
	List<DiagnosticTag> tags = diagnostics.get(0).getTags();
	assertEquals(1, tags.size());
	assertEquals(DiagnosticTag.Unnecessary, tags.get(0));
}
 
Example 4
/**
 * {@inheritDoc}
 */
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
	int result= 0;
	
	boolean addAnnotations= isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS);
	boolean addMissingOverride= addAnnotations && isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE);
	boolean addMissingOverrideInterfaceMethods= addMissingOverride && isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE_FOR_INTERFACE_METHOD_IMPLEMENTATION);
	boolean addMissingDeprecated= addAnnotations && isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS_DEPRECATED);
	boolean useTypeArgs= isEnabled(CleanUpConstants.VARIABLE_DECLARATION_USE_TYPE_ARGUMENTS_FOR_RAW_TYPE_REFERENCES);
	
	IProblem[] problems= compilationUnit.getProblems();
	for (int i= 0; i < problems.length; i++) {
		int id= problems[i].getID();
		if (addMissingOverride && Java50Fix.isMissingOverrideAnnotationProblem(id))
			if (! Java50Fix.isMissingOverrideAnnotationInterfaceProblem(id) || addMissingOverrideInterfaceMethods)
				result++;
		if (addMissingDeprecated && Java50Fix.isMissingDeprecationProblem(id))
			result++;
		if (useTypeArgs && Java50Fix.isRawTypeReferenceProblem(id))
			result++;
	}
	return result;
}
 
Example 5
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean removeUnusedPrivateMethods,
		boolean removeUnusedPrivateConstructors,
		boolean removeUnusedPrivateFields,
		boolean removeUnusedPrivateTypes,
		boolean removeUnusedLocalVariables,
		boolean removeUnusedImports,
		boolean removeUnusedCast) {

	IProblem[] problems= compilationUnit.getProblems();
	IProblemLocation[] locations= new IProblemLocation[problems.length];
	for (int i= 0; i < problems.length; i++) {
		locations[i]= new ProblemLocation(problems[i]);
	}

	return createCleanUp(compilationUnit, locations,
			removeUnusedPrivateMethods,
			removeUnusedPrivateConstructors,
			removeUnusedPrivateFields,
			removeUnusedPrivateTypes,
			removeUnusedLocalVariables,
			removeUnusedImports,
			removeUnusedCast);
}
 
Example 6
/**
 * {@inheritDoc}
 */
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
	int result= 0;
	IProblem[] problems= compilationUnit.getProblems();
	if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_CASTS))
		result+= getNumberOfProblems(problems, IProblem.UnnecessaryCast);
	return result;
}
 
Example 7
private void checkCompileErrors(RefactoringStatus result, CompilationUnit root, ICompilationUnit element) {
	IProblem[] messages = root.getProblems();
	for (int i = 0; i < messages.length; i++) {
		IProblem problem = messages[i];
		if (!isIgnorableProblem(problem)) {
			result.addWarning(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_compiler_errors_update, BasicElementLabels.getFileName(element)), JavaStatusContext.create(element));
			return;
		}
	}
}
 
Example 8
/**
	 * {@inheritDoc}
	 */
	@Override
	public int computeNumberOfFixes(CompilationUnit compilationUnit) {
		int result= 0;
		IProblem[] problems= compilationUnit.getProblems();
		for (int i= 0; i < problems.length; i++) {
			int id= problems[i].getID();
			if (id == this.handledProblemID) {
				// FIXME search specifically: return param (which??)
//				if (!QuickFixes.hasExplicitNullnessAnnotation(compilationUnit, problems[i].getSourceStart()))
				result++;
			}
		}
		return result;
	}
 
Example 9
/**
 * {@inheritDoc}
 */
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
	if (fOptions == null)
		return 0;
	int result= 0;
	IProblem[] problems= compilationUnit.getProblems();
	if (isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS))
		result= getNumberOfProblems(problems, IProblem.RedundantSpecificationOfTypeArguments);
	else if (isEnabled(CleanUpConstants.INSERT_INFERRED_TYPE_ARGUMENTS))
		result= getNumberOfProblems(problems, IProblem.DiamondNotBelow17);
	return result;

}
 
Example 10
protected List<Either<Command, CodeAction>> evaluateCodeActions(ICompilationUnit cu) throws JavaModelException {

		CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null);
		IProblem[] problems = astRoot.getProblems();

		Range range = getRange(cu, problems);
		return evaluateCodeActions(cu, range);
	}
 
Example 11
protected void failHelper(ICompilationUnit cu) throws OperationCanceledException, CoreException {
	CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null);
	IProblem[] problems = astRoot.getProblems();
	Range range = getRange(cu, problems);
	int start = DiagnosticsHelper.getStartOffset(cu, range);
	int end = DiagnosticsHelper.getEndOffset(cu, range);
	ExtractFieldRefactoring refactoring = new ExtractFieldRefactoring(astRoot, start, end - start);
	RefactoringStatus result = refactoring.checkInitialConditions(new NullProgressMonitor());
	assertNotNull("precondition was supposed to fail", result);
	assertEquals("precondition was supposed to fail", false, result.isOK());
}
 
Example 12
protected boolean helper(ICompilationUnit cu, InitializeScope initializeIn, String expected) throws Exception {
	CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null);
	IProblem[] problems = astRoot.getProblems();
	Range range = getRange(cu, problems);
	int start = DiagnosticsHelper.getStartOffset(cu, range);
	int end = DiagnosticsHelper.getEndOffset(cu, range);
	ExtractFieldRefactoring refactoring = new ExtractFieldRefactoring(astRoot, start, end - start);
	refactoring.setFieldName(refactoring.guessFieldName());

	RefactoringStatus activationResult = refactoring.checkInitialConditions(new NullProgressMonitor());
	assertTrue("activation was supposed to be successful", activationResult.isOK());
	if (initializeIn != null) {
		if (initializeIn == InitializeScope.CURRENT_METHOD && !refactoring.canEnableSettingDeclareInMethod()) {
			return false;
		} else if (initializeIn == InitializeScope.CLASS_CONSTRUCTORS && !refactoring.canEnableSettingDeclareInConstructors()) {
			return false;
		} else if (initializeIn == InitializeScope.FIELD_DECLARATION && !refactoring.canEnableSettingDeclareInFieldDeclaration()) {
			return false;
		}

		refactoring.setInitializeIn(initializeIn.ordinal());
	}

	RefactoringStatus checkInputResult = refactoring.checkFinalConditions(new NullProgressMonitor());
	assertTrue("precondition was supposed to pass but was " + checkInputResult.toString(), checkInputResult.isOK());

	Change change = refactoring.createChange(new NullProgressMonitor());
	WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);
	assertNotNull(change);
	String actual = evaluateChanges(edit.getChanges());
	assertEquals(expected, actual);
	return true;
}
 
Example 13
private void checkCompileErrors(RefactoringStatus result, CompilationUnit root, ICompilationUnit element) {
	IProblem[] messages= root.getProblems();
	for (int i= 0; i < messages.length; i++) {
		IProblem problem= messages[i];
		if (!isIgnorableProblem(problem)) {
			result.addWarning(Messages.format(
					RefactoringCoreMessages.SelfEncapsulateField_compiler_errors_update,
					BasicElementLabels.getFileName(element)), JavaStatusContext.create(element));
			return;
		}
	}
}
 
Example 14
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean addSerialVersionIds) {

		IProblem[] problems= compilationUnit.getProblems();
		IProblemLocation[] locations= new IProblemLocation[problems.length];
		for (int i= 0; i < problems.length; i++) {
			locations[i]= new ProblemLocation(problems[i]);
		}
		return createCleanUp(compilationUnit, locations, addSerialVersionIds);
	}
 
Example 15
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean addThisQualifier,
		boolean changeNonStaticAccessToStatic,
		boolean qualifyStaticFieldAccess,
		boolean changeIndirectStaticAccessToDirect,
		boolean qualifyMethodAccess,
		boolean qualifyStaticMethodAccess,
		boolean removeFieldQualifier,
		boolean removeMethodQualifier) {

	if (!addThisQualifier && !changeNonStaticAccessToStatic && !qualifyStaticFieldAccess && !changeIndirectStaticAccessToDirect && !qualifyMethodAccess && !qualifyStaticMethodAccess && !removeFieldQualifier && !removeMethodQualifier)
		return null;

	List<CompilationUnitRewriteOperation> operations= new ArrayList<CompilationUnitRewriteOperation>();
	if (addThisQualifier || qualifyStaticFieldAccess || qualifyMethodAccess || qualifyStaticMethodAccess) {
		CodeStyleVisitor codeStyleVisitor= new CodeStyleVisitor(compilationUnit, addThisQualifier, qualifyStaticFieldAccess, qualifyMethodAccess, qualifyStaticMethodAccess, operations);
		compilationUnit.accept(codeStyleVisitor);
	}

	IProblem[] problems= compilationUnit.getProblems();
	IProblemLocation[] locations= new IProblemLocation[problems.length];
	for (int i= 0; i < problems.length; i++) {
        locations[i]= new ProblemLocation(problems[i]);
       }
	addToStaticAccessOperations(compilationUnit, locations, changeNonStaticAccessToStatic, changeIndirectStaticAccessToDirect, operations);

	if (removeFieldQualifier || removeMethodQualifier) {
		ThisQualifierVisitor visitor= new ThisQualifierVisitor(removeFieldQualifier, removeMethodQualifier, compilationUnit, operations);
		compilationUnit.accept(visitor);
	}

	if (operations.isEmpty())
		return null;

	CompilationUnitRewriteOperation[] operationsArray= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new CodeStyleFix(FixMessages.CodeStyleFix_change_name, compilationUnit, operationsArray);
}
 
Example 16
private static boolean hasFatalError(CompilationUnit compilationUnit) {
	try {
		if (!((ICompilationUnit) compilationUnit.getJavaElement()).isStructureKnown())
			return true;
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
		return true;
	}

	IProblem[] problems= compilationUnit.getProblems();
	for (int i= 0; i < problems.length; i++) {
		if (problems[i].isError()) {
			if (!(problems[i] instanceof CategorizedProblem))
				return true;

			CategorizedProblem categorizedProblem= (CategorizedProblem) problems[i];
			int categoryID= categorizedProblem.getCategoryID();

			if (categoryID == CategorizedProblem.CAT_BUILDPATH)
				return true;
			if (categoryID == CategorizedProblem.CAT_SYNTAX)
				return true;
			if (categoryID == CategorizedProblem.CAT_IMPORT)
				return true;
			if (categoryID == CategorizedProblem.CAT_TYPE)
				return true;
			if (categoryID == CategorizedProblem.CAT_MEMBER)
				return true;
			if (categoryID == CategorizedProblem.CAT_INTERNAL)
				return true;
		}
	}

	return false;
}
 
Example 17
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean insertInferredTypeArguments, boolean removeRedundantTypeArguments) {

		IProblem[] problems= compilationUnit.getProblems();
		IProblemLocation[] locations= new IProblemLocation[problems.length];
		for (int i= 0; i < problems.length; i++) {
			locations[i]= new ProblemLocation(problems[i]);
		}

		return createCleanUp(compilationUnit, locations,
				insertInferredTypeArguments,
				removeRedundantTypeArguments);
	}
 
Example 18
Source Project: APDE   File: Preprocessor.java    License: GNU General Public License v2.0 4 votes vote down vote up
private void findSyntaxProblems() throws TextTransform.LockException {
	CompilationUnit compilable = parse(preprocessedText);
	for (IProblem problem : compilable.getProblems()) {
		addCompilerProblem(buildCompilerProblem(problem));
	}
}
 
Example 19
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean addOverrideAnnotation,
		boolean addOverrideInterfaceAnnotation,
		boolean addDeprecatedAnnotation,
		boolean rawTypeReference) {

	ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement();
	if (!JavaModelUtil.is50OrHigher(cu.getJavaProject()))
		return null;

	if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReference)
		return null;

	List<CompilationUnitRewriteOperation> operations= new ArrayList<CompilationUnitRewriteOperation>();

	IProblem[] problems= compilationUnit.getProblems();
	IProblemLocation[] locations= new IProblemLocation[problems.length];
	for (int i= 0; i < problems.length; i++) {
		locations[i]= new ProblemLocation(problems[i]);
	}

	if (addOverrideAnnotation)
		createAddOverrideAnnotationOperations(compilationUnit, addOverrideInterfaceAnnotation, locations, operations);

	if (addDeprecatedAnnotation)
		createAddDeprecatedAnnotationOperations(compilationUnit, locations, operations);

	if (rawTypeReference)
		createRawTypeReferenceOperations(compilationUnit, locations, operations);

	if (operations.size() == 0)
		return null;

	String fixName;
	if (rawTypeReference) {
		fixName= FixMessages.Java50Fix_add_type_parameters_change_name;
	} else {
		fixName= FixMessages.Java50Fix_add_annotations_change_name;
	}

	CompilationUnitRewriteOperation[] operationsArray= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new Java50Fix(fixName, compilationUnit, operationsArray);
}
 
Example 20
/**
 * 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;
}