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

The following examples show how to use com.github.javaparser.ast.expr.CastExpr. 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: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceGenericWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance")
            .addArgument(new NameExpr(BUSINESS_KEY))
            .addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #2
Source File: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private String getReturnType(ClassOrInterfaceDeclaration clazz) {
    MethodDeclaration toResultMethod = clazz.getMethodsByName("toResult").get(0);
    String returnType;
    if (query.getBindings().size() == 1) {
        Map.Entry<String, Class<?>> binding = query.getBindings().entrySet().iterator().next();
        String name = binding.getKey();
        returnType = binding.getValue().getCanonicalName();

        Statement statement = toResultMethod
                .getBody()
                .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
                .getStatement(0);

        statement.findFirst(CastExpr.class).orElseThrow(() -> new NoSuchElementException("CastExpr not found in template.")).setType(returnType);
        statement.findFirst(StringLiteralExpr.class).orElseThrow(() -> new NoSuchElementException("StringLiteralExpr not found in template.")).setString(name);
    } else {
        returnType = "Result";
        generateResultClass(clazz, toResultMethod);
    }

    toResultMethod.setType(returnType);
    return returnType;
}
 
Example #3
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
   * visitor for field access expressions
   *   - convert ((...type_Type)jcasType).casFeatCode_XXXX to _FI_xxx
   * @param n -
   * @param ignore -
   */
  @Override
  public void visit(FieldAccessExpr n, Object ignore) {
    Expression e;
    Optional<Expression> oe;
    String nname = n.getNameAsString();
    
    if (get_set_method != null) {  
      if (nname.startsWith("casFeatCode_") &&
          ((oe = n.getScope()).isPresent()) &&
          ((e = getUnenclosedExpr(oe.get())) instanceof CastExpr) &&
          ("jcasType".equals(getName(((CastExpr)e).getExpression())))) {
        String featureName = nname.substring("casFeatCode_".length());
//        replaceInParent(n, new NameExpr("_FI_" + featureName)); // repl last in List<Expression> (args)
        
        MethodCallExpr getint = new MethodCallExpr(null, "wrapGetIntCatchException");
        getint.addArgument(new NameExpr("_FH_" + featureName));
        replaceInParent(n, getint);
        
        return;
      } else if (nname.startsWith("casFeatCode_")) {
        reportMigrateFailed("Found field casFeatCode_ ... without a previous cast expr using jcasType");
      }
    }
    super.visit(n,  ignore);      
  }
 
Example #4
Source File: TriggerMetaData.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static LambdaExpr buildLambdaExpr(Node node, ProcessMetaData metadata) {
    Map<String, Object> nodeMetaData = node.getMetaData();
    TriggerMetaData triggerMetaData = new TriggerMetaData(
            (String) nodeMetaData.get(TRIGGER_REF),
            (String) nodeMetaData.get(TRIGGER_TYPE),
            (String) nodeMetaData.get(MESSAGE_TYPE),
            (String) nodeMetaData.get(MAPPING_VARIABLE),
            String.valueOf(node.getId()))
            .validate();
    metadata.getTriggers().add(triggerMetaData);

    // and add trigger action
    BlockStmt actionBody = new BlockStmt();
    CastExpr variable = new CastExpr(
            new ClassOrInterfaceType(null, triggerMetaData.getDataType()),
            new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getVariable")
                    .addArgument(new StringLiteralExpr(triggerMetaData.getModelRef())));
    MethodCallExpr producerMethodCall = new MethodCallExpr(new NameExpr("producer_" + node.getId()), "produce").addArgument(new MethodCallExpr(new NameExpr("kcontext"), "getProcessInstance")).addArgument(variable);
    actionBody.addStatement(producerMethodCall);
    return new LambdaExpr(
            new Parameter(new UnknownType(), KCONTEXT_VAR), // (kcontext) ->
            actionBody
    );
}
 
Example #5
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private void addCastExpr(Statement stmt, Type castType) {
  ReturnStmt rstmt = (ReturnStmt) stmt;
  Optional<Expression> o_expr = rstmt.getExpression(); 
  Expression expr = o_expr.isPresent() ? o_expr.get() : null;
  CastExpr ce = new CastExpr(castType, expr);
  rstmt.setExpression(ce);  // removes the parent link from expr
  if (expr != null) {
    expr.setParentNode(ce); // restore it
  }
}
 
