javax.lang.model.element.Modifier Java Examples

The following examples show how to use javax.lang.model.element.Modifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HashCodeMethod.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
static MethodSpec generate(TypeElement annotation) {
  MethodSpec.Builder hashCodeBuilder =
      MethodSpec.methodBuilder("hashCode")
          .addModifiers(Modifier.PUBLIC)
          .addAnnotation(Override.class)
          .returns(int.class);

  List<ExecutableElement> methods = ElementFilter.methodsIn(annotation.getEnclosedElements());
  if (methods.isEmpty()) {
    hashCodeBuilder.addCode("return 0;\n");
    return hashCodeBuilder.build();
  }

  CodeBlock.Builder code = CodeBlock.builder().add("return ");
  for (ExecutableElement method : methods) {
    code.add(
        "+ ($L ^ $L)\n",
        127 * method.getSimpleName().toString().hashCode(),
        hashExpression(method));
  }
  code.add(";\n");
  hashCodeBuilder.addCode(code.build());

  return hashCodeBuilder.build();
}
 
Example #2
Source File: RetainedStateIntegrationTestBase.java    From Akatsuki with Apache License 2.0 6 votes vote down vote up
protected void testGenericType(String parameterName, Class<?>... input) {
	// we could make Field support <T> but that's too much effort for this
	// single use case

	String fieldName = parameterName.toLowerCase(Locale.ENGLISH);
	final TypeVariableName typeVariable = TypeVariableName.get(parameterName, input);
	FieldSpec field = field(TypeVariableName.get(parameterName), fieldName, Retained.class);
	final TestSource source = new TestSource(TEST_PACKAGE, generateClassName(), Modifier.PUBLIC)
			.appendFields(field)
			.appendTransformation((b, s) -> b.addTypeVariable(typeVariable));
	final RetainedStateTestEnvironment environment = new RetainedStateTestEnvironment(this,
			source);
	environment.tester().invokeSaveAndRestore();
	environment.tester().testSaveRestoreInvocation(name -> true, BundleRetainerTester.CLASS_EQ,
			Collections.singletonList(new RetainedTestField(input[0], fieldName)), f -> 1);

}
 
Example #3
Source File: DAOCreator.java    From AirData with MIT License 6 votes vote down vote up
private MethodSpec generatorQueryMethod() {
    MethodSpec.Builder queryBuilder = MethodSpec.methodBuilder("query")
            .addModifiers(Modifier.PUBLIC)
            .returns(ClassName.get(List.class))
            .addParameter(TypeName.BOOLEAN, "distinct")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns")
            .addParameter(ClassName.get(String.class), "selection")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs")
            .addParameter(ClassName.get(String.class), "groupBy")
            .addParameter(ClassName.get(String.class), "having")
            .addParameter(ClassName.get(String.class), "orderBy")
            .addParameter(ClassName.get(String.class), "limit")
            .addStatement("$T cursor = this.rawQuery(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", ClassName.get("android.database", "Cursor"));
    queryBuilder.addStatement("$T list = new $T()", ArrayList.class, ArrayList.class);
    queryBuilder.addCode("if (cursor.moveToFirst()) {");
    queryBuilder.addCode("  do {");
    queryBuilder.addCode("     list.add(fillData(cursor));");
    queryBuilder.addCode("  } while (cursor.moveToNext());");
    queryBuilder.addCode("}");
    queryBuilder.addStatement("return list");
    return queryBuilder.build();
}
 
