forked from geodmms/xdgnjobs

?? ?
2008-04-14 7840e31dd97db0efe77bdf859ac2fe9767d3dd1a
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package com.ximple.eofms.jobs;
 
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Date;
import java.io.IOException;
 
import org.apache.commons.collections.OrderedMap;
import org.apache.commons.collections.OrderedMapIterator;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
import com.vividsolutions.jts.geom.GeometryFactory;
 
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleResultSet;
import oracle.sql.ARRAY;
import oracle.sql.BLOB;
 
import com.ximple.eofms.util.BinConverter;
import com.ximple.eofms.util.ByteArrayCompressor;
import com.ximple.io.dgn7.ComplexElement;
import com.ximple.io.dgn7.Dgn7fileException;
import com.ximple.io.dgn7.Element;
import com.ximple.io.dgn7.ElementType;
import com.ximple.io.dgn7.IElementHandler;
import com.ximple.util.PrintfFormat;
 
/**
 *
 */
public class OracleConvertDgn2ShpJob extends AbstractOracleDatabaseJob
{
    static Log logger = LogFactory.getLog(OracleConvertDgn2ShpJob.class);
 
    private static final int FETCHSIZE = 30;
    private static final int BATCHSIZE = 25;
    private static final int COMMITSIZE = 20;
 
    class Pair
    {
        Object first;
        Object second;
 
        public Pair(Object first, Object second)
        {
            this.first = first;
            this.second = second;
        }
    }
 
    GeometryFactory _geomFactory = new GeometryFactory();
 
    public Log getLogger()
    {
        return logger;
    }
 
    protected AbstractOracleJobContext prepareJobContext(String filterPath)
    {
        return new OracleConvertJobContext(filterPath);
    }
 
