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

The following examples show how to use com.github.javaparser.ast.expr.FieldAccessExpr. 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: PrintStatement.java    From TestSmellDetector with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        // if the name of a method being called is 'print' or 'println' or 'printf' or 'write'
        if (n.getNameAsString().equals("print") || n.getNameAsString().equals("println") || n.getNameAsString().equals("printf") || n.getNameAsString().equals("write")) {
            //check the scope of the method & proceed only if the scope is "out"
            if ((n.getScope().isPresent() &&
                    n.getScope().get() instanceof FieldAccessExpr &&
                    (((FieldAccessExpr) n.getScope().get())).getNameAsString().equals("out"))) {

                FieldAccessExpr f1 = (((FieldAccessExpr) n.getScope().get()));

                //check the scope of the field & proceed only if the scope is "System"
                if ((f1.getScope() != null &&
                        f1.getScope() instanceof NameExpr &&
                        ((NameExpr) f1.getScope()).getNameAsString().equals("System"))) {
                    //a print statement exists in the method body
                    printCount++;
                }
            }

        }
    }
}
 
Example #2
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 #3
Source File: DecisionContainerGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodCallExpr getReadResourceMethod( ClassOrInterfaceType applicationClass, DMNResource resource ) {
    String source = resource.getDmnModel().getResource().getSourcePath();
    Path sourcePath = Paths.get(source);
    if (resource.getPath().toString().endsWith( ".jar" )) {
        return new MethodCallExpr( new NameExpr( IoUtils.class.getCanonicalName() ), "readFileInJar" )
                .addArgument(new StringLiteralExpr(resource.getPath().toString()))
                .addArgument(new StringLiteralExpr(source));
    }
    Path relativizedPath = resource.getPath().relativize(sourcePath);
    String resourcePath = "/" + relativizedPath.toString().replace( File.separatorChar, '/');
    return new MethodCallExpr(new FieldAccessExpr(applicationClass.getNameAsExpression(), "class"), "getResourceAsStream")
            .addArgument(new StringLiteralExpr(resourcePath));
}
 
Example #4
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 FieldAccessExpr n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    if (n.getScope().isPresent())
        n.getScope().get().accept(this, arg);
    printer.print(".");
    n.getName().accept(this, arg);
}
 
Example #5
Source File: FieldAccessExprMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public FieldAccessExpr doMerge(FieldAccessExpr first, FieldAccessExpr second) {
  FieldAccessExpr fae = new FieldAccessExpr();

  fae.setFieldExpr(mergeSingle(first.getFieldExpr(),second.getFieldExpr()));
  fae.setScope(mergeSingle(first.getScope(),second.getScope()));
  fae.setTypeArgs(mergeCollections(first.getTypeArgs(),second.getTypeArgs()));

  return fae;
}
 
Example #6
Source File: FieldAccessExprMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public boolean doIsEquals(FieldAccessExpr first, FieldAccessExpr second) {

    if(!isEqualsUseMerger(first.getScope(), second.getScope())) return false;
    if(!isEqualsUseMerger(first.getTypeArgs(),second.getTypeArgs())) return false;
    if(!isEqualsUseMerger(first.getFieldExpr(),second.getFieldExpr())) return false;

    return true;
  }
 
Example #7
Source File: JavaparserTest.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
  CompilationUnit cu = new CompilationUnit();
  // set the package
  cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr("java.parser.test")));

  // create the type declaration
  ClassOrInterfaceDeclaration type = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, "GeneratedClass");
  ASTHelper.addTypeDeclaration(cu, type);

  // create a method
  MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "main");
  method.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.STATIC));
  ASTHelper.addMember(type, method);

  // add a parameter to the method
  Parameter param = ASTHelper.createParameter(ASTHelper.createReferenceType("String", 0), "args");
  param.setVarArgs(true);
  ASTHelper.addParameter(method, param);

  // add a body to the method
  BlockStmt block = new BlockStmt();
  method.setBody(block);

  // add a statement do the method body
  NameExpr clazz = new NameExpr("System");
  FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
  MethodCallExpr call = new MethodCallExpr(field, "println");
  ASTHelper.addArgument(call, new StringLiteralExpr("Hello World!"));
  ASTHelper.addStmt(block, call);

  unit = cu;
}
 
Example #8
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(FieldAccessExpr n, Void arg) {
    super.visit(n, arg);
    if (n.getScope() instanceof NameExpr) {
        NameExpr name = (NameExpr) n.getScope();
        name.setName(translateQueueName(name.getNameAsString()));
    }
}
 
