Java Code Examples for com.github.javaparser.ast.NodeList

The following examples show how to use com.github.javaparser.ast.NodeList. These examples are extracted from open source projects. 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 Project: impsort-maven-plugin   Author: revelc   File: ImpSort.java    License: Apache License 2.0 7 votes vote down vote up
private static Set<String> tokensInUse(CompilationUnit unit) {

    // Extract tokens from the java code:
    Stream<Node> packageDecl =
        unit.getPackageDeclaration().isPresent()
            ? Stream.of(unit.getPackageDeclaration().get()).map(PackageDeclaration::getAnnotations)
                .flatMap(NodeList::stream)
            : Stream.empty();
    Stream<String> typesInCode = Stream.concat(packageDecl, unit.getTypes().stream())
        .map(Node::getTokenRange).filter(Optional::isPresent).map(Optional::get)
        .filter(r -> r != TokenRange.INVALID).flatMap(r -> {
          // get all JavaTokens as strings from each range
          return StreamSupport.stream(r.spliterator(), false);
        }).map(JavaToken::asString);

    // Extract referenced class names from parsed javadoc comments:
    Stream<String> typesInJavadocs = unit.getAllComments().stream()
        .filter(c -> c instanceof JavadocComment).map(JavadocComment.class::cast)
        .map(JavadocComment::parse).flatMap(ImpSort::parseJavadoc);

    return Stream.concat(typesInCode, typesInJavadocs)
        .filter(t -> t != null && !t.isEmpty() && Character.isJavaIdentifierStart(t.charAt(0)))
        .collect(Collectors.toSet());
  }
 
Example #2
Source Project: molicode   Author: cn2oo8   File: SourceCodeProcessHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(FieldDeclaration n, Void arg) {
    if (n.isFinal() || n.isStatic()) {
        return;
    }
    NodeList<VariableDeclarator> nodeList = n.getVariables();
    for (VariableDeclarator declarator : nodeList) {
        FieldInfoDto fieldInfoDto = new FieldInfoDto();
        fieldInfoDto.setDataName(declarator.getNameAsString());
        fieldInfoDto.setFieldClass(declarator.getType().asString());

        Optional<Comment> commentOptional = n.getComment();
        if (commentOptional.isPresent()) {
            String commentContent = commentOptional.get().getContent();
            commentContent = commentContent.replaceAll("\\*", "");
            fieldInfoDto.setComment(commentContent.trim());
        } else {
            fieldInfoDto.setComment(fieldInfoDto.getDataName());
        }
        sourceCodeDto.addField(fieldInfoDto);
    }
    sourceCodeDto.addFieldDeclaration(n);
    super.visit(n, arg);
}
 
Example #3
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new ObjectCreationExpr()
                    .setType(processInstanceFQCN)
                    .setArguments(NodeList.nodeList(
                            new ThisExpr(),
                            new NameExpr("value"),
                            createProcessRuntime())));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #4
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new ObjectCreationExpr()
                    .setType(processInstanceFQCN)
                    .setArguments(NodeList.nodeList(
                            new ThisExpr(),
                            new NameExpr("value"),
                            new NameExpr(BUSINESS_KEY),
                            createProcessRuntime())));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #5
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessesContainerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public ProcessesContainerGenerator(String packageName) {
    super("Processes", "processes", Processes.class);
    this.packageName = packageName;
    this.processes = new ArrayList<>();
    this.factoryMethods = new ArrayList<>();
    this.applicationDeclarations = new NodeList<>();

    byProcessIdMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processById")
            .setType(new ClassOrInterfaceType(null, org.kie.kogito.process.Process.class.getCanonicalName())
                             .setTypeArguments(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName()))))
            .setBody(new BlockStmt())
            .addParameter("String", "processId");

    processesMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processIds")
            .setType(new ClassOrInterfaceType(null, Collection.class.getCanonicalName())
                             .setTypeArguments(new ClassOrInterfaceType(null, "String")))
            .setBody(new BlockStmt());

    applicationDeclarations.add(byProcessIdMethodDeclaration);
    applicationDeclarations.add(processesMethodDeclaration);
}
 
