forked from geodmms/xdgnjobs

?? ?
2008-05-24 c6d666b64e226acfae9f98872ba7d7942e68f238
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package com.ximple.eofms.jobs;
 
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.transaction.memory.PessimisticMapWrapper;
import org.apache.commons.transaction.util.CommonsLoggingLogger;
import org.apache.commons.transaction.util.LoggerFacade;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.indexed.IndexedShapefileDataStore;
import org.geotools.feature.AttributeTypeFactory;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureType;
import org.geotools.feature.FeatureTypeBuilder;
import org.geotools.feature.IllegalAttributeException;
import org.geotools.feature.SchemaException;
import org.geotools.feature.SimpleFeature;
 
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
 
import com.ximple.eofms.util.DefaultColorTable;
import com.ximple.eofms.util.TPCLIDConverter;
import com.ximple.eofms.util.TWDDatumConverter;
import com.ximple.io.dgn7.Element;
import com.ximple.io.dgn7.FrammeAttributeData;
import com.ximple.io.dgn7.TextElement;
import com.ximple.io.dgn7.UserAttributeData;
 
public class IndexDgnConvertJobContext extends AbstractDgnFileJobContext
{
    static final Log logger = LogFactory.getLog(IndexDgnConvertJobContext.class);
    static final LoggerFacade sLogger = new CommonsLoggingLogger(logger);
    static final GeometryFactory geometryFactory = new GeometryFactory();
    TWD97GeometryConverterDecorator convertDecorator = new TWD97GeometryConverterDecorator();
    static final String SHPOUTPATH = "shpout";
 
    private String dataOut = null;
 
    private HashMap<String, ArrayList<Feature>> featuresContext = new HashMap<String, ArrayList<Feature>>();
    private HashMap<String, FeatureWriter> featuresWriterContext = new HashMap<String, FeatureWriter>();
 
    private PessimisticMapWrapper txFeaturesContext;
    private FeatureTypeBuilder typeBuilder2 = null;
    private FeatureTypeBuilder typeBuilder = null;
    private FeatureType featureType = null;
    private FeatureType featureType2 = null;
 
    public IndexDgnConvertJobContext(String dataPath)
    {
        super(dataPath);
        txFeaturesContext = new PessimisticMapWrapper(featuresContext, sLogger);
    }
 
    public void putFeatureCollection(Element element) throws IllegalAttributeException, SchemaException
    {
        if (!(element instanceof TextElement))
        {
            return;
        }
 
        Feature feature = createFeature((TextElement) element);
        if (feature == null)
        {
            logger.info("cannot craete feature." + element.toString() + "'" +
                    ((TextElement) element).getText() + "'");
            return;
        }
 
        if (!txFeaturesContext.containsKey(feature.getFeatureType()))
        {
            txFeaturesContext.put(feature.getFeatureType(), new ArrayList());
        }
        ArrayList arrayList = (ArrayList) txFeaturesContext.get(feature.getFeatureType());
        arrayList.add(feature);
 
        feature = createFeature2((TextElement) element);
        if (feature == null)
        {
            logger.info("cannot craete feature2." + element.toString() + "'" +
                    ((TextElement) element).getText() + "'");
            return;
        }
 
        if (!txFeaturesContext.containsKey(feature.getFeatureType()))
        {
            txFeaturesContext.put(feature.getFeatureType(), new ArrayList());
        }
        arrayList = (ArrayList) txFeaturesContext.get(feature.getFeatureType());
        arrayList.add(feature);
    }
 
    public void startTransaction()
    {
    }
 
    public void commitTransaction()
    {
        if (!txFeaturesContext.isEmpty())
        {
            logger.debug("Transaction size = " + txFeaturesContext.size());
            //txFeaturesContext.commitTransaction();
        } else
        {
            logger.debug("Transaction is empty.");
        }
 
        if (!featuresContext.isEmpty())
        {
            updateDataStore();
        }
    }
 
    public void rollbackTransaction()
    {
        //txFeaturesContext.rollbackTransaction();
        if (!featuresContext.isEmpty())
        {
            updateDataStore();
        }
    }
 
    private void updateDataStore()
    {
        Iterator it = featuresContext.keySet().iterator();
 
        try
        {
            while (it.hasNext())
            {
                FeatureType featureType = (FeatureType) it.next();
                File sfile = new File(getDataOutPath() + File.separator + featureType.getTypeName());
                logger.debug("Begin Save shapefile:" + sfile.toURI());
 
                FeatureWriter writer;
                if (featuresWriterContext.containsKey(featureType.getTypeName()))
                {
                    writer = featuresWriterContext.get(featureType.getTypeName());
                } else
                {
                    /*
                    ShapefileDataStore shapefileDataStore = new ShapefileDataStore(sfile.toURI().toURL(),
                            true, Charset.forName("UTF-8"));
                    */
                    ShapefileDataStore shapefileDataStore = new IndexedShapefileDataStore(sfile.toURI().toURL(),
                            null, true, true, IndexedShapefileDataStore.TREE_QIX, Charset.forName("UTF-8"));
                    shapefileDataStore.createSchema(featureType);
                    writer = shapefileDataStore.getFeatureWriter(featureType.getTypeName(), Transaction.AUTO_COMMIT);
                    featuresWriterContext.put(featureType.getTypeName(), writer);
                }
 
                ArrayList<Feature> features = featuresContext.get(featureType);
                for (Feature feature1 : features)
                {
                    ((SimpleFeature) writer.next()).setAttributes(feature1.getAttributes(null));
                }
                //writer.close();
                logger.debug("End Save shapefile:" + sfile.toURI());
            }
            featuresContext.clear();
        } catch (MalformedURLException e)
        {
            logger.error(e.getMessage(), e);
        } catch (IllegalAttributeException e)
        {
            logger.error(e.getMessage(), e);
        } catch (IOException e)
        {
            logger.error(e.getMessage(), e);
        }
    }
 
