javaparser

How could I insert a statement before try statement in method using github.parser


I am using Com.GitHub.java parser for generating java code. i am facing a problem . problem is :

I have need bellow output . This line "String result = null;" need to show before try statement . But it is showing inside of try statement.

My Source code: https://pastebin.mozilla.org/McXbnU7w

Maven dependency:

<!-- https://mvnrepository.com/artifact/com.github.javaparser/javaparser-core -->
<dependency>
  <groupId>com.github.javaparser</groupId>
  <artifactId>javaparser-core</artifactId>
  <version>3.24.4</version>
</dependency>

Expected output of my code:

public Response saveProduct(ProductDto productDto) throws ServletException, IOException {
String result = null;
try {
createMyProduct.setProduct(productDto.getProduct());
createMyProduct.execute(parameterMap);
result = createMyProduct.getResult();

    } catch (BusinessException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity(result).build();
    }

Solution

  • You need to add as many blocks as you need. E.g. String result = null should be treated as a separate block and try block should be another block. You cannot shove all statements in one block. Also in addingException method, you are adding try block into another BlockStmt. That is not needed. It will put extra curly braces. Here is updated code:

    import java.io.IOException;
    
    import com.github.javaparser.ast.CompilationUnit;
    import com.github.javaparser.ast.Modifier;
    import com.github.javaparser.ast.NodeList;
    import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
    import com.github.javaparser.ast.body.MethodDeclaration;
    import com.github.javaparser.ast.body.Parameter;
    import com.github.javaparser.ast.expr.MethodCallExpr;
    import com.github.javaparser.ast.expr.NameExpr;
    import com.github.javaparser.ast.expr.StringLiteralExpr;
    import com.github.javaparser.ast.stmt.BlockStmt;
    import com.github.javaparser.ast.stmt.CatchClause;
    import com.github.javaparser.ast.stmt.EmptyStmt;
    import com.github.javaparser.ast.stmt.ExpressionStmt;
    import com.github.javaparser.ast.stmt.ReturnStmt;
    import com.github.javaparser.ast.stmt.Statement;
    import com.github.javaparser.ast.stmt.TryStmt;
    import com.github.javaparser.ast.type.ClassOrInterfaceType;
    
    public class ProductCreate2 {
    
      public static void main(String[] args) {
        CompilationUnit compilationUnit = new CompilationUnit();
        compilationUnit.setPackageDeclaration("org.meveo.mymodule.resource");
        compilationUnit.addImport("java.util", false, true);
    
        ClassOrInterfaceDeclaration restEndpointClass = compilationUnit.addClass("ProductCreate",Modifier.Keyword.PUBLIC);
        restEndpointClass.addField("CreateMyProduct", "createMyProduct", Modifier.Keyword.PRIVATE);
    
        NodeList<ClassOrInterfaceType> extendsList = new NodeList<>();
        extendsList.add(new ClassOrInterfaceType("CustomEndpointResource"));
        restEndpointClass.setExtendedTypes(extendsList);
    
        MethodDeclaration restMethod = restEndpointClass.addMethod("saveProduct", Modifier.Keyword.PUBLIC);
        restMethod.addParameter("ProductDto", "productDto");
        restMethod.setType("Response");
        restMethod.addAndGetAnnotation("POST");
        restMethod.addThrownException(IOException.class);
        //restMethod.addThrownException(ServletException.class);
        //restMethod.getBody().get().getStatements().add(new ExpressionStmt(new NameExpr("String result = null")));
        //restMethod.createBody().addStatement(new ExpressionStmt(new NameExpr("String result = // null")));
            
    
    
        BlockStmt blockStmt = new BlockStmt();
    
    
        blockStmt.addStatement(new ExpressionStmt(new NameExpr("String result = null")));
    
        BlockStmt blockStmt1 = new BlockStmt();
        blockStmt1.addStatement(new MethodCallExpr(new NameExpr("createMyProduct"), "setProduct").addArgument("productDto.getProduct()"));
        blockStmt1.addStatement(new MethodCallExpr(new NameExpr("createMyProduct"), "init").addArgument("parameterMap"));
        blockStmt1.addStatement(new MethodCallExpr(new NameExpr("createMyProduct"), "execute").addArgument("parameterMap"));
        blockStmt1.addStatement(new MethodCallExpr(new NameExpr("createMyProduct"), "finalize").addArgument("parameterMap"));
        blockStmt1.addStatement(new MethodCallExpr(new NameExpr("createMyProduct"), "getResult()"));
    
        Statement blockStmt2 =addingException(blockStmt1);
        blockStmt.addStatement(blockStmt2);
    
        restMethod.setBody(blockStmt);
    
        restMethod.getBody().get().getStatements().add(new ReturnStmt(new NameExpr("Response.status(Response.Status.OK).entity(result).build()")));
    
        System.out.println(compilationUnit);
    
      }
    
      private static Statement addingException(BlockStmt body) {
        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(new ExpressionStmt(new NameExpr("return Response.status(Response.Status.BAD_REQUEST).entity(result).build()")));
        // cb.addStatement(new ThrowStmt(new NameExpr(exceptionName)));
        cc.setBody(cb);
        ts.setCatchClauses(new NodeList<>(cc));
        return ts;
      }
    
    }