com.github.javaparser.ast.expr.SimpleName Java Examples

The following examples show how to use com.github.javaparser.ast.expr.SimpleName. 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: ProcessesContainerGenerator.java    From kogito-runtimes with 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 #2
Source File: LocationSearcher.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("try")
private static Location getFieldLocation(
    SearchContext context, File targetFile, FieldDeclaration declaration) throws IOException {

  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("LocationSearcher.getFieldLocation")) {

    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder().put("targetFile", targetFile.getPath()).build("args"));

    final List<VariableDeclarator> variables = declaration.getVariables();
    for (final VariableDeclarator variable : variables) {
      final SimpleName simpleName = variable.getName();
      final String name = simpleName.getIdentifier();
      final Optional<Position> begin = simpleName.getBegin();
      if (name.equals(context.name) && begin.isPresent()) {
        final Position position = begin.get();
        return new Location(targetFile.getCanonicalPath(), position.line, position.column);
      }
    }
    return null;
  }
}
 
Example #3
Source File: CodegenUtils.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static void interpolateTypes(ClassOrInterfaceType t, String dataClazzName) {
    SimpleName returnType = t.getName();
    Map<String, String> interpolatedTypes = new HashMap<>();
    interpolatedTypes.put("$Type$", dataClazzName);
    interpolateTypes(returnType, interpolatedTypes);
    t.getTypeArguments().ifPresent(ta -> interpolateTypeArguments(ta, interpolatedTypes));
}
 
Example #4
Source File: CodegenUtils.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static void interpolateTypes(SimpleName returnType, Map<String, String> typeInterpolations) {
    typeInterpolations.entrySet().stream().forEach(entry -> {
        String identifier = returnType.getIdentifier();
        String newIdentifier = identifier.replace(entry.getKey(), entry.getValue());
        returnType.setIdentifier(newIdentifier);
    });
}
 
Example #5
Source File: PersistenceGenerator.java    From kogito-runtimes with 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 #6
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
protected ClassOrInterfaceType simpleParametricType(String className, String... typeArgs) {
    NodeList<Type> typeArguments = new NodeList<Type>();
    for (String typeArg : typeArgs) {
        typeArguments.add(classType(typeArg));
    }
    return new ClassOrInterfaceType(null, new SimpleName(className), typeArguments);
}
 
Example #7
Source File: AbstractResourceGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void interpolateUserTaskTypes(SimpleName returnType, String inputClazzName, String outputClazzName) {
    String identifier = returnType.getIdentifier();

    returnType.setIdentifier(identifier.replace("$TaskInput$", inputClazzName));

    identifier = returnType.getIdentifier();
    returnType.setIdentifier(identifier.replace("$TaskOutput$", outputClazzName));
}
 
Example #8
Source File: ParameterNameVisitor.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
  super.visit(n, arg);
  NodeList<Modifier> modifiers = n.getModifiers();
  if (!modifiers.contains(Modifier.privateModifier())) {
    final List<BodyDeclaration<?>> members = n.getMembers();
    final SimpleName simpleName = n.getName();
    final String clazz = simpleName.getId();
    // String clazz = n.getName();
    this.className = this.pkg + '.' + clazz;
    log.debug("class {}", this.className);
    int i = 0;
    for (final BodyDeclaration<?> body : members) {
      if (body instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) body;
        this.getParameterNames(methodDeclaration, n.isInterface());
        i++;
      } else if (body instanceof ConstructorDeclaration) {
        // Constructor
      } else if (body instanceof ClassOrInterfaceDeclaration) {
        final ClassOrInterfaceDeclaration classOrInterfaceDeclaration =
            (ClassOrInterfaceDeclaration) body;
        String name = classOrInterfaceDeclaration.getName().getIdentifier();
        String key = this.pkg + '.' + name;
        name = this.originClassName + '.' + name;
        for (MethodParameterNames mpn : this.parameterNamesList) {
          if (mpn != null && mpn.className != null && mpn.className.equals(key)) {
            mpn.className = name;
          }
        }
      }
    }

    if (i > 0 && this.names.className != null) {
      this.parameterNamesList.add(this.names);
      this.names = new MethodParameterNames();
    }
  }
}
 