    public void execute(JobExecutionContext context) throws JobExecutionException
    {
        // Every job has its own job detail
        JobDetail jobDetail = context.getJobDetail();
 
        // The name is defined in the job definition
        String jobName = jobDetail.getName();
 
        // Log the time the job started
        logger.info(jobName + " fired at " + new Date());
        extractJobConfiguration(jobDetail);
 
        OracleConvertJobContext jobContext = (OracleConvertJobContext) prepareJobContext(_filterPath);
        jobContext.setConnectionInfo(_oracleHost, _oraclePort, _oracleInstance);
        jobContext.setLogin(_username, _password);
        jobContext.setShapeData(_dataPath);
        jobContext.setExecutionContext(context);
     
        try
        {
            copyConnectivity(jobContext);
            exetcuteConvert(jobContext, _orgSchema, _dataPath);
            //exetcuteConvert(jobContext, "CMMS_SPATIALDB", _dataPath);
 
            //close all open filewriter instance
            jobContext.closeFeatureWrite();
        } catch (SQLException e)
        {
            logger.warn(e.getMessage(), e);
            throw new JobExecutionException("Database error.", e);
        }   catch (IOException ex) {
            ex.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
 
    }
 
    //Connectivity複製一個版本,在查詢電流方向時用來比對OMS資料庫的電器連接性(Connectivity)
    private void copyConnectivity(OracleConvertJobContext jobContext)  throws SQLException
    {
       OracleConnection connection =  jobContext.getOracleConnection() ;
       Statement stmt = connection.createStatement();
       stmt.execute(OracleConvertJobContext.TRUNCATE_CONNECTIVITY_WEBCHECK);
       stmt.execute(OracleConvertJobContext.COPY_CONNECTIVITY_TO_WEBCHECK);
    }
 
    private void exetcuteConvert(OracleConvertJobContext jobContext,
                                 String querySchema, String dataPath) throws SQLException
    {
        int order = 0;
        OrderedMap map = getBlobStorageList(jobContext.getOracleConnection(), querySchema, "SD$SPACENODES"
                , null);
 
        logger.info("begin convert job:[" + map.size() + "]:testmode=" + _testMode);
 
        int total = map.size(); //spacenodes count
        int step = total / 100;
        int current = 0;
        
        //jobContext.startTransaction();
        jobContext.getExecutionContext().put("ConvertDgn2ShpJobProgress", 0);
        for (OrderedMapIterator it = map.orderedMapIterator(); it.hasNext();)
        {
            it.next();
 
            Pair pair = (Pair) it.getValue();
            String tableSrc = (String) pair.first;
 
            logger.info("begin convert:[" + order + "]-" + tableSrc);
            queryIgsetElement(jobContext, querySchema, tableSrc);
 
            order++;
 
            if (_testMode)
            {
                if ((_testCount < 0) || (order >= _testCount))
                    break;
            }
 
            if ((order % COMMITSIZE) == 0)
            {
                // OracleConnection connection = jobContext.getOracleConnection();
                // connection.commitTransaction();
                jobContext.commitTransaction();
                //jobContext.startTransaction();
                System.gc();
            }
 
            int now = order % step;
            if (now != current)
            {
                current = now;
                jobContext.getExecutionContext().put("ConvertDgn2ShpJobProgress", current);
 
            }
        }
        jobContext.getExecutionContext().put("ConvertDgn2ShpJobProgress", 100);
 
        jobContext.commitTransaction();
 
        logger.info("end convert job:[" + order + "]");
        System.gc();
    }
 
    protected OrderedMap getBlobStorageList(OracleConnection connection, String schemaSrc, String tableSrc,
                                            OrderedMap orderedMap) throws SQLException
    {
        if (orderedMap == null)
            orderedMap = new LinkedMap(99);
        String fetchStmtFmt = "SELECT SNID, SPACETABLE FROM \"%s\".\"%s\"";
        PrintfFormat spf = new PrintfFormat(fetchStmtFmt);
        String fetchStmt = spf.sprintf(new Object[]{schemaSrc, tableSrc});
        Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
 
        stmt.setFetchSize(FETCHSIZE);
 
        ResultSet rs = stmt.executeQuery(fetchStmt);
 
        while (rs.next())
        {
            int size = rs.getMetaData().getColumnCount();
            Object[] values = new Object[size];
 
            for (int i = 0; i < size; i++)
            {
                values[i] = rs.getObject(i + 1);
            }
 
            Integer key = ((BigDecimal) values[0]).intValue();
            String name = (String) values[1];
 
            Pair pair = (Pair) orderedMap.get(key);
            if (pair == null)
                orderedMap.put(key, new Pair(name, null));
            else
                pair.first = name;
        }
 
        rs.close();
        stmt.close();
 
        return orderedMap;
    }
 
    protected OrderedMap getRawFormatStorageList(OracleConnection connection, String schemaSrc, String tableSrc,
                                                 OrderedMap orderedMap) throws SQLException
    {
        if (orderedMap == null)
            orderedMap = new LinkedMap(99);
        String fetchStmtFmt = "SELECT RNID, SPACETABLE FROM \"%s\".\"%s\"";
        PrintfFormat spf = new PrintfFormat(fetchStmtFmt);
        String fetchStmt = spf.sprintf(new Object[]{schemaSrc, tableSrc});
        Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
 
        stmt.setFetchSize(FETCHSIZE);
 
        ResultSet rs = stmt.executeQuery(fetchStmt);
 
        while (rs.next())
        {
            int size = rs.getMetaData().getColumnCount();
            Object[] values = new Object[size];
 
            for (int i = 0; i < size; i++)
            {
                values[i] = rs.getObject(i + 1);
            }
 
            Integer key = ((BigDecimal) values[0]).intValue();
            String name = (String) values[1];
 
            Pair pair = (Pair) orderedMap.get(key);
            if (pair == null)
                orderedMap.put(key, new Pair(null, name));
            else
                pair.second = name;
        }
 
        rs.close();
        stmt.close();
 
        return orderedMap;
    }
 
    protected void queryIgsetElement(OracleConvertJobContext jobContext,
                                     String srcschema, String srctable) throws SQLException
    {
        OracleConnection connection = jobContext.getOracleConnection();
        String fetchSrcStmtFmt = "SELECT IGDSELM FROM \"%s\".\"%s\" ORDER BY ROWID";
        PrintfFormat spf = new PrintfFormat(fetchSrcStmtFmt);
        String fetchSrcStmt = spf.sprintf(new Object[]{srcschema, srctable});
        Statement stmtSrc = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
 
       stmtSrc.setFetchSize(FETCHSIZE);
 
        ResultSet rsSrc = stmtSrc.executeQuery(fetchSrcStmt);
 
        while (rsSrc.next())
        {
            byte[] raw = null;
 
            if (rsSrc.getMetaData().getColumnType(1) == Types.BLOB)
            {
                BLOB blob = (BLOB) rsSrc.getBlob(1);
 
                raw = getBytesFromBLOB(blob);
                blob.close();
            } else
            {
                raw = rsSrc.getBytes(1);
            }
 
            try
            {
                Element element = fetchBinaryElement(raw);
                jobContext.putFeatureCollection(element);
            } catch (Dgn7fileException e)
            {
                logger.warn("Dgn7Exception", e);
            }
        }
 
        rsSrc.close();
        stmtSrc.close();
    }
 
    protected void queryRawElement(OracleConvertJobContext jobContext,
                                   String srcschema, String srctable) throws SQLException
    {
        OracleConnection connection = jobContext.getOracleConnection();
        String fetchDestStmtFmt = "SELECT ELEMENT FROM \"%s\".\"%s\" ORDER BY ROWID";
        PrintfFormat spf = new PrintfFormat(fetchDestStmtFmt);
        String fetchDestStmt = spf.sprintf(new Object[]{srcschema, srctable});
        Statement stmtDest = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
 
        stmtDest.setFetchSize(FETCHSIZE);
 
        ResultSet rsDest = stmtDest.executeQuery(fetchDestStmt);
 
        while (rsDest.next())
        {
            ARRAY rawsValue = ((OracleResultSet) rsDest).getARRAY(1);
            long[] rawData = rawsValue.getLongArray();
            byte[] comparessedValue;
 
            /*
            if (dataMode == TransferTask.DataMode.Normal)
            {
                comparessedValue = BinConverter.unmarshalByteArray(rawData, true);
            } else
            {
                comparessedValue = BinConverter.unmarshalCompactByteArray(rawData);
            }
            */
            comparessedValue = BinConverter.unmarshalByteArray(rawData, true);
 
            byte[] rawDest = ByteArrayCompressor.decompressByteArray(comparessedValue);
 
 
            try
            {
                Element element = fetchBinaryElement(rawDest);
                jobContext.putFeatureCollection(element);
            } catch (Dgn7fileException e)
            {
                logger.warn("Dgn7Exception:" + e.getMessage(), e);
            }
        }
 
        rsDest.close();
        stmtDest.close();
    }
 
    // Binary to Element
    private Element fetchBinaryElement(byte[] raws) throws Dgn7fileException
    {
        ByteBuffer buffer = ByteBuffer.wrap(raws);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        short signature = buffer.getShort();
 
        // byte type = (byte) (buffer.get() & 0x7f);
        byte type = (byte) ((signature >>> 8) & 0x007f);
 
        // silly Bentley say contentLength is in 2-byte words
        // and ByteByffer uses raws.
        // track the record location
        int elementLength = (buffer.getShort() * 2) + 4;
        ElementType recordType = ElementType.forID(type);
        IElementHandler handler;
 
        handler = recordType.getElementHandler();
 
        Element dgnElement = (Element) handler.read(buffer, signature, elementLength);
        if (recordType.isComplexElement() && (elementLength < raws.length))
        {
            int offset = elementLength;
            while (offset < (raws.length - 4))
            {
                buffer.position(offset);
                signature = buffer.getShort();
                type = (byte) ((signature >>> 8) & 0x007f);
                elementLength = (buffer.getShort() * 2) + 4;
                if (raws.length < (offset + elementLength))
                {
                    System.out.println("Length not match:" + offset + ":" + buffer.position() + ":" + buffer.limit());
                    break;
                }
                recordType = ElementType.forID(type);
                handler = recordType.getElementHandler();
                if (handler != null)
                {
                    Element subElement = (Element) handler.read(buffer, signature, elementLength);
                    ((ComplexElement) dgnElement).add(subElement);
                    offset += elementLength;
                } else
                {
                    byte[] remain = new byte[buffer.remaining()];
                    System.arraycopy(raws, offset, remain, 0, buffer.remaining());
                    for (int i = 0; i < remain.length; i++)
                    {
                        if (remain[i] != 0)
                        {
                            logger.info("fetch element has some error. index=" + (offset + i) + ":value=" + remain[i]);
                            System.out.println("fetch element has some error. index=" + (offset + i) + ":value=" + remain[i]);
                        }
                    }
                    break;
                }
            }
        }
 
        return dgnElement;
    }
}