Example #9
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
   * Visitor for if stmts
   *   - removes feature missing test
   */
  @Override
  public void visit(IfStmt n, Object ignore) {
    do {
      // if (get_set_method == null) break;  // sometimes, these occur outside of recogn. getters/setters
      
      Expression c = n.getCondition(), e;
      BinaryExpr be, be2; 
      List<Statement> stmts;
      if ((c instanceof BinaryExpr) &&
          ((be = (BinaryExpr)c).getLeft() instanceof FieldAccessExpr) &&
          ((FieldAccessExpr)be.getLeft()).getNameAsString().equals("featOkTst")) {
        // remove the feature missing if statement
        
        // verify the remaining form 
        if (! (be.getRight() instanceof BinaryExpr) 
         || ! ((be2 = (BinaryExpr)be.getRight()).getRight() instanceof NullLiteralExpr) 
         || ! (be2.getLeft() instanceof FieldAccessExpr)

         || ! ((e = getExpressionFromStmt(n.getThenStmt())) instanceof MethodCallExpr)
         || ! (((MethodCallExpr)e).getNameAsString()).equals("throwFeatMissing")) {
          reportDeletedCheckModified("The featOkTst was modified:\n" + n.toString() + '\n');
        }
              
        BlockStmt parent = (BlockStmt) n.getParentNode().get();
        stmts = parent.getStatements();
        stmts.set(stmts.indexOf(n), new EmptyStmt()); //dont remove
                                            // otherwise iterators fail
//        parent.getStmts().remove(n);
        return;
      }
    } while (false);
    
    super.visit(n,  ignore);
  }
 
Example #10
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Get the name of a field
 * @param e -
 * @return the field name or null
 */
private String getName(Expression e) {
  e = getUnenclosedExpr(e);
  if (e instanceof NameExpr) {
    return ((NameExpr)e).getNameAsString();
  }
  if (e instanceof FieldAccessExpr) {
    return ((FieldAccessExpr)e).getNameAsString();
  }
  return null;
}
 
Example #11
Source File: RuleUnitContainerGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public ClassOrInterfaceDeclaration classDeclaration() {

    NodeList<BodyDeclaration<?>> declarations = new NodeList<>();

    // declare field `application`
    FieldDeclaration applicationFieldDeclaration = new FieldDeclaration();
    applicationFieldDeclaration
            .addVariable( new VariableDeclarator( new ClassOrInterfaceType(null, "Application"), "application") )
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    declarations.add(applicationFieldDeclaration);

    ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration("RuleUnits")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter( "Application", "application" )
            .setBody( new BlockStmt().addStatement( "this.application = application;" ) );
    declarations.add(constructorDeclaration);

    // declare field `ruleRuntimeBuilder`
    FieldDeclaration kieRuntimeFieldDeclaration = new FieldDeclaration();
    kieRuntimeFieldDeclaration
            .addVariable(new VariableDeclarator( new ClassOrInterfaceType(null, KieRuntimeBuilder.class.getCanonicalName()), "ruleRuntimeBuilder")
            .setInitializer(new ObjectCreationExpr().setType(ProjectSourceClass.PROJECT_RUNTIME_CLASS)))
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    declarations.add(kieRuntimeFieldDeclaration);

    // declare method ruleRuntimeBuilder()
    MethodDeclaration methodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("ruleRuntimeBuilder")
            .setType(KieRuntimeBuilder.class.getCanonicalName())
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new FieldAccessExpr(new ThisExpr(), "ruleRuntimeBuilder"))));
    declarations.add(methodDeclaration);

    declarations.addAll(factoryMethods);
    declarations.add(genericFactoryById());

    ClassOrInterfaceDeclaration cls = super.classDeclaration()
            .setMembers(declarations);

    cls.getMembers().sort(new BodyDeclarationComparator());

    return cls;
}
 
Example #12
Source File: KieModuleModelMethod.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private void createEnum( BlockStmt stmt, Expression expr, String enumType, String enumName, String enumSetter) {
    String sessionType = enumType + "." + enumName;
    FieldAccessExpr sessionTypeEnum = parseExpression(sessionType);
    stmt.addStatement(new MethodCallExpr(expr, enumSetter, nodeList(sessionTypeEnum)));
}
 
Example #13
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 #14
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(FieldAccessExpr n, Void arg) {
    out.println("FieldAccessExpr: " + (extended ? n : n.getNameAsString()));
    super.visit(n, arg);
}