Example #6
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessesContainerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CompilationUnit injectableClass() {
    CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream(RESOURCE)).setPackageDeclaration(packageName);                        
    ClassOrInterfaceDeclaration cls = compilationUnit
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));
    
    cls.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("processes")).forEach(fd -> {
        annotator.withInjection(fd);
        fd.getVariable(0).setType(new ClassOrInterfaceType(null, new SimpleName(annotator.multiInstanceInjectionType()), 
                                                           NodeList.nodeList(new ClassOrInterfaceType(null, new SimpleName(org.kie.kogito.process.Process.class.getCanonicalName()), NodeList.nodeList(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName())))))));
    });
    
    annotator.withApplicationComponent(cls);
    
    return compilationUnit;
}
 
Example #7
Source Project: groovy   Author: apache   File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void setConstructorOrMethodCommon(CallableDeclaration<? extends CallableDeclaration<?>> n, SimpleGroovyExecutableMemberDoc methOrCons) {
    n.getJavadocComment().ifPresent(javadocComment ->
            methOrCons.setRawCommentText(javadocComment.getContent()));
    NodeList<Modifier> mods = n.getModifiers();
    if (currentClassDoc.isInterface()) {
        mods.add(Modifier.publicModifier());
    }
    setModifiers(mods, methOrCons);
    processAnnotations(methOrCons, n);
    for (Parameter param : n.getParameters()) {
        SimpleGroovyParameter p = new SimpleGroovyParameter(param.getNameAsString());
        processAnnotations(p, param);
        p.setType(makeType(param.getType()));
        methOrCons.add(p);
    }
}
 
Example #8
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private BlockStmt wrapBodyAddingExceptionLogging(BlockStmt body, String nameURL) {
    TryStmt ts = new TryStmt();
    ts.setTryBlock(body);
    CatchClause cc = new CatchClause();
    String exceptionName = "e";
    cc.setParameter(new Parameter().setName(exceptionName).setType(Exception.class));
    BlockStmt cb = new BlockStmt();
    cb.addStatement(parseStatement(
            String.format(
                    "SystemMetricsCollector.registerException(\"%s\", %s.getStackTrace()[0].toString());",
                    nameURL,
                    exceptionName)
    ));
    cb.addStatement(new ThrowStmt(new NameExpr(exceptionName)));
    cc.setBody(cb);
    ts.setCatchClauses(new NodeList<>(cc));
    return new BlockStmt(new NodeList<>(ts));
}
 
Example #9
Source Project: kogito-runtimes   Author: kiegroup   File: RuleConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedRuleEventListenerConfig.class,
            callMerge(
                    VAR_RULE_EVENT_LISTENER_CONFIGS,
                    RuleEventListenerConfig.class, "agendaListeners",
                    VAR_AGENDA_EVENT_LISTENERS
            ),
            callMerge(
                    VAR_RULE_EVENT_LISTENER_CONFIGS,
                    RuleEventListenerConfig.class, "ruleRuntimeListeners",
                    VAR_RULE_RUNTIME_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, RuleEventListenerConfig.class, METHOD_MERGE_RULE_EVENT_LISTENER_CONFIG,
            NodeList.nodeList(
                    new Parameter().setType(genericType(Collection.class, RuleEventListenerConfig.class)).setName(VAR_RULE_EVENT_LISTENER_CONFIGS),
                    new Parameter().setType(genericType(Collection.class, AgendaEventListener.class)).setName(VAR_AGENDA_EVENT_LISTENERS),
                    new Parameter().setType(genericType(Collection.class, RuleRuntimeEventListener.class)).setName(VAR_RULE_RUNTIME_EVENT_LISTENERS)
            ),
            body);
}
 
Example #10
Source Project: kogito-runtimes   Author: kiegroup   File: DecisionContainerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Statement> setupStatements() {
    return Collections.singletonList(
            new IfStmt(
                    new BinaryExpr(
                            new MethodCallExpr(new MethodCallExpr(null, "config"), "decision"),
                            new NullLiteralExpr(),
                            BinaryExpr.Operator.NOT_EQUALS
                    ),
                    new BlockStmt().addStatement(new ExpressionStmt(new MethodCallExpr(
                            new NameExpr("decisionModels"), "init", NodeList.nodeList(new ThisExpr())
                    ))),
                    null
            )
    );
}
 