Example #9
Source File: CodegenUtils.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public static void interpolateTypes(ClassOrInterfaceType t, Map<String, String> typeInterpolations) {
    SimpleName returnType = t.getName();
    interpolateTypes(returnType, typeInterpolations);
    t.getTypeArguments().ifPresent(ta -> interpolateTypeArguments(ta, typeInterpolations));
}
 
Example #10
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(SimpleName n, Void arg) {
    out.println("SimpleName: " + (extended ? n : n.getIdentifier()));
    super.visit(n, arg);
}
 
Example #11
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void visit(SimpleName n, Void arg) {
    printer.print(n.getIdentifier());
}
 
Example #12
Source File: UserTaskModelMetaData.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
private CompilationUnit compilationUnitOutput() {
    CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream("/class-templates/TaskOutputTemplate.java"));
    compilationUnit.setPackageDeclaration(packageName);
    Optional<ClassOrInterfaceDeclaration> processMethod = compilationUnit.findFirst(ClassOrInterfaceDeclaration.class, sl1 -> true);

    if (!processMethod.isPresent()) {
        throw new RuntimeException("Cannot find class declaration in the template");
    }
    ClassOrInterfaceDeclaration modelClass = processMethod.get();
    compilationUnit.addOrphanComment(new LineComment("Task output model for user task '" + humanTaskNode.getName() + "' in process '" + processId + "'"));
    addUserTaskAnnotation(modelClass);
    modelClass.setName(outputModelClassSimpleName);

    // setup of the toMap method body
    BlockStmt toMapBody = new BlockStmt();
    ClassOrInterfaceType toMap = new ClassOrInterfaceType(null, new SimpleName(Map.class.getSimpleName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getSimpleName()), new ClassOrInterfaceType(
                                                                                                                                                                                                                    null,
                                                                                                                                                                                                                    Object.class.getSimpleName())));
    VariableDeclarationExpr paramsField = new VariableDeclarationExpr(toMap, "params");
    toMapBody.addStatement(new AssignExpr(paramsField, new ObjectCreationExpr(null, new ClassOrInterfaceType(null, HashMap.class.getSimpleName()), NodeList.nodeList()), AssignExpr.Operator.ASSIGN));

    for (Entry<String, String> entry : humanTaskNode.getOutMappings().entrySet()) {
        if (entry.getValue() == null || INTERNAL_FIELDS.contains(entry.getKey())) {
            continue;
        }

        Variable variable = Optional.ofNullable(variableScope.findVariable(entry.getValue()))
                .orElse(processVariableScope.findVariable(entry.getValue()));

        if (variable == null) {
            // check if given mapping is an expression
            Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(entry.getValue());
            if (matcher.find()) {
                Map<String, String> dataOutputs = (Map<String, String>) humanTaskNode.getMetaData("DataOutputs");
                variable = new Variable();
                variable.setName(entry.getKey());
                variable.setType(new ObjectDataType(dataOutputs.get(entry.getKey())));
            } else {
                throw new IllegalStateException("Task " + humanTaskNode.getName() +" (output) " + entry.getKey() + " reference not existing variable " + entry.getValue());
            }
        }

        FieldDeclaration fd = new FieldDeclaration().addVariable(
                                                                 new VariableDeclarator()
                                                                                         .setType(variable.getType().getStringType())
                                                                                         .setName(entry.getKey()))
                                                    .addModifier(Modifier.Keyword.PRIVATE);
        modelClass.addMember(fd);
        addUserTaskParamAnnotation(fd, UserTaskParam.ParamType.OUTPUT);

        fd.createGetter();
        fd.createSetter();

        // toMap method body
        MethodCallExpr putVariable = new MethodCallExpr(new NameExpr("params"), "put");
        putVariable.addArgument(new StringLiteralExpr(entry.getKey()));
        putVariable.addArgument(new FieldAccessExpr(new ThisExpr(), entry.getKey()));
        toMapBody.addStatement(putVariable);
    }

    Optional<MethodDeclaration> toMapMethod = modelClass.findFirst(MethodDeclaration.class, sl -> sl.getName().asString().equals("toMap"));

    toMapBody.addStatement(new ReturnStmt(new NameExpr("params")));
    toMapMethod.ifPresent(methodDeclaration -> methodDeclaration.setBody(toMapBody));
    return compilationUnit;
}
 
