Skip to content

java.lang.ClassCastException in AnsiProcessor.java #305

@fouzhe

Description

@fouzhe

Hi, there is an java.lang.ClassCastException in AnsiProcessor.java. The following is the reproduce steps:

Prepare an app file

jansi/RenderAPP/src/ReJansi/Render.java

package ReJansi;

import org.fusesource.jansi.AnsiColors;
import org.fusesource.jansi.AnsiMode;
import org.fusesource.jansi.AnsiType;
import org.fusesource.jansi.io.AnsiOutputStream;
import static org.fusesource.jansi.AnsiRenderer.render;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;

public class Render {
    public static void main(String[] args) throws IOException {
        if (args.length < 2) {
            System.err.println("Usage: java ReJansi.CombinedAnsi <inputFile> <mode>");
            System.err.println("Modes: strip - Strip ANSI escape codes");
            System.err.println("       render - Render markup into ANSI sequences");
            System.err.println("       strip-then-render - Strip ANSI codes then render markup");
            System.err.println("       render-then-strip - Render markup then strip ANSI codes");
            return;
        }

        String inputFile = args[0];
        String mode = args[1];

        // read the file content
        String content = readFile(inputFile);
        if (content == null)
            return;

        String result = "";

        switch (mode.toLowerCase()) {
            case "strip":
                result = stripAnsi(content);
                break;
            case "render":
                result = render(content);
                break;
            case "strip-then-render":
                result = render(stripAnsi(content));
                break;
            case "render-then-strip":
                result = stripAnsi(render(content));
                break;
            default:
                System.err.println("Unknown mode: " + mode);
                return;
        }

        System.out.println("Result:");
        System.out.println(result);
    }

    private static String readFile(String filePath) {
        StringBuilder input = new StringBuilder();
        try {
            File file = new File(filePath);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null) {
                input.append(line).append("\n");
            }
            reader.close();
            System.out.println("Input content: " + input.toString());
            return input.toString();
        } catch (IOException e) {
            System.err.println("File read error: " + e.getMessage());
            return null;
        }
    }

    private static String stripAnsi(String input) throws IOException {
        // convert the string to byte array
        byte[] inputBytes = input.getBytes(Charset.forName("UTF-8"));

        // use AnsiOutputStream to strip the ANSI escape sequences
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final AnsiOutputStream ansiOutput = new AnsiOutputStream(baos, null, AnsiMode.Strip, null,
                AnsiType.Emulation, AnsiColors.TrueColor, Charset.forName("UTF-8"), null, null, false);
        ansiOutput.write(inputBytes);
        ansiOutput.close();

        return baos.toString("UTF-8");
    }
}

Build

make download-includes && \
    make clean-native native OS_NAME=Linux OS_ARCH=x86_64 && \
    mvn clean package -Dmaven.javadoc.skip=true -Dspotless.check.skip=true -Dspotless.apply.skip=true

export JANSI_PATH=$(find /jansi_instr/target -maxdepth 1 -name "jansi-*-SNAPSHOT.jar") && \
    cd RenderAPP && \
    export JAVA_SOURCE=./src && \
    export JAVA_LIB=./lib && \
    export JAVA_CLASS=./bin && \
    mkdir -p $JAVA_CLASS && \
    find $JAVA_SOURCE -name "*.java" > $JAVA_SOURCE/sources.list && \
    javac -d $JAVA_CLASS -encoding utf-8 -cp .:$JANSI_PATH -g -sourcepath $JAVA_SOURCE @$JAVA_SOURCE/sources.list && \
    cd $JAVA_CLASS && \
    jar -cvfm ../Render.jar ../MANIFEST.MF * && \
    chmod a+x ../Render.jar

Reproduce scripts

def execute_program(timeout: int) -> tuple[str, int]:
      import signal
      import subprocess
      import tempfile

      # Create a temporary file with a CSI (Control Sequence Introducer) sequence
      # \033[ - Escape followed by '[' to start CSI sequence
      # \"string content\" - Quoted string argument
      # m - SGR (Select Graphic Rendition) command character
      with tempfile.NamedTemporaryFile(mode="w") as temp_file:
          # Using CSI sequence with a quoted string argument to trigger the target branch
          temp_file.write("\033[\"This is a test string\"mThis text follows a CSI sequence")
          temp_file.flush()
          temp_file_path = temp_file.name

          try:
              result = subprocess.run(
                  [
                      "java",
                      "-Djava.library.path=./target/classes/org/fusesource/jansi/internal/native/Linux/x86_64/",
                      "-cp",
                      "target/jansi-2.4.3-SNAPSHOT.jar:RenderAPP/Render.jar",
                      "ReJansi.Render",
                      temp_file_path,
                      "render-then-strip",
                  ],
                  capture_output=True,
                  encoding="utf-8",
                  errors="replace",
                  timeout=timeout,
              )
              # return stderr and the returncode
              return result.stderr, result.returncode
          except subprocess.TimeoutExpired as e:
              # Timeout occurred, also ensure to return stderr captured before timeout and return code -signal.SIGKILL
              return e.stderr, -signal.SIGKILL
          except Exception as e:
              # ensure to raise the error if run failed
              raise e
if __name__ == "__main__":
    print(execute_program(timeout=10))

Stderr

  Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
  at org.fusesource.jansi.io.AnsiProcessor.optionInt(AnsiProcessor.java:375)
  at org.fusesource.jansi.io.AnsiProcessor.processEscapeCommand(AnsiProcessor.java:136)
  at org.fusesource.jansi.io.AnsiOutputStream.processEscapeCommand(AnsiOutputStream.java:416)
  at org.fusesource.jansi.io.AnsiOutputStream.write(AnsiOutputStream.java:288)
  at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:137)
  at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:108)
  at ReJansi.Render.stripAnsi(Render.java:113)
  at ReJansi.Render.main(Render.java:61)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions