1 package org
.argeo
.jts
.jcr
;
3 import java
.io
.ByteArrayInputStream
;
4 import java
.io
.InputStream
;
6 import javax
.jcr
.Binary
;
7 import javax
.jcr
.Property
;
8 import javax
.jcr
.Session
;
10 import org
.apache
.commons
.io
.IOUtils
;
11 import org
.argeo
.ArgeoException
;
12 import org
.argeo
.jcr
.JcrUtils
;
14 import com
.vividsolutions
.jts
.geom
.Geometry
;
15 import com
.vividsolutions
.jts
.geom
.GeometryFactory
;
16 import com
.vividsolutions
.jts
.io
.InputStreamInStream
;
17 import com
.vividsolutions
.jts
.io
.WKBReader
;
18 import com
.vividsolutions
.jts
.io
.WKBWriter
;
20 /** Utilities depending only from the JTS library. */
21 public class JtsJcrUtils
{
22 private static GeometryFactory geometryFactory
= new GeometryFactory();
23 private static ThreadLocal
<WKBWriter
> wkbWriters
= new ThreadLocal
<WKBWriter
>();
24 private static ThreadLocal
<WKBReader
> wkbReaders
= new ThreadLocal
<WKBReader
>() {
25 protected WKBReader
initialValue() {
26 return new WKBReader(getGeometryFactory());
30 public static GeometryFactory
getGeometryFactory() {
31 return geometryFactory
;
34 public final static Geometry
readWkb(Property property
) {
35 Binary wkbBinary
= null;
36 InputStream in
= null;
38 wkbBinary
= property
.getBinary();
39 in
= wkbBinary
.getStream();
40 WKBReader wkbReader
= wkbReaders
.get();
41 return wkbReader
.read(new InputStreamInStream(in
));
42 } catch (Exception e
) {
43 throw new ArgeoException("Cannot read WKB from " + property
, e
);
45 IOUtils
.closeQuietly(in
);
46 JcrUtils
.closeQuietly(wkbBinary
);
50 /** The returned binary should be disposed by the caller */
51 public final static Binary
writeWkb(Session session
, Geometry geometry
) {
52 Binary wkbBinary
= null;
53 InputStream in
= null;
55 WKBWriter wkbWriter
= wkbWriters
.get();
56 byte[] arr
= wkbWriter
.write(geometry
);
57 in
= new ByteArrayInputStream(arr
);
58 wkbBinary
= session
.getValueFactory().createBinary(in
);
60 } catch (Exception e
) {
61 throw new ArgeoException("Cannot write WKB", e
);
63 IOUtils
.closeQuietly(in
);