Example #11
Source Project: kogito-runtimes   Author: kiegroup   File: RuleSetNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleRuleFlowGroup(RuleSetNode.RuleType ruleType) {
    // build supplier for rule runtime
    BlockStmt actionBody = new BlockStmt();
    LambdaExpr lambda = new LambdaExpr(new Parameter(new UnknownType(), "()"), actionBody);

    MethodCallExpr ruleRuntimeBuilder = new MethodCallExpr(
            new MethodCallExpr(new NameExpr("app"), "ruleUnits"), "ruleRuntimeBuilder");
    MethodCallExpr ruleRuntimeSupplier = new MethodCallExpr(
            ruleRuntimeBuilder, "newKieSession",
            NodeList.nodeList(new StringLiteralExpr("defaultStatelessKieSession"), new NameExpr("app.config().rule()")));
    actionBody.addStatement(new ReturnStmt(ruleRuntimeSupplier));

    return new MethodCallExpr("ruleFlowGroup")
            .addArgument(new StringLiteralExpr(ruleType.getName()))
            .addArgument(lambda);

}
 
Example #12
Source Project: groovy   Author: apache   File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void setModifiers(NodeList<Modifier> modifiers, SimpleGroovyAbstractableElementDoc elementDoc) {
    if (modifiers.contains(Modifier.publicModifier())) {
        elementDoc.setPublic(true);
    }
    if (modifiers.contains(Modifier.staticModifier())) {
        elementDoc.setStatic(true);
    }
    if (modifiers.contains(Modifier.abstractModifier())) {
        elementDoc.setAbstract(true);
    }
    if (modifiers.contains(Modifier.finalModifier())) {
        elementDoc.setFinal(true);
    }
    if (modifiers.contains(Modifier.protectedModifier())) {
        elementDoc.setProtected(true);
    }
    if (modifiers.contains(Modifier.privateModifier())) {
        elementDoc.setPrivate(true);
    }
}
 
Example #13
Source Project: groovy   Author: apache   File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private SimpleGroovyClassDoc visit(TypeDeclaration<?> n) {
    SimpleGroovyClassDoc parent = null;
    List<String> imports = getImports();
    String name = n.getNameAsString();
    if (n.isNestedType()) {
        parent = currentClassDoc;
        name = parent.name() + "$" + name;
    }
    currentClassDoc = new SimpleGroovyClassDoc(imports, aliases, name.replace('$', '.'), links);
    NodeList<Modifier> mods = n.getModifiers();
    if (parent != null) {
        parent.addNested(currentClassDoc);
        if (parent.isInterface()) {
            // an inner interface/class within an interface is public
            mods.add(Modifier.publicModifier());
        }
    }
    setModifiers(mods, currentClassDoc);
    processAnnotations(currentClassDoc, n);
    currentClassDoc.setFullPathName(withSlashes(packagePath + FS + name));
    classDocs.put(currentClassDoc.getFullPathName(), currentClassDoc);
    n.getJavadocComment().ifPresent(javadocComment ->
            currentClassDoc.setRawCommentText(javadocComment.getContent()));
    return parent;
}
 
Example #14
Source Project: JRemapper   Author: Col-E   File: ParserTypeUtil.java    License: MIT License 6 votes vote down vote up
/**
 * @param md
 *            JavaParser method declaration.
 * @return Internal descriptor from declaration, or {@code null} if any parsing
 *         failures occured.
 */
private static String getMethodDesc(MethodDeclaration md) {
	StringBuilder sbDesc = new StringBuilder("(");
	// Append the method parameters for the descriptor
	NodeList<Parameter> params = md.getParameters();
	for (Parameter param : params) {
		Type pType = param.getType();
		String pDesc = getDescriptor(pType);
		if (pDesc == null)
			return null;
		sbDesc.append(pDesc);
	}
	// Append the return type for the descriptor
	Type typeRet = md.getType();
	String retDesc = getDescriptor(typeRet);
	if (retDesc == null)
		return null;
	sbDesc.append(")");
	sbDesc.append(retDesc);
	return sbDesc.toString();
}
 
