io.vertx.codegen.writer.CodeWriter Java Examples

The following examples show how to use io.vertx.codegen.writer.CodeWriter. 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: CodeWriterTest.java    From vertx-codegen with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndentation(){
  CodeWriter writer = assertWriter(w ->
    w.codeln("line 1")
      .indent()
        .codeln("line 2")
        .codeln("line 3")
        .indent()
          .codeln("line 4")
        .unindent()
      .unindent()
      .code("line 5"),
    "line 1\n" +
      "  line 2\n" +
      "  line 3\n" +
      "    line 4\n" +
      "line 5"
  );
  assertEquals("", writer.indentation());
  assertEquals(2, writer.indentSize());
}
 
Example #2
Source File: CodeWriterTest.java    From vertx-codegen with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndentationFactor(){
  CodeWriter writer = assertWriter(w -> {
    w.indentSize(4);
      w.codeln("line 1")
        .indent()
        .codeln("line 2")
        .codeln("line 3")
        .indent()
        .codeln("line 4")
        .unindent()
        .unindent()
        .code("line 5");
    },
    "line 1\n" +
      "    line 2\n" +
      "    line 3\n" +
      "        line 4\n" +
      "line 5"
  );
  assertEquals("", writer.indentation());
  assertEquals(4, writer.indentSize());
}
 
Example #3
Source File: CodeWriterTest.java    From vertx-codegen with Apache License 2.0 6 votes vote down vote up
@Test
public void testStmt(){
  CodeWriter writer = assertWriter(w ->
      w.stmt("line 1")
        .indent()
        .stmt("line 2")
        .stmt("line 3")
        .indent()
        .stmt("line 4")
        .unindent()
        .unindent()
        .stmt("line 5"),
    "line 1;\n" +
      "  line 2;\n" +
      "  line 3;\n" +
      "    line 4;\n" +
      "line 5;\n"
  );
}
 
Example #4
Source File: ServiceProxyGen.java    From vertx-service-proxy with Apache License 2.0 6 votes vote down vote up
private void generateMethods(ProxyModel model, CodeWriter writer) {
  for (MethodInfo m : model.getMethods()) {
    if (!m.isStaticMethod()) {
      writer.code("@Override\n");
      writer.code("public");
      if (!m.getTypeParams().isEmpty()) {
        writer.write(" <");
        writer.writeSeq(m.getTypeParams().stream().map(TypeParamInfo::getName), ", ");
        writer.write(">");
      }
      writer.write(" " + m.getReturnType().getSimpleName() + " " + m.getName() + "(");
      writer.writeSeq(m.getParams().stream().map(p -> p.getType().getSimpleName() + " " + p.getName()), ", ");
      writer.write("){\n");
      writer.indent();
      if (!((ProxyMethodInfo) m).isProxyIgnore()) generateMethodBody((ProxyMethodInfo) m, writer);
      if (m.isFluent()) writer.stmt("return this");
      writer.unindent();
      writer.code("}\n");
    }
  }
}
 
Example #5
Source File: DataObjectHelperGen.java    From vertx-codegen with Apache License 2.0 5 votes vote down vote up
@Override
public String render(DataObjectModel model, int index, int size, Map<String, Object> session) {

  formatter = getCase(model);

  StringWriter buffer = new StringWriter();
  PrintWriter writer = new PrintWriter(buffer);
  CodeWriter code = new CodeWriter(writer);
  String visibility= model.isPublicConverter() ? "public" : "";
  boolean inheritConverter = model.getInheritConverter();

  writer.print("package " + model.getType().getPackageName() + ";\n");
  writer.print("\n");
  writer.print("import io.vertx.core.json.JsonObject;\n");
  writer.print("import io.vertx.core.json.JsonArray;\n");
  writer.print("import java.time.Instant;\n");
  writer.print("import java.time.format.DateTimeFormatter;\n");
  writer.print("\n");
  writer.print("/**\n");
  writer.print(" * Converter and mapper for {@link " + model.getType() + "}.\n");
  writer.print(" * NOTE: This class has been automatically generated from the {@link " + model.getType() + "} original class using Vert.x codegen.\n");
  writer.print(" */\n");
  code
    .codeln("public class " + model.getType().getSimpleName() + "Converter {"
    ).newLine();
  if (model.getGenerateConverter()) {
    writer.print("\n");
    genFromJson(visibility, inheritConverter, model, writer);
    writer.print("\n");
    genToJson(visibility, inheritConverter, model, writer);
  }
  writer.print("}\n");
  return buffer.toString();
}
 