Example #4
Source File: RouterProcessor.java    From ActivityRouter with Apache License 2.0 6 votes vote down vote up
private void generateModulesRouterInit(String[] moduleNames) {
    MethodSpec.Builder initMethod = MethodSpec.methodBuilder("init")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC);
    for (String module : moduleNames) {
        initMethod.addStatement("RouterMapping_" + module + ".map()");
    }
    TypeSpec routerInit = TypeSpec.classBuilder("RouterInit")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(initMethod.build())
            .build();
    try {
        JavaFile.builder("com.github.mzule.activityrouter.router", routerInit)
                .build()
                .writeTo(filer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #5
Source File: ClassStructure.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    TreePath path = ctx.getPath();
    final ClassTree cls = (ClassTree) path.getLeaf();
    gu.importComments(cls, wc.getCompilationUnit());
    final TreeMaker treeMaker = wc.getTreeMaker();
    ModifiersTree mods = cls.getModifiers();
    if (mods.getFlags().contains(Modifier.ABSTRACT)) {
        Set<Modifier> modifiers = EnumSet.copyOf(mods.getFlags());
        modifiers.remove(Modifier.ABSTRACT);
        ModifiersTree nmods = treeMaker.Modifiers(modifiers, mods.getAnnotations());
        gu.copyComments(mods, nmods, true);
        gu.copyComments(mods, nmods, false);
        mods = nmods;
    }
    Tree nue = treeMaker.Interface(mods, cls.getSimpleName(), cls.getTypeParameters(), cls.getImplementsClause(), cls.getMembers());
    gu.copyComments(cls, nue, true);
    gu.copyComments(cls, nue, false);
    wc.rewrite(path.getLeaf(), nue);
}
 
Example #6
Source File: GenerationUtilsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCreateProperty() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "   private Object x;" +
            "   public TestClass() {" +
            "   }" +
            "}");
    runModificationTask(testFO, new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws Exception {
            GenerationUtils genUtils = GenerationUtils.newInstance(copy);
            ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
            TypeElement scope = SourceUtils.classTree2TypeElement(copy, classTree);
            VariableTree field = genUtils.createField(scope, genUtils.createModifiers(Modifier.PRIVATE), "someProp", "java.lang.String", null);
            MethodTree getter = genUtils.createPropertyGetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
            MethodTree setter = genUtils.createPropertySetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
            TreeMaker make = copy.getTreeMaker();
            ClassTree newClassTree = classTree;
            newClassTree = make.insertClassMember(newClassTree, 0, field);
            newClassTree = make.addClassMember(newClassTree, getter);
            newClassTree = make.addClassMember(newClassTree, setter);
            copy.rewrite(classTree, newClassTree);
        }
    }).commit();
    // TODO check the field and methods
}
 
Example #7
Source File: NodeFactoryGenerator.java    From caffeine with Apache License 2.0 6 votes vote down vote up
private void addNewFactoryMethods() {
  nodeFactory.addMethod(MethodSpec.methodBuilder("newFactory")
      .addJavadoc("Returns a factory optimized for the specified features.\n")
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addTypeVariable(kTypeVar)
      .addTypeVariable(vTypeVar)
      .addParameter(BUILDER_PARAM)
      .addParameter(boolean.class, "isAsync")
      .addCode(NodeSelectorCode.get())
      .returns(NODE_FACTORY)
      .build());
  nodeFactory.addMethod(MethodSpec.methodBuilder("weakValues")
      .addJavadoc("Returns whether this factory supports weak values.\n")
      .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
      .addStatement("return false")
      .returns(boolean.class)
      .build());
  nodeFactory.addMethod(MethodSpec.methodBuilder("softValues")
      .addJavadoc("Returns whether this factory supports soft values.\n")
      .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
      .addStatement("return false")
      .returns(boolean.class)
      .build());
}
 
Example #8
Source File: ClipboardHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Element fqn2element(final Elements elements, final String fqn) {
    if (fqn == null) {
        return null;
    }
    TypeElement type = elements.getTypeElement(fqn);
    if (type != null) {
        return type;
    }
    int idx = fqn.lastIndexOf('.');
    if (idx > 0) {
        type = elements.getTypeElement(fqn.substring(0, idx));
        String name = fqn.substring(idx + 1);
        if (type != null && name.length() > 0) {
            for (Element el : type.getEnclosedElements()) {
                if (el.getModifiers().contains(Modifier.STATIC) && name.contentEquals(el.getSimpleName())) {
                    return el;
                }
            }
        }
    }
    return null;
}
 
Example #9
Source File: ArgProcessor.java    From fragmentargs with Apache License 2.0 6 votes vote down vote up
private void writeNewFragmentWithRequiredMethod(String builder, TypeElement element,
                                                JavaWriter jw, String[] args) throws IOException {

    if (supportAnnotations) jw.emitAnnotation("NonNull");
    jw.beginMethod(element.getQualifiedName().toString(), "new" + element.getSimpleName(),
            EnumSet.of(Modifier.STATIC, Modifier.PUBLIC), args);
    StringBuilder argNames = new StringBuilder();
    for (int i = 1; i < args.length; i += 2) {
        argNames.append(args[i]);
        if (i < args.length - 1) {
            argNames.append(", ");
        }
    }
    jw.emitStatement("return new %1$s(%2$s).build()", builder, argNames);
    jw.endMethod();
}
 