Example #6
Source File: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodDeclaration createInstanceGenericMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance").addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #7
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(CastExpr n, Void arg) {
    super.visit(n, arg);

    if (isRefArray(n.getType(), "E")) {
        n.setType(atomicRefArrayType((ArrayType) n.getType()));
    }
}
 
Example #8
Source File: CastExprMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public CastExpr doMerge(CastExpr first, CastExpr second) {
  CastExpr ce = new CastExpr();
  ce.setType(mergeSingle(first.getType(),second.getType()));
  ce.setExpr(mergeSingle(first.getExpr(),second.getExpr()));

  return ce;
}
 
Example #9
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void visit(final CastExpr n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printer.print("(");
    n.getType().accept(this, arg);
    printer.print(") ");
    n.getExpression().accept(this, arg);
}
 
Example #10
Source File: ProcessContextMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Expression getVariable(String procVar) {
    String interpolatedVar = extractVariableFromExpression(procVar);
    Variable v = variableScope.findVariable(interpolatedVar);
    if (v == null) {
        throw new IllegalArgumentException("No such variable " + procVar);
    }
    MethodCallExpr getter = new MethodCallExpr().setScope(new NameExpr(kcontext))
            .setName("getVariable")
            .addArgument(new StringLiteralExpr(interpolatedVar));
    CastExpr castExpr = new CastExpr()
            .setExpression(new EnclosedExpr(getter))
            .setType(v.getType().getStringType());
    return castExpr;
}
 
Example #11
Source File: ModelMetaData.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public MethodCallExpr callSetter(String targetVar, String destField, Expression value) {
    String name = variableScope.getTypes().get(destField).getSanitizedName();
    String type = variableScope.getType(destField);
    String setter = "set" + StringUtils.capitalize(name); // todo cache FieldDeclarations in compilationUnit()
    return new MethodCallExpr(new NameExpr(targetVar), setter).addArgument(
            new CastExpr(
                    new ClassOrInterfaceType(null, type),
                    new EnclosedExpr(value)));
}
 
Example #12
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected Statement makeAssignmentFromModel(Variable v, String name) {
    ClassOrInterfaceType type = parseClassOrInterfaceType(v.getType().getStringType());
    // `type` `name` = (`type`) `model.get<Name>
    AssignExpr assignExpr = new AssignExpr(
            new VariableDeclarationExpr(type, name),
            new CastExpr(
                    type,
                    new MethodCallExpr(
                            new NameExpr("model"),
                            "get" + StringUtils.capitalize(name))),
            AssignExpr.Operator.ASSIGN);

    return new ExpressionStmt(assignExpr);
}
 
Example #13
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static Statement makeAssignment(String targetLocalVariable, Variable processVariable) {
    ClassOrInterfaceType type = parseClassOrInterfaceType(processVariable.getType().getStringType());
    // `type` `name` = (`type`) `kcontext.getVariable
    AssignExpr assignExpr = new AssignExpr(
            new VariableDeclarationExpr(type, targetLocalVariable),
            new CastExpr(
                    type,
                    new MethodCallExpr(
                            new NameExpr(KCONTEXT_VAR),
                            "getVariable")
                            .addArgument(new StringLiteralExpr(targetLocalVariable))),
            AssignExpr.Operator.ASSIGN);
    return new ExpressionStmt(assignExpr);
}
 
Example #14
Source File: QueryEndpointGenerator.java    From kogito-runtimes with 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));
    });
}
 
Example #15
Source File: ServiceTaskDescriptor.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String unqualifiedName = StaticJavaParser.parseName(mangledName).removeQualifier().asString();
    ClassOrInterfaceDeclaration cls = new ClassOrInterfaceDeclaration()
            .setName(unqualifiedName)
            .setModifiers(Modifier.Keyword.PUBLIC)
            .addImplementedType(WorkItemHandler.class.getCanonicalName());
    ClassOrInterfaceType serviceType = new ClassOrInterfaceType(null, interfaceName);
    FieldDeclaration serviceField = new FieldDeclaration()
            .addVariable(new VariableDeclarator(serviceType, "service"));
    cls.addMember(serviceField);

    // executeWorkItem method
    BlockStmt executeWorkItemBody = new BlockStmt();
    MethodDeclaration executeWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("executeWorkItem")
            .setBody(executeWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    MethodCallExpr callService = new MethodCallExpr(new NameExpr("service"), operationName);

    for (Map.Entry<String, String> paramEntry : parameters.entrySet()) {
        MethodCallExpr getParamMethod = new MethodCallExpr(new NameExpr("workItem"), "getParameter").addArgument(new StringLiteralExpr(paramEntry.getKey()));
        callService.addArgument(new CastExpr(new ClassOrInterfaceType(null, paramEntry.getValue()), getParamMethod));
    }
    MethodCallExpr completeWorkItem = completeWorkItem(executeWorkItemBody, callService);

    executeWorkItemBody.addStatement(completeWorkItem);

    // abortWorkItem method
    BlockStmt abortWorkItemBody = new BlockStmt();
    MethodDeclaration abortWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("abortWorkItem")
            .setBody(abortWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    // getName method
    MethodDeclaration getName = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(String.class)
            .setName("getName")
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new StringLiteralExpr(mangledName))));
    cls.addMember(executeWorkItem)
            .addMember(abortWorkItem)
            .addMember(getName);

    return cls;
}
 