Example #6
Source File: CodeWriterTest.java    From vertx-codegen with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaImport(){
  CodeWriter writer = assertWriter(w ->
      w.javaImport("io.vertx.test.codegen.utils.CodeWriterTest"),
    "import io.vertx.test.codegen.utils.CodeWriterTest;\n"
  );
}
 
Example #7
Source File: CodeWriterTest.java    From vertx-codegen with Apache License 2.0 5 votes vote down vote up
private CodeWriter assertWriter(Consumer<CodeWriter> codeToExecute, String expectedOutput) {
  StringWriter w = new StringWriter();
  CodeWriter codeWriter = new CodeWriter(w);
  codeToExecute.accept(codeWriter);
  assertEquals(expectedOutput, w.toString());
  return codeWriter;
}
 
Example #8
Source File: ServiceProxyHandlerGen.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
public void generateActionSwitchEntry(ProxyMethodInfo m, CodeWriter writer) {
  ParamInfo lastParam = !m.getParams().isEmpty() ? m.getParam(m.getParams().size() - 1) : null;
  boolean hasResultHandler = utils.isResultHandler(lastParam);
  writer
    .code("case \"" + m.getName() + "\": {\n")
    .indent()
    .code("service." + m.getName() + "(")
    .indent();
  if (hasResultHandler) {
    writer.writeSeq(
      Stream.concat(
        m.getParams().subList(0, m.getParams().size() - 1).stream().map(this::generateJsonParamExtract),
        Stream.of(generateHandler(lastParam))
      ),
      ",\n" + writer.indentation()
    );
  } else {
    writer.writeSeq(
      m.getParams().stream().map(this::generateJsonParamExtract),
      ",\n" + writer.indentation()
    );
  }
  writer.unindent();
  writer.write(");\n");
  if (m.isProxyClose()) writer.stmt("close()");
  writer.stmt("break");
  writer.unindent();
  writer.code("}\n");
}
 
Example #9
Source File: ServiceProxyGen.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
private void generateMethodBody(ProxyMethodInfo method, CodeWriter writer) {
  ParamInfo lastParam = !method.getParams().isEmpty() ? method.getParam(method.getParams().size() - 1) : null;
  boolean hasResultHandler = utils.isResultHandler(lastParam);
  if (hasResultHandler) {
    writer.code("if (closed) {\n");
    writer.indent();
    writer.stmt(lastParam.getName() + ".handle(Future.failedFuture(new IllegalStateException(\"Proxy is closed\")))");
    if (method.isFluent())
      writer.stmt("return this");
    else
      writer.stmt("return");
    writer.unindent();
    writer.code("}\n");
  } else {
    writer.code("if (closed) throw new IllegalStateException(\"Proxy is closed\");\n");
  }
  if (method.isProxyClose())
    writer.stmt("closed = true");
  writer.stmt("JsonObject _json = new JsonObject()");
  List<ParamInfo> paramsExcludedHandler =
    (method.getParams().isEmpty()) ? new ArrayList<>() :
      (hasResultHandler) ? method.getParams().subList(0, method.getParams().size() - 1) : method.getParams();
  paramsExcludedHandler.forEach(p -> generateAddToJsonStmt(p, writer));
  writer.newLine();
  writer.stmt("DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions()");
  writer.stmt("_deliveryOptions.addHeader(\"action\", \"" + method.getName() + "\")");
  if (hasResultHandler) {
    generateSendCallWithResultHandler(lastParam, writer);
  } else {
    writer.stmt("_vertx.eventBus().send(_address, _json, _deliveryOptions)");
  }
}
 
Example #10
Source File: WebApiProxyHandlerGen.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public void generateAdditionalMethods(ProxyModel model, CodeWriter writer) {
  super.generateAdditionalMethods(model, writer);
  writer.write(utilsFunctions);
}
 
