@Override
  public StringBuilder visitDefinition_function(
      @NotNull SiddhiQLParser.Definition_functionContext ctx) {
    StringBuilder functionText = new StringBuilder(" {  \"Function\":  ");

    functionText
        .append("  [{ \"functionName\":\"")
        .append(ctx.function_name().getText())
        .append("\",");
    functionText.append("\"languageName\":\"").append(ctx.language_name().getText()).append("\",");

    functionText
        .append("\"attributeType\":\"")
        .append(ctx.attribute_type().getText())
        .append("\",");
    String functionBody =
        excapeCode(
            tokenStreamRewriter
                .getTokenStream()
                .getText(ctx.function_body().getStart(), ctx.function_body().getStop()));
    functionText.append("\"functionBody\":\"").append(functionBody).append("\",");
    ;
    String function_Text =
        excapeCode(tokenStreamRewriter.getTokenStream().getText(ctx.getStart(), ctx.getStop()));
    functionText.append("\"functionText\":\"").append(function_Text).append("\",");

    functionText = new StringBuilder(functionText.substring(0, functionText.length() - 1));
    functionText.append(" }]}");

    return functionText;
  }
  @Override
  public StringBuilder visitQuery(@NotNull SiddhiQLParser.QueryContext ctx) {
    StringBuilder queryText = new StringBuilder(" {  \"Query\": [{ ");

    if (ctx.annotation().isEmpty()) {
      queryText.append(" \"annotationElement\":\"").append("query").append("\",");
    } else {
      queryText
          .append("\"annotationElement\":\"")
          .append(ctx.annotation().get(0).annotation_element().get(0).property_value().getText())
          .append("\",");
    }

    queryText.append("\"inputStream\":").append(visit(ctx.query_input())).append(",");

    if (ctx.query_section() != null) {
      queryText.append("\"selection\":\"").append(ctx.query_section().getText()).append("\",");
    }

    queryText.append("\"outputStream\":").append(visit(ctx.query_output())).append(",");

    String q_Text =
        excapeCode(tokenStreamRewriter.getTokenStream().getText(ctx.getStart(), ctx.getStop()));
    queryText.append("\"query_Text\":\"").append(q_Text).append("\",");

    queryText = new StringBuilder(queryText.substring(0, queryText.length() - 1));
    queryText.append(" }]}");

    return queryText;
  }
  @Override
  public StringBuilder visitPartition(@NotNull SiddhiQLParser.PartitionContext ctx) {
    StringBuilder partitionText = new StringBuilder(" { \"Partition\":  ");

    for (SiddhiQLParser.Partition_with_streamContext with_streamContext :
        ctx.partition_with_stream()) {
      String pw_Text =
          excapeCode(
              tokenStreamRewriter
                  .getTokenStream()
                  .getText(with_streamContext.getStart(), with_streamContext.getStop()));
      partitionText.append("  [{  \"Partition_with_Text\":\"").append(pw_Text).append("\", ");
    }

    for (SiddhiQLParser.Partition_with_streamContext with_streamContext :
        ctx.partition_with_stream()) {
      partitionText.append(visitPartition_with_stream(with_streamContext));
    }

    partitionText.append(" \"Query_size\":").append(ctx.query().size()).append(",");

    for (int i = 0; i < ctx.query().size(); i++) {
      SiddhiQLParser.QueryContext queryContext = ctx.query().get(i);
      partitionText
          .append("\"Query_" + i + "\" : [")
          .append(visitQuery(queryContext))
          .append("], ");
    }
    String p_Text =
        excapeCode(tokenStreamRewriter.getTokenStream().getText(ctx.getStart(), ctx.getStop()));
    partitionText.append(" \"Partition_Text\":\"").append(p_Text).append("\",");

    partitionText = new StringBuilder(partitionText.substring(0, partitionText.length() - 1));
    partitionText.append(" }]}");

    return partitionText;
  }
  @Override
  public StringBuilder visitDefinition_table(@NotNull SiddhiQLParser.Definition_tableContext ctx) {
    StringBuilder tableText = new StringBuilder(" { \"Table\":  ");

    tableText
        .append("  [{ \"tableId\":\"")
        .append(ctx.source().stream_id().getText())
        .append("\",");

    String table_Text =
        excapeCode(tokenStreamRewriter.getTokenStream().getText(ctx.getStart(), ctx.getStop()));
    tableText.append(" \"table_Text\":\"").append(table_Text).append("\",");
    tableText = new StringBuilder(tableText.substring(0, tableText.length() - 1));
    tableText.append(" }]}");

    return tableText;
  }
  @Override
  public StringBuilder visitDefinition_stream(
      @NotNull SiddhiQLParser.Definition_streamContext ctx) {

    StringBuilder streamText = new StringBuilder("  {\"Stream\":  ");

    streamText
        .append("  [{ \"streamId\":\"")
        .append(ctx.source().stream_id().getText())
        .append("\" ,");

    String stream_Text =
        excapeCode(tokenStreamRewriter.getTokenStream().getText(ctx.getStart(), ctx.getStop()));
    streamText.append(" \"stream_Text\":\"").append(stream_Text).append("\" ,");

    if (ctx.annotation().isEmpty()) {
      streamText.append(" \"annoName\": ").append("null").append(" ,");
      streamText.append(" \"annoElement\": ").append("null").append(" ,");
    } else {
      for (SiddhiQLParser.AnnotationContext annotationContext : ctx.annotation()) {
        streamText
            .append(" \"annoName\":\"")
            .append(annotationContext.name().getText())
            .append("\" ,");
        if (annotationContext.annotation_element().isEmpty()) {
          streamText.append(" \"annoElement\": ").append("null").append(" ,");
        } else {
          for (SiddhiQLParser.Annotation_elementContext elementContext :
              annotationContext.annotation_element()) {
            streamText
                .append(" \"annoElement\":\"")
                .append(elementContext.property_value().getText())
                .append("\" ,");
          }
        }
      }
    }
    streamText = new StringBuilder(streamText.substring(0, streamText.length() - 1));
    streamText.append(" }]}");

    return streamText;
  }
  @Override
  public StringBuilder visitPartition_with_stream(
      @NotNull SiddhiQLParser.Partition_with_streamContext ctx) {
    StringBuilder partitionWith = new StringBuilder(" \"PartitionWith\": [{  ");

    partitionWith
        .append(" \"Partition_Stream\":\"")
        .append(ctx.stream_id().getText())
        .append("\", ");

    List<String> condition = new ArrayList<String>();
    List<String> attribute = new ArrayList<String>();

    if (ctx.condition_ranges() != null) {
      for (SiddhiQLParser.Condition_rangeContext context :
          ctx.condition_ranges().condition_range()) {
        condition.add(
            "\""
                + excapeCode(
                    tokenStreamRewriter
                        .getTokenStream()
                        .getText(context.expression().getStart(), context.expression().getStop()))
                + "\"");
        attribute.add("\"" + context.string_value().getText() + "\"");
      }
      partitionWith.append(" \"condition\":").append(condition).append(", ");
      partitionWith.append(" \"attribute\":").append(attribute).append(" ");

    } else if (ctx.attribute() != null) {
      condition.add("null");
      attribute.add("\"" + ctx.attribute().getText() + "\"");
      partitionWith.append(" \"condition\":").append(condition).append(", ");
      partitionWith.append(" \"attribute\":").append(attribute).append("  ");
    }
    partitionWith = new StringBuilder(partitionWith.substring(0, partitionWith.length() - 1));
    partitionWith.append(" }],");

    return partitionWith;
  }
  @Override
  public StringBuilder visitDefinition_trigger(
      @NotNull SiddhiQLParser.Definition_triggerContext ctx) {
    StringBuilder triggerText = new StringBuilder(" {  \"Trigger\":  ");

    triggerText
        .append("  [{ \"triggerName\":\"")
        .append(ctx.trigger_name().getText())
        .append("\",");
    if (ctx.time_value() != null) {
      triggerText.append(" \"triggerValue\":\"").append(ctx.time_value().getText()).append("\",");
    } else {
      triggerText.append(" \"triggerValue\":\"").append(ctx.string_value().getText()).append("\",");
    }
    String trigger_text =
        excapeCode(tokenStreamRewriter.getTokenStream().getText(ctx.getStart(), ctx.getStop()));
    triggerText.append(" \"triggerText\":\"").append(trigger_text).append("\",");

    triggerText = new StringBuilder(triggerText.substring(0, triggerText.length() - 1));
    triggerText.append(" }]}");

    return triggerText;
  }
  @Override
  public void enterStatement(StatementContext ctx) {
    if (patternMatchedInMethod) {
      boolean isIfStmt = (ctx.getText().indexOf("if") == 0);

      for (String searchKeyword : searchPatterns) {

        if (patternMatchFlagsForMethod.get(searchKeyword) != null) {

          if (patternMatchFlagsForMethod.get(searchKeyword).booleanValue()) {

            if (isIfStmt) {

              conditionText.append("From statement handler" + "\n");
              conditionText.append("Line no==>" + ctx.start.getLine() + "\n");
              conditionText.append(
                  rewriter
                          .getText()
                          .substring(ctx.start.getStartIndex(), ctx.stop.getStopIndex() + 1)
                      + "\n");

              String actualPropertyValue = "";
              if (messageMap != null && messageMap.get(searchKeyword) != null) {
                actualPropertyValue = " [" + messageMap.get(searchKeyword) + "] ";
              }

              CodePart lastMatchingCodePart = lastMatchingIfForPattern.get(searchKeyword);

              if (lastMatchingCodePart != null) {

                if (lastMatchingCodePart.getBlockText().indexOf(ctx.getText()) == -1) {
                  if (lastMatchingCodePart.isElseIf()) {
                    List<CodePart> allMatchingIfStmts =
                        allMatchingIfStmtsForPattern.get(searchKeyword);
                    int length = allMatchingIfStmts.size();
                    for (int j = length - 1; j >= 0; j--) {
                      if (allMatchingIfStmts
                              .get(j)
                              .getBlockText()
                              .indexOf(lastMatchingCodePart.getBlockText())
                          > 0) {
                        patternText.append("MATCHING IFELSEIF START: " + searchKeyword + "\n");
                        if (actClassName != null && actMethodName != null) {
                          patternText.append("\nClass name==>" + actClassName + "\n");
                          patternText.append("Method name==>" + actMethodName + "\n");
                        }
                        System.out.println("MATCHING IF : " + searchKeyword + "\n");
                        // System.out.println(ifConditionList.get(j));

                        CommonUtils.addValueToTargetMap(
                            ruleID, allMatchingIfStmts.get(j), nearestMatchingIfsForPattern);

                        patternText.append(
                            "Line Number==>"
                                + tokens.get(allMatchingIfStmts.get(j).getStartIndex()).getLine()
                                + "\n");
                        System.out.println(
                            "Line Number==>"
                                + tokens.get(allMatchingIfStmts.get(j).getStartIndex()).getLine()
                                + "\n");

                        patternText.append(
                            tokens.getText(
                                    tokens.get(allMatchingIfStmts.get(j).getStartIndex()),
                                    tokens.get(allMatchingIfStmts.get(j).getEndIndex()))
                                + "\n");
                        System.out.println(
                            tokens.getText(
                                    tokens.get(allMatchingIfStmts.get(j).getStartIndex()),
                                    tokens.get(allMatchingIfStmts.get(j).getEndIndex()))
                                + "\n");
                        patternText.append("MATCHING IF END: " + searchKeyword + "\n");
                        break;
                      }
                    }

                  } else {

                    patternText.append("MATCHING IF START: " + searchKeyword + "\n");

                    CommonUtils.addValueToTargetMap(
                        ruleID, lastMatchingCodePart, nearestMatchingIfsForPattern);
                    if (actClassName != null && actMethodName != null) {
                      patternText.append("\nClass name==>" + actClassName + "\n");
                      patternText.append("Method name==>" + actMethodName + "\n");
                    }
                    System.out.println("MATCHING IF : " + searchKeyword + "\n");

                    patternText.append(
                        "Line Number==>"
                            + tokens.get(lastMatchingCodePart.getStartIndex()).getLine()
                            + "\n");

                    System.out.println(
                        "Line Number==>"
                            + tokens.get(lastMatchingCodePart.getStartIndex()).getLine()
                            + "\n");

                    patternText.append(
                        tokens.getText(
                                tokens.get(lastMatchingCodePart.getStartIndex()),
                                tokens.get(lastMatchingCodePart.getEndIndex()))
                            + "\n");

                    System.out.println(
                        tokens.getText(
                                tokens.get(lastMatchingCodePart.getStartIndex()),
                                tokens.get(lastMatchingCodePart.getEndIndex()))
                            + "\n");

                    patternText.append("MATCHING IF END: " + searchKeyword + "\n");
                  }
                  lastMatchingIfForPattern.put(searchKeyword, null);
                }
              }

              if (searchKeyword != null) {
                String keywordWOQuote = Pattern.quote(searchKeyword);
                pattern = Pattern.compile(keywordWOQuote, Pattern.CASE_INSENSITIVE);
                if (pattern.matcher(ctx.getText()).find()) {

                  CodePart codePart = null;
                  // We need to check for else closer to if
                  // condition
                  // TODO ( Last 3 tokens generally
                  // matches..Need to double check this )
                  StringBuffer strBufferToChkforElseIf = new StringBuffer();
                  for (int i = 3; i >= 1; i--) {
                    strBufferToChkforElseIf.append(
                        tokens.get(ctx.start.getTokenIndex() - i).getText());
                  }
                  String elseIfChkStr = strBufferToChkforElseIf.toString().trim();
                  System.out.println("elseIfChkStr-->" + elseIfChkStr);

                  codePart =
                      new CodePart(
                          ctx.start.getTokenIndex(),
                          ctx.stop.getTokenIndex(),
                          ctx.getText(),
                          false,
                          ctx.start.getLine());
                  codePart.setReadableText(tokens.getText(ctx));

                  if (elseIfChkStr.equals("else")) {

                    codePart.setElseIf(true);
                  } else {
                    CommonUtils.addValueToTargetMap(
                        searchKeyword, codePart, allMatchingIfStmtsForPattern);
                  }

                  lastMatchingIfForPattern.put(searchKeyword, codePart);
                }
              }
            } else {

              if (searchKeyword != null) {
                CodePart lastMatchingCodePart = lastMatchingIfForPattern.get(searchKeyword);

                if (lastMatchingCodePart != null
                    && lastMatchingCodePart.getBlockText().indexOf(ctx.getText()) == -1) {

                  patternText.append("MATCHING LAST IF START: " + searchKeyword + "\n");

                  CommonUtils.addValueToTargetMap(
                      ruleID, lastMatchingCodePart, nearestMatchingIfsForPattern);
                  if (actClassName != null && actMethodName != null) {
                    patternText.append("\nClass name==>" + actClassName + "\n");
                    patternText.append("Method name==>" + actMethodName + "\n");
                  }
                  System.out.println("MATCHING IF : " + searchKeyword + "\n");

                  patternText.append(
                      "Line Number==>"
                          + tokens.get(lastMatchingCodePart.getStartIndex()).getLine()
                          + "\n");

                  System.out.println(
                      "Line Number==>"
                          + tokens.get(lastMatchingCodePart.getStartIndex()).getLine()
                          + "\n");

                  patternText.append(
                      tokens.getText(
                              tokens.get(lastMatchingCodePart.getStartIndex()),
                              tokens.get(lastMatchingCodePart.getEndIndex()))
                          + "\n");

                  System.out.println(
                      tokens.getText(
                              tokens.get(lastMatchingCodePart.getStartIndex()),
                              tokens.get(lastMatchingCodePart.getEndIndex()))
                          + "\n");

                  patternText.append("MATCHING IF END: " + searchKeyword + "\n");

                  lastMatchingIfForPattern.put(searchKeyword, null);
                }
              }
            }
          }
        }
      }
    }
  }
  @Override
  public void enterMethodBody(MethodBodyContext ctx) {
    patternMatchFlagsForMethod = new HashMap<String, Boolean>();
    patternMatchedInMethod = false;

    lastMatchingIfForPattern = new HashMap<String, CodePart>();
    allMatchingIfStmtsForPattern = new HashMap<String, List<CodePart>>();
    nearestMatchingIfsForPattern = new HashMap<String, List<CodePart>>();

    if (searchPatterns != null) {
      String methodText =
          rewriter.getText().substring(ctx.start.getStartIndex(), ctx.stop.getStopIndex() + 1);

      if (methodText.toLowerCase().indexOf("processfacade") != -1
          || methodText.toLowerCase().indexOf("processdelegate") != -1) {
        conditionText.append(
            "\nProcessCalls References are found. Class : ["
                + className
                + "] Method :["
                + actMethodName
                + "]\n");
        patternText.append(
            "\nProcessCalls References are found. Class : ["
                + className
                + "] Method :["
                + actMethodName
                + "]\n");
        conditionText.append("Line Number==>" + ctx.start.getLine() + "\n");
        patternText.append("Line Number==>" + ctx.start.getLine() + "\n");
      }

      for (String searchKeyword : searchPatterns) {
        String actualPropertyValue = "";
        if (messageMap != null && messageMap.get(searchKeyword) != null) {
          actualPropertyValue = " [" + messageMap.get(searchKeyword) + "] ";
        }

        if (searchKeyword != null) {
          String keywordWOQuote = Pattern.quote(searchKeyword);
          pattern = Pattern.compile(keywordWOQuote, Pattern.CASE_INSENSITIVE);

          if (pattern.matcher(methodText).find()) {
            Matcher match = pattern.matcher(methodText);
            match.find();
            patternMatchedInMethod = true;
            patternMatchFlagsForMethod.put(searchKeyword, true);

            if (actClassName != null) {
              patternText.append("\nClass name==>" + actClassName + "\n");
              actClassName = null;
            }
            if (actMethodName != null) {
              patternText.append("Method name==>" + actMethodName + "\n");
              actMethodName = null;
            }
            patternText.append(
                "Pattern Matched for searchPattern==>"
                    + searchKeyword
                    + actualPropertyValue
                    + "\n");
          }
        }
      }
    }
  }
  @Override
  public void enterClassDeclaration(ClassDeclarationContext ctx) {

    boolean patternFound = false;
    conditionText = new StringBuffer();
    patternText = new StringBuffer();
    // System.out.println("Class Data ==>"+tokens.getText());
    if (ctx == null || ctx.Identifier() == null) {
      return;
    }
    // System.out.println("Class name==>"+ ctx.Identifier().getText());
    if (LogUtil.isDebugEnabled(LOG_NAME)) {
      LogUtil.debug(CLASS_NAME, "", "Class name==>" + ctx.Identifier().getText(), LOG_NAME);
    }
    // getJavaDocMatch();

    className = ctx.Identifier().getText();

    if (className.toLowerCase().indexOf("processfacade") != -1
        || className.toLowerCase().indexOf("processdelegate") != -1) {
      conditionText.append(
          "\nProcessCalls References are found. Class : " + ctx.Identifier().getText() + "\n");
      patternText.append(
          "\nProcessCalls References are found. Class : " + ctx.Identifier().getText() + "\n");
    }

    conditionText.append("\n Class name-->" + ctx.Identifier().getText() + "\n");

    if (searchPatterns != null) {

      for (String searchKeyword : searchPatterns) {

        String actualPropertyValue = "";
        if (messageMap != null && messageMap.get(searchKeyword) != null) {
          actualPropertyValue = " [" + messageMap.get(searchKeyword) + "] ";
        }
        // System.out.println("SearchKeyword ==> "+searchKeyword+" =
        // "+rewriter.getText().toUpperCase().contains(searchKeyword.toUpperCase()));
        if (searchKeyword != null) {
          try {
            String keywordWOQuote = Pattern.quote(searchKeyword);
            pattern = Pattern.compile(keywordWOQuote, Pattern.CASE_INSENSITIVE);
            System.out.println(pattern.compile(keywordWOQuote));
            // Need to add pattern for finding keyword
            // if(rewriter.getText().indexOf(searchKeyword)!=-1) {
            if (pattern.matcher(rewriter.getText()).find()) {
              conditionText.append(
                  "Pattern Matched for searchPattern-->"
                      + searchKeyword
                      + actualPropertyValue
                      + "\n");
              actClassName = ctx.Identifier().getText();
              patternText.append("\n Class name-->" + className + "\n");
              patternText.append(
                  "Pattern Matched for searchPattern-->"
                      + searchKeyword
                      + actualPropertyValue
                      + "\n");

              // System.out.println("Pattern Matched for
              // searchPattern=="+searchKeyword+actualPropertyValue);
              if (LogUtil.isDebugEnabled(LOG_NAME)) {
                LogUtil.debug(
                    CLASS_NAME,
                    "enterClassDeclaration",
                    "Pattern Matched for searchPattern=" + searchKeyword + actualPropertyValue,
                    LOG_NAME);
              }
              patternFound = true;
            }
          } catch (Exception ex) {
            ex.printStackTrace();
          }
        }
      }
    }
    if (!patternFound) throw new PatternNotFoundException("Keyword not match");
  }