    public String getDataOutPath()
    {
        if (dataOut == null)
        {
            File outPath = new File(getDataPath(), SHPOUTPATH);
            if (!outPath.exists())
            {
                outPath.mkdir();
            } else if (!outPath.isDirectory())
            {
                outPath.mkdir();
            }
            dataOut = outPath.toString();
        }
        return dataOut;
    }
 
    public void closeFeatureWriter() throws IOException
    {
 
        for (FeatureWriter featureWriter : this.featuresWriterContext.values())
        {
            featureWriter.close();
        }
 
        this.featuresWriterContext.clear();
    }
 
    public FeatureType createFeatureElement(String featureName) throws SchemaException
    {
        if (typeBuilder == null)
        {
            typeBuilder = FeatureTypeBuilder.newInstance(featureName);
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("GEOM", Geometry.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("X1", Double.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("Y1", Double.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("X2", Double.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("Y2", Double.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("TPCID", String.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("SYMCOLOR", String.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("SYMWEIGHT", Integer.class));
            typeBuilder.addType(AttributeTypeFactory.newAttributeType("SYMSTYLE", Integer.class));
        }
        return typeBuilder.getFeatureType();
    }
 
    public FeatureType createFeatureElement2(String featureName) throws SchemaException
    {
        if (typeBuilder2 == null)
        {
            typeBuilder2 = FeatureTypeBuilder.newInstance(featureName);
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("GEOM", Geometry.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("SYMCOLOR", String.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("SYMWEIGHT", Integer.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("SYMSTYLE", Integer.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("JUST", Integer.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("HEIGHT", Double.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("WIDTH", Double.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("ANGLE", Double.class));
            typeBuilder2.addType(AttributeTypeFactory.newAttributeType("TPCID", String.class));
        }
        return typeBuilder2.getFeatureType();
    }
 
    public Feature createFeature(FeatureType featureType, Element element) throws IllegalAttributeException
    {
        DefaultColorTable colorTable = (DefaultColorTable) DefaultColorTable.getInstance();
        if (element instanceof TextElement)
        {
            TextElement textElement = (TextElement) element;
            String tpclid = textElement.getText();
 
            Envelope extent = TPCLIDConverter.convertTpclIdToEnvelope(tpclid);
            Geometry geom = geometryFactory.createLinearRing(new Coordinate[]
                    {
                            TWDDatumConverter.fromTM2ToTWD97(new Coordinate(extent.getMinX(), extent.getMinY())),
                            TWDDatumConverter.fromTM2ToTWD97(new Coordinate(extent.getMaxX(), extent.getMinY())),
                            TWDDatumConverter.fromTM2ToTWD97(new Coordinate(extent.getMaxX(), extent.getMaxY())),
                            TWDDatumConverter.fromTM2ToTWD97(new Coordinate(extent.getMinX(), extent.getMaxY())),
                            TWDDatumConverter.fromTM2ToTWD97(new Coordinate(extent.getMinX(), extent.getMinY())),
                    });
 
            return featureType.create(new Object[]{
                    geom,
                    extent.getMinX(),
                    extent.getMinY(),
                    extent.getMaxX(),
                    extent.getMaxY(),
                    tpclid,
                    colorTable.getColorCode(textElement.getColorIndex()),
                    textElement.getWeight(),
                    textElement.getLineStyle()
            });
        }
        return null;
    }
 
    public Feature createFeature2(FeatureType featureType, Element element) throws IllegalAttributeException
    {
        DefaultColorTable colorTable = (DefaultColorTable) DefaultColorTable.getInstance();
        if (element instanceof TextElement)
        {
            TextElement txtElement = (TextElement) element;
            double angle = txtElement.getRotationAngle();
            angle = BigDecimal.valueOf(angle).setScale(3, RoundingMode.HALF_UP).doubleValue();
            convertDecorator.setConverter(txtElement);
            Feature feature = featureType.create(new Object[]{
                    convertDecorator.toGeometry(geometryFactory),
                    colorTable.getColorCode(txtElement.getColorIndex()),
                    txtElement.getWeight(),
                    txtElement.getLineStyle(),
                    txtElement.getJustification(),
                    txtElement.getTextHeight(),
                    txtElement.getTextWidth(),
                    angle,
                    txtElement.getText()
            });
            return feature;
        }
        return null;
    }
 
    private Feature createFeature(TextElement element) throws SchemaException, IllegalAttributeException
    {
        if (featureType == null)
        {
            String dgnname = getFilename().toLowerCase();
            int i = dgnname.lastIndexOf(".");
            if (i != -1)
            {
                dgnname = dgnname.substring(0, i);
            }
            featureType = createFeatureElement(dgnname);
        }
        return createFeature(featureType, element);
    }
 
    private Feature createFeature2(TextElement element) throws SchemaException, IllegalAttributeException
    {
        if (featureType2 == null)
        {
            String dgnname = getFilename().toLowerCase();
            int i = dgnname.lastIndexOf(".");
            if (i != -1)
            {
                dgnname = dgnname.substring(0, i);
            }
            dgnname = dgnname + "P";
            featureType2 = createFeatureElement2(dgnname);
        }
        return createFeature2(featureType2, element);
    }
 
    protected FrammeAttributeData getFeatureLinkage(Element element)
    {
        if (!element.hasUserAttributeData())
            return null;
 
        List<UserAttributeData> usrDatas = element.getUserAttributeData();
        for (UserAttributeData anUsrData : usrDatas)
        {
            if (anUsrData instanceof FrammeAttributeData)
            {
                return (FrammeAttributeData) anUsrData;
            }
        }
        return null;
    }
}