Example #10
Source File: TypeSpecTest.java    From javapoet with Apache License 2.0 6 votes vote down vote up
@Test public void classImplementsNestedClass() throws Exception {
  ClassName outer = ClassName.get(tacosPackage, "Outer");
  ClassName inner = outer.nestedClass("Inner");
  ClassName callable = ClassName.get(Callable.class);
  TypeSpec typeSpec = TypeSpec.classBuilder("Outer")
      .superclass(ParameterizedTypeName.get(callable,
          inner))
      .addType(TypeSpec.classBuilder("Inner")
          .addModifiers(Modifier.STATIC)
          .build())
      .build();

  assertThat(toString(typeSpec)).isEqualTo(""
      + "package com.squareup.tacos;\n"
      + "\n"
      + "import java.util.concurrent.Callable;\n"
      + "\n"
      + "class Outer extends Callable<Outer.Inner> {\n"
      + "  static class Inner {\n"
      + "  }\n"
      + "}\n");
}
 
Example #11
Source File: ModelMethodPlugin.java    From squidb with Apache License 2.0 6 votes vote down vote up
private void emitModelMethod(JavaFileWriter writer, ExecutableElement e, Modifier... modifiers)
        throws IOException {
    MethodDeclarationParameters params = utils.methodDeclarationParamsFromExecutableElement(e, modifiers);

    ModelMethod methodAnnotation = e.getAnnotation(ModelMethod.class);
    List<Object> arguments = new ArrayList<>();
    if (methodAnnotation != null) {
        String name = methodAnnotation.name();
        if (!AptUtils.isEmpty(name)) {
            params.setMethodName(name);
        }
        params.getArgumentTypes().remove(0);
        params.getArgumentNames().remove(0);
        arguments.add(0, "this");
    }
    arguments.addAll(params.getArgumentNames());
    Expression methodCall = Expressions.staticMethod(modelSpec.getModelSpecName(),
            e.getSimpleName().toString(), arguments);
    if (!CoreTypes.VOID.equals(params.getReturnType())) {
        methodCall = methodCall.returnExpr();
    }
    JavadocPlugin.writeJavadocFromElement(pluginEnv, writer, e);
    writer.beginMethodDefinition(params)
            .writeStatement(methodCall)
            .finishMethodDefinition();
}
 
Example #12
Source File: TypeSpecTest.java    From javapoet with Apache License 2.0 6 votes vote down vote up
@Test public void innerAnnotationInAnnotationDeclaration() throws Exception {
  TypeSpec bar = TypeSpec.annotationBuilder("Bar")
      .addMethod(MethodSpec.methodBuilder("value")
          .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
          .defaultValue("@$T", Deprecated.class)
          .returns(Deprecated.class)
          .build())
      .build();

  assertThat(toString(bar)).isEqualTo(""
      + "package com.squareup.tacos;\n"
      + "\n"
      + "import java.lang.Deprecated;\n"
      + "\n"
      + "@interface Bar {\n"
      + "  Deprecated value() default @Deprecated;\n"
      + "}\n"
  );
}
 
Example #13
Source File: JUnit5TestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a set-up or a tear-down method.
 * The generated method will have no arguments, void return type
 * and a declaration that it may throw {@code java.lang.Exception}.
 * The method will have a declared protected member access.
 * The method contains call of the corresponding super method, i.e.
 * {@code super.setUp()} or {@code super.tearDown()}.
 *
 * @param  methodName  name of the method to be created
 * @return  created method
 * @see  http://junit.sourceforge.net/javadoc/junit/framework/TestCase.html
 *       methods {@code setUp()} and {@code tearDown()}
 */