Example #16
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(CastExpr n, Void arg) {
    out.println("CastExpr: " + (extended ? n : ""));
    super.visit(n, arg);
}
 
Example #17
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/** 
 * visitor for method calls
 */
@Override
public void visit(MethodCallExpr n, Object ignore) {
  Optional<Node> p1, p2, p3 = null; 
  Node updatedNode = null;
  NodeList<Expression> args;
  
  do {
    if (get_set_method == null) break;
   
    /** remove checkArraybounds statement **/
    if (n.getNameAsString().equals("checkArrayBounds") &&
        ((p1 = n.getParentNode()).isPresent() && p1.get() instanceof ExpressionStmt) &&
        ((p2 = p1.get().getParentNode()).isPresent() && p2.get() instanceof BlockStmt) &&
        ((p3 = p2.get().getParentNode()).isPresent() && p3.get() == get_set_method)) {
      NodeList<Statement> stmts = ((BlockStmt)p2.get()).getStatements();
      stmts.set(stmts.indexOf(p1.get()), new EmptyStmt());
      return;
    }
         
    // convert simpleCore expression ll_get/setRangeValue
    boolean useGetter = isGetter || isArraySetter;
    if (n.getNameAsString().startsWith("ll_" + (useGetter ? "get" : "set") + rangeNameV2Part + "Value")) {
      args = n.getArguments();
      if (args.size() != (useGetter ? 2 : 3)) break;
      String suffix = useGetter ? "Nc" : rangeNamePart.equals("Feature") ? "NcWj" : "Nfc";
      String methodName = "_" + (useGetter ? "get" : "set") + rangeNamePart + "Value" + suffix; 
      args.remove(0);    // remove the old addr arg
      // arg 0 converted when visiting args FieldAccessExpr 
      n.setScope(null);
      n.setName(methodName);
    }
    
    // convert array sets/gets
    String z = "ll_" + (isGetter ? "get" : "set");
    String nname = n.getNameAsString();
    if (nname.startsWith(z) &&
        nname.endsWith("ArrayValue")) {
      
      String s = nname.substring(z.length());
      s = s.substring(0,  s.length() - "Value".length()); // s = "ShortArray",  etc.
      if (s.equals("RefArray")) s = "FSArray";
      if (s.equals("IntArray")) s = "IntegerArray";
      EnclosedExpr ee = new EnclosedExpr(
          new CastExpr(new ClassOrInterfaceType(s), n.getArguments().get(0)));
      
      n.setScope(ee);    // the getter for the array fs
      n.setName(isGetter ? "get" : "set");
      n.getArguments().remove(0);
    }
    
    /** remove ll_getFSForRef **/
    /** remove ll_getFSRef **/
    if (n.getNameAsString().equals("ll_getFSForRef") ||
        n.getNameAsString().equals("ll_getFSRef")) {
      updatedNode = replaceInParent(n, n.getArguments().get(0));        
    }
    
    
    
  } while (false);
      
  if (updatedNode != null) {
    updatedNode.accept(this,  null);
  } else {
    super.visit(n, null);
  }
}
 
Example #18
Source File: CastExprMerger.java    From dolphin with Apache License 2.0 3 votes vote down vote up
@Override public boolean doIsEquals(CastExpr first, CastExpr second) {

    if(!isEqualsUseMerger(first.getType(),second.getType())) return false;
    if(!isEqualsUseMerger(first.getExpr(),second.getExpr())) return false;

    return true;
  }