Java 类com.sun.codemodel.JFormatter 实例源码

项目:aml    文件:GenericAcAdapterWriter.java   
protected JBlock generateWriter(AcScheme scheme, JavaWriter writer) {
    JBlock bl=new JBlock();
    for (AbstractType tp:scheme.getSchemes().keySet()){
        String name = getName(tp, writer);
        String ge="value.get"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"()";
        JBlock th=bl._if(JExpr.direct(ge+"!=null"))._then();
        th.add(new JStatement() {

            @Override
            public void state(JFormatter f) {
                f.p("gson.toJson("+ge+","+ge+".getClass(), out);");
                f.nl();
            }
        });
    }
    return bl;
}
项目:aml    文件:JacksonSerializerWriter.java   
protected JBlock generateWriter(AcScheme scheme, JavaWriter writer) {
    JBlock bl=new JBlock();
    for (AbstractType tp:scheme.getSchemes().keySet()){
        String name = getName(tp, writer);
        String ge="value.get"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"()";
        JBlock th=bl._if(JExpr.direct(ge+"!=null"))._then();
        th.add(new JStatement() {

            @Override
            public void state(JFormatter f) {
                f.p("gen.writeObject("+ge+");");
                f.nl();
            }
        });
    }
    return bl;
}
项目:aml    文件:ClonableCustomizer.java   
@Override
public void customize(ClassCustomizerParameters parameters) {
    parameters.clazz._implements(Cloneable.class);
    parameters.clazz.method(JMod.PUBLIC, parameters.clazz, "clone").body().add(new JStatement() {

        @Override
        public void state(JFormatter f) {
            f.p("try {");
            f.nl();
            f.p("return ("+parameters.clazz.name()+")super.clone();");
            f.nl();
            f.p("} catch (CloneNotSupportedException e){ throw new IllegalStateException(e);}");
            f.nl();
        }
    });

}
项目:aml    文件:GenericAcAdapterWriter.java   
private String doReader(AcScheme scheme, JavaWriter writer, String template) {
    JBlock bl=generateAc(scheme,writer);        
    StringWriter w = new StringWriter();
    JFormatter f = new JFormatter(w);
    for (int i=0;i<4;i++){
        f.i();
    }
    bl.generate(f);
    template=template.replace((CharSequence)"{acCode}", w.toString());
    return template;
}
项目:org.ops4j.ramler    文件:AbstractGeneratorTest.java   
protected void assertSimpleAnnotation(JMethod method, String annotation, String argument) {
    JAnnotationUse annotationUse = method.annotations().stream()
        .filter(a -> a.getAnnotationClass().name().equals(annotation)).findFirst().get();
    JAnnotationValue value = annotationUse.getAnnotationMembers().get("value");
    StringWriter writer = new StringWriter();
    JFormatter formatter = new JFormatter(writer);
    value.generate(formatter);
    assertThat(writer.toString()).isEqualTo(argument);
}
项目:org.ops4j.ramler    文件:AbstractGeneratorTest.java   
protected void assertNoArgAnnotation(JMethod method, Class<?> annotation) {
    JAnnotationUse annotationUse = method.annotations().stream()
        .filter(a -> a.getAnnotationClass().name().equals(annotation.getSimpleName())).findFirst().get();
    StringWriter writer = new StringWriter();
    JFormatter formatter = new JFormatter(writer);
    annotationUse.generate(formatter);
    assertThat(writer.toString()).isEqualTo("@" + annotation.getName());
}
项目:drill    文件:DebugStringBuilder.java   
public DebugStringBuilder( Object obj ) {
  strWriter = new StringWriter( );
  writer = new PrintWriter( strWriter );
  writer.print( "[" );
  writer.print( obj.getClass().getSimpleName() );
  writer.print( ": " );
  fmt = new JFormatter( writer );
}
项目:springmvc-raml-plugin    文件:CodeModelHelper.java   
/**
 * Returns the string equivalent of the code model element
 * @param type The element to stringify
 * @return the element as a string (generated code)
 */
