1

In my Java program, I have parsed a Cucumber Feature File to a GherkinDocument. I have edited some tags in this Document. Now I want to write the Code of the GherkinDocument in a Feature File.

For that, I want to translate the Gherkin Document to a String or String Array, a De-Parsing if you will. This is how I parsed the Feature File Text to a GherkinDocument:

        Parser<GherkinDocument> parser = new Parser<>(new GherkinDocumentBuilder(idGenerator));
        GherkinDocument doc = parser.parse(reader);
        return doc;

The Parser is from the repo: https://github.com/cucumber/common/blob/gherkin/v21.0.0/gherkin/java/src/test/java/io/cucumber/gherkin/GherkinDocumentBuilderTest.java

Is there a way to do this?

Thank you very much and regards, Lukas

1 Answers1

0

I had a similar problem recently, i wanted to store my string and retrieve it without loosing its formating, what i did was to simply compress the string before storing it, then uncompress it at retrievial, more like this:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPCompression {
  public static byte[] compress(final String str) throws IOException {
    if ((str == null) || (str.length() == 0)) {
      return null;
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.flush();
    gzip.close();
    return obj.toByteArray();
  }

  public static String decompress(final byte[] compressed) throws IOException {
    final StringBuilder outStr = new StringBuilder();
    if ((compressed == null) || (compressed.length == 0)) {
      return "";
    }
    if (isCompressed(compressed)) {
      final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
      final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        outStr.append(line);
      }
    } else {
      outStr.append(compressed);
    }
    return outStr.toString();
  }

  public static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
  }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135