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 protected WKBWriter
initialValue() {
25 return new WKBWriter();
28 private static ThreadLocal
<WKBReader
> wkbReaders
= new ThreadLocal
<WKBReader
>() {
29 protected WKBReader
initialValue() {
30 return new WKBReader(getGeometryFactory());
34 public static GeometryFactory
getGeometryFactory() {
35 return geometryFactory
;
38 public final static Geometry
readWkb(Property property
) {
39 Binary wkbBinary
= null;
40 InputStream in
= null;
42 wkbBinary
= property
.getBinary();
43 in
= wkbBinary
.getStream();
44 WKBReader wkbReader
= wkbReaders
.get();
45 return wkbReader
.read(new InputStreamInStream(in
));
46 } catch (Exception e
) {
47 throw new ArgeoException("Cannot read WKB from " + property
, e
);
49 IOUtils
.closeQuietly(in
);
50 JcrUtils
.closeQuietly(wkbBinary
);
54 /** The returned binary should be disposed by the caller */
55 public final static Binary
writeWkb(Session session
, Geometry geometry
) {
56 Binary wkbBinary
= null;
57 InputStream in
= null;
59 WKBWriter wkbWriter
= wkbWriters
.get();
60 byte[] arr
= wkbWriter
.write(geometry
);
61 in
= new ByteArrayInputStream(arr
);
62 wkbBinary
= session
.getValueFactory().createBinary(in
);
64 } catch (Exception e
) {
65 throw new ArgeoException("Cannot write WKB", e
);
67 IOUtils
.closeQuietly(in
);