Java Code Examples for javax.lang.model.element.Modifier

The following are top voted examples for showing how to use javax.lang.model.element.Modifier. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: DeclarativeHintsParser.java   Source Code and License 7 votes vote down vote up
private static ClassPath getJavacApiJarClasspath() {
    Reference<ClassPath> r = javacApiClasspath;
    ClassPath res = r.get();
    if (res != null) {
        return res;
    }
    if (r == NONE) {
        return null;
    }
    CodeSource codeSource = Modifier.class.getProtectionDomain().getCodeSource();
    URL javacApiJar = codeSource != null ? codeSource.getLocation() : null;
    if (javacApiJar != null) {
        Logger.getLogger(DeclarativeHintsParser.class.getName()).log(Level.FINE, "javacApiJar={0}", javacApiJar);
        File aj = FileUtil.archiveOrDirForURL(javacApiJar);
        if (aj != null) {
            res = ClassPathSupport.createClassPath(FileUtil.urlForArchiveOrDir(aj));
            javacApiClasspath = new WeakReference<>(res);
            return res;
        }
    }
    javacApiClasspath = NONE;
    return null;
}
 
Example 2
Project: incubator-netbeans   File: Tiny.java   Source Code and License 6 votes vote down vote up
private static boolean isSynced(HintContext ctx, TreePath inspect) {
    while (inspect != null && !TreeUtilities.CLASS_TREE_KINDS.contains(inspect.getLeaf().getKind())) {
        if (inspect.getLeaf().getKind() == Kind.SYNCHRONIZED) {
            return true;
        }

        if (inspect.getLeaf().getKind() == Kind.METHOD) {
            if (((MethodTree) inspect.getLeaf()).getModifiers().getFlags().contains(Modifier.SYNCHRONIZED)) {
                return true;
            }

            break;
        }

        inspect = inspect.getParentPath();
    }

    return false;
}
 
Example 3
Project: jso-builder   File: SerializerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec createToJSONMethod() {
    return MethodSpec.methodBuilder("toJSON")
            .addModifiers(Modifier.FINAL)
            .addAnnotation(ClassNames.GWT_INCOMPATIBLE)
            .addParameter(Object.class, "object")
            .returns(String.class)
            .beginControlFlow("if (!isJsObject(object.getClass()))")
                .addStatement("throw new $T($S + object.getClass() + $S)", IllegalStateException.class,
                        "Class ", " isn't a JavaScript object")
            .endControlFlow()
            .addStatement("$T writer = new $T()", StringWriter.class, StringWriter.class)
            .beginControlFlow("try")
                .addStatement("writeJSON(writer, object)")
            .nextControlFlow("catch ($T e)", IOException.class)
                .addStatement("throw new $T(e)", RuntimeException.class)
            .endControlFlow()
            .addStatement("return writer.toString()")
            .build();
}
 
Example 4
Project: json2java4idea   File: ModelClassBuilder.java   Source Code and License 6 votes vote down vote up
@Nonnull
@Override
protected List<FieldSpec> buildFields() {
    return getProperties()
            .entrySet()
            .stream()
            .map(property -> {
                final String name = property.getKey();
                final TypeName type = property.getValue();
                final String fieldName = fieldNamePolicy.convert(name, type);
                return FieldSpec.builder(type, fieldName)
                        .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                        .build();
            })
            .collect(Collectors.toList());
}
 
Example 5
Project: incubator-netbeans   File: ImportAnalysisTest.java   Source Code and License 6 votes vote down vote up
public void testImportGetterSetter() throws IOException {
    testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest8.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            ExpressionTree type = make.QualIdent(workingCopy.getElements().getTypeElement("java.awt.geom.Point2D.Double"));
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test",type, null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testImportGetterSetter.pass");
}
 
Example 6
Project: aws-sdk-java-v2   File: ModelBuilderSpecs.java   Source Code and License 6 votes vote down vote up
private MethodSpec modelCopyConstructor() {
    MethodSpec.Builder copyBuilderCtor = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PRIVATE)
            .addParameter(classToBuild(), "model");

    shapeModel.getNonStreamingMembers().forEach(m -> {
        String name = m.getVariable().getVariableName();
        copyBuilderCtor.addStatement("$N(model.$N)", m.getFluentSetterMethodName(), name);
    });

    if (isException()) {
        copyBuilderCtor.addStatement("this.message = model.getMessage()");
    }

    return copyBuilderCtor.build();
}
 
Example 7
Project: incubator-netbeans   File: ConvertToLambdaPreconditionChecker.java   Source Code and License 6 votes vote down vote up
@Override
public Tree visitNewClass(NewClassTree node, Trees p) {
    Tree t = super.visitNewClass(node, p);
    // new class tree > expression statement tree > block. Does not accept anonymous classes for ctor references.
    if (node.getClassBody() == null && singleStatementLambdaMethodBody == getCurrentPath().getParentPath().getParentPath().getLeaf()) {
        Tree parent = getCurrentPath().getParentPath().getLeaf();
        Element el = info.getTrees().getElement(getCurrentPath());
        if (el == null || el.getKind() != ElementKind.CONSTRUCTOR || !el.getEnclosingElement().getKind().isClass()) {
            return t;
        }
        el = el.getEnclosingElement();
        if (parent.getKind() == Tree.Kind.EXPRESSION_STATEMENT || parent.getKind() == Tree.Kind.RETURN) {
            ExpressionTree et = node.getEnclosingExpression();
            if (et != null) {
                if (el.getModifiers().contains(Modifier.STATIC) || !isMeaninglessQualifier(new TreePath(getCurrentPath().getParentPath(), et))) {
                    return t;
                }
            }
            foundConstructorReferenceCandidate = true;
        }
    }
    return t;
}
 
Example 8
Project: incubator-netbeans   File: ImportAnalysisTest.java   Source Code and License 6 votes vote down vote up
public void test157566b() throws IOException {
    testFile = getFile(getSourceDir(), "org/netbeans/test/codegen/imports157566/b/Test.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            final TypeElement foo = workingCopy.getElements().getTypeElement("org.netbeans.test.codegen.imports157566.b.String");
            assertNotNull(foo);
            Tree type = make.QualIdent(foo);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", type, null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testImports157566b.pass");
}
 
