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: Tiny.java   View source code 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 2
Project: jso-builder   File: SerializerGenerator.java   View source code 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 3
Project: json2java4idea   File: ModelClassBuilder.java   View source code 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 4
Project: incubator-netbeans   File: ImportAnalysisTest.java   View source code 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 5
Project: aws-sdk-java-v2   File: ModelBuilderSpecs.java   View source code 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 6
Project: incubator-netbeans   File: ConvertToLambdaPreconditionChecker.java   View source code 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 7
Project: incubator-netbeans   File: ImportAnalysisTest.java   View source code 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 8
Project: Alligator   File: NavigationFactoryGenerator.java   View source code 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 9
Project: incubator-netbeans   File: ControllerGenerator.java   View source code 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 10
Project: incubator-netbeans   File: IntroduceHintTest.java   View source code 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 11
Project: incubator-netbeans   File: JavaUtil.java   View source code 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 12
Project: incubator-netbeans   File: IntroduceHintTest.java   View source code 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 13
Project: incubator-netbeans   File: EnumTest.java   View source code 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 14
Project: Witch-Android   File: OnOnBindGetAdapterView.java   View source code 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 15
Project: data-mediator   File: HashEqualsGenerator.java   View source code 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 16
Project: incubator-netbeans   File: DeclarativeHintsParser.java   View source code 6 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 17
Project: auto-value-node   File: AutoValueNodeProcessor.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 5 votes vote down vote up
private MethodSpec closeMethod() {
    return MethodSpec.methodBuilder("close")
                     .addAnnotation(Override.class)
                     .addStatement("clientHandler.close()")
                     .addModifiers(Modifier.PUBLIC)
                     .build();
}