private MethodTree generateInitMethod(String methodName,
                                      String annotationClassName,
                                      boolean isStatic,
                                      WorkingCopy workingCopy) {
    Set<Modifier> methodModifiers
            = isStatic ? createModifierSet(PUBLIC, STATIC)
                       : Collections.<Modifier>singleton(PUBLIC);
    ModifiersTree modifiers = createModifiersTree(annotationClassName,
                                                  methodModifiers,
                                                  workingCopy);
    TreeMaker maker = workingCopy.getTreeMaker();
    BlockTree methodBody = maker.Block(
            Collections.<StatementTree>emptyList(),
            false);
    MethodTree method = maker.Method(
            modifiers,              // modifiers
            methodName,             // name
            maker.PrimitiveType(TypeKind.VOID),         // return type
            Collections.<TypeParameterTree>emptyList(), // type params
            Collections.<VariableTree>emptyList(),      // parameters
            Collections.<ExpressionTree>singletonList(
                    maker.Identifier("Exception")),     // throws...//NOI18N
            methodBody,
            null);                                      // default value
    return method;
}
 
Example #14
Source File: DestructorGenerator.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void addDeallocMethod(AbstractTypeDeclaration node) {
  TypeElement type = node.getTypeElement();
  boolean hasFinalize = hasFinalizeMethod(type);
  List<Statement> releaseStatements = createReleaseStatements(node);
  if (releaseStatements.isEmpty() && !hasFinalize) {
    return;
  }

  ExecutableElement deallocElement = GeneratedExecutableElement.newMethodWithSelector(
      NameTable.DEALLOC_METHOD, typeUtil.getVoid(), type)
      .addModifiers(Modifier.PUBLIC);
  MethodDeclaration deallocDecl = new MethodDeclaration(deallocElement);
  deallocDecl.setHasDeclaration(false);
  Block block = new Block();
  deallocDecl.setBody(block);
  List<Statement> stmts = block.getStatements();
  if (hasFinalize) {
    String clsName = nameTable.getFullName(type);
    stmts.add(new NativeStatement("JreCheckFinalize(self, [" + clsName + " class]);"));
  }
  stmts.addAll(releaseStatements);
  if (options.useReferenceCounting()) {
    stmts.add(new ExpressionStatement(
        new SuperMethodInvocation(new ExecutablePair(superDeallocElement))));
  }

  node.addBodyDeclaration(deallocDecl);
}
 
Example #15
Source File: ContentProviderWriter.java    From android-sqlite-generator with Apache License 2.0 5 votes vote down vote up
private void emitFields() throws IOException
{
	writer.emitEmptyLine();
	writer.emitField( "String", "TAG", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), "\"" + mModel.getContentProviderName() + "\"" );
	writer.emitField( "String", "DATABASE_NAME", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), "\"" + mModel.getDbClassName() + ".db\"" );
	writer.emitField( "int", "DATABASE_VERSION", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), String.valueOf( mModel.getDbVersion() ) );
	writer.emitField( "String", "ROW_ID", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), "\"" + Table.ANDROID_ID + "\"" );
	writer.emitEmptyLine();
	writer.emitField( "String", "AUTHORITY", EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "\"" + mModel.getContentAuthority() + "\"" );
	writer.emitEmptyLine();
	writer.emitField( mModel.getDbClassName(), "mLocalDatabase", EnumSet.of( Modifier.PRIVATE ) );
	writer.emitEmptyLine();
}
 
Example #16
Source File: BinderFactory.java    From IntentLife with Apache License 2.0 5 votes vote down vote up
static void produce(Elements elementUtils, Filer filer,
                    Map<TypeElement, List<TargetField>> targetClasses) {
    // bind method for proxy class.
    MethodSpec.Builder proxyBindMethodBuilder = MethodSpec.methodBuilder(BIND)
            .addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC)
            .addParameter(ClassName.bestGuess(OBJECT_CLASS_NAME), TARGET, Modifier.FINAL)
            .addParameter(ClassName.bestGuess(BUNDLE_CLASS_NAME), SOURCE, Modifier.FINAL);
    for (Map.Entry<TypeElement, List<TargetField>> entry : targetClasses.entrySet()) {
        final List<TargetField> fields = entry.getValue();
        if (fields == null || fields.isEmpty()) {
            continue;
        }
        /*
          Common parameter
         */
        final TypeElement targetTypeElement = entry.getKey();
        // Activity package name,like "cn.icheny.intentlife.sample".
        final String packageName = elementUtils.getPackageOf(targetTypeElement).getQualifiedName().toString();
        // Activity class name ,like "cn.icheny.intentlife.sample.MainActivity"
        final String targetClassName = targetTypeElement.getQualifiedName().toString();
        // binder class simple name,like "MainActivity_Binder"
        final String binderSimpleClassName = targetClassName.substring(packageName.length() + 1) + BINDER_CLASS_SUFFIX;

        // Generate binder.
        final JavaFile binder = produceBinder(packageName, targetClassName, binderSimpleClassName, fields);
        generateFile(filer, binder);
        // Add proxy control.
        addProxyControl(proxyBindMethodBuilder, packageName, targetClassName, binderSimpleClassName);
    }
    // Generate proxy.
    final JavaFile proxy = produceProxy(proxyBindMethodBuilder);
    generateFile(filer, proxy);
}
 