Example 9
Project: Alligator   File: NavigationFactoryGenerator.java   Source Code and License 6 votes vote down vote up
public JavaFile generate(List<RegistrationAnnotatedClass> annotatedClasses) throws ProcessingException {
	MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
			.addModifiers(Modifier.PUBLIC);

	for (RegistrationAnnotatedClass annotatedClass : annotatedClasses) {
		ClassName annotatedClassName = ClassName.get(annotatedClass.getClassElement());
		ClassName screenClassName = ClassName.bestGuess(annotatedClass.getScreenClassName());

		if (annotatedClass.getScreenResultClassName() == null) {
			String registrationMethod = getRegistrationMethod(annotatedClass.getScreenType());
			constructorBuilder.addStatement(registrationMethod, screenClassName, annotatedClassName);
		} else {
			String registrationForResultMethod = getRegistrationForResultMethod(annotatedClass.getScreenType());
			ClassName screenResultClassName = ClassName.bestGuess(annotatedClass.getScreenResultClassName());
			constructorBuilder.addStatement(registrationForResultMethod, screenClassName, annotatedClassName, screenResultClassName);
		}
	}

	TypeSpec navigationFactory = TypeSpec.classBuilder(CLASS_NAME)
			.addModifiers(Modifier.PUBLIC)
			.superclass(ClassName.get(PACKAGE, SUPERCLASS_NAME))
			.addMethod(constructorBuilder.build())
			.build();

	return JavaFile.builder(PACKAGE, navigationFactory).build();
}
 
Example 10
Project: incubator-netbeans   File: ControllerGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Defines a new method as event handler, and marks it with @FXML annotation.
 * 
 * @param h handler definition
 */
private void defineNewHandler(CharSequence handlerName, TypeElement eventType) {
    TreeMaker mk = wcopy.getTreeMaker();
    
    // @FXML private void {handlerName}({eventType} event);
    MethodTree handler = mk.Method(
            mk.Modifiers(Collections.singleton(Modifier.PRIVATE), 
                Collections.singletonList(fxmlAnnotationTree)
            ),
            handlerName, 
            mk.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.singletonList(
                mk.Variable(
                    mk.Modifiers(Collections.<Modifier>emptySet()), 
                    "event", mk.Type(eventType.asType()), null)
            ), 
            Collections.<ExpressionTree>emptyList(),
            mk.Block(Collections.<StatementTree>emptyList(), false), 
            null);
    
    // add to class
    controllerClass = genUtils().insertClassMember(controllerClass, handler);
    addMethod(handlerName.toString(), eventType.asType());
}
 
Example 11
Project: incubator-netbeans   File: IntroduceHintTest.java   Source Code and License 6 votes vote down vote up
public void testConstantFix208072c() throws Exception {
    Preferences prefs = CodeStylePreferences.get((FileObject) null, JavacParser.MIME_TYPE).getPreferences();
    prefs.put("classMembersOrder", "STATIC_INIT;STATIC METHOD;INSTANCE_INIT;CONSTRUCTOR;METHOD;STATIC CLASS;CLASS;STATIC FIELD;FIELD");
    prefs.put("classMemberInsertionPoint", "LAST_IN_CATEGORY");
    performFixTest("package test;\n" +
                   "import java.util.logging.Level;\n" +
                   "import java.util.logging.Logger;\n" +
                   "public class Test {\n" +
                   "     {\n" +
                   "         int ii = |1 + 2 * 3|;\n" +
                   "     }\n" +
                   "     private static final int II = 0;\n" +
                   "}\n",
                   ("package test;\n" +
                    "import java.util.logging.Level;\n" +
                    "import java.util.logging.Logger;\n" +
                    "public class Test {\n" +
                   "     {\n" +
                   "         int ii = ZZ;\n" +
                   "     }\n" +
                   "     private static final int II = 0;\n" +
                   "     private static final int ZZ = 1 + 2 * 3;\n" +
                    "}\n").replaceAll("[ \t\n]+", " "),
                   new DialogDisplayerImpl("ZZ", true, true, true, EnumSet.of(Modifier.PRIVATE)),
                   5, 1);
}
 
Example 12
Project: incubator-netbeans   File: JavaUtil.java   Source Code and License 6 votes vote down vote up
public static void addInputParamFields(JavaSource source,
        final List<ParameterInfo> params,
        final javax.lang.model.element.Modifier[] modifier) throws IOException {
    ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {

        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            List<ParameterInfo> addList = new ArrayList<ParameterInfo>();
            for (ParameterInfo p : params) {
                if (JavaSourceHelper.getField(copy, Util.getParameterName(p, true, true, true)) == null) {
                    addList.add(p);
                }
            }
            JavaSourceHelper.addFields(copy, Util.getParamNames(addList),
                    Util.getParamTypeNames(addList), Util.getParamValues(addList), modifier);
        }
    });
    result.commit();
}
 
Example 13
Project: incubator-netbeans   File: IntroduceHintTest.java   Source Code and License 6 votes vote down vote up
public void testIntroduceMethodReplaceDuplicatesSimpleRemapNotUseAfterMethod() throws Exception {
    performFixTest("package test;\n" +
                   "public class Test {\n" +
                   "    public static void test1() {\n" +
                   "        int i = 0;\n" +
                   "        |System.err.println(i);|\n" +
                   "    }\n" +
                   "    public static void test2() {\n" +
                   "        int a = 0;\n" +
                   "        System.err.println(a);\n" +
                   "    }\n" +
                   "}",
                   "package test; public class Test { public static void test1() { int i = 0; name(i); } public static void test2() { int a = 0; name(a); } private static void name(int i) { System.err.println(i); } }",
                   new DialogDisplayerImpl3("name", EnumSet.of(Modifier.PRIVATE), true, true),
                   1, 0);
}
 
