org.eclipse.jdt.core.dom.Modifier.ModifierKeyword Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.Modifier.ModifierKeyword. 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: PrivateConstructorMethodDefinitionCreationFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public MethodDeclaration createPrivateConstructorDefinition(AST ast, TypeDeclaration originalType, TypeDeclaration builderType,
        List<BuilderField> builderFields) {

    MethodDeclaration method = ast.newMethodDeclaration();
    method.setConstructor(true);
    method.setName(ast.newSimpleName(originalType.getName().toString()));
    if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) {
        generatedAnnotationPopulator.addGeneratedAnnotation(ast, method);
    }
    method.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));

    SingleVariableDeclaration methodParameterDeclaration = ast.newSingleVariableDeclaration();
    methodParameterDeclaration.setType(ast.newSimpleType(ast.newName(builderType.getName().toString())));
    methodParameterDeclaration.setName(ast.newSimpleName(camelCaseConverter.toLowerCamelCase(builderType.getName().toString())));

    method.parameters().add(methodParameterDeclaration);
    return method;
}
 
Example #2
Source File: RegularBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private MethodDeclaration createNewWithMethod(AST ast, String fieldName, Block newBlock,
        SingleVariableDeclaration methodParameterDeclaration, TypeDeclaration builderType,
        BuilderField builderField) {
    MethodDeclaration builderMethod = ast.newMethodDeclaration();
    builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName)));
    builderMethod.setReturnType2(ast.newSimpleType(
            ast.newName(builderType.getName().getIdentifier())));
    builderMethod.setBody(newBlock);
    builderMethod.parameters().add(methodParameterDeclaration);

    javadocAdder.addJavadocForWithMethod(ast, fieldName, builderMethod);
    if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) {
        markerAnnotationAttacher.attachNonNull(ast, builderMethod);
    }
    builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    return builderMethod;
}
 
Example #3
Source File: FinalParametersQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(SingleVariableDeclaration node) {
            if (containsPosition(node, markerStartOffset) && !Modifier.isFinal(node.getModifiers())) {
                if (!Modifier.isFinal(node.getModifiers())) {
                    final Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
                    node.modifiers().add(finalModifier);
                }
            }
            return true;
        }
    };
}
 
Example #4
Source File: EmptyBuilderClassGeneratorFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
public TypeDeclaration createBuilderClass(AST ast, TypeDeclaration originalType) {
    TypeDeclaration builderType = ast.newTypeDeclaration();
    builderType.setName(ast.newSimpleName(getBuilderName(originalType)));

    if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) {
        generatedAnnotationPopulator.addGeneratedAnnotation(ast, builderType);
    }
    builderType.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    builderType.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
    builderType.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));

    if (preferencesManager.getPreferenceValue(ADD_JACKSON_DESERIALIZE_ANNOTATION)) {
        jsonPOJOBuilderAdderFragment.addJsonPOJOBuilder(ast, builderType);
    }

    if (preferencesManager.getPreferenceValue(GENERATE_JAVADOC_ON_BUILDER_CLASS)) {
        Javadoc javadoc = javadocGenerator.generateJavadoc(ast, String.format(Locale.ENGLISH, "Builder to build {@link %s}.", originalType.getName().toString()),
                Collections.emptyMap());
        builderType.setJavadoc(javadoc);
    }

    return builderType;
}
 
Example #5
Source File: StagedBuilderWithMethodDefiniationCreatorFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
public MethodDeclaration createNewWithMethod(AST ast, BuilderField builderField,
        StagedBuilderProperties nextStage) {
    String fieldName = builderField.getBuilderFieldName();
    MethodDeclaration builderMethod = ast.newMethodDeclaration();
    builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName)));
    builderMethod.setReturnType2(ast.newSimpleType(ast.newName(nextStage.getInterfaceName())));
    builderMethod.parameters()
            .add(withMethodParameterCreatorFragment.createWithMethodParameter(ast, builderField.getFieldType(), fieldName));

    if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) {
        markerAnnotationAttacher.attachNonNull(ast, builderMethod);
    }
    builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    return builderMethod;
}
 
Example #6
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the visibility threshold from a type to a field.
 *
 * @param referencing the referencing type
 * @param referenced the referenced field
 * @param monitor the progress monitor to use
 * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
 * @throws JavaModelException if the java elements could not be accessed
 */