Example #15
Source Project: butterfly   Author: paypal   File: Extends.java    License: MIT License 6 votes vote down vote up
@Override
protected String getTypeName(CompilationUnit compilationUnit, int index) {
    ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
    NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes();
    ClassOrInterfaceType extendedType = extendedTypes.get(index);
    String typeSimpleName = extendedType.getName().getIdentifier();
    Optional<ClassOrInterfaceType> scope = extendedType.getScope();
    String typeName;
    if (scope.isPresent()) {
        String typePackageName = scope.get().toString();
        typeName = String.format("%s.%s", typePackageName, typeSimpleName);
    } else {
        typeName = typeSimpleName;
    }
    return typeName;
}
 
Example #16
Source Project: Recaf   Author: Col-E   File: JavaParserUtil.java    License: MIT License 6 votes vote down vote up
/**
 * @param md
 *            JavaParser method declaration.
 * @return Internal descriptor from declaration, or {@code null} if any parsing
 *         failures occured.
 */
public static String getDescriptor(MethodDeclaration md) {
	StringBuilder sbDesc = new StringBuilder("(");
	// Append the method parameters for the descriptor
	NodeList<Parameter> params = md.getParameters();
	for (Parameter param : params) {
		Type pType = param.getType();
		String pDesc = getDescriptor(pType);
		if (pDesc == null)
			return null;
		sbDesc.append(pDesc);
	}
	// Append the return type for the descriptor
	Type typeRet = md.getType();
	String retDesc = getDescriptor(typeRet);
	if (retDesc == null)
		return null;
	sbDesc.append(")");
	sbDesc.append(retDesc);
	return sbDesc.toString();
}
 
Example #17
Source Project: molicode   Author: cn2oo8   File: JavaParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    CompilationUnit compilationUnit = new CompilationUnit();
    ClassOrInterfaceDeclaration myClass = compilationUnit
            .addClass("MyClass")
            .setPublic(true);
    myClass.addField(int.class, "A_CONSTANT", PUBLIC, STATIC);
    myClass.addField(String.class, "name", PRIVATE);
    Comment comment= new JavadocComment();
    comment.setContent("你大爷!");
    myClass.addMethod("helloWorld", PUBLIC).setParameters(NodeList.nodeList()).setComment(comment);
    String code = myClass.toString();
    System.out.println(code);
}
 
Example #18
Source Project: kogito-runtimes   Author: kiegroup   File: ConfigGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodCallExpr callMerge(String configsName, Class<?> configToListenersScope, String configToListenersIdentifier, String listenersName) {
    return new MethodCallExpr(null, "merge", NodeList.nodeList(
            new NameExpr(configsName),
            new MethodReferenceExpr(
                    new TypeExpr(new ClassOrInterfaceType(null, configToListenersScope.getCanonicalName())),
                    null,
                    configToListenersIdentifier
            ),
            new NameExpr(listenersName)
    ));
}
 
Example #19
Source Project: kogito-runtimes   Author: kiegroup   File: CDIDependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Expression getMultiInstance(String fieldName) {
    return new MethodCallExpr(
            new MethodCallExpr(new NameExpr("java.util.stream.StreamSupport"), "stream", NodeList.nodeList(
                    new MethodCallExpr(new NameExpr(fieldName), "spliterator"),
                    new BooleanLiteralExpr(false)
            )),
            "collect",
            NodeList.nodeList(
                    new MethodCallExpr(new NameExpr("java.util.stream.Collectors"), "toList")
            )
    );
}
 
Example #20
Source Project: kogito-runtimes   Author: kiegroup   File: CDIDependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey) {
    node.addAnnotation(new NormalAnnotationExpr(
            new Name("org.eclipse.microprofile.config.inject.ConfigProperty"),
            NodeList.nodeList(
                    new MemberValuePair("name", new StringLiteralExpr(configKey))
            )
    ));
    return node;
}
 
Example #21
Source Project: kogito-runtimes   Author: kiegroup   File: CDIDependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey, String defaultValue) {
    node.addAnnotation(new NormalAnnotationExpr(
            new Name("org.eclipse.microprofile.config.inject.ConfigProperty"),
            NodeList.nodeList(
                    new MemberValuePair("name", new StringLiteralExpr(configKey)),
                    new MemberValuePair("defaultValue", new StringLiteralExpr(defaultValue))
            )
    ));
    return node;
}
 