Example 14
Project: incubator-netbeans   File: EnumTest.java   Source Code and License 6 votes vote down vote up
private void testAddFirstMember(String code, String golden) throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, code);
    JavaSource src = getJavaSource(testFile);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            final TreeMaker make = workingCopy.getTreeMaker();

            ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PUBLIC));
            Tree ret = make.Type(workingCopy.getTypes().getNoType(TypeKind.VOID));
            MethodTree mt = make.Method(mods, "run", ret, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null);

            ClassTree en = (ClassTree) cut.getTypeDecls().get(0);
            workingCopy.rewrite(en, make.addClassMember(en, mt));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example 15
Project: Witch-Android   File: OnOnBindGetAdapterView.java   Source Code and License 6 votes vote down vote up
@Override
public String create() {
    MethodSpec method = MethodSpec.methodBuilder("onBind")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(viewType, "target")
            .addParameter(valueType, "value")
            .returns(void.class)
            .addStatement("(($T)$N.getAdapter()).$N(($T)value)", adapterType, "target", getPropertySetter(property), valueType)
            .build();

    TypeSpec anonymous = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName
                    .get(TypeUtils.SYNC_ON_BIND, viewType, valueType))
            .addMethod(method)
            .build();

    return anonymous.toString();
}
 
Example 16
Project: data-mediator   File: HashEqualsGenerator.java   Source Code and License 6 votes vote down vote up
private static void generateHashCode(TypeSpec.Builder typeBuilder, Collection<FieldData> fields,
                                     Collection<FieldData> superFields, boolean hasSuperClass){
    if(fields.isEmpty()){
        return;
    }
    MethodSpec.Builder hashBuilder = MethodSpec.methodBuilder("hashCode")
            .returns(TypeName.INT)
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class);

    if(hasSuperClass && !superFields.isEmpty()){
        hashBuilder.addStatement("int result = super.hashCode()");
    }else{
        hashBuilder.addStatement("int result = 0");
    }
    for(FieldData fd : fields){
        addStatementForHashcode(hashBuilder, fd);
    }
    hashBuilder.addStatement("return result");
    sTemp_defined = false;

    typeBuilder.addMethod(hashBuilder.build());
}
 
Example 17
Project: auto-value-node   File: AutoValueNodeProcessor.java   Source Code and License 5 votes vote down vote up
private MethodSpec generateNodeablePropertyMethod(String propertyTypePackage, String returnTypeSuffix, String methodName, Modifier visibility) {
    MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName)
            .returns(ClassName.get(propertyTypePackage, "Node_" + returnTypeSuffix))
            .addModifiers(Modifier.FINAL)
            .addStatement("return new Node_$L(value == null ? null : value.$L())", returnTypeSuffix, methodName);
    if (visibility != null) {
        builder.addModifiers(visibility);
    }
    return builder.build();
}
 
Example 18
Project: shortbread   File: CodeGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec callMethodShortcut() {
    HashMap<String, List<String>> classMethodsMap = new HashMap<>();

    for (final ShortcutAnnotatedElement annotatedElement : annotatedElements) {
        if (annotatedElement instanceof ShortcutAnnotatedMethod) {
            final ShortcutAnnotatedMethod annotatedMethod = (ShortcutAnnotatedMethod) annotatedElement;
            if (classMethodsMap.containsKey(annotatedMethod.getClassName())) {
                classMethodsMap.get(annotatedElement.getClassName()).add(annotatedMethod.getMethodName());
            } else {
                classMethodsMap.put(annotatedMethod.getClassName(), new ArrayList<String>() {{
                    add(annotatedMethod.getMethodName());
                }});
            }
        }
    }

    final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("callMethodShortcut")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(void.class)
            .addParameter(activity, "activity");

    for (final Map.Entry<String, List<String>> annotatedMethodName : classMethodsMap.entrySet()) {
        ClassName activityClassName = ClassName.bestGuess(annotatedMethodName.getKey());
        List<String> methodNames = annotatedMethodName.getValue();
        methodBuilder.beginControlFlow("if (activity instanceof $T)", activityClassName);
        for (final String methodName : methodNames) {
            methodBuilder.beginControlFlow("if ($S.equals(activity.getIntent().getStringExtra($S)))", methodName, EXTRA_METHOD);
            methodBuilder.addStatement("(($T) activity).$L()", activityClassName, methodName);
            methodBuilder.endControlFlow();
        }
        methodBuilder.endControlFlow();
    }

    return methodBuilder
            .build();
}
 
Example 19
Project: react4j   File: Generator.java   Source Code and License 5 votes vote down vote up
@Nonnull
private static MethodSpec.Builder buildRenderAdapterMethod( @Nonnull final MethodDescriptor renderMethod )
{
  return MethodSpec.methodBuilder( "render" ).
    addModifiers( Modifier.PROTECTED ).
    addAnnotation( Override.class ).
    addAnnotation( NULLABLE_CLASSNAME ).
    returns( REACT_NODE_CLASSNAME ).
    addStatement( "return $T.of( $N() )", REACT_NODE_CLASSNAME, renderMethod.getMethod().getSimpleName().toString() );
}
 
Example 20
Project: GitHub   File: RealmBacklinkProcessorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void ignoreStaticLinkingObjects() throws IOException {
    RealmSyntheticTestClass javaFileObject = createBacklinkTestClass()
            .modifiers(Modifier.PUBLIC, Modifier.STATIC)
            .type("RealmResults")
            .clearAnnotations()
            .annotation("LinkingObjects(\"xxx\")")
            .builder().build();
    ASSERT.about(javaSources())
            .that(Arrays.asList(backlinksTarget, javaFileObject))
            .processedWith(new RealmProcessor())
            .compilesWithoutError();
}
 
Example 21
Project: aws-sdk-java-v2   File: AwsServiceModel.java   Source Code and License 5 votes vote down vote up
private MethodSpec exceptionConstructor() {
    MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder()
                                               .addModifiers(Modifier.PRIVATE)
                                               .addParameter(modelBuilderSpecs.builderImplName(), "builder");

    ctorBuilder.addStatement("super(builder.message)");

    shapeModelSpec.fields().forEach(f -> ctorBuilder.addStatement("this.$N = builder.$N", f, f));

    return ctorBuilder.build();
}
 
