Search in sources :

Example 11 with CodeBuilder

use of core.framework.internal.asm.CodeBuilder in project core-ng-project by neowu.

the class ArchDiagram method dot.

public String dot() {
    var dot = new CodeBuilder().append("digraph {\n");
    dot.append("rankdir=LR;\n");
    dot.append("node [style=\"rounded, filled\", fontname=arial, fontsize=17, fontcolor=white];\n");
    dot.append("edge [arrowsize=0.5];\n");
    for (String app : apps()) {
        if (excludeApps.contains(app))
            continue;
        if (app.startsWith("_direct_")) {
            dot.append("\"{}\" [label=direct, shape=point];\n", app);
            continue;
        }
        String color = color(app);
        String tooltip = tooltip(app);
        dot.append("\"{}\" [label=\"{}\", shape=circle, width=3, color=\"{}\", fillcolor=\"{}\", tooltip=\"{}\"];\n", app, app, color, color, tooltip);
    }
    for (MessageSubscription subscription : messageSubscriptions) {
        dot.append("\"{}\" [label=\"{}\", shape=box, color=\"#6C757D\", fillcolor=\"#6C757D\", tooltip=\"{}\"];\n", subscription.topic, subscription.topic, tooltip(subscription));
    }
    for (APIDependency dependency : apiDependencies) {
        if (!excludeApps.contains(dependency.client)) {
            // excluded services are filtered on loading
            String tooltip = tooltip(dependency);
            dot.append("\"{}\" -> \"{}\" [color=\"{}\", weight=5, penwidth=2, tooltip=\"{}\"];\n", dependency.client, dependency.service, colors.get(dependency.client), tooltip);
        }
    }
    for (MessageSubscription subscription : messageSubscriptions) {
        for (Map.Entry<String, Long> entry : subscription.publishers.entrySet()) {
            String publisher = entry.getKey();
            if (!excludeApps.contains(publisher)) {
                dot.append("\"{}\" -> \"{}\" [color=\"#495057\", style=dashed];\n", publisher, subscription.topic);
            }
        }
        for (Map.Entry<String, Long> entry : subscription.consumers.entrySet()) {
            // excluded consumers are filtered on loading
            dot.append("\"{}\" -> \"{}\" [color=\"#ADB5BD\", style=dashed];\n", subscription.topic, entry.getKey());
        }
    }
    dot.append("}\n");
    return dot.build();
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) Map(java.util.Map) CodeBuilder(core.framework.internal.asm.CodeBuilder)

Example 12 with CodeBuilder

use of core.framework.internal.asm.CodeBuilder in project core-ng-project by neowu.

the class InsertQueryBuilder method buildSQL.

private void buildSQL() {
    List<Field> fields = Classes.instanceFields(entityClass);
    int size = fields.size();
    paramFieldNames = new ArrayList<>(size);
    List<String> columns = new ArrayList<>(size);
    List<String> params = new ArrayList<>(size);
    List<String> updates = new ArrayList<>(size);
    for (Field field : fields) {
        PrimaryKey primaryKey = field.getDeclaredAnnotation(PrimaryKey.class);
        String column = field.getDeclaredAnnotation(Column.class).name();
        if (primaryKey != null) {
            if (primaryKey.autoIncrement()) {
                generatedColumn = column;
                continue;
            }
            // pk fields is only needed for assigned id
            primaryKeyFieldNames.add(field.getName());
        } else {
            // since MySQL 8.0.20, VALUES(column) syntax is deprecated, currently gcloud MySQL is still on 8.0.18
            updates.add(Strings.format("{} = VALUES({})", column, column));
        }
        paramFieldNames.add(field.getName());
        columns.add(column);
        params.add("?");
    }
    var builder = new CodeBuilder().append("INSERT INTO {} (", entityClass.getDeclaredAnnotation(Table.class).name()).appendCommaSeparatedValues(columns).append(") VALUES (").appendCommaSeparatedValues(params).append(')');
    sql = builder.build();
    var upsertBuilder = new CodeBuilder().append(" ON DUPLICATE KEY UPDATE ").appendCommaSeparatedValues(updates);
    upsertClause = upsertBuilder.build();
}
Also used : Field(java.lang.reflect.Field) Column(core.framework.db.Column) ArrayList(java.util.ArrayList) PrimaryKey(core.framework.db.PrimaryKey) CodeBuilder(core.framework.internal.asm.CodeBuilder)