Example #22
Source Project: kogito-runtimes   Author: kiegroup   File: DependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Annotates given node with set of roles to enforce security
 *
 * @param node  node to be annotated
 * @param roles roles that are allowed
 */
default <T extends NodeWithAnnotations<?>> T withSecurityRoles(T node, String[] roles) {
    if (roles != null && roles.length > 0) {
        List<Expression> rolesExpr = new ArrayList<>();

        for (String role : roles) {
            rolesExpr.add(new StringLiteralExpr(role.trim()));
        }

        node.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.annotation.security.RolesAllowed"), new ArrayInitializerExpr(NodeList.nodeList(rolesExpr))));
    }
    return node;
}
 
Example #23
Source Project: jaxrs-analyzer   Author: sdaschner   File: JavaDocParserVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private MemberParameterTag createMethodParameterTag(JavadocBlockTag tag, MethodDeclaration method) {
    Stream<AnnotationExpr> annotations = method.getParameterByName(tag.getName().orElse(null))
            .map(Parameter::getAnnotations)
            .map(NodeList::stream)
            .orElseGet(Stream::empty);

    return createMemberParamTag(tag.getContent(), annotations);
}
 
Example #24
Source Project: kogito-runtimes   Author: kiegroup   File: CodegenUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodDeclaration method(Modifier.Keyword modifier, Class<?> type, String name, NodeList<Parameter> parameters, BlockStmt body) {
    return new MethodDeclaration()
            .setModifiers(modifier)
            .setType(type == null ? "void" : type.getCanonicalName())
            .setName(name)
            .setParameters(parameters)
            .setBody(body);
}
 
Example #25
Source Project: kogito-runtimes   Author: kiegroup   File: PersistenceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected void fileSystemBasedPersistence(List<GeneratedFile> generatedFiles) {
	ClassOrInterfaceDeclaration persistenceProviderClazz = new ClassOrInterfaceDeclaration()
            .setName("KogitoProcessInstancesFactoryImpl")
            .setModifiers(Modifier.Keyword.PUBLIC)
            .addExtendedType("org.kie.kogito.persistence.KogitoProcessInstancesFactory");
    
    CompilationUnit compilationUnit = new CompilationUnit("org.kie.kogito.persistence");            
    compilationUnit.getTypes().add(persistenceProviderClazz);                 
    
    if (useInjection()) {
        annotator.withApplicationComponent(persistenceProviderClazz);            
        
        FieldDeclaration pathField = new FieldDeclaration().addVariable(new VariableDeclarator()
                                                                                 .setType(new ClassOrInterfaceType(null, new SimpleName(Optional.class.getCanonicalName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getCanonicalName()))))
                                                                                 .setName(PATH_NAME));
        annotator.withConfigInjection(pathField, KOGITO_PERSISTENCE_FS_PATH_PROP);
        // allow to inject path for the file system storage
        BlockStmt pathMethodBody = new BlockStmt();                
        pathMethodBody.addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(PATH_NAME), "orElse").addArgument(new StringLiteralExpr("/tmp"))));
        
        MethodDeclaration pathMethod = new MethodDeclaration()
                .addModifier(Keyword.PUBLIC)
                .setName(PATH_NAME)
                .setType(String.class)                                
                .setBody(pathMethodBody);
        
        persistenceProviderClazz.addMember(pathField);
        persistenceProviderClazz.addMember(pathMethod);
    }
    
    String packageName = compilationUnit.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
    String clazzName = packageName + "." + persistenceProviderClazz.findFirst(ClassOrInterfaceDeclaration.class).map(c -> c.getName().toString()).get();
 
    generatedFiles.add(new GeneratedFile(GeneratedFile.Type.CLASS,
                                         clazzName.replace('.', '/') + ".java",
                                         compilationUnit.toString().getBytes(StandardCharsets.UTF_8))); 
    
    persistenceProviderClazz.getMembers().sort(new BodyDeclarationComparator());
}
 