Example 22
Project: gwt-jackson-apt   File: DeserializerBuilder.java   Source Code and License 5 votes vote down vote up
private MethodSpec buildDeserializerMethod(){
    return MethodSpec.methodBuilder( "newDeserializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( ParameterizedTypeName.get( ClassName.get( JsonDeserializer.class ), DEFAULT_WILDCARD ) )
            .addStatement( "return $L", new FieldDeserializersChainBuilder(beanType).getInstance(field) )
            .build();
}
 
Example 23
Project: data-mediator   File: BaseMemberBuilder.java   Source Code and License 5 votes vote down vote up
protected MethodSpec.Builder onBuildGet(FieldData field,
                                        String nameForMethod, TypeInfo info) {
    MethodSpec.Builder get = MethodSpec.methodBuilder(field.getGetMethodPrefix() + nameForMethod)
            .returns(info.typeName)
            .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC);
    return get;
}
 
Example 24
Project: GitHub   File: BaseDecorator.java   Source Code and License 5 votes vote down vote up
private MethodSpec getAttachViewMethod() {
    MethodSpec.Builder method =
            MethodSpec.methodBuilder(METHOD_ATTACH_VIEW)
                    .addModifiers(Modifier.PUBLIC)
                    .addAnnotation(Override.class)
                    .addParameter(delegateClassGenerator.getViewClass(), "view").returns(TypeName.VOID);
    method.addStatement(
            callPresenterAttachView(FIELD_PRESENTER, "view", "$T"),
            ClassName.bestGuess(delegateClassGenerator.getPresenterViewQualifiedName()));
    return method.build();
}
 
Example 25
Project: incubator-netbeans   File: FieldEncapsulation.java   Source Code and License 5 votes vote down vote up
private static boolean hasRequiredVisibility(final Set<Modifier> mods, final Modifier reqMod) {
    return reqMod != null ?
        mods.contains(reqMod):
        mods.isEmpty() ?
            true:
            !EnumSet.copyOf(mods).removeAll(EnumSet.of(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC));
}
 
Example 26
Project: aws-sdk-java-v2   File: ClientSimpleMethodsIntegrationTests.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a setup method for instantiating a new client. If no regions are present for a service,
 * us-east-1 will be used. If the service is available in aws-global, that region will be used. If the
 * service is not available in aws-global but is in us-east-1, that region will be used. If a service is
 * not available in us-east-1 or aws-global, the first region in the available regions for a service will
 * be used.
 */
private MethodSpec setup() {
    ClassName beforeClass = ClassName.get("org.junit", "BeforeClass");
    ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getSyncInterface());
    return MethodSpec.methodBuilder("setup")
                     .addAnnotation(beforeClass)
                     .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                     .beginControlFlow("if ($T.serviceMetadata().regions().isEmpty())", interfaceClass)
                     .addStatement("client = $T.builder().region($T.US_EAST_1).build()", interfaceClass, Region.class)
                     .endControlFlow()
                     .beginControlFlow("else if ($T.serviceMetadata().regions().contains($T.AWS_GLOBAL))",
                                       interfaceClass,
                                       Region.class)
                     .addStatement("client = $T.builder().region($T.AWS_GLOBAL).build()",
                                   interfaceClass,
                                   Region.class)
                     .endControlFlow()
                     .beginControlFlow("else if ($T.serviceMetadata().regions().contains($T.US_EAST_1))",
                                       interfaceClass,
                                       Region.class)
                     .addStatement("client = $T.builder().region($T.US_EAST_1).build()",
                                   interfaceClass,
                                   Region.class)
                     .endControlFlow()
                     .beginControlFlow("else")
                     .addStatement("client = $1T.builder().region($1T.serviceMetadata().regions().get(0)).build()",
                                   interfaceClass)
                     .endControlFlow()
                     .build();
}
 
Example 27
Project: android-auto-mapper   File: AutoMappperProcessor.java   Source Code and License 5 votes vote down vote up
private Iterable<FieldSpec> generateFieldSpecs(ImmutableList<Property> properties) {
    List<FieldSpec> fields = new ArrayList<>();
    for (Property property : properties) {
        fields.add(FieldSpec.builder(property.typeName, property.fieldName, new Modifier[]{PUBLIC}).build());
    }

    return fields;
}
 
Example 28
Project: aws-sdk-java-v2   File: SyncClientInterface.java   Source Code and License 5 votes vote down vote up
/**
 * @return Simple method for streaming output operations to write response content to a file.
 */
private MethodSpec downloadToFileSimpleMethod(OperationModel opModel, TypeName responseType, ClassName requestType) {
    return MethodSpec.methodBuilder(opModel.getMethodName())
                     .returns(responseType)
                     .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
                     .addParameter(requestType, opModel.getInput().getVariableName())
                     .addParameter(ClassName.get(Path.class), "filePath")
                     .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.FILE))
                     .addExceptions(getExceptionClasses(model, opModel))
                     .addStatement("return $L($L, $T.toFile($L))", opModel.getMethodName(),
                                   opModel.getInput().getVariableName(),
                                   ClassName.get(StreamingResponseHandler.class),
                                   "filePath")
                     .build();
}
 
Example 29
Project: dataenum   File: ValueTypeFactory.java   Source Code and License 5 votes vote down vote up
private static MethodSpec createConstructor(OutputValue value) {
  MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE);
  for (Parameter parameter : value.parameters()) {
    constructor.addParameter(parameter.type(), parameter.name());

    if (parameter.type().isPrimitive() || parameter.canBeNull()) {
      constructor.addStatement("this.$1L = $1L", parameter.name());
    } else {
      constructor.addStatement("this.$1L = checkNotNull($1L)", parameter.name());
    }
  }
  return constructor.build();
}
 
Example 30
Project: GitHub   File: Constitution.java   Source Code and License 5 votes vote down vote up
private void lateValidateExtending(TypeElement t) {
  if (t.getModifiers().contains(Modifier.ABSTRACT)) {
    protoclass()
        .report()
        .withElement(t)
        .error("Extending %s shouldn't be abstract, it has to be instantiable",
            t.getSimpleName());
  }

  if (!this.generics.def().equals(generics().def())) {
    protoclass()
        .report()
        .withElement(t)
        .error("Inner type %s should have the same type parameters as abstract value type: %s",
            t.getSimpleName(),
            generics().def());
  }

  if (protoclass().styles().style().stagedBuilder()) {
    protoclass()
        .report()
        .withElement(t)
        .warning("Extending %s shouldn't be used with stagedBuilder style attribute, they are incompartible:"
            + " Staged builder generate series of staged interfaces, but extending builder actually"
            + " extends implementation and do not provide type safety for setting first attribute,"
            + " as well as stagedBuilder forces generated builder interfaces to leak in code using the builder"
            + " and hence defeating the purpose of using extending builder.",
            t.getSimpleName());
  }
}
 
