Search code examples
jts

How to read WKB using JTS WKBReader when input bytestream contains SRID in it?


The documentation for WKBReader says:

It also partiually handles the Extended WKB format used by PostGIS (by reading SRID values)

but when I pass a byte array that has an SRID in the first 4 bytes to WKBReader I get an exception from WKBReader. This link also runs into same issue and skips the first 4 bytes before passing the byte stream to WKBReader. Looking at the code itself for WKBReader:

private Geometry readGeometry() throws IOException, ParseException {
        byte byteOrderWKB = this.dis.readByte();
        int byteOrder = byteOrderWKB == 1?2:1;
        this.dis.setOrder(byteOrder);
        int typeInt = this.dis.readInt();
        int geometryType = typeInt & 255;
        boolean hasZ = (typeInt & -2147483648) != 0;
        this.inputDimension = hasZ?3:2;
        this.hasSRID = (typeInt & 536870912) != 0;
        int SRID = 0;
        if(this.hasSRID) {
            SRID = this.dis.readInt();
        }

It looks incorrect as it doesn't decode first 4 bytes as SRID. I also tried following:

g = some JTS Geometry
g.setSRID(4326);
new WKBReader().read(new WKBWriter().write(g)).getSRID()

returns 0 instead of expected 4326. My question is could anyone from JTS confirm that this is indeed a bug? If not, what is wrong? It would be good to have it fixed.


Solution

  • Answering my own question: This is not a bug. WKBReader supports SRID in WKBWriter's format.

    new WKBReader().read(new WKBWriter(2, true).write(g)).getSRID();
    

    returns expected answer. This method signature is not present in official docs but is present here.