Example #17
Source File: ClassMemberBuilder.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
@Override
protected MethodSpec.Builder onBuildSuperSparseArrayEditor(FieldData field, String nameForMethod,
                                                           TypeInfo info, TypeName curModule) {
    String methodName = BEGIN_PREFIX + nameForMethod + EDITOR_SUFFIX;
    ClassName cn_editor = ClassName.get(PKG_PROP, SIMPLE_NAME_SPARSE_ARRAY_EDITOR);
    return PropertyEditorBuildUtils.buildSparseArrayEditorWithoutModifier(field,
                 nameForMethod, info, curModule)
            .addModifiers(Modifier.PUBLIC)
            .addStatement("return ($T<? extends $T, $T>) super.$N()",
                    cn_editor, curModule, info.getSimpleTypeNameBoxed(), methodName);
}
 
Example #18
Source File: ModelInjection.java    From vault with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void appendConstructor(TypeSpec.Builder builder) {
  MethodSpec.Builder ctor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);

  for (FieldMeta f : fields) {
    CodeBlock.Builder block = CodeBlock.builder();

    block.add("$N.add($T.builder()", specFields, ClassName.get(FieldMeta.class))
        .add(".setId($S)", f.id())
        .add(".setName($S)", f.name());

    if (f.sqliteType() != null) {
      block.add(".setSqliteType($S)", f.sqliteType());
    }

    if (f.isLink()) {
      block.add(".setLinkType($S)", f.linkType());
    }

    if (f.isArray()) {
      block.add(".setArrayType($S)", f.arrayType());
    }

    block.add(".build());\n");

    ctor.addCode(block.build());
  }

  builder.addMethod(ctor.build());
}
 
Example #19
Source File: RemoverAllSupport.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Override
public MethodSpec buildRemoverAll(RDFSClazz domainClazz, OntGenerationConfig config) throws RepositoryException {
    // Add the abstract modifier to the signature, because there is no implementation in the interface:
    return buildSignature(domainClazz, config)
            .toBuilder()
            .addModifiers(Modifier.ABSTRACT)
            .build();
}
 
Example #20
Source File: TableSpec.java    From alchemy with Apache License 2.0 5 votes vote down vote up
private FieldSpec makeEntryField() {
    return FieldSpec.builder(ParameterizedTypeName
                    .get(ClassName.get(SQLiteEntry.class), ClassName.get(mElement)),
            "mEntry", Modifier.PRIVATE, Modifier.FINAL)
            .initializer("new $T()", mEntrySpec.getClassName())
            .build();
}
 
Example #21
Source File: EntityGenerateFromIntfVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void visit(HomeMethodType hmt) {
    implMethod = hmt.getMethodElement();
    String origName = implMethod.getName();
    String newName = prependAndUpper(origName,"ejbHome"); //NOI18N
    String body = TODO + implMethod.getName() + implMethod.getReturnType();
    implMethod = MethodModel.create(
            newName, 
            implMethod.getReturnType(),
            body,
            implMethod.getParameters(),
            implMethod.getExceptions(),
            Collections.singleton(Modifier.PUBLIC)
            );
}
 
Example #22
Source File: JavaFileTest.java    From javapoet with Apache License 2.0 5 votes vote down vote up
private TypeSpec importStaticTypeSpec(String name) {
  MethodSpec method = MethodSpec.methodBuilder("minutesToSeconds")
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .returns(long.class)
      .addParameter(long.class, "minutes")
      .addStatement("$T.gc()", System.class)
      .addStatement("return $1T.SECONDS.convert(minutes, $1T.MINUTES)", TimeUnit.class)
      .build();
  return TypeSpec.classBuilder(name).addMethod(method).build();

}
 