Example 31
Project: auto-adapter   File: ViewBinderGenerator.java   Source Code and License 5 votes vote down vote up
private TypeSpec.Builder createClassBuilder(final TypeElement model, final ClassName viewBinderClassName) {
    TypeName modelType = ParameterizedTypeName.get(model.asType());
    ParameterizedTypeName viewHolderBinderTypeName = ParameterizedTypeName.get(VIEW_BINDER_NAME, modelType);

    return TypeSpec.classBuilder(viewBinderClassName).addModifiers(Modifier.FINAL).addSuperinterface(
            viewHolderBinderTypeName);
}
 
Example 32
Project: aws-sdk-java-v2   File: SyncClientInterface.java   Source Code and License 5 votes vote down vote up
private MethodSpec create() {
    return MethodSpec.methodBuilder("create")
                     .returns(className)
                     .addModifiers(Modifier.STATIC, Modifier.PUBLIC)
                     .addJavadoc(
                             "Create a {@link $T} with the region loaded from the {@link $T} and credentials loaded from the "
                             + "{@link $T}.", className, DefaultAwsRegionProviderChain.class,
                             DefaultCredentialsProvider.class)
                     .addStatement("return builder().build()")
                     .build();
}
 
Example 33
Project: arez   File: AutorunDescriptor.java   Source Code and License 5 votes vote down vote up
/**
 * Build any fields required by
 */
void buildFields( @Nonnull final TypeSpec.Builder builder )
{
  final FieldSpec.Builder field =
    FieldSpec.builder( GeneratorUtil.OBSERVER_CLASSNAME,
                       GeneratorUtil.FIELD_PREFIX + getName(),
                       Modifier.FINAL,
                       Modifier.PRIVATE ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
  builder.addField( field.build() );
}
 
Example 34
Project: RxAndroidOrm   File: QueryLoggerGenerator.java   Source Code and License 5 votes vote down vote up
public TypeSpec generate() {
    return TypeSpec.interfaceBuilder(Constants.QUERY_LOGGER)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(MethodSpec.methodBuilder("onQuery")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(ClassName.get(String.class), "query")
                    .addParameter(ArrayTypeName.get(String[].class), "datas")
                    .build())
            .build();
}
 
Example 35
Project: remoter   File: FieldBuilder.java   Source Code and License 5 votes vote down vote up
private void addCommonFields(TypeSpec.Builder classBuilder) {
    //Add descriptor
    classBuilder.addField(FieldSpec.builder(ClassName.get(String.class), "DESCRIPTOR")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("\"" + getRemoterInterfacePackageName() + "." + getRemoterInterfaceClassName() + "\"")
            .build());
    classBuilder.addField(FieldSpec.builder(TypeName.INT, "REMOTER_EXCEPTION_CODE")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("-99999")
            .build());

}
 
Example 36
Project: incubator-netbeans   File: IntroduceHint.java   Source Code and License 5 votes vote down vote up
/**
 * Crates method formal parameters, following code style conventions.
 * The trees in 'statements' will be rewritten to use the new identifiers.
 * 
 * @param copy working copy
 * @param parameters variables to turn into parameters
 * @param statements trees that should refer to parameters
 * @return 
 */
static List<VariableTree> createVariables(WorkingCopy copy, List<VariableElement> parameters, 
        TreePath targetParent,
        List<TreePath> statements) {
    final TreeMaker make = copy.getTreeMaker();
    List<VariableTree> formalArguments = new LinkedList<VariableTree>();
    CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());
    
    String prefix = cs.getParameterNamePrefix();
    String suffix = cs.getParameterNameSuffix(); 
    Map<VariableElement, CharSequence> renamedVariables = new HashMap<VariableElement, CharSequence>();
    Set<Name> changedNames = new HashSet<Name>();
    for (VariableElement p : parameters) {
        TypeMirror tm = p.asType();
        Tree type = make.Type(tm);
        Name formalArgName = p.getSimpleName();
        Set<Modifier> formalArgMods = EnumSet.noneOf(Modifier.class);
        
        if (p.getModifiers().contains(Modifier.FINAL)) {
            formalArgMods.add(Modifier.FINAL);
        }
        String strippedName = Utilities.stripVariableName(cs, p);
        CharSequence codeStyleName = Utilities.guessName(copy, strippedName, targetParent, prefix, suffix, p.getKind() == ElementKind.PARAMETER);
        if (!formalArgName.contentEquals(codeStyleName)) {
            renamedVariables.put(p, codeStyleName);
            changedNames.add(formalArgName);
        } else {
            codeStyleName = formalArgName;
        }
        formalArguments.add(make.Variable(make.Modifiers(formalArgMods), codeStyleName, type, null));
    }
    if (!changedNames.isEmpty()) {
        VariableRenamer renamer = new VariableRenamer(copy, renamedVariables, changedNames);
        for (TreePath stPath : statements) {
            renamer.scan(stPath, null);
        }
    }
    return formalArguments;
}
 
Example 37
Project: annotation-processor-toolkit   File: ElementUtils_CheckModifierOfElementTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testHasTransientModifier() {

    Element e = Mockito.mock(Element.class);
    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.TRANSIENT));
    MatcherAssert.assertThat("Modifier should be found", ElementUtils.CheckModifierOfElement.hasTransientModifier(e));

    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.PRIVATE));
    MatcherAssert.assertThat("Modifier should not be found", !ElementUtils.CheckModifierOfElement.hasTransientModifier(e));

    // check null valued element
    MatcherAssert.assertThat("Modifier should not be found for null valued elements", !ElementUtils.CheckModifierOfElement.hasTransientModifier(null));

}
 