Example #26
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessesContainerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public void addProcessToApplication(ProcessGenerator r) {
    ObjectCreationExpr newProcess = new ObjectCreationExpr()
            .setType(r.targetCanonicalName())
            .addArgument("application");
    IfStmt byProcessId = new IfStmt(new MethodCallExpr(new StringLiteralExpr(r.processId()), "equals", NodeList.nodeList(new NameExpr("processId"))),
                                    new ReturnStmt(new MethodCallExpr(
                                            newProcess,
                                            "configure")),
                                    null);

    byProcessIdMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(byProcessId);
}
 
Example #27
Source Project: JCTools   Author: JCTools   File: JavaParsingAtomicLinkedQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void replaceParentClassesForAtomics(NodeList<ClassOrInterfaceType> types) {
    for (ClassOrInterfaceType parent : types) {
        if ("BaseLinkedQueue".equals(parent.getNameAsString())) {
            parent.setName("BaseLinkedAtomicQueue");
        } else {
            // Padded super classes are to be renamed and thus so does the
            // class we must extend.
            parent.setName(translateQueueName(parent.getNameAsString()));
        }
    }
}
 
Example #28
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessConfigGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration generateExtractEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), METHOD_MERGE_PROCESS_EVENT_LISTENER_CONFIG, NodeList.nodeList(
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENER_CONFIGS),
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENERS)
            ))
    ));

    return method(Modifier.Keyword.PRIVATE, ProcessEventListenerConfig.class, METHOD_EXTRACT_PROCESS_EVENT_LISTENER_CONFIG, body);
}
 
Example #29
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void addMonitoringToResource(CompilationUnit cu, MethodDeclaration[] methods, String nameURL) {
    cu.addImport(new ImportDeclaration(new Name("org.kie.kogito.monitoring.system.metrics.SystemMetricsCollector"), false, false));

    for (MethodDeclaration md : methods) {
        BlockStmt body = md.getBody().orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"));
        NodeList<Statement> statements = body.getStatements();
        ReturnStmt returnStmt = body.findFirst(ReturnStmt.class).orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a return statement!"));
        statements.addFirst(parseStatement("double startTime = System.nanoTime();"));
        statements.addBefore(parseStatement("double endTime = System.nanoTime();"), returnStmt);
        statements.addBefore(parseStatement("SystemMetricsCollector.registerElapsedTimeSampleMetrics(\"" + nameURL + "\", endTime - startTime);"), returnStmt);
        md.setBody(wrapBodyAddingExceptionLogging(body, nameURL));
    }
}
 
Example #30
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateResultClass(ClassOrInterfaceDeclaration clazz, MethodDeclaration toResultMethod) {
    ClassOrInterfaceDeclaration resultClass = new ClassOrInterfaceDeclaration(new NodeList<Modifier>(Modifier.publicModifier(), Modifier.staticModifier()), false, "Result");
    clazz.addMember(resultClass);

    ConstructorDeclaration constructor = resultClass.addConstructor(Modifier.Keyword.PUBLIC);
    BlockStmt constructorBody = constructor.createBody();

    ObjectCreationExpr resultCreation = new ObjectCreationExpr();
    resultCreation.setType("Result");
    BlockStmt resultMethodBody = toResultMethod.createBody();
    resultMethodBody.addStatement(new ReturnStmt(resultCreation));

    query.getBindings().forEach((name, type) -> {
        resultClass.addField(type, name, Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL);

        MethodDeclaration getterMethod = resultClass.addMethod("get" + ucFirst(name), Modifier.Keyword.PUBLIC);
        getterMethod.setType(type);
        BlockStmt body = getterMethod.createBody();
        body.addStatement(new ReturnStmt(new NameExpr(name)));

        constructor.addAndGetParameter(type, name);
        constructorBody.addStatement(new AssignExpr(new NameExpr("this." + name), new NameExpr(name), AssignExpr.Operator.ASSIGN));

        MethodCallExpr callExpr = new MethodCallExpr(new NameExpr("tuple"), "get");
        callExpr.addArgument(new StringLiteralExpr(name));
        resultCreation.addArgument(new CastExpr(classToReferenceType(type), callExpr));
    });
}