Example #23
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static MethodSpec applySignerOverrideMethod(PoetExtensions poetExtensions, IntermediateModel model) {
    String signerOverrideVariable = "signerOverride";

    TypeVariableName typeVariableName =
        TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName()));

    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName
        .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class));

    CodeBlock codeBlock = CodeBlock.builder()
                                   .beginControlFlow("if (request.overrideConfiguration().flatMap(c -> c.signer())"
                                                     + ".isPresent())")
                                   .addStatement("return request")
                                   .endControlFlow()
                                   .addStatement("$T $L = b -> b.signer(signer).build()",
                                                 parameterizedTypeName,
                                                 signerOverrideVariable)
                                   .addStatement("$1T overrideConfiguration =\n"
                                                 + "            request.overrideConfiguration().map(c -> c.toBuilder()"
                                                 + ".applyMutation($2L).build())\n"
                                                 + "            .orElse((AwsRequestOverrideConfiguration.builder()"
                                                 + ".applyMutation($2L).build()))",
                                                 AwsRequestOverrideConfiguration.class,
                                                 signerOverrideVariable)
                                   .addStatement("return (T) request.toBuilder().overrideConfiguration"
                                                 + "(overrideConfiguration).build()")
                                   .build();

    return MethodSpec.methodBuilder("applySignerOverride")
                     .addModifiers(Modifier.PRIVATE)
                     .addParameter(typeVariableName, "request")
                     .addParameter(Signer.class, "signer")
                     .addTypeVariable(typeVariableName)
                     .addCode(codeBlock)
                     .returns(typeVariableName)
                     .build();
}
 
Example #24
Source File: PubapiVisitor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitType(TypeElement e, Void p) {
    if (e.getModifiers().contains(Modifier.PUBLIC)
        || e.getModifiers().contains(Modifier.PROTECTED))
    {
        sb.append(depth(indent) + "TYPE " + e.getQualifiedName() + "\n");
        indent += 2;
        Void v = super.visitType(e, p);
        indent -= 2;
        return v;
    }
    return null;
}
 
Example #25
Source File: ModifierOrderer.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
     * Returns the {@link Modifier} for the given token kind, or {@code
     * null}.
     */
    private static Modifier getModifier(TokenKind kind) {
        if (kind == null) {
            return null;
        }
        switch (kind) {
            case PUBLIC:
                return Modifier.PUBLIC;
            case PROTECTED:
                return Modifier.PROTECTED;
            case PRIVATE:
                return Modifier.PRIVATE;
            case ABSTRACT:
                return Modifier.ABSTRACT;
            case STATIC:
                return Modifier.STATIC;
            // TODO: 22-Jul-17 unsupported lambdas expr
//            case DEFAULT:
//                return Modifier.DEFAULT;
            case FINAL:
                return Modifier.FINAL;
            case TRANSIENT:
                return Modifier.TRANSIENT;
            case VOLATILE:
                return Modifier.VOLATILE;
            case SYNCHRONIZED:
                return Modifier.SYNCHRONIZED;
            case NATIVE:
                return Modifier.NATIVE;
            case STRICTFP:
                return Modifier.STRICTFP;
            default:
                return null;
        }
    }
 
Example #26
Source File: Common.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static MethodTree createMethod(TreeMaker make,String name, Map<String,String> params) {
    ModifiersTree methodModifiers = make.Modifiers(
            Collections.<Modifier>singleton(Modifier.PUBLIC),
            Collections.<AnnotationTree>emptyList()
            );
    List<VariableTree> paramList = new LinkedList<VariableTree>();
    for(String paramName: params.keySet()) {
        Tree paramType = getTreeForType(params.get(paramName), make);
        VariableTree parameter = make.Variable(
                make.Modifiers(
                Collections.<Modifier>emptySet(),
                Collections.<AnnotationTree>emptyList()
                ),
                paramName, // name
                paramType, // parameter type
                null // initializer - does not make sense in parameters.
                );
        paramList.add(parameter);
    }
    MethodTree newMethod = make.Method(
            methodModifiers, // public
            name, // name
            make.PrimitiveType(TypeKind.VOID), // return type "void"
            Collections.<TypeParameterTree>emptyList(), // type parameters - none
            paramList, // final ObjectOutput arg0
            Collections.<ExpressionTree>emptyList(), // throws
            "{ throw new UnsupportedOperationException(\"Not supported yet.\") }", // body text
            null // default value - not applicable here, used by annotations
            );
    return newMethod;
}
 