Example 38
Project: resourceprovider   File: RpCodeGenerator.java   Source Code and License 5 votes vote down vote up
TypeSpec generateColorProviderClass() {
    MethodSpec constructor = MethodSpec.constructorBuilder()
                                       .addModifiers(PUBLIC)
                                       .addParameter(contextClassName, "context")
                                       .addStatement("this.context = context")
                                       .build();

    TypeSpec.Builder classBuilder = classBuilder("ColorProvider")
            .addModifiers(PUBLIC)
            .addField(contextField)
            .addMethod(constructor)
            .addAnnotation(suppressLint);

    for (String var : rClassColorVars) {
        try {
            classBuilder.addMethod(MethodSpec.methodBuilder("get" + getterSuffix(var))
                                             .addModifiers(Modifier.PUBLIC)
                                             .returns(INT)
                                             .addStatement("return $T.getColor(context, R.color." + var + ")", contextCompatClassName)
                                             .varargs(false)
                                             .build());
        } catch (IllegalArgumentException e) {
            System.out.println("\n\nResourceProvider Compiler Error: " + e.getMessage() + ".\n\nUnable to generate API for R.color." + var + "\n\n") ;
        }
    }

    return classBuilder.build();
}
 
Example 39
Project: annotation-processor-toolkit   File: ElementUtils_CheckModifierOfElementTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testHasSynchronizedModifier() {

    Element e = Mockito.mock(Element.class);
    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.SYNCHRONIZED));
    MatcherAssert.assertThat("Modifier should be found", ElementUtils.CheckModifierOfElement.hasSynchronizedModifier(e));

    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.PRIVATE));
    MatcherAssert.assertThat("Modifier should not be found", !ElementUtils.CheckModifierOfElement.hasSynchronizedModifier(e));

    // check null valued element
    MatcherAssert.assertThat("Modifier should not be found for null valued elements", !ElementUtils.CheckModifierOfElement.hasSynchronizedModifier(null));

}
 
Example 40
Project: aws-sdk-java-v2   File: SyncClientClass.java   Source Code and License 5 votes vote down vote up
private MethodSpec closeMethod() {
    return MethodSpec.methodBuilder("close")
                     .addAnnotation(Override.class)
                     .addStatement("clientHandler.close()")
                     .addModifiers(Modifier.PUBLIC)
                     .build();
}
 
Example 41
Project: auto-value-variant   File: AutoValueVariantExtension.java   Source Code and License 5 votes vote down vote up
private static MethodSpec generateGroupFieldsEqual(TypeName superName, Map<String, ExecutableElement> properties) {
    MethodSpec.Builder builder = MethodSpec.methodBuilder("groupFieldsEqual")
            .addModifiers(Modifier.PRIVATE) //
            .returns(TypeName.BOOLEAN)
            .addParameter(superName, "other")
            .addParameter(String.class, "group");

    Map<String, List<ExecutableElement>> groups = getGroupedProperties(properties);

    if (groups.size() == 0) {
        builder.addCode("return true;\n");
        return builder.build();
    }

    boolean firstIfBranch = true;
    boolean firstProperty;
    for (Map.Entry<String, List<ExecutableElement>> group : groups.entrySet()) {
        builder.addCode(firstIfBranch ? "if(" : "else if(");
        builder.addCode("group.equals(\"$L\")){\n", group.getKey());
        builder.addCode("   return ");

        firstProperty = true;
        for (ExecutableElement property : group.getValue()) {
            if (!firstProperty) {
                builder.addCode("\n      && ");
            }
            builder.addCode(generateEqualsExpression(property));
            firstProperty = false;
        }

        builder.addCode(";\n");
        builder.addCode("}");

        firstIfBranch = false;
    }

    builder.addCode("else{\n   throw new RuntimeException(\"no properties for group: \" + group);\n}\n");

    return builder.build();
}
 
Example 42
Project: gwt-jackson-apt   File: AptDeserializerBuilder.java   Source Code and License 5 votes vote down vote up
private MethodSpec getDeserializerMethod(TypeMirror beanType) {
    return MethodSpec.methodBuilder("getParametersDeserializer")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .addStatement("return deserializers")
            .returns(ParameterizedTypeName.get(ClassName.get(MapLike.class),
                    ClassName.get(HasDeserializerAndParameters.class)))
            .build();
}
 
Example 43
Project: Witch-Android   File: SetViewHolderView.java   Source Code and License 5 votes vote down vote up
@Override
public MethodSpec create() {
    return MethodSpec.methodBuilder("setView")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(viewHolderTypeName, "viewHolder")
            .addParameter(viewTypeName, "view")
            .returns(void.class)
            .addStatement("viewHolder.$N = $N", valueAccessor.viewHolderFieldName(), "view")
            .build();
}
 
Example 44
Project: arez   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
static void copyAccessModifiers( @Nonnull final ExecutableElement element, @Nonnull final MethodSpec.Builder builder )
{
  if ( element.getModifiers().contains( Modifier.PUBLIC ) )
  {
    builder.addModifiers( Modifier.PUBLIC );
  }
  else if ( element.getModifiers().contains( Modifier.PROTECTED ) )
  {
    builder.addModifiers( Modifier.PROTECTED );
  }
}
 
Example 45
Project: incubator-netbeans   File: JavaI18nSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Finds the target position within the source class element.
 * In the current implementation, the target position is just below
 * the last static field of the class; if there is no static field
 * in the class, the target position is the top of the class.
 * 
 * @param  classMembers  list of all members of the class
 * @param  fields  list of the fields in the class
 * @return  target position ({@code 0}-based) of the field,
 *          or {@code -1} if the field should be added to the end
 *          of the class
 */
private int findTargetPosition(
        List<? extends javax.lang.model.element.Element> classMembers,
        List<? extends VariableElement> fields) {
    if (fields.isEmpty()) {
        return 0;
    }

    int target = 0;
    boolean skippingStaticFields = false;
    Iterator<? extends javax.lang.model.element.Element> membersIt
            = classMembers.iterator();
    for (int index = 0; membersIt.hasNext(); index++) {
        javax.lang.model.element.Element member = membersIt.next();
        ElementKind kind = member.getKind();
        if (kind.isField()
                && (kind != ElementKind.ENUM_CONSTANT)
                && member.getModifiers().contains(Modifier.STATIC)) {
            /* it is a static field - skip it! */
            skippingStaticFields = true;
        } else if (skippingStaticFields) {
            /* we were skipping all static fields - until now */
            skippingStaticFields = false;
            target = index;
        }
    }

    return !skippingStaticFields ? target : -1;
}
 