private ModifierKeyword thresholdTypeToField(final IType referencing, final IField referenced, final IProgressMonitor monitor) throws JavaModelException {
	ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
	final ICompilationUnit referencedUnit= referenced.getCompilationUnit();
	if (referenced.getDeclaringType().equals(referencing))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else {
		final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
		final IType[] types= hierarchy.getSupertypes(referencing);
		IType superType= null;
		for (int index= 0; index < types.length; index++) {
			superType= types[index];
			if (superType.equals(referenced.getDeclaringType())) {
				keyword= ModifierKeyword.PROTECTED_KEYWORD;
				return keyword;
			}
		}
	}
	final ICompilationUnit typeUnit= referencing.getCompilationUnit();
	if (referencedUnit != null && referencedUnit.equals(typeUnit))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else if (referencedUnit != null && typeUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
		keyword= null;
	return keyword;
}
 
Example #7
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void adjustOutgoingVisibilityChain(final IMember member, final IProgressMonitor monitor) throws JavaModelException {

		if (!Modifier.isPublic(member.getFlags())) {
			final ModifierKeyword threshold= computeOutgoingVisibilityThreshold(fReferencing, member, monitor);
			if (member instanceof IMethod) {
				adjustOutgoingVisibility(member, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning);
			} else if (member instanceof IField) {
				adjustOutgoingVisibility((IField) member, threshold);
			} else if (member instanceof IType) {
				adjustOutgoingVisibility(member, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning);
			}
		}

		if (member.getDeclaringType() != null)
			adjustOutgoingVisibilityChain(member.getDeclaringType(), monitor);
	}
 
Example #8
Source File: StagedBuilderCreationWithMethodAdder.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
public void addBuilderMethodToCompilationUnit(CompilationUnitModificationDomain modificationDomain, TypeDeclaration builderType,
        StagedBuilderProperties currentStage) {
    AST ast = modificationDomain.getAst();
    ListRewrite listRewrite = modificationDomain.getListRewrite();
    BuilderField firstField = currentStage.getNamedVariableDeclarationField().get(0);

    StagedBuilderProperties nextStage = currentStage.getNextStage().orElse(currentStage);
    MethodDeclaration staticWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast, firstField, nextStage);
    staticWithMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));

    String parameterName = firstField.getBuilderFieldName();
    String withMethodName = staticWithMethod.getName().toString();
    Block block = newBuilderAndWithMethodCallCreationFragment.createReturnBlock(ast, builderType, withMethodName, parameterName);

    javadocAdder.addJavadocForWithBuilderMethod(ast, builderType.getName().toString(), parameterName, staticWithMethod);

    staticWithMethod.setBody(block);

    listRewrite.insertLast(staticWithMethod, null);
}
 
Example #9
Source File: DefaultConstructorAppender.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private MethodDeclaration createConstructor(CompilationUnitModificationDomain domain) {
    AST ast = domain.getAst();

    Block emptyBody = ast.newBlock();
    MethodDeclaration defaultConstructor = ast.newMethodDeclaration();
    defaultConstructor.setBody(emptyBody);
    defaultConstructor.setConstructor(true);
    defaultConstructor.setName(ast.newSimpleName(domain.getOriginalType().getName().toString()));
    defaultConstructor.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) {
        generatedAnnotationPopulator.addGeneratedAnnotation(ast, defaultConstructor);
    }

    return defaultConstructor;
}
 
Example #10
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void updateLocalVariableDeclarations(final ASTRewrite rewrite, final Set<String> variables, Block block) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(block);
    Assert.isNotNull(variables);

    final AST ast = rewrite.getAST();
    block.accept(new ASTVisitor() {

        @Override
        public boolean visit(VariableDeclarationFragment fragment) {
            if (variables.contains(fragment.getName().getFullyQualifiedName())) {
                ASTNode parent = fragment.getParent();
                if (parent instanceof VariableDeclarationStatement) {
                    ListRewrite listRewrite = rewrite
                            .getListRewrite(parent, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
                    listRewrite.insertLast(ast.newModifier(ModifierKeyword.FINAL_KEYWORD), null);
                }
            }
            return true;
        }

    });

}
 
