下面列出了com.sun.source.tree.ThrowTree#com.sun.source.tree.ModifiersTree 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
void testPositionForEnumModifiers() throws IOException {
final String theString = "public";
String code = "package test; " + theString + " enum Test {A;}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
ModifiersTree mt = clazz.getModifiers();
int spos = code.indexOf(theString);
int epos = spos + theString.length();
assertEquals("testPositionForEnumModifiers",
spos, pos.getStartPosition(cut, mt));
assertEquals("testPositionForEnumModifiers",
epos, pos.getEndPosition(cut, mt));
}
private ClassTree moveRestMethod( TreeMaker maker, String movedName,
MethodTree method, WorkingCopy copy, ClassTree classTree)
{
List<? extends VariableTree> parameters = method.getParameters();
Tree returnType = method.getReturnType();
BlockTree body = method.getBody();
ModifiersTree modifiers = maker.Modifiers(EnumSet.of(Modifier.PRIVATE));
MethodTree newMethod = maker.Method(modifiers, movedName,
returnType,
Collections.<TypeParameterTree> emptyList(),
parameters,
Collections.<ExpressionTree> emptyList(),body,null);
ClassTree newClass = maker.addClassMember(classTree, newMethod);
newClass = maker.removeClassMember(newClass, method);
return newClass;
}
/**
*/
@Override
protected ClassTree composeNewTestClass(WorkingCopy workingCopy,
String name,
List<? extends Tree> members) {
final TreeMaker maker = workingCopy.getTreeMaker();
ModifiersTree modifiers = maker.Modifiers(
Collections.<Modifier>singleton(PUBLIC));
return maker.Class(
modifiers, //modifiers
name, //name
Collections.<TypeParameterTree>emptyList(),//type params
null, //extends
Collections.<ExpressionTree>emptyList(), //implements
members); //members
}
@Override
protected void performRewrite(TransformationContext ctx) {
WorkingCopy wc = ctx.getWorkingCopy();
GeneratorUtilities gu = GeneratorUtilities.get(wc);
TreePath path = ctx.getPath();
final ClassTree cls = (ClassTree) path.getLeaf();
gu.importComments(cls, wc.getCompilationUnit());
final TreeMaker treeMaker = wc.getTreeMaker();
ModifiersTree mods = cls.getModifiers();
if (mods.getFlags().contains(Modifier.ABSTRACT)) {
Set<Modifier> modifiers = EnumSet.copyOf(mods.getFlags());
modifiers.remove(Modifier.ABSTRACT);
ModifiersTree nmods = treeMaker.Modifiers(modifiers, mods.getAnnotations());
gu.copyComments(mods, nmods, true);
gu.copyComments(mods, nmods, false);
mods = nmods;
}
Tree nue = treeMaker.Interface(mods, cls.getSimpleName(), cls.getTypeParameters(), cls.getImplementsClause(), cls.getMembers());
gu.copyComments(cls, nue, true);
gu.copyComments(cls, nue, false);
wc.rewrite(path.getLeaf(), nue);
}
private VariableTree generateEjbInjection(WorkingCopy workingCopy, TreeMaker make, String beanInterface, boolean[] onClassPath) {
TypeElement ejbAnElement = workingCopy.getElements().getTypeElement("javax.ejb.EJB"); //NOI18N
TypeElement interfaceElement = workingCopy.getElements().getTypeElement(beanInterface); //NOI18N
AnnotationTree ejbAnnotation = make.Annotation(
make.QualIdent(ejbAnElement),
Collections.<ExpressionTree>emptyList());
// create method modifier: public and no annotation
ModifiersTree methodModifiers = make.Modifiers(
Collections.<Modifier>singleton(Modifier.PRIVATE),
Collections.<AnnotationTree>singletonList(ejbAnnotation));
onClassPath[0] = interfaceElement != null;
return make.Variable(
methodModifiers,
"ejbRef", //NOI18N
onClassPath[0] ? make.Type(interfaceElement.asType()) : make.Identifier(beanInterface),
null);
}
private ClassTree createMethodsOlderVersion(Collection<String> classNames,
TreeMaker maker,ClassTree modified,
CompilationController controller) throws IOException
{
WildcardTree wildCard = maker.Wildcard(Tree.Kind.UNBOUNDED_WILDCARD,
null);
ParameterizedTypeTree wildClass = maker.ParameterizedType(
maker.QualIdent(Class.class.getCanonicalName()),
Collections.singletonList(wildCard));
ParameterizedTypeTree wildSet = maker.ParameterizedType(
maker.QualIdent(Set.class.getCanonicalName()),
Collections.singletonList(wildClass));
//StringBuilder builder = new StringBuilder();
String methodBody = MiscPrivateUtilities.collectRestResources(classNames, restSupport, true);
ModifiersTree modifiersTree = maker.Modifiers(EnumSet
.of(Modifier.PRIVATE));
MethodTree methodTree = maker.Method(modifiersTree,
GET_REST_RESOURCE_CLASSES, wildSet,
Collections.<TypeParameterTree> emptyList(),
Collections.<VariableTree> emptyList(),
Collections.<ExpressionTree> emptyList(), methodBody,
null);
modified = maker.addClassMember(modified, methodTree);
return modified;
}
/**
*/
@Override
protected ClassTree composeNewTestClass(WorkingCopy workingCopy,
String name,
List<? extends Tree> members) {
final TreeMaker maker = workingCopy.getTreeMaker();
ModifiersTree modifiers = maker.Modifiers(
Collections.<Modifier>singleton(PUBLIC));
return maker.Class(
modifiers, //modifiers
name, //name
Collections.<TypeParameterTree>emptyList(),//type params
null, //extends
Collections.<ExpressionTree>emptyList(), //implements
members); //members
}
private ModifiersTree computeMods(Element e) {
Set<Modifier> implicitModifiers = IMPLICIT_MODIFIERS.get(Arrays.asList(e.getKind()));
if (implicitModifiers == null) {
implicitModifiers = IMPLICIT_MODIFIERS.get(Arrays.asList(e.getKind(), e.getEnclosingElement().getKind()));
}
Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class);
modifiers.addAll(e.getModifiers());
if (implicitModifiers != null) {
modifiers.removeAll(implicitModifiers);
}
List<AnnotationTree> annotations = new LinkedList<AnnotationTree>();
for (AnnotationMirror m : e.getAnnotationMirrors()) {
annotations.add(computeAnnotationTree(m));
}
return make.Modifiers(modifiers, annotations);
}
public ChangeInfo implement(){
CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>(){
public void cancel() {}
public void run(WorkingCopy workingCopy) throws Exception {
workingCopy.toPhase(JavaSource.Phase.RESOLVED);
TypeElement clazz = classHandle.resolve(workingCopy);
if (clazz != null){
ClassTree clazzTree = workingCopy.getTrees().getTree(clazz);
TreeMaker make = workingCopy.getTreeMaker();
Set<Modifier> flags = new HashSet<Modifier>(clazzTree.getModifiers().getFlags());
flags.add(Modifier.PUBLIC);
ModifiersTree newModifiers = make.Modifiers(flags, clazzTree.getModifiers().getAnnotations());
workingCopy.rewrite(clazzTree.getModifiers(), newModifiers);
}
}
};
JavaSource javaSource = JavaSource.forFileObject(fileObject);
try{
javaSource.runModificationTask(task).commit();
} catch (IOException e){
JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e);
}
return null;
}
/**
* Creates a new field.
*
* @param scope the scope in which to create the field (will be e.g. used
* to parse <code>fieldType</code>).
* @param modifiersTree the field modifiers; cannot be null.
* @param fieldType the fully-qualified name of the field type; cannot be null.
* @param fieldName the field name; cannot be null.
* @param expressionTree expression to initialize the field; can be null.
* @return the new field; never null.
*/
public VariableTree createField(TypeElement scope, ModifiersTree modifiersTree, String fieldName, String fieldType, ExpressionTree expressionTree) {
Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
Parameters.javaIdentifier("fieldName", fieldName); // NOI18N
Parameters.notNull("fieldType", fieldType); // NOI18N
return getTreeMaker().Variable(
modifiersTree,
fieldName,
createType(fieldType, scope),
expressionTree);
}
@Override
public Void visitModifiers(ModifiersTree expected, Tree actual) {
Optional<ModifiersTree> other = checkTypeAndCast(expected, actual);
if (!other.isPresent()) {
addTypeMismatch(expected, actual);
return null;
}
checkForDiff(expected.getFlags().equals(other.get().getFlags()),
"Expected modifier set to be <%s> but was <%s>.",
expected.getFlags(), other.get().getFlags());
parallelScan(expected.getAnnotations(), other.get().getAnnotations());
return null;
}
/** Output combined modifiers and annotations and the trailing break. */
void visitAndBreakModifiers(
ModifiersTree modifiers,
Direction annotationDirection,
Optional<BreakTag> declarationAnnotationBreak) {
builder.addAll(visitModifiers(modifiers, annotationDirection, declarationAnnotationBreak));
}
/**
* Output combined modifiers and annotations and returns the trailing break.
*/
private List<Op> visitModifiers(
ModifiersTree modifiersTree,
Direction annotationsDirection,
Optional<BreakTag> declarationAnnotationBreak) {
return visitModifiers(
modifiersTree.getAnnotations(),
annotationsDirection,
declarationAnnotationBreak);
}
@Override
public ChangeInfo implement() {
CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() {
@Override
public void cancel() {
}
@Override
public void run(WorkingCopy workingCopy) throws Exception {
workingCopy.toPhase(JavaSource.Phase.RESOLVED);
TypeElement clazz = classHandle.resolve(workingCopy);
if (clazz != null) {
ClassTree clazzTree = workingCopy.getTrees().getTree(clazz);
TreeMaker make = workingCopy.getTreeMaker();
Set<Modifier> flags = new HashSet<>(clazzTree.getModifiers().getFlags());
flags.add(Modifier.PUBLIC);
ModifiersTree newModifiers = make.Modifiers(flags, clazzTree.getModifiers().getAnnotations());
workingCopy.rewrite(clazzTree.getModifiers(), newModifiers);
}
}
};
JavaSource javaSource = JavaSource.forFileObject(fileObject);
try {
javaSource.runModificationTask(task).commit();
} catch (IOException e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
}
return null;
}
/**
* Output combined modifiers and annotations and the trailing break.
*/
void visitAndBreakModifiers(
ModifiersTree modifiers,
Direction annotationDirection,
Optional<BreakTag> declarationAnnotationBreak) {
builder.addAll(visitModifiers(modifiers, annotationDirection, declarationAnnotationBreak));
}
/**
* Should a field with a set of modifiers be declared with horizontal annotations? This is
* currently true if all annotations are marker annotations.
*/
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (!annotation.getArguments().isEmpty()) {
return Direction.VERTICAL;
}
}
return Direction.HORIZONTAL;
}
private TreeNode convertAnnotationTypeDeclaration(ClassTree node, TreePath parent) {
AnnotationTypeDeclaration newNode = new AnnotationTypeDeclaration();
TreePath path = getTreePath(parent, node);
Element element = getElement(path);
convertBodyDeclaration(node, path, node.getModifiers(), newNode);
for (Tree bodyDecl : node.getMembers()) {
if (bodyDecl.getKind() == Kind.METHOD) {
MethodTree methodTree = (MethodTree) bodyDecl;
TreePath methodPath = getTreePath(path, methodTree);
ExecutableElement methodElement = (ExecutableElement) getElement(methodPath);
Tree defaultValue = methodTree.getDefaultValue();
ModifiersTree modifiers = methodTree.getModifiers();
AnnotationTypeMemberDeclaration newMember =
new AnnotationTypeMemberDeclaration()
.setDefault((Expression) convert(defaultValue, methodPath))
.setExecutableElement(methodElement);
newMember
.setModifiers((int) ((JCModifiers) modifiers).flags)
.setAnnotations(convertAnnotations(modifiers, getTreePath(methodPath, modifiers)))
.setJavadoc((Javadoc) getAssociatedJavaDoc(methodTree, methodPath));
newNode.addBodyDeclaration(newMember);
} else {
newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl, path));
}
}
return newNode
.setName(convertSimpleName(element, getTypeMirror(path), getNamePosition(node)))
.setTypeElement((TypeElement) element);
}
public ClassTree generate() {
ClassTree modifiedClazz = getClassTree();
String body = "";
FieldInfo em = getEntityManagerFieldInfo();
if (!em.isExisting()){
FieldInfo emf = getEntityManagerFactoryFieldInfo();
if (!emf.isExisting()){
modifiedClazz = getTreeMaker().insertClassMember(getClassTree(), getIndexForField(getClassTree()), createEntityManagerFactory(emf.getName()));
}
body += getEmInitCode(em, emf);
}
body += getMethodBody(em);
ModifiersTree methodModifiers = getTreeMaker().Modifiers(
getGenerationOptions().getModifiers(),
Collections.<AnnotationTree>emptyList()
);
MethodTree newMethod = getTreeMaker().Method(
methodModifiers,
computeMethodName(),
getTreeMaker().PrimitiveType(TypeKind.VOID),
Collections.<TypeParameterTree>emptyList(),
getParameterList(),
Collections.<ExpressionTree>emptyList(),
"{ " + body + "}",
null
);
return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod));
}
public static ClassTree addVariable(ClassTree classTree, WorkingCopy wc, String name, TypeInfo type, int modifiers, Object initializer, AnnotationInfo[] annotations) {
Tree typeTree = createType(wc, type);
ModifiersTree modTree = createModifiers(wc, modifiers, annotations);
TreeMaker make = wc.getTreeMaker();
VariableTree tree = make.Variable(modTree, name, typeTree, make.Literal(initializer));
return make.addClassMember(classTree, tree);
}
private ClassTree insertSecurityFetaureField(WorkingCopy workingCopy,
TreeMaker make, ClassTree javaClass, TypeElement classElement )
{
for (VariableElement var :
ElementFilter.fieldsIn( classElement.getEnclosedElements()))
{
TypeMirror varType = var.asType();
if (!varType.getKind().equals(TypeKind.ARRAY)) {
continue;
}
if ( var.getSimpleName().contentEquals(PolicyManager.SECURITY_FEATURE)) {
/*
* there is no way to find existing comments. So if field is
* already in the class. Just return
*/
return javaClass;
}
}
Set<Modifier> modifiers = new HashSet<Modifier>();
modifiers.add( Modifier.PRIVATE);
modifiers.add( Modifier.STATIC);
modifiers.add( Modifier.FINAL);
ModifiersTree modifiersTree = make.Modifiers(
modifiers);
Tree typeTree = manager.createSecurityFeatureType( workingCopy , make );
ExpressionTree initializer = manager.createSecurityFeatureInitializer(
workingCopy, make );
VariableTree securityFeature = make.Variable(
modifiersTree, PolicyManager.SECURITY_FEATURE,
typeTree,
initializer);
if ( manager.isSupported() ){
manager.modifySecurityFeatureAttribute( securityFeature , workingCopy ,
make );
}
return make.insertClassMember(javaClass, 0, securityFeature);
}
private MethodTree createMethodDefinition(boolean mustStatic) {
// if all the statements are contained within a Block, get just the block, it will be processed recursively
List<VariableTree> formalArguments = IntroduceHint.createVariables(copy, parameters, pathToClass,
statementPaths.subList(from, to + 1));
if (formalArguments == null) {
return null; //XXX
}
List<ExpressionTree> thrown = IntroduceHint.typeHandleToTree(copy, thrownTypes);
if (thrown == null) {
return null; //XXX
}
List<TypeParameterTree> typeVars = new LinkedList<TypeParameterTree>();
for (TreePathHandle tph : IntroduceMethodFix.this.typeVars) {
typeVars.add((TypeParameterTree) tph.resolve(copy).getLeaf());
}
List<StatementTree> methodStatements = new ArrayList<StatementTree>();
generateMethodContents(methodStatements);
makeReturnsFromExtractedMethod(methodStatements);
Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class);
modifiers.addAll(access);
if (target.iface) {
modifiers.add(Modifier.DEFAULT);
} else if (mustStatic) {
modifiers.add(Modifier.STATIC);
}
ModifiersTree mods = make.Modifiers(modifiers);
MethodTree method = make.Method(mods, name, returnTypeTree, typeVars, formalArguments, thrown, make.Block(methodStatements, false), null);
return method;
}
private static MethodTree createToStringMethod(WorkingCopy wc, Iterable<? extends VariableElement> fields, String typeName, boolean useStringBuilder) {
TreeMaker make = wc.getTreeMaker();
Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
List<AnnotationTree> annotations = new LinkedList<>();
if (GeneratorUtils.supportsOverride(wc)) {
TypeElement override = wc.getElements().getTypeElement("java.lang.Override"); //NOI18N
if (override != null) {
annotations.add(wc.getTreeMaker().Annotation(wc.getTreeMaker().QualIdent(override), Collections.<ExpressionTree>emptyList()));
}
}
ModifiersTree modifiers = make.Modifiers(mods, annotations);
BlockTree body = createToStringMethodBody(make, typeName, fields, useStringBuilder);
return make.Method(modifiers, "toString", make.Identifier("String"), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}
/**
* Resolves all fields that belong to the same field group.
*/
private static @NonNull List<? extends Tree> collectFieldGroup(@NonNull CompilationInfo info,
@NonNull TreePath parentPath, Tree leaf) {
Iterable<? extends Tree> children;
switch (parentPath.getLeaf().getKind()) {
case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
case ANNOTATION_TYPE:
case CLASS:
case ENUM:
case INTERFACE:
children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
case CASE: children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
default: children = Collections.singleton(leaf); break;
}
List<Tree> result = new LinkedList<>();
ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();
for (Tree c : children) {
if (c.getKind() != Kind.VARIABLE) continue;
if (((VariableTree) c).getModifiers() == currentModifiers) {
result.add(c);
}
}
return result;
}
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
WorkingCopy wc = ctx.getWorkingCopy();
wc.toPhase(JavaSource.Phase.RESOLVED);
TreeMaker make = wc.getTreeMaker();
// rewrite annotations in case of ManagedBean
if (MANAGED_BEAN.equals(annotation.getAnnotationType().toString())) {
ModifiersTree modifiers = ((ClassTree) wc.getTrees().getTree(element)).getModifiers();
AnnotationTree annotationTree = (AnnotationTree) wc.getTrees().getTree(element, annotation);
List<ExpressionTree> arguments = new ArrayList<>();
for (ExpressionTree expressionTree : annotationTree.getArguments()) {
if (expressionTree.getKind() == Tree.Kind.ASSIGNMENT) {
AssignmentTree at = (AssignmentTree) expressionTree;
String varName = ((IdentifierTree) at.getVariable()).getName().toString();
if (varName.equals("name")) { //NOI18N
ExpressionTree valueTree = make.Identifier(at.getExpression().toString());
arguments.add(valueTree);
}
}
}
ModifiersTree newModifiersTree = make.removeModifiersAnnotation(modifiers, (AnnotationTree) wc.getTrees().getTree(element, annotation));
AnnotationTree newTree = GenerationUtils.newInstance(wc).createAnnotation(replacingClass, arguments);
newModifiersTree = make.addModifiersAnnotation(newModifiersTree, newTree);
wc.rewrite(modifiers, newModifiersTree);
}
// rewrite imports
List<? extends ImportTree> imports = wc.getCompilationUnit().getImports();
ImportTree newImportTree = make.Import(make.QualIdent(replacingClass), false);
for (ImportTree importTree : imports) {
if (deprecatedClass.equals(importTree.getQualifiedIdentifier().toString())) {
wc.rewrite(importTree, newImportTree);
}
}
}
public MethodTree createConstructor(ModifiersTree modifiersTree, String constructorName, List parameters, String body) {
Parameters.notNull("modifiersTree", modifiersTree);
Parameters.javaIdentifier("constructorName", constructorName); // NOI18N
Parameters.notNull("parameters", parameters); // NOI18N
TreeMaker make = getTreeMaker();
return make.Constructor(
modifiersTree,
Collections.<TypeParameterTree>emptyList(),
parameters,
Collections.<ExpressionTree>emptyList(),
body);
}
/**
* Original:
*
* public static void method() {
* }
*
* Result:
*
* void method() {
* }
*/
public void testMethodMods2() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" public static void method() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" void method() {\n" +
" }\n" +
"}\n";
JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws java.io.IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
// finally, find the correct body and rewrite it.
ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>emptySet()));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
/**
* Original:
*
* public Test() {
* }
*
* Result:
*
* Test() {
* }
*/
public void testMethodMods4() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" public Test() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" Test() {\n" +
" }\n" +
"}\n";
JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws java.io.IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
// finally, find the correct body and rewrite it.
ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>emptySet()));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
/**
* Original:
*
* public Test() {
* }
*
* Result:
*
* protected Test() {
* }
*/
public void testMethodMods6() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" public Test() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" protected Test() {\n" +
" }\n" +
"}\n";
JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws java.io.IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
// finally, find the correct body and rewrite it.
ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.PROTECTED)));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
@Override
protected ModifiersTree addResourceAnnotation( String entityFQN,
ClassTree classTree, GenerationUtils genUtils, TreeMaker maker )
{
ModifiersTree tree = super.addResourceAnnotation(entityFQN, classTree,
genUtils, maker);
tree = maker.addModifiersAnnotation( tree, genUtils.createAnnotation(
RestConstants.SINGLETON));
tree = maker.addModifiersAnnotation( tree, genUtils.createAnnotation(
SpringConstants.AUTOWIRE));
return tree;
}
/**
* Should a field with a set of modifiers be declared with horizontal annotations? This is
* currently true if all annotations are marker annotations.
*/
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
for (AnnotationTree annotation : modifiers.getAnnotations()) {
if (!annotation.getArguments().isEmpty()) {
return Direction.VERTICAL;
}
}
return Direction.HORIZONTAL;
}