Example 13 with CodeBuilder

use of core.framework.internal.asm.CodeBuilder in project core-ng-project by neowu.

the class WebServiceClientBuilderTest method buildPath.

@Test
void buildPath() {
    var builder = new CodeBuilder();
    this.builder.buildPath(builder, "/test", Map.of());
    assertThat(builder.build()).isEqualToIgnoringWhitespace("String path = \"/test\";");
    builder = new CodeBuilder();
    this.builder.buildPath(builder, "/test/:id", Map.of("id", 0));
    assertThat(builder.build()).contains("builder.append(\"/test/\").append(core.framework.internal.web.service.PathParamHelper.toString(param0));");
    builder = new CodeBuilder();
    this.builder.buildPath(builder, "/:id/status", Map.of("id", 0));
    assertThat(builder.build()).contains("builder.append(\"/\").append(core.framework.internal.web.service.PathParamHelper.toString(param0));").contains("builder.append(\"/status\");");
    builder = new CodeBuilder();
    this.builder.buildPath(builder, "/test/:key1/:key2", Map.of("key1", 0, "key2", 1));
    assertThat(builder.build()).contains("builder.append(\"/test/\").append(core.framework.internal.web.service.PathParamHelper.toString(param0));").contains("builder.append(\"/\").append(core.framework.internal.web.service.PathParamHelper.toString(param1));");
    builder = new CodeBuilder();
    this.builder.buildPath(builder, "/test/:key1/:key2/", Map.of("key1", 0, "key2", 1));
    assertThat(builder.build()).contains("builder.append(\"/test/\").append(core.framework.internal.web.service.PathParamHelper.toString(param0));").contains("builder.append(\"/\").append(core.framework.internal.web.service.PathParamHelper.toString(param1));").contains("builder.append(\"/\");");
}
Also used : CodeBuilder(core.framework.internal.asm.CodeBuilder) Test(org.junit.jupiter.api.Test)

Example 14 with CodeBuilder

use of core.framework.internal.asm.CodeBuilder in project core-ng-project by neowu.

the class WebServiceClientBuilder method buildImplMethod.

private String buildImplMethod(Method method) {
    var builder = new CodeBuilder();
    Type returnType = method.getGenericReturnType();
    Class<?> returnClass = method.getReturnType();
    Map<String, Integer> pathParamIndexes = Maps.newHashMap();
    Class<?> requestBeanClass = null;
    Integer requestBeanIndex = null;
    builder.append("public {} {}(", type(returnClass), method.getName());
    Annotation[][] annotations = method.getParameterAnnotations();
    Class<?>[] parameterTypes = method.getParameterTypes();
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> paramClass = parameterTypes[i];
        if (i > 0)
            builder.append(", ");
        builder.append("{} param{}", type(paramClass), i);
        PathParam pathParam = Params.annotation(annotations[i], PathParam.class);
        if (pathParam != null) {
            pathParamIndexes.put(pathParam.value(), i);
        } else {
            requestBeanIndex = i;
            requestBeanClass = paramClass;
        }
    }
    builder.append(") {\n");
    builder.indent(1).append("client.logCallWebService({});\n", variable(Methods.path(method)));
    buildPath(builder, method.getDeclaredAnnotation(Path.class).value(), pathParamIndexes);
    builder.indent(1).append("Class requestBeanClass = {};\n", requestBeanClass == null ? "null" : variable(requestBeanClass));
    builder.indent(1).append("Object requestBean = {};\n", requestBeanIndex == null ? "null" : "param" + requestBeanIndex);
    builder.indent(1);
    if (returnType != void.class)
        builder.append("return ({}) ", type(returnClass));
    builder.append("client.execute({}, path, requestBeanClass, requestBean, {});\n", variable(HTTPMethods.httpMethod(method)), variable(returnType));
    builder.append("}");
    return builder.build();
}
Also used : Type(java.lang.reflect.Type) PathParam(core.framework.api.web.service.PathParam) CodeBuilder(core.framework.internal.asm.CodeBuilder)