Example #11
Source File: FinalParametersQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartOffset) {
  return new ASTVisitor() {

    @SuppressWarnings("unchecked")
    @Override
    public boolean visit(SingleVariableDeclaration node) {
      if (containsPosition(node, markerStartOffset) && !Modifier.isFinal(node.getModifiers())) {
        if (!Modifier.isFinal(node.getModifiers())) {
          Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
          node.modifiers().add(finalModifier);
        }
      }
      return true;
    }
  };
}
 
Example #12
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<ResourceChange> createParameterObject(ParameterObjectFactory pof, IPackageFragmentRoot packageRoot) throws CoreException {
	FieldUpdate fieldUpdate= new FieldUpdate();
	if (fDescriptor.isCreateTopLevel())
		return pof.createTopLevelParameterObject(packageRoot, fieldUpdate);
	else {
		CompilationUnit root= fBaseCURewrite.getRoot();
		TypeDeclaration typeDecl= ASTNodeSearchUtil.getTypeDeclarationNode(fDescriptor.getType(), root);
		ASTRewrite rewrite= fBaseCURewrite.getASTRewrite();
		ListRewrite listRewrite= rewrite.getListRewrite(typeDecl, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		TypeDeclaration paramClass= pof.createClassDeclaration(typeDecl.getName().getFullyQualifiedName(), fBaseCURewrite, fieldUpdate);
		paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		if (shouldParamClassBeStatic(typeDecl)) {
			paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
		}
		listRewrite.insertFirst(paramClass, fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_insert_parameter));
		return new ArrayList<ResourceChange>(); //Change will be generated later for fBaseCURewrite
	}

}
 
