Dennis Kao
2013-08-01 617bff91fba317f36740ecdecc7ae6b699afbd80
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
406
407
408
409
410
411
412
413
414
package com.ximple.eofms.jobs;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.ListIterator;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
import com.vividsolutions.jts.util.Assert;
 
import oracle.sql.BLOB;
 
import com.ximple.eofms.util.PrintfFormat;
import com.ximple.io.dgn7.ArcElement;
import com.ximple.io.dgn7.ComplexChainElement;
import com.ximple.io.dgn7.ComplexShapeElement;
import com.ximple.io.dgn7.Dgn7fileException;
import com.ximple.io.dgn7.Element;
import com.ximple.io.dgn7.EllipseElement;
import com.ximple.io.dgn7.IElementHandler;
import com.ximple.io.dgn7.LineElement;
import com.ximple.io.dgn7.LineStringElement;
import com.ximple.io.dgn7.ShapeElement;
import com.ximple.io.dgn7.TextElement;
import com.ximple.io.dgn7.TextNodeElement;
 
public class OracleElementLogger {
    static Log logger = LogFactory.getLog(OracleElementLogger.class);
    private static final String DEFAULT_ELMOUTPATH = "elmout";
    private static final String TAB_IGDSSEED = "SD$IGDSSET_SEED";
 
    private Connection connection;
    private String dataOut = null;
    private String dataPath;
    private String currentSchema;
    private boolean schemaChanged;
    private FileOutputStream fos = null;
    private FileChannel fch = null;
    private int logCount = 0;
    private int elmCount = 0;
    private int maxElmCount = 3000;
    private boolean useElementCount = true;
    private ArrayList<byte[]> dgnFileHeader = null;
    private String elmOutPath;
    private String prefix = null;
 
    public OracleElementLogger(Connection connection) {
        this.connection = connection;
        elmOutPath = DEFAULT_ELMOUTPATH;
    }
 
    public OracleElementLogger(Connection connection, String elmOutPath) {
        this.connection = connection;
        this.elmOutPath = elmOutPath;
    }
 
    public OracleElementLogger(Connection connection, int maxCount) {
        this.connection = connection;
        elmOutPath = DEFAULT_ELMOUTPATH;
        this.maxElmCount = maxCount;
    }
 
    public OracleElementLogger(Connection connection, String elmOutPath, int maxCount) {
        this.connection = connection;
        this.elmOutPath = elmOutPath;
        this.maxElmCount = maxCount;
    }
 
    public String getDataOutPath() {
        if (dataOut == null) {
            File outPath = new File(getDataPath(), elmOutPath);
            if (!outPath.exists()) {
                outPath.mkdir();
            } else if (!outPath.isDirectory()) {
                outPath.mkdir();
            }
            dataOut = outPath.toString();
        }
        return dataOut;
    }
 
    public String getDataPath() {
        return dataPath;
    }
 
    public void setDataPath(String dataPath) {
        this.dataPath = dataPath;
    }
 