Example 15 with CodeBuilder

use of core.framework.internal.asm.CodeBuilder in project core-ng-project by neowu.

the class UpdateQueryBuilder method updateMethod.

private String updateMethod(Class<T> entityClass, List<Field> primaryKeyFields, List<Field> columnFields) {
    var builder = new CodeBuilder();
    String entityClassLiteral = type(entityClass);
    builder.append("public {} update(Object value, boolean partial, String where, Object[] whereParams) {\n", type(UpdateQuery.Statement.class)).indent(1).append("{} entity = ({}) value;\n", entityClassLiteral, entityClassLiteral);
    for (Field primaryKeyField : primaryKeyFields) {
        builder.indent(1).append("if (entity.{} == null) throw new Error(\"primary key must not be null, field={}\");\n", primaryKeyField.getName(), primaryKeyField.getName());
    }
    builder.indent(1).append("StringBuilder sql = new StringBuilder(\"UPDATE {} SET \");\n", entityClass.getDeclaredAnnotation(Table.class).name());
    builder.indent(1).append("java.util.List params = new java.util.ArrayList();\n");
    builder.indent(1).append("int index = 0;\n");
    for (Field field : columnFields) {
        builder.indent(1).append("if (!partial || entity.{} != null) {\n", field.getName()).indent(2).append("if (index > 0) sql.append(\", \");\n").indent(2).append("sql.append(\"{} = ?\");\n", field.getDeclaredAnnotation(Column.class).name()).indent(2).append("params.add(entity.{});\n", field.getName()).indent(2).append("index++;\n").indent(1).append("}\n");
    }
    builder.indent(1).append("sql.append(\"");
    int index = 0;
    for (Field primaryKeyField : primaryKeyFields) {
        if (index == 0) {
            builder.append(" WHERE ");
        } else {
            builder.append(" AND ");
        }
        builder.append("{} = ?", primaryKeyField.getDeclaredAnnotation(Column.class).name());
        index++;
    }
    builder.append("\");\n");
    for (Field primaryKeyField : primaryKeyFields) {
        builder.indent(1).append("params.add(entity.{});\n", primaryKeyField.getName());
    }
    builder.indent(1).append("if (where != null) {\n").indent(2).append("sql.append(\" AND (\").append(where).append(')');\n").indent(2).append("for (int i = 0; i< whereParams.length; i++) params.add(whereParams[i]);\n").indent(1).append("}\n");
    builder.indent(1).append("return new {}(sql.toString(), params.toArray());\n", type(UpdateQuery.Statement.class)).append("}");
    return builder.build();
}
Also used : Field(java.lang.reflect.Field) CodeBuilder(core.framework.internal.asm.CodeBuilder)

Aggregations

CodeBuilder (core.framework.internal.asm.CodeBuilder)22 Field (java.lang.reflect.Field)9 Type (java.lang.reflect.Type)4 Column (core.framework.db.Column)3 ArrayList (java.util.ArrayList)3 PathParam (core.framework.api.web.service.PathParam)2 QueryParam (core.framework.api.web.service.QueryParam)2 PrimaryKey (core.framework.db.PrimaryKey)2 LocalDate (java.time.LocalDate)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ErrorCause (co.elastic.clients.elasticsearch._types.ErrorCause)1 BulkResponseItem (co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem)1 NotNull (core.framework.api.validate.NotNull)1 ResponseStatus (core.framework.api.web.service.ResponseStatus)1 Table (core.framework.db.Table)1 SearchException (core.framework.search.SearchException)1 Request (core.framework.web.Request)1 Response (core.framework.web.Response)1 ActionDocument (core.log.domain.ActionDocument)1