Example #13
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private FieldDeclaration createField(ParameterInfo pi, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit unit= cuRewrite.getCu();

	VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	String lineDelim= StubUtility.getLineDelimiterUsed(unit);
	SimpleName fieldName= ast.newSimpleName(pi.getNewName());
	fragment.setName(fieldName);
	FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
	if (createComments(unit.getJavaProject())) {
		String comment= StubUtility.getFieldComment(unit, pi.getNewTypeName(), pi.getNewName(), lineDelim);
		if (comment != null) {
			Javadoc doc= (Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	List<Modifier> modifiers= new ArrayList<Modifier>();
	if (fCreateGetter) {
		modifiers.add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
	} else {
		modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	}
	declaration.modifiers().addAll(modifiers);
	declaration.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	return declaration;
}
 
Example #14
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Does the specified member need further visibility adjustment?
 *
 * @param member the member to test
 * @param threshold the visibility threshold to test for, or <code>null</code> for default visibility
 * @param adjustments the map of members to visibility adjustments
 * @return <code>true</code> if the member needs further adjustment, <code>false</code> otherwise
 */
public static boolean needsVisibilityAdjustments(final IMember member, final ModifierKeyword threshold, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments) {
	Assert.isNotNull(member);
	Assert.isNotNull(adjustments);
	final IncomingMemberVisibilityAdjustment adjustment= adjustments.get(member);
	if (adjustment != null)
		return hasLowerVisibility(adjustment.getKeyword(), threshold);
	return true;
}
 
Example #15
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adjusts the visibility of the referenced field found in a compilation unit.
 *
 * @param field the referenced field to adjust
 * @param threshold the visibility threshold, or <code>null</code> for default visibility
 * @throws JavaModelException if an error occurs
 */
private void adjustOutgoingVisibility(final IField field, final ModifierKeyword threshold) throws JavaModelException {
	Assert.isTrue(!field.isBinary() && !field.isReadOnly());
	//bug 100555 (moving inner class to top level class; taking private fields with you)
	final IType declaring= field.getDeclaringType();
	if (declaring != null && declaring.equals(fReferenced)) return;
	if (hasLowerVisibility(field.getFlags(), keywordToVisibility(threshold)) && needsVisibilityAdjustment(field, threshold))
		adjustOutgoingVisibility(field, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_field_warning);
}
 
Example #16
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addAdjustment(IMember whoToAdjust, ModifierKeyword neededVisibility, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments) throws JavaModelException {
	ModifierKeyword currentVisibility= ModifierKeyword.fromFlagValue(JdtFlags.getVisibilityCode(whoToAdjust));
	if (MemberVisibilityAdjustor.hasLowerVisibility(currentVisibility, neededVisibility)
			&& MemberVisibilityAdjustor.needsVisibilityAdjustments(whoToAdjust, neededVisibility, adjustments))
		adjustments.put(whoToAdjust, new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(whoToAdjust, neededVisibility,
				RefactoringStatus.createWarningStatus(Messages.format(MemberVisibilityAdjustor.getMessage(whoToAdjust), new String[] {
						MemberVisibilityAdjustor.getLabel(whoToAdjust), MemberVisibilityAdjustor.getLabel(neededVisibility) }), JavaStatusContext
						.create(whoToAdjust))));
}
 
Example #17
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createGetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit cu= cuRewrite.getCu();
	IJavaProject project= cu.getJavaProject();

	MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
	String fieldName= pi.getNewName();
	String getterName= getGetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	if (createComments(project)) {
		String comment= CodeGeneration.getGetterComment(cu, declaringType, getterName, fieldName, pi.getNewTypeName(), bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(getterName));
	methodDeclaration.setReturnType2(importBinding(pi.getNewTypeBinding(), cuRewrite));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getGetterMethodBodyContent(cu, declaringType, getterName, fieldName, lineDelim);
	ASTNode getterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(getterBody);
	return methodDeclaration;
}
 
Example #18
Source File: IntroduceParameterObjectProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createParameterClass(MethodDeclaration methodDeclaration, CompilationUnitRewrite cuRewrite) throws CoreException {
	if (fCreateAsTopLevel) {
		IPackageFragmentRoot root= (IPackageFragmentRoot) cuRewrite.getCu().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
		fOtherChanges.addAll(fParameterObjectFactory.createTopLevelParameterObject(root));
	} else {
		ASTRewrite rewriter= cuRewrite.getASTRewrite();
		TypeDeclaration enclosingType= (TypeDeclaration) methodDeclaration.getParent();
		ListRewrite bodyRewrite= rewriter.getListRewrite(enclosingType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		String fqn= enclosingType.getName().getFullyQualifiedName();
		TypeDeclaration classDeclaration= fParameterObjectFactory.createClassDeclaration(fqn, cuRewrite, null);
		classDeclaration.modifiers().add(rewriter.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		classDeclaration.modifiers().add(rewriter.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
		bodyRewrite.insertBefore(classDeclaration, methodDeclaration, null);
	}
}
 
Example #19
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the visibility threshold from a type to a method.
 *
 * @param referencing the referencing type
 * @param referenced the referenced method
 * @param monitor the progress monitor to use
 * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
 * @throws JavaModelException if the java elements could not be accessed
 */
private ModifierKeyword thresholdTypeToMethod(final IType referencing, final IMethod referenced, final IProgressMonitor monitor) throws JavaModelException {
	final ICompilationUnit referencedUnit= referenced.getCompilationUnit();
	ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
	if (referenced.getDeclaringType().equals(referencing))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else {
		final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
		final IType[] types= hierarchy.getSupertypes(referencing);
		IType superType= null;
		for (int index= 0; index < types.length; index++) {
			superType= types[index];
			if (superType.equals(referenced.getDeclaringType())) {
				keyword= ModifierKeyword.PROTECTED_KEYWORD;
				return keyword;
			}
		}
	}
	final ICompilationUnit typeUnit= referencing.getCompilationUnit();
	if (referencedUnit != null && referencedUnit.equals(typeUnit)) {
		if (referenced.getDeclaringType().getDeclaringType() != null)
			keyword= null;
		else
			keyword= ModifierKeyword.PRIVATE_KEYWORD;
	} else if (referencedUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
		keyword= null;
	return keyword;
}
 
Example #20
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the visibility threshold from a type to another type.
 *
 * @param referencing the referencing type
 * @param referenced the referenced type
 * @param monitor the progress monitor to use
 * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
 * @throws JavaModelException if the java elements could not be accessed
 */
private ModifierKeyword thresholdTypeToType(final IType referencing, final IType referenced, final IProgressMonitor monitor) throws JavaModelException {
	ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
	final ICompilationUnit referencedUnit= referenced.getCompilationUnit();
	if (referencing.equals(referenced.getDeclaringType()))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else {
		final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
		final IType[] types= hierarchy.getSupertypes(referencing);
		IType superType= null;
		for (int index= 0; index < types.length; index++) {
			superType= types[index];
			if (superType.equals(referenced)) {
				keyword= null;
				return keyword;
			}
		}
	}
	final ICompilationUnit typeUnit= referencing.getCompilationUnit();
	if (referencedUnit != null && referencedUnit.equals(typeUnit)) {
		if (referenced.getDeclaringType() != null)
			keyword= null;
		else
			keyword= ModifierKeyword.PRIVATE_KEYWORD;
	} else if (referencedUnit != null && typeUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
		keyword= null;
	return keyword;
}
 
Example #21
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adjusts the visibility of the referenced body declaration.
 *
 * @param member the member where to adjust the visibility
 * @param threshold the visibility keyword representing the required visibility, or <code>null</code> for default visibility
 * @param template the message template to use
 * @throws JavaModelException if an error occurs
 */
private void adjustOutgoingVisibility(final IMember member, final ModifierKeyword threshold, final String template) throws JavaModelException {
	Assert.isTrue(!member.isBinary() && !member.isReadOnly());
	boolean adjust= true;
	final IType declaring= member.getDeclaringType();
	if (declaring != null && (JavaModelUtil.isInterfaceOrAnnotation(declaring)
			|| (member instanceof IField) && Flags.isEnum(member.getFlags()) 
			|| declaring.equals(fReferenced)))
		adjust= false;
	if (adjust && hasLowerVisibility(member.getFlags(), keywordToVisibility(threshold)) && needsVisibilityAdjustment(member, threshold))
		fAdjustments.put(member, new OutgoingMemberVisibilityAdjustment(member, threshold, RefactoringStatus.createStatus(fVisibilitySeverity, Messages.format(template, new String[] { JavaElementLabels.getTextLabel(member, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.ALL_FULLY_QUALIFIED), getLabel(threshold)}), JavaStatusContext.create(member), null, RefactoringStatusEntry.NO_CODE, null)));
}
 
Example #22
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Does the specified member need further visibility adjustment?
 *
 * @param member the member to test
 * @param threshold the visibility threshold to test for
 * @param adjustments the map of members to visibility adjustments
 * @return <code>true</code> if the member needs further adjustment, <code>false</code> otherwise
 */
public static boolean needsVisibilityAdjustments(final IMember member, final int threshold, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments) {
	Assert.isNotNull(member);
	Assert.isTrue(isVisibilityModifier(threshold));
	Assert.isNotNull(adjustments);
	final IncomingMemberVisibilityAdjustment adjustment= adjustments.get(member);
	if (adjustment != null) {
		final ModifierKeyword keyword= adjustment.getKeyword();
		return hasLowerVisibility(keyword == null ? Modifier.NONE : keyword.toFlagValue(), threshold);
	}
	return true;
}
 
Example #23
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Converts a given modifier keyword into a visibility flag.
 *
 * @param keyword the keyword to convert
 * @return the visibility flag
 */
private static int keywordToVisibility(final ModifierKeyword keyword) {
	int visibility= 0;
	if (keyword == ModifierKeyword.PUBLIC_KEYWORD)
		visibility= Flags.AccPublic;
	else if (keyword == ModifierKeyword.PRIVATE_KEYWORD)
		visibility= Flags.AccPrivate;
	else if (keyword == ModifierKeyword.PROTECTED_KEYWORD)
		visibility= Flags.AccProtected;
	return visibility;
}
 
Example #24
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the label for the specified visibility keyword.
 *
 * @param keyword the keyword to get the label for, or <code>null</code> for default visibility
 * @return the label for the keyword
 */
public static String getLabel(final ModifierKeyword keyword) {
	Assert.isTrue(isVisibilityKeyword(keyword));
	if (keyword == null)
		return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_default;
	else if (ModifierKeyword.PUBLIC_KEYWORD.equals(keyword))
		return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_public;
	else if (ModifierKeyword.PROTECTED_KEYWORD.equals(keyword))
		return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_protected;
	else
		return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_private;
}
 
Example #25
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new incoming member visibility adjustment.
 *
 * @param member the member which is adjusted
 * @param keyword the keyword representing the adjusted visibility
 * @param status the associated status, or <code>null</code>
 */
public IncomingMemberVisibilityAdjustment(final IMember member, final ModifierKeyword keyword, final RefactoringStatus status) {
	Assert.isNotNull(member);
	Assert.isTrue(!(member instanceof IInitializer));
	Assert.isTrue(isVisibilityKeyword(keyword));
	fMember= member;
	fKeyword= keyword;
	fRefactoringStatus= status;
}
 
Example #26
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return a statement in form of <code>final int maxLen = 10;</code>
 */
protected VariableDeclarationStatement createMaxLenDeclaration() {
	VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
	fragment.setName(fAst.newSimpleName(fMaxLenVariableName));
	fragment.setInitializer(fAst.newNumberLiteral(String.valueOf(fContext.getLimitItemsValue())));
	VariableDeclarationStatement declExpression= fAst.newVariableDeclarationStatement(fragment);
	declExpression.setType(fAst.newPrimitiveType(PrimitiveType.INT));
	declExpression.modifiers().add(fAst.newModifier(ModifierKeyword.FINAL_KEYWORD));
	return declExpression;
}
 
Example #27
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createSetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit cu= cuRewrite.getCu();
	IJavaProject project= cu.getJavaProject();

	MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
	String fieldName= pi.getNewName();
	String setterName= getSetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	String paramName= StubUtility.suggestArgumentName(project, bareFieldname, null);
	if (createComments(project)) {
		String comment= CodeGeneration.getSetterComment(cu, declaringType, setterName, fieldName, pi.getNewTypeName(), paramName, bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(setterName));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
	variable.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	variable.setName(ast.newSimpleName(paramName));
	methodDeclaration.parameters().add(variable);
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis || fieldName.equals(paramName)) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getSetterMethodBodyContent(cu, declaringType, setterName, fieldName, paramName, lineDelim);
	ASTNode setterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(setterBody);
	return methodDeclaration;
}
 
Example #28
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getDisplayString() {
	if (fModifier == 0) {
		return CorrectionMessages.ModifierCorrectionSubProcessor_default_visibility_label;
	} else {
		return ModifierKeyword.fromFlagValue(fModifier).toString();
	}
}
 
Example #29
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Modifier findVisibilityModifier(List<IExtendedModifier> modifiers) {
	for (int i= 0; i < modifiers.size(); i++) {
		IExtendedModifier curr= modifiers.get(i);
		if (curr instanceof Modifier) {
			Modifier modifier= (Modifier) curr;
			ModifierKeyword keyword= modifier.getKeyword();
			if (keyword == ModifierKeyword.PUBLIC_KEYWORD || keyword == ModifierKeyword.PROTECTED_KEYWORD || keyword == ModifierKeyword.PRIVATE_KEYWORD) {
				return modifier;
			}
		}
	}
	return null;
}
 
Example #30
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adjusts the visibility of the specified member.
 *
 * @param element the "source" point from which to calculate the visibility
 * @param referencedMovedElement the moved element which may be adjusted in visibility
 * @param monitor the progress monitor to use
 * @throws JavaModelException if the visibility adjustment could not be computed
 */
private void adjustIncomingVisibility(final IJavaElement element, IMember referencedMovedElement, final IProgressMonitor monitor) throws JavaModelException {
	final ModifierKeyword threshold= getVisibilityThreshold(element, referencedMovedElement, monitor);
	int flags= referencedMovedElement.getFlags();
	IType declaring= referencedMovedElement.getDeclaringType();
	if (declaring != null && declaring.isInterface() || referencedMovedElement instanceof IField && Flags.isEnum(referencedMovedElement.getFlags()))
		return;
	if (hasLowerVisibility(flags, threshold == null ? Modifier.NONE : threshold.toFlagValue()) && needsVisibilityAdjustment(referencedMovedElement, threshold))
		fAdjustments.put(referencedMovedElement, new IncomingMemberVisibilityAdjustment(referencedMovedElement, threshold, RefactoringStatus.createStatus(fVisibilitySeverity, Messages.format(getMessage(referencedMovedElement), new String[] { getLabel(referencedMovedElement), getLabel(threshold)}), JavaStatusContext.create(referencedMovedElement), null, RefactoringStatusEntry.NO_CODE, null)));
}