Example #11
Source File: WebApiProxyHandlerGen.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void generateActionSwitchEntry(ProxyMethodInfo m, CodeWriter writer) {
  if (m.isProxyClose()) {
    super.generateActionSwitchEntry(m, writer);
    return;
  }
  TypeInfo returnType = m.getReturnType();
  writer
    .codeln(String.format("case \"%s\": {", m.getName()))
    .indent()
    .stmt("JsonObject contextSerialized = json.getJsonObject(\"context\")")
    .codeln("if (contextSerialized == null)")
    .indent()
    .stmt("throw new IllegalStateException(\"Received action \" + action + \" without ServiceRequest \\\"context\\\"\")")
    .unindent()
    .stmt("ServiceRequest context = new ServiceRequest(contextSerialized)")
    .stmt("JsonObject params = context.getParams()")
    .codeln("try {")
    .indent()
    .code(String.format("service.%s(", m.getName()))
    .indent();

  Stream<String> methodParamsTail = Stream.of("context", serviceCallHandler);

  writer.writeSeq(
    Stream.concat(
      ((WebApiProxyMethodInfo) m).getParamsToExtract().stream().map(this::generateJsonParamExtractFromContext),
      methodParamsTail
    ),
    ",\n" + writer.indentation()
  );
  writer.unindent();
  writer.write(");\n");
  writer.unindent()
    .codeln("} catch (Exception e) {")
    .indent()
    .stmt("HelperUtils.manageFailure(msg, e, includeDebugInfo)")
    .unindent()
    .codeln("}");
  if (m.isProxyClose()) writer.stmt("close()");
  writer.stmt("break");
  writer.unindent();
  writer.codeln("}");
}
 
Example #12
Source File: CodeWriterTest.java    From vertx-codegen with Apache License 2.0 4 votes vote down vote up
@Test
public void testUnderlyingWriter() {
  StringWriter w = new StringWriter();
  CodeWriter writer = new CodeWriter(w);
  assertSame(w, writer.writer());
}
 
Example #13
Source File: ServiceProxyHandlerGen.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public String render(ProxyModel model, int index, int size, Map<String, Object> session) {
  StringWriter buffer = new StringWriter();
  CodeWriter writer = new CodeWriter(buffer);
  String className = className(model);
  utils.classHeader(writer);
  writer.stmt("package " + model.getIfacePackageName());
  writer.newLine();
  utils.writeImport(writer, model.getIfaceFQCN());
  utils.handlerGenImports(writer);
  Stream.concat(utils.additionalImports(model), additionalImports()).distinct().forEach(i -> utils.writeImport(writer, i));
  utils.roger(writer);
  writer
    .code("@SuppressWarnings({\"unchecked\", \"rawtypes\"})\n")
    .code("public class " + className + " extends ProxyHandler {\n")
    .newLine()
    .indent()
    .code("public static final long DEFAULT_CONNECTION_TIMEOUT = 5 * 60; // 5 minutes \n")
    .stmt("private final Vertx vertx")
    .stmt("private final " + model.getIfaceSimpleName() + " service")
    .stmt("private final long timerID")
    .stmt("private long lastAccessed")
    .stmt("private final long timeoutSeconds")
    .stmt("private final boolean includeDebugInfo")
    .newLine()
    .code("public " + className + "(Vertx vertx, " + model.getIfaceSimpleName() + " service){\n")
    .indent()
    .stmt("this(vertx, service, DEFAULT_CONNECTION_TIMEOUT)")
    .unindent()
    .code("}\n")
    .newLine()
    .code("public "+ className + "(Vertx vertx, " + model.getIfaceSimpleName() + " service, long timeoutInSecond){\n")
    .indent()
    .stmt("this(vertx, service, true, timeoutInSecond)")
    .unindent()
    .code("}\n")
    .newLine()
    .code("public "+ className + "(Vertx vertx, " + model.getIfaceSimpleName() + " service, boolean topLevel, long timeoutInSecond){\n")
    .indent()
    .stmt("this(vertx, service, true, timeoutInSecond, false)")
    .unindent()
    .code("}\n")
    .newLine()
    .code("public " + className + "(Vertx vertx, " + model.getIfaceSimpleName() + " service, boolean topLevel, long timeoutSeconds, boolean includeDebugInfo) {\n");
  utils.handlerConstructorBody(writer);
  writer.code("private void checkTimedOut(long id) {\n")
    .indent()
    .stmt("long now = System.nanoTime()")
    .code("if (now - lastAccessed > timeoutSeconds * 1000000000) {\n")
    .indent();
  model.getMethods().stream()
    .filter(m -> ((ProxyMethodInfo)m).isProxyClose())
    .forEach(m -> {
      if (m.getParams().isEmpty()) writer.stmt("service." + m.getName() + "()");
      else writer.stmt("service." + m.getName() + "(done -> {})");
    });
  writer
    .stmt("close()")
    .unindent()
    .code("}\n")
    .unindent()
    .code("}\n")
    .newLine();
  utils.handleCloseAccessed(writer);
  writer.code("public void handle(Message<JsonObject> msg) {\n")
    .indent()
    .code("try{\n")
    .indent()
    .stmt("JsonObject json = msg.body()")
    .stmt("String action = msg.headers().get(\"action\")")
    .stmt("if (action == null) throw new IllegalStateException(\"action not specified\")")
    .stmt("accessed()")
    .code("switch (action) {\n")
    .indent();
  model.getMethods().stream().filter(m -> !m.isStaticMethod()).forEach(m -> generateActionSwitchEntry((ProxyMethodInfo) m, writer));
  writer
    .code("default: throw new IllegalStateException(\"Invalid action: \" + action);\n")
    .unindent()
    .code("}\n")
    .unindent()
    .code("} catch (Throwable t) {\n")
    .indent()
    .stmt("if (includeDebugInfo) msg.reply(new ServiceException(500, t.getMessage(), HelperUtils.generateDebugInfo(t)))")
    .stmt("else msg.reply(new ServiceException(500, t.getMessage()))")
    .stmt("throw t")
    .unindent()
    .code("}\n")
    .unindent()
    .code("}\n");
  generateAdditionalMethods(model, writer);
  writer
    .unindent()
    .code("}");
  return buffer.toString();
}
 
