javabase64gzipoutputstream

XML Gzip and Base64 encode and store in DB


I was trying to Gzip and Base64 encode XML and then persist in the database.

Code:

    public static Base64OutputStream compressAndEncode(String file) throws IOException, URISyntaxException {

        String filePath = getAbsoluteFilePath("test.xml");
        String fileContent = Files.readString(Path.of(filePath), StandardCharsets.UTF_8);
        Base64OutputStream gzipBase64 = fileGzipAndBase64(fileContent);
        LOG.info("gzipBase64: " + gzipBase64.toString());
        return gzipBase64;
    }

    public static Base64OutputStream fileGzipAndBase64(String fileContent) throws IOException {

        try {
            Base64OutputStream b64os = new Base64OutputStream(System.out);
            GZIPOutputStream gzip = new GZIPOutputStream(b64os);
            gzip.write(fileContent.getBytes("UTF-8"));
            gzip.close();
            b64os.close();
            return b64os;
        } catch (Throwable t) {
            t.printStackTrace();
        }

        return null;
    }


  Base64OutputStream data = TestResourceHelper.compressAndEncode1(paymentFile);

  sql = "insert into file (xml-content) values(decode('" + data + "', 'base64'))";

But in the db insertion step I get below error

ERROR: invalid symbol "." found while decoding base64 sequence

However if I used hardocoded string as data = "H4sIAAAAAAA..xftH+CWV0apGQAA" it works

So I guess some issue with the output in the compressAndEncode() method


Solution

  • The error was due to invalid input in this decode('" + data + "', 'base64') wahere base64 data insertion into the DB column(bytea).

    So the reson for above data issue was as missing the conversion from ByteArrayOutputStream to ByteArray.

    public static Base64OutputStream fileGzipAndBase64(String fileContent) throws IOException {

    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();   //** new-line ***
        Base64OutputStream b64os = new Base64OutputStream(System.out);
        GZIPOutputStream gzip = new GZIPOutputStream(b64os);
        gzip.write(fileContent.getBytes("UTF-8"));
        gzip.close();
        b64os.close();
        String base64 = new String(os.toByteArray(), "UTF-8");  //** new-line ***
        return base64;
    } catch (Throwable t) {
        t.printStackTrace();
    }
    
    return null;
    

    }