Example 46
Project: cuckoo   File: DelegationProcessor.java   Source Code and License 5 votes vote down vote up
@TargetApi(24)
private List<MethodSpec> getConstructorSpecs(List<ExecutableElement> constructorElements, TypeElement originalClass) {
    return constructorElements.stream()
            .map(constructor -> {
                List<String> parameterNames = constructor.getParameters()
                        .stream()
                        .map(parameter -> parameter.getSimpleName().toString())
                        .collect(Collectors.toList());

                List<ParameterSpec> parameters = constructor.getParameters()
                        .stream()
                        .map(ParameterSpec::get)
                        .collect(Collectors.toList());

                MethodSpec.Builder constructorBuilder = MethodSpec
                        .constructorBuilder()
                        .addModifiers(Modifier.PRIVATE)
                        .addParameters(parameters)
                        .addStatement("super($L)", String.join(",", parameterNames));

                MethodSpec.Builder initializerBuilder = MethodSpec
                        .methodBuilder("newInstance")
                        .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                        .returns(TypeName.get(originalClass.asType()))
                        .addParameters(parameters)
                        .addStatement("return new $L($L)", getSubclassName(originalClass), String.join(",", parameterNames));

                return Arrays.asList(constructorBuilder.build(), initializerBuilder.build());
            })
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
}
 
Example 47
Project: hashsdn-controller   File: MethodDefinition.java   Source Code and License 5 votes vote down vote up
public MethodDefinition(List<Modifier> modifiers, String returnType,
        String name, List<Field> parameters, List<String> throwsExceptions,
        List<Annotation> annotations, String body) {
    this.modifiers = modifiers;
    this.returnType = returnType;
    this.name = name;
    this.parameters = parameters;
    this.throwsExceptions = throwsExceptions;
    this.body = body;
    this.annotations = annotations;
}
 
Example 48
Project: incubator-netbeans   File: JavaUtils.java   Source Code and License 5 votes vote down vote up
public static boolean isGetter(ExecutableElement ee) {
    String methodName = ee.getSimpleName().toString();
    TypeMirror retType = ee.getReturnType();

    // discard private and static methods
    if (ee.getModifiers().contains(Modifier.PRIVATE) || ee.getModifiers().contains(Modifier.STATIC)) {
        return false;
    }
    
    
    boolean retVal = methodName.startsWith(GET_PREFIX) && methodName.length() > GET_PREFIX.length() && retType.getKind() != TypeKind.VOID;
    retVal = retVal || methodName.startsWith(IS_PREFIX) && methodName.length() > IS_PREFIX.length() && retType.getKind() == TypeKind.BOOLEAN;
    
    return retVal;
}
 
Example 49
Project: jso-builder   File: JSOBuilderProcessor.java   Source Code and License 5 votes vote down vote up
private TypeSpec createJsonInterface() {
    return TypeSpec.classBuilder("JSON")
            .addModifiers(Modifier.STATIC, Modifier.FINAL)
            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSTYPE)
                    .addMember("isNative", "true")
                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                    .addMember("name", "$S", "JSON")
                    .build())
            .addMethod(MethodSpec.methodBuilder("stringify")
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.NATIVE)
                    .addParameter(Object.class, "object")
                    .returns(String.class)
                    .build())
            .build();
}
 
Example 50
Project: GitHub   File: RealmProxyMediatorGenerator.java   Source Code and License 5 votes vote down vote up
private void emitGetClassModelList(JavaWriter writer) throws IOException {
    writer.emitAnnotation("Override");
    writer.beginMethod("Set<Class<? extends RealmModel>>", "getModelClasses", EnumSet.of(Modifier.PUBLIC));
    writer.emitStatement("return MODEL_CLASSES");
    writer.endMethod();
    writer.emitEmptyLine();
}
 
Example 51
Project: aws-sdk-java-v2   File: PaginatorResponseClassSpec.java   Source Code and License 5 votes vote down vote up
private MethodSpec constructor() {
    return MethodSpec.constructorBuilder()
                     .addModifiers(Modifier.PUBLIC)
                     .addParameter(getClientInterfaceName(), CLIENT_MEMBER, Modifier.FINAL)
                     .addParameter(requestType(), REQUEST_MEMBER, Modifier.FINAL)
                     .addStatement("this.$L = $L", CLIENT_MEMBER, CLIENT_MEMBER)
                     .addStatement("this.$L = $L", REQUEST_MEMBER, REQUEST_MEMBER)
                     .addStatement("this.$L = new $L()", NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherClassName())
            .build();
}
 
Example 52
Project: incubator-netbeans   File: EncapsulateFieldsTest.java   Source Code and License 5 votes vote down vote up
public void testEncapsulateFieldsCompoundByte() throws Exception {
    writeFilesAndWaitForScan(src,
            new File("encap/A.java", "package encap;\n"
            + "public class A {\n"
            + "    public byte i;\n"
            + "}\n"),
            new File("encap/B.java", "package encap;\n"
            + "public class B extends A {\n"
            + "\n"
            + "    public void foo() {\n"
            + "        (i)++;\n"
            + "        i += 5;\n"
            + "        System.out.println(i);\n"
            + "    }\n"
            + "}\n"));
    performEncapsulate(src.getFileObject("encap/A.java"), new int[]{0}, EnumSet.of(Modifier.PUBLIC), false);
    verifyContent(src,
            new File("encap/A.java", "package encap;\n"
            + "public class A {\n"
            + "    private byte i;\n"
            + "\n"
            + "    public byte getI() {\n"
            + "        return i;\n"
            + "    }\n"
            + "\n"
            + "    public void setI(byte i) {\n"
            + "        this.i = i;\n"
            + "    }\n"
            + "}\n"),
            new File("encap/B.java", "package encap;\n"
            + "public class B extends A {\n"
            + "\n"
            + "    public void foo() {\n"
            + "        setI((byte) (getI() + 1));\n"
            + "        setI((byte) (getI() + 5));\n"
            + "        System.out.println(getI());\n"
            + "    }\n"
            + "}\n"));
}
 
Example 53
Project: incubator-netbeans   File: AbstractTestGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a {@code Set} of {@code Modifier}s from the given list
 * of modifiers.
 * 
 * @param  modifiers  modifiers that should be contained in the set
 * @return  set containing exactly the given modifiers
 */
static Set<Modifier> createModifierSet(Modifier... modifiers) {
    EnumSet<Modifier> modifierSet = EnumSet.noneOf(Modifier.class);
    for (Modifier m : modifiers) {
        modifierSet.add(m);
    }
    return modifierSet;
}
 
Example 54
Project: GitHub   File: RealmProxyClassGenerator.java   Source Code and License 5 votes vote down vote up
private void emitMutableRealmInteger(JavaWriter writer, VariableElement field, String fieldName, String fieldTypeCanonicalName) throws IOException {
    writer.emitAnnotation("Override")
        .beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC))
            .emitStatement("proxyState.getRealm$realm().checkIfValid()")
            .emitStatement("return this.%s", mutableRealmIntegerFieldName(field))
        .endMethod();
}
 
Example 55
Project: arez   File: ComponentDescriptor.java   Source Code and License 5 votes vote down vote up
@Nonnull
private MethodSpec buildFindAllMethod()
{
  return MethodSpec.methodBuilder( "findAll" ).
    addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
    addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
    returns( ParameterizedTypeName.get( ClassName.get( List.class ), TypeName.get( getElement().asType() ) ) ).
    addStatement( "return toList( entities().stream() )", Collectors.class ).
    build();
}
 
Example 56
Project: incubator-netbeans   File: IsOverriddenVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree tree, Tree d) {
    if (currentClass != null) {
        Element el = info.getTrees().getElement(getCurrentPath());
        
        if (el != null && el.getKind()  == ElementKind.METHOD) {
            if (!el.getModifiers().contains(Modifier.PRIVATE) && !el.getModifiers().contains(Modifier.STATIC)) {
                ExecutableElement overridee = (ExecutableElement) el;
                List<ElementHandle<ExecutableElement>> methods = type2Declaration.get(currentClass);
                
                if (methods == null) {
                    type2Declaration.put(currentClass, methods = new ArrayList<ElementHandle<ExecutableElement>>());
                }

                try {
                    ElementHandle<ExecutableElement> methodHandle = ElementHandle.create(overridee);
                    methods.add(methodHandle);
                    declaration2Tree.put(methodHandle, tree);
                } catch (IllegalArgumentException iae) {
                    LOG.log(
                        Level.INFO,
                        "Unresolvable method: {0}, reason: {1}",    //NOI18N
                        new Object[]{
                            overridee,
                            iae.getMessage()
                        });
                }
            }
        }
    }
    
    super.visitMethod(tree, tree);
    return null;
}
 
Example 57
Project: incubator-netbeans   File: ModifiersTest.java   Source Code and License 5 votes vote down vote up
/**
 * Original:
 * 
 * Test() {
 * }
 * 
 * Result:
 * 
 * public Test() {
 * }
 */
public void testMethodMods3() 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" +
            "    Test() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    public 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.PUBLIC)));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example 58
Project: KiiAnnotation   File: ConstructorGenerator.java   Source Code and License 5 votes vote down vote up
public static MethodSpec constructorGroup(String name) {
    ClassName className = ClassName.get("com.kii.cloud.storage", "KiiGroup");
    ParameterSpec parameterSpec = ParameterSpec.builder(className, "kiiGroup").build();

    return MethodSpec
            .constructorBuilder()
            .addModifiers(Modifier.PRIVATE)
            .addParameter(parameterSpec)
            .addStatement("this.kiiObject = kiiGroup.bucket(\"$N\").object()", name)
            .build();
}
 
Example 59
Project: incubator-netbeans   File: CommentsTest.java   Source Code and License 4 votes vote down vote up
public void testComments175889b() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "/**test\n" +
        " * test\n" +
        " */\n" +
        "package hierbas.del.litoral;\n" +
        "\n" +
        "/**test\n" +
        " * test\n" +
        " */\n" +
        "public class Test {\n" +
        "}\n");
    String golden =
        "/**test\n" +
        " * test\n" +
        " */\n" +
        "package hierbas.del.litoral;\n" +
        "\n" +
        "/**test\n" +
        " * test\n" +
        " */\n" +
        "public class Test {\n\n" +
        "    public void test() {\n" +
        "    }\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = make.Method(make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
                                            "test",
                                            make.Type(workingCopy.getTypes().getNoType(TypeKind.VOID)),
                                            Collections.<TypeParameterTree>emptyList(),
                                            Collections.<VariableTree>emptyList(),
                                            Collections.<ExpressionTree>emptyList(),
                                            "{}",
                                            null);
            String commentText = "TESTTTT";
            Comment comment = Comment.create(Comment.Style.JAVADOC, -1, -1, -1, commentText);
            make.addComment(clazz, comment, true);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, method));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example 60
Project: incubator-netbeans   File: ForLoopTest.java   Source Code and License 4 votes vote down vote up
public void testAddInitializer175866() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package javaapplication1;\n" +
        "\n" +
        "class UserTask {\n" +
        "\n" +
        "    public void method() {\n" +
        "        for (; j<1; j++);\n" +
        "    }\n" +
        "}\n"
        );
    String golden =
        "package javaapplication1;\n" +
        "\n" +
        "class UserTask {\n" +
        "\n" +
        "    public void method() {\n" +
        "        for (int j = 0; j<1; j++);\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();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            BlockTree block = method.getBody();
            ForLoopTree flt = (ForLoopTree) block.getStatements().get(0);
            VariableTree init = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)),
                                              "j",
                                              make.Type(workingCopy.getTypes().getPrimitiveType(TypeKind.INT)),
                                              make.Literal(0));
            workingCopy.rewrite(flt, make.addForLoopInitializer(flt, init));
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}