Example #13
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private void interpolateMethods(MethodDeclaration m) {
    SimpleName methodName = m.getName();
    String interpolated = methodName.asString().replace("$name$", decisionName);
    m.setName(interpolated);
}
 
Example #14
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/DMNRestResourceTemplate.java"));
    clazz.setPackageDeclaration(this.packageName);

    ClassOrInterfaceDeclaration template = clazz
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));

    template.setName(resourceClazzName);

    template.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);
    template.findAll(MethodDeclaration.class).forEach(this::interpolateMethods);

    interpolateInputType(template);

    if (useInjection()) {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd));
    } else {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(this::initializeApplicationField);
    }

    MethodDeclaration dmnMethod = template.findAll(MethodDeclaration.class, x -> x.getName().toString().equals("dmn")).get(0);
    for (DecisionService ds : dmnModel.getDefinitions().getDecisionService()) {
        if (ds.getAdditionalAttributes().keySet().stream().anyMatch(qn -> qn.getLocalPart().equals("dynamicDecisionService"))) {
            continue;
        }

        MethodDeclaration clonedMethod = dmnMethod.clone();
        String name = CodegenStringUtil.escapeIdentifier("decisionService_" + ds.getName());
        clonedMethod.setName(name);
        MethodCallExpr evaluateCall = clonedMethod.findFirst(MethodCallExpr.class, x -> x.getNameAsString().equals("evaluateAll")).orElseThrow(() -> new RuntimeException("Template was modified!"));
        evaluateCall.setName(new SimpleName("evaluateDecisionService"));
        evaluateCall.addArgument(new StringLiteralExpr(ds.getName()));
        clonedMethod.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.ws.rs.Path"), new StringLiteralExpr("/" + ds.getName())));
        ReturnStmt returnStmt = clonedMethod.findFirst(ReturnStmt.class).orElseThrow(() -> new RuntimeException("Template was modified!"));
        if (ds.getOutputDecision().size() == 1) {
            MethodCallExpr rewrittenReturnExpr = returnStmt.findFirst(MethodCallExpr.class,
                                                                      mce -> mce.getNameAsString().equals("extractContextIfSucceded"))
                                                           .orElseThrow(() -> new RuntimeException("Template was modified!"));
            rewrittenReturnExpr.setName("extractSingletonDSIfSucceded");
        }

        if (useMonitoring) {
            addMonitoringToMethod(clonedMethod, ds.getName());
        }

        template.addMember(clonedMethod);
    }

    if (useMonitoring) {
        addMonitoringImports(clazz);
        ClassOrInterfaceDeclaration exceptionClazz = clazz.findFirst(ClassOrInterfaceDeclaration.class, x -> "DMNEvaluationErrorExceptionMapper".equals(x.getNameAsString()))
                .orElseThrow(() -> new NoSuchElementException("Could not find DMNEvaluationErrorExceptionMapper, template has changed."));
        addExceptionMetricsLogging(exceptionClazz, nameURL);
        addMonitoringToMethod(dmnMethod, nameURL);
    }

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example #15
Source File: AbstractResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private void interpolateUserTaskTypes(ClassOrInterfaceType t, String inputClazzName, String outputClazzName) {
    SimpleName returnType = t.asClassOrInterfaceType().getName();
    interpolateUserTaskTypes(returnType, inputClazzName, outputClazzName);
    t.getTypeArguments().ifPresent(o -> interpolateUserTaskTypeArguments(o, inputClazzName, outputClazzName));
}
 
Example #16
Source File: AbstractResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private void interpolateMethods(MethodDeclaration m) {
    SimpleName methodName = m.getName();
    String interpolated =
            methodName.asString().replace("$name$", processName);
    m.setName(interpolated);
}
 
Example #17
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 2 votes vote down vote up
/**
 * 
 * @param p the parameter to modify
 * @param t the name of class or interface
 * @param name the name of the variable
 */
private void setParameter(List<Parameter> ps, int i, String t, String name) {
  Parameter p = ps.get(i);
  p.setType(new ClassOrInterfaceType(t));
  p.setName(new SimpleName(name));
}