Example #27
Source File: EnableBeansFilter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean hasModifier ( Element element , Modifier mod){
    Set<Modifier> modifiers = element.getModifiers();
    for (Modifier modifier : modifiers) {
        if ( modifier.equals( mod )){
            return true;
        }
    }
    return false;
}
 
Example #28
Source File: GeneratedPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void register(PrintWriter out) {
    out.printf("        plugins.register(new %s(", pluginName);
    if (needInjectionProvider) {
        out.printf("injection");
    }
    out.printf("), %s.class, \"%s\"", intrinsicMethod.getEnclosingElement(), intrinsicMethod.getSimpleName());
    if (!intrinsicMethod.getModifiers().contains(Modifier.STATIC)) {
        out.printf(", InvocationPlugin.Receiver.class");
    }
    for (VariableElement arg : intrinsicMethod.getParameters()) {
        out.printf(", %s.class", getErasedType(arg.asType()));
    }
    out.printf(");\n");
}
 
Example #29
Source File: ArrayRewriter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private MethodInvocation newInitializedArrayInvocation(
    ArrayType arrayType, List<Expression> elements, boolean retainedResult) {
  TypeMirror componentType = arrayType.getComponentType();
  TypeElement iosArrayElement = typeUtil.getIosArray(componentType);

  GeneratedExecutableElement methodElement = GeneratedExecutableElement.newMethodWithSelector(
      getInitializeSelector(componentType, retainedResult), iosArrayElement.asType(),
      iosArrayElement)
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC);
  methodElement.addParameter(GeneratedVariableElement.newParameter(
      "values", new PointerType(componentType), methodElement));
  methodElement.addParameter(GeneratedVariableElement.newParameter(
      "count", typeUtil.getInt(), methodElement));
  if (!componentType.getKind().isPrimitive()) {
    methodElement.addParameter(GeneratedVariableElement.newParameter(
        "type", TypeUtil.IOS_CLASS.asType(), methodElement));
  }
  MethodInvocation invocation = new MethodInvocation(
      new ExecutablePair(methodElement), arrayType, new SimpleName(iosArrayElement));

  // Create the array initializer and add it as the first parameter.
  ArrayInitializer arrayInit = new ArrayInitializer(arrayType);
  for (Expression element : elements) {
    arrayInit.addExpression(element.copy());
  }
  invocation.addArgument(arrayInit);

  // Add the array size parameter.
  invocation.addArgument(
      NumberLiteral.newIntLiteral(arrayInit.getExpressions().size(), typeUtil));

  // Add the type argument for object arrays.
  if (!componentType.getKind().isPrimitive()) {
    invocation.addArgument(new TypeLiteral(componentType, typeUtil));
  }

  return invocation;
}
 
Example #30
Source File: TypeAs.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public TypeDef apply(TypeDef item) {
    BuilderContext ctx = BuilderContextManager.getContext();
    TypeDef fluent = SHALLOW_FLUENT.apply(item);

    List<TypeParamDef> parameters = new ArrayList<>(item.getParameters());
    List<TypeRef> superClassParameters = new ArrayList<>();
    TypeParamDef nextParameter = getNextGeneric(item, parameters);

    ClassRef builableSuperClassRef = findBuildableSuperClassRef(item);
    if (builableSuperClassRef != null) {
        superClassParameters.addAll(builableSuperClassRef.getArguments());
    }

    TypeParamDef parameterFluent = new TypeParamDefBuilder(nextParameter).addToBounds(fluent.toInternalReference()).build();
    parameters.add(parameterFluent);
    superClassParameters.add(parameterFluent.toReference());

    TypeDef buildableSuperClass = findBuildableSuperClass(item);

    TypeDef superClass = buildableSuperClass != null
            ? FLUENT_IMPL.apply(buildableSuperClass)
            : ctx.getBaseFluentClass();

    return new TypeDefBuilder(item)
            .withKind(Kind.CLASS)
            .withModifiers(TypeUtils.modifiersToInt(Modifier.PUBLIC))
            .withName(item.getName() + "FluentImpl")
            .withPackageName(item.getPackageName())
            .withParameters(parameters)
            .withExtendsList(superClass.toReference(superClassParameters))
            .withImplementsList(SHALLOW_FLUENT.apply(item).toInternalReference())
            .withInnerTypes()
            .build();
}