public static String getElementAsString(JDeclaration type) {
    StringBuilder builder = new StringBuilder();
    JFormatter jFormatter = new JFormatter(new StringBuilderWriter(builder));
    type.declare(jFormatter);
    return builder.toString();
}
项目:jaxb2-rich-contract-plugin    文件:JTypedInvocation.java   
@Override
public void generate(JFormatter f) {
    if (this.lhs != null) {
        f = f.g(this.lhs).p('.');
    } else if(this.type != null && !this.constructor) {
        f = f.g(this.type).p('.');
    }
    if (this.type != null && this.constructor) {
        f = f.p("new").g(this.type).p('(');
    } else {
        if (!this.typeArguments.isEmpty()) {
            f = f.p("<");
            boolean first = true;
            for (final JType typeArg : this.typeArguments) {
                if (!first) {
                    f = f.p(", ");
                } else {
                    first = false;
                }
                f = f.g(typeArg);
            }
            f = f.p(">");
        }
        f = f.p(this.method).p('(');
    }
    f.g(this.args);
    f.p(')');
}
项目:jaxb2-rich-contract-plugin    文件:MetaPlugin.java   
private JExpression dotClass(final JType cl) {
    if (cl instanceof JClass) {
        return ((JClass)cl).dotclass();
    } else {
        return new JExpressionImpl() {
            public void generate(final JFormatter f) {
                f.g(cl).p(".class");
            }
        };
    }
}
项目:jaxb-visitor    文件:ClassDiscoverer.java   
/**
 * Handles the extraction of the schema type from the XmlElement
 * annotation. This was surprisingly difficult. Apparently the
 * model doesn't provide access to the annotation we're referring to
 * so I need to print it and read the string back. Even the formatter
 * itself is final!
 * @param outline root of the generated code
 * @param directClasses set of classes to append to
 * @param type annotation we're analysing
 */
private static void handleXmlElement(Outline outline, Set<String> directClasses, JAnnotationValue type) {
    StringWriter sw = new StringWriter();
    JFormatter jf = new JFormatter(new PrintWriter(sw));
    type.generate(jf);
    String s = sw.toString();
    s = s.substring(0, s.length()-".class".length());
    if (!s.startsWith("java") && outline.getCodeModel()._getClass(s) == null && !foundWithinOutline(s, outline)) {
        directClasses.add(s);
    }
}
项目:jaxb-visitor    文件:CreateJAXBElementNameCallback.java   
private String annotationValueToString(JAnnotationValue ns) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JFormatter jf = new JFormatter(pw, "");
    ns.generate(jf);
    pw.flush();
    String s = sw.toString();
    return s.substring(1, s.length()-1);
}
项目:jaxb2-annotate-plugin    文件:AnnotatingSingleValueVisitor.java   
private JAnnotationUse param(final JType type) {
    if (type instanceof JClass) {
        return annotationUse.param(this.name, (JClass) type);
    } else {
        return annotationUse.param(this.name, new JExpressionImpl() {
            public void generate(JFormatter f) {
                f.g(type).p(".class");
            }
        });
    }
}
项目:jaxb2-annotate-plugin    文件:AnnotatingArrayValueVisitor.java   
private JAnnotationArrayMember param(final JType type) {
    if (type instanceof JClass) {
        return annotationArrayMember.param((JClass) type);
    } else {
        return annotationArrayMember.param(new JExpressionImpl() {
            public void generate(JFormatter f) {
                f.g(type).p(".class");
            }
        });
    }
}
项目:xero-java-client    文件:PluginImpl.java   
/**
 * Update getters to use Java List. For example:
 * ArrayOfInvoices getInvoices() -> List<Invoice> getInvoices()
 */
private void updateArrayOfGetters(ClassOutline co, JCodeModel model) {
  JDefinedClass implClass = co.implClass;

  List<JMethod> removedMethods = new ArrayList<>();
  Iterator<JMethod> iter = implClass.methods().iterator();
  while (iter.hasNext()) {
    JMethod method = iter.next();
    if (method.type().name().startsWith("ArrayOf")) {
      removedMethods.add(method);
      iter.remove();
    }
  }

  for (JMethod removed : removedMethods) {
    // Parse the old code to get the variable name
    StringWriter oldWriter = new StringWriter();
    removed.body().state(new JFormatter(oldWriter));
    String oldBody = oldWriter.toString();
    String varName = oldBody.substring(oldBody.indexOf("return ") + "return ".length(), oldBody.indexOf(";"));

    // Build the new method
    JClass newReturnType = (JClass) ((JDefinedClass) removed.type()).fields().values().iterator().next().type();
    JMethod newMethod = implClass.method(removed.mods().getValue(), newReturnType, removed.name());
    JFieldVar field = implClass.fields().get(varName);          
    JClass typeParameter = newReturnType.getTypeParameters().get(0);
    String fieldName = model._getClass(field.type().fullName()).fields().keySet().iterator().next();

    newMethod.body()._return(
        JOp.cond(field.eq(JExpr._null()),
            JExpr._new(model.ref("java.util.ArrayList").narrow(typeParameter)),
            field.invoke("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1))));
  }    
}
项目:QDrill    文件:DirectExpression.java   
public void generate( JFormatter f ) {
  f.p('(').p(source).p(')');
}
项目:dremio-oss    文件:DirectExpression.java   
public void generate( JFormatter f ) {
  f.p('(').p(source).p(')');
}
项目:aml    文件:GsonAcElementWriter.java   
protected void contribute(CompositeAcElement ac,JBlock block,AbstractType target,JavaWriter writer){
    JExpression expression=null;
    switch (ac.getFamily()) {
    case BOOLEAN:
        expression=JExpr.direct("vl.isJsonPrimitive()&&vl.getAsJsonPrimitive().isBoolean()");
        break;
    case ARRAY:
        expression=JExpr.direct("vl.isJsonArray()");
        break;
    case NUMBER:
        expression=JExpr.direct("vl.isJsonPrimitive()&&vl.getAsJsonPrimitive().isNumber()");
        break;
    case STRING:
        expression=JExpr.direct("vl.isJsonPrimitive()&&vl.getAsJsonPrimitive().isString()");
        break;
    case OBJECT:
        expression=JExpr.direct("vl.isJsonObject()");
        break;
    default:
        break;
    }
    JBlock _then = block._if(expression)._then();
    for (AcElement x:ac.getChildren()){
        if (x.kind()==AcElementKind.PROPERTY_EXISTANCE){
            _then=_then._if(JExpr.direct("vl.getAsJsonObject().has(\""+x.getProperty()+"\")"))._then();
        }
        if (x.kind()==AcElementKind.PROPERTY_VALUE){
             TestPropertyValueAcElement pv=(TestPropertyValueAcElement) x;
            _then=_then._if(JExpr.direct("vl.getAsJsonObject().has(\""+x.getProperty()+"\")&&vl.getAsJsonObject().get(\""+x.getProperty()+"\").getAsString()!=null&&vl.getAsJsonObject().get(\""+x.getProperty()+"\").getAsString().equals(\""+pv.getValue()+"\")"))._then();
        }
    };
    _then.add(new JStatement() {

        @Override
        public void state(JFormatter f) {
            String name = getName(target, writer);
            if (ac.getFamily()==TypeFamily.ARRAY&&writer.getConfig().containerStrategyCollection){
                JType type = writer.getType(target);
                if (type.erasure()!=type){
                    String elementName=((JClass) type).getTypeParameters().get(0).fullName();
                    String vv="new SimpleParameterizedType("+type.erasure().fullName()+".class,"+elementName+".class)";

                    f.p("union.set"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"(gson.fromJson(vl, "+vv+"));");
                }
                else{
                f.p("union.set"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"(gson.fromJson(vl,"+getJavaTypeName(target, writer)+".class));");
                }
            }
            else{
                f.p("union.set"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"(gson.fromJson(vl,"+getJavaTypeName(target, writer)+".class));");
            }
            f.nl();
            f.p("return union;");
            f.nl();
        }
    });
}
项目:aml    文件:JacksonDeserializerWriter.java   
protected void contribute(CompositeAcElement ac,JBlock block,AbstractType target,JavaWriter writer){
    JExpression expression=null;
    switch (ac.getFamily()) {
    case BOOLEAN:
        expression=JExpr.direct("vl.isValueNode()&&vl.isBoolean()");
        break;
    case ARRAY:
        expression=JExpr.direct("vl.isArray()");
        break;
    case NUMBER:
        expression=JExpr.direct("vl.isValueNode()&&vl.isNumber()");
        break;
    case STRING:
        expression=JExpr.direct("vl.isValueNode()&&vl.isTextual()");
        break;
    case OBJECT:
        expression=JExpr.direct("vl.isObject()");
        break;
    default:
        break;
    }
    JBlock _then = block._if(expression)._then();
    for (AcElement x:ac.getChildren()){
        if (x.kind()==AcElementKind.PROPERTY_EXISTANCE){
            _then=_then._if(JExpr.direct("vl.has(\""+x.getProperty()+"\")"))._then();
        }
        if (x.kind()==AcElementKind.PROPERTY_VALUE){
            TestPropertyValueAcElement el=(TestPropertyValueAcElement) x;

            _then=_then._if(JExpr.direct("vl.has(\""+x.getProperty()+"\")&&vl.get(\""+x.getProperty()+"\").asText().equals(\""+el.getValue()+"\")"))._then();
        }
    };
    _then.add(new JStatement() {

        @Override
        public void state(JFormatter f) {
            String name = getName(target, writer);
            if (ac.getFamily()==TypeFamily.ARRAY&&writer.getConfig().containerStrategyCollection){
                JType type = writer.getType(target);
                if (type.erasure()!=type){
                    String elementName=((JClass) type).getTypeParameters().get(0).fullName();
                    String vv="com.fasterxml.jackson.databind.type.CollectionType.construct("+type.erasure().fullName()+".class,com.fasterxml.jackson.databind.type.SimpleType.construct("+elementName+".class))";

                    f.p("union.set"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"(codec.readValue(vl.traverse(), "+vv+"));");
                }
            }
            else{
                f.p("union.set"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"(codec.readValue(vl.traverse(), "+getJavaTypeName(target, writer)+".class));");
            }
            f.nl();
            f.p("return union;");
            f.nl();
        }
    });
}
项目:drill    文件:DirectExpression.java   
@Override
public void generate(JFormatter f) {
  f.p('(').p(source).p(')');
}
项目:raml-maven-plugin    文件:BinaryOperator.java   
@Override
public void generate(JFormatter f) {
    f.g(left).p(operator).g(right);
}
项目:jsignalml    文件:TypeBytes.java   
/**
 *
 * @see com.sun.codemodel.JGenerable#generate(com.sun.codemodel.JFormatter)
 */
@Override
public void generate(JFormatter jformatter) {
    jformatter.p(str);

}
项目:jsignalml    文件:TypeBytes.java   
/**
 *
 * @see com.sun.codemodel.JGenerable#generate(com.sun.codemodel.JFormatter)
 */
@Override
public void generate(JFormatter jformatter) {
    jformatter.p(str);

}
项目:jaxb2-rich-contract-plugin    文件:JTypedInvocation.java   
@Override
public void state(final JFormatter f) {
    f.g(this).p(";").nl();
}
项目:jaxb2-rich-contract-plugin    文件:NestedThisRef.java   
@Override
public void generate(final JFormatter f) {
    f.g(jClass);
    f.p(".this");
}
项目:drill    文件:DebugStringBuilder.java   
public JFormatter formatter() { return fmt; }