    public void logElement(Element element, String currentSchema) {
        if ((this.currentSchema == null) ||
            (!this.currentSchema.equalsIgnoreCase(currentSchema))) {
            schemaChanged = true;
            this.currentSchema = currentSchema;
            try {
                createNewStream();
            } catch (IOException e) {
                logger.warn(e.getMessage(), e);
                return;
            } catch (SQLException e) {
                logger.warn(e.getMessage(), e);
                return;
            }
        } else {
            if (fch == null) {
                try {
                    createNewStream();
                } catch (IOException e) {
                    logger.warn(e.getMessage(), e);
                    return;
                } catch (SQLException e) {
                    logger.warn(e.getMessage(), e);
                    return;
                }
            }
        }
 
        ArrayList<ByteBuffer> subBuffers = new ArrayList<ByteBuffer>();
        if (fch != null) {
            ByteBuffer buf = null;
            if (element instanceof LineElement) {
                int size = LineElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                LineElement.ElementHandler.getInstance().write(buf, element);
            } else if (element instanceof ShapeElement) {
                int size = ShapeElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                ShapeElement.ElementHandler.getInstance().write(buf, element);
            } else if (element instanceof LineStringElement) {
                int size = LineStringElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                LineStringElement.ElementHandler.getInstance().write(buf, element);
            } else if (element instanceof ComplexChainElement) {
                int size = ComplexChainElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                ComplexChainElement.ElementHandler.getInstance().write(buf, element);
                ComplexChainElement complexElement = (ComplexChainElement) element;
                ListIterator it = complexElement.listIterator();
                while (it.hasNext()) {
                    Element subElm = (Element) it.next();
                    try {
                        IElementHandler handler = subElm.getElementType().getElementHandler();
                        size = handler.getLength(subElm);
                        ByteBuffer subBuf = ByteBuffer.allocate(size * 2);
                        handler.write(subBuf, subElm);
                        subBuffers.add(subBuf);
                    } catch (Dgn7fileException e) {
                        logger.warn(e.getMessage(), e);
                    }
                }
            } else if (element instanceof ComplexShapeElement) {
                int size = ComplexShapeElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                ComplexShapeElement.ElementHandler.getInstance().write(buf, element);
                ComplexShapeElement complexElement = (ComplexShapeElement) element;
                ListIterator it = complexElement.listIterator();
                while (it.hasNext()) {
                    Element subElm = (Element) it.next();
                    try {
                        IElementHandler handler = subElm.getElementType().getElementHandler();
                        size = handler.getLength(subElm);
                        ByteBuffer subBuf = ByteBuffer.allocate(size * 2);
                        handler.write(subBuf, subElm);
                        subBuffers.add(subBuf);
                    } catch (Dgn7fileException e) {
                        logger.warn(e.getMessage(), e);
                    }
                }
            } else if (element instanceof ArcElement) {
                int size = ArcElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                ArcElement.ElementHandler.getInstance().write(buf, element);
            } else if (element instanceof EllipseElement) {
                int size = EllipseElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                EllipseElement.ElementHandler.getInstance().write(buf, element);
            } else if (element instanceof TextElement) {
                int size = TextElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                TextElement.ElementHandler.getInstance().write(buf, element);
            } else if (element instanceof TextNodeElement) {
                int size = TextNodeElement.ElementHandler.getInstance().getLength(element);
                buf = ByteBuffer.allocate(size * 2);
                TextNodeElement.ElementHandler.getInstance().write(buf, element);
                TextNodeElement nodeElement = (TextNodeElement) element;
                ListIterator it = nodeElement.listIterator();
                while (it.hasNext()) {
                    Element subElm = (Element) it.next();
                    try {
                        IElementHandler handler = subElm.getElementType().getElementHandler();
                        size = handler.getLength(subElm);
                        ByteBuffer subBuf = ByteBuffer.allocate(size * 2);
                        handler.write(subBuf, subElm);
                        subBuffers.add(subBuf);
                    } catch (Dgn7fileException e) {
                        logger.warn(e.getMessage(), e);
                    }
                }
            }
 
            if ((buf != null) && (fch != null)) {
                try {
                    buf.position(0);
                    int size = fch.write(buf);
                    if (size != buf.limit()) {
                        long position = fch.position();
                        logger.info("Pos:" + position);
                    }
                } catch (IOException e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        }
 
        elmCount++;
        if ((subBuffers.size() != 0) && (fch != null)) {
            for (ByteBuffer buf : subBuffers) {
                try {
                    buf.position(0);
                    int size = fch.write(buf);
                    if (size != buf.limit()) {
                        long position = fch.position();
                        logger.info("Pos:" + position);
                    }
                } catch (IOException e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        }
    }
 
    private void createNewStream() throws IOException, SQLException {
        if (fos != null) {
            putEndOfFileElement();
            fos.close();
            fos = null;
            fch = null;
        }
 
        String outLogName = currentSchema + ".dgn";
        if (prefix != null) {
            outLogName = prefix + outLogName;
        }
        File logFile = new File(getDataOutPath(), outLogName);
        while (logFile.exists()) {
            outLogName = this.currentSchema + "-" + (++logCount) + ".dgn";
            if (prefix != null) {
                outLogName = prefix + outLogName;
            }
 
            logFile = new File(getDataOutPath(), outLogName);
        }
 
        logger.warn("Create Dgn Logging File:" + logFile.toString());
        fos = new FileOutputStream(logFile);
        fch = fos.getChannel();
        prepareOutputElementStream();
        schemaChanged = false;
        elmCount = 0;
    }
 
    private void putEndOfFileElement() throws IOException {
        if (fch == null)
            return;
        ByteBuffer bf = ByteBuffer.allocate(4);
        bf.putInt(-1);
        fch.write(bf);
    }
 
    private void prepareOutputElementStream() throws SQLException, IOException {
        if (connection == null) {
            logger.warn("connection is null");
            return;
        }
 
        if (dgnFileHeader != null) {
            for (byte[] raw : dgnFileHeader) {
                putElementIntoStream(raw);
            }
            return;
        }
 
        dgnFileHeader = new ArrayList<byte[]>();
        String fetchSrcStmtFmt = "SELECT IGDSELM FROM \"%s\".\"%s\" ORDER BY ROWID";
        PrintfFormat spf = new PrintfFormat(fetchSrcStmtFmt);
        String fetchSrcStmt = spf.sprintf(new Object[]{currentSchema, TAB_IGDSSEED});
        Statement stmtSrc = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        ResultSet rsSrc = stmtSrc.executeQuery(fetchSrcStmt);
        int igdsMetaType = rsSrc.getMetaData().getColumnType(1);
 
        while (rsSrc.next()) {
            byte[] raw;
 
            if (igdsMetaType == Types.BLOB) {
                BLOB blob = (BLOB) rsSrc.getBlob(1);
 
                raw = getBytesFromBLOB(blob);
                // blob.close();
            } else {
                raw = rsSrc.getBytes(1);
            }
 
            if (raw != null) {
                dgnFileHeader.add(raw);
                putElementIntoStream(raw);
            }
        }
        rsSrc.close();
        stmtSrc.close();
    }
 
    private void putElementIntoStream(byte[] raw) throws IOException {
        if (fch != null)
            fch.write(ByteBuffer.wrap(raw));
    }
 
    protected byte[] getBytesFromBLOB(BLOB blob) throws SQLException {
        byte[] raw = null;
 
        int optimalSize = blob.getChunkSize();
        byte[] chunk = new byte[optimalSize];
        InputStream is = blob.getBinaryStream(0);
        ByteBuffer buffer = null;    // ByteBuffer.allocate(optimalSize);
        int len;
 
        try {
            while ((len = (is.read(chunk))) != -1) {
                if (buffer != null) {
                    buffer.limit(buffer.limit() + len);
                } else {
                    buffer = ByteBuffer.allocate(len);
                }
 
                buffer.put(chunk);
            }
 
            assert buffer != null;
            buffer.position(0);
            raw = buffer.array();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            Assert.shouldNeverReachHere();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                logger.warn("InputStream cannot close", e);
            }
            ;
        }
        return raw;
    }
 
    public void flashLogging() {
        if ((useElementCount) && (elmCount < maxElmCount)) {
            return;
        }
 
        if (fos != null) {
            try {
                putEndOfFileElement();
                fos.close();
            } catch (IOException e) {
                logger.warn(e.getMessage(), e);
            }
            fos = null;
            fch = null;
            elmCount = 0;
        }
    }
 
    public boolean isSchemaChanged() {
        return schemaChanged;
    }
 
    public boolean isUseElementCount() {
        return useElementCount;
    }
 
    public void setUseElementCount(boolean useElementCount) {
        this.useElementCount = useElementCount;
    }
 
    public int getElmCount() {
        return elmCount;
    }
 
    public int getMaxElmCount() {
        return maxElmCount;
    }
 
    public void setMaxElmCount(int maxElmCount) {
        this.maxElmCount = maxElmCount;
    }
 
    public String getLogPrefix() {
        return prefix;
    }
 
    public void setLogPrefix(String prefix) {
        this.prefix = prefix;
    }
}