Example #14
Source File: ServiceProxyGen.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public String render(ProxyModel model, int index, int size, Map<String, Object> session) {
  StringWriter buffer = new StringWriter();
  CodeWriter writer = new CodeWriter(buffer);

  String className = model.getIfaceSimpleName() + "VertxEBProxy";

  utils.classHeader(writer);
  writer.code("package " + model.getIfacePackageName() + ";\n");
  writer.code("\n");
  utils.proxyGenImports(writer);
  utils.additionalImports(model).forEach(i -> utils.writeImport(writer, i));
  utils.roger(writer);
  writer
    .code("@SuppressWarnings({\"unchecked\", \"rawtypes\"})\n")
    .code("public class " + className + " implements " + model.getIfaceSimpleName() + " {\n")
    .indent()
      .stmt("private Vertx _vertx")
      .stmt("private String _address")
      .stmt("private DeliveryOptions _options")
      .stmt("private boolean closed")
      .newLine()
      .code("public " + className + "(Vertx vertx, String address) {\n")
      .indent()
        .stmt("this(vertx, address, null)")
      .unindent()
      .code("}\n")
      .newLine()
      .code("public " + className +  "(Vertx vertx, String address, DeliveryOptions options) {\n")
      .indent()
        .stmt("this._vertx = vertx")
        .stmt("this._address = address")
        .stmt("this._options = options")
        .code("try {")
        .indent()
          .stmt("this._vertx.eventBus().registerDefaultCodec(ServiceException.class, new ServiceExceptionMessageCodec())")
        .unindent()
        .code("} catch (IllegalStateException ex) {\n}")
      .unindent()
      .code("}\n")
      .newLine();
  generateMethods(model, writer);
  writer
    .unindent()
    .code("}\n");
  return buffer.toString();
}
 
Example #15
Source File: ServiceProxyGen.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
private void generateSendCallWithResultHandler(ParamInfo lastParam, CodeWriter writer) {
  String name = lastParam.getName();
  TypeInfo t = ((ParameterizedTypeInfo)((ParameterizedTypeInfo)lastParam.getType()).getArg(0)).getArg(0);

  wrapResult(t, name, false, writer);
}
 
Example #16
Source File: ServiceProxyHandlerGen.java    From vertx-service-proxy with Apache License 2.0 votes vote down vote up
public void generateAdditionalMethods(ProxyModel model, CodeWriter writer) {}