Source Code Cross Referenced for WbExport.java in  » Database-Client » SQL-Workbench » workbench » sql » wbcommands » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database Client » SQL Workbench » workbench.sql.wbcommands 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * WbExport.java
003:         *
004:         * This file is part of SQL Workbench/J, http://www.sql-workbench.net
005:         *
006:         * Copyright 2002-2008, Thomas Kellerer
007:         * No part of this code maybe reused without the permission of the author
008:         *
009:         * To contact the author please send an email to: support@sql-workbench.net
010:         *
011:         */
012:        package workbench.sql.wbcommands;
013:
014:        import java.io.File;
015:        import java.io.IOException;
016:        import java.sql.ResultSet;
017:        import java.sql.SQLException;
018:        import java.util.Collection;
019:        import java.util.List;
020:        import workbench.WbManager;
021:        import workbench.db.exporter.DataExporter;
022:        import workbench.interfaces.ProgressReporter;
023:        import workbench.log.LogMgr;
024:        import workbench.resource.ResourceMgr;
025:        import workbench.resource.Settings;
026:        import workbench.sql.SqlCommand;
027:        import workbench.sql.StatementRunnerResult;
028:        import workbench.storage.RowActionMonitor;
029:        import workbench.util.ArgumentParser;
030:        import workbench.util.ArgumentType;
031:        import workbench.util.CharacterRange;
032:        import workbench.util.EncodingUtil;
033:        import workbench.util.StringUtil;
034:        import workbench.db.TableIdentifier;
035:        import workbench.db.exporter.BlobMode;
036:        import workbench.db.exporter.ControlFileFormat;
037:        import workbench.db.exporter.PoiHelper;
038:        import workbench.util.ExceptionUtil;
039:        import workbench.util.WbFile;
040:
041:        /**
042:         * SQL Command for running an export.
043:         * @see workbench.db.exporter.DataExporter
044:         *
045:         * @author  support@sql-workbench.net
046:         */
047:        public class WbExport extends SqlCommand implements  RowActionMonitor,
048:                ProgressReporter {
049:            public static final String VERB = "WBEXPORT";
050:            private DataExporter exporter;
051:            private boolean directExport = false;
052:            private boolean continueOnError = false;
053:            private String currentTable;
054:            private String defaultExtension;
055:            private boolean showProgress = true;
056:            private int progressInterval = 1;
057:
058:            public WbExport() {
059:                cmdLine = new ArgumentParser();
060:                CommonArgs.addDelimiterParameter(cmdLine);
061:                CommonArgs.addEncodingParameter(cmdLine);
062:                CommonArgs.addProgressParameter(cmdLine);
063:                CommonArgs.addCommitParameter(cmdLine);
064:                CommonArgs.addVerboseXmlParameter(cmdLine);
065:                CommonArgs.addQuoteEscaping(cmdLine);
066:
067:                cmdLine
068:                        .addArgument(
069:                                "type",
070:                                StringUtil
071:                                        .stringToList("text,xml,sql,sqlinsert,sqlupdate,sqldeleteinsert,ods,xlsx,xls,html"));
072:                cmdLine.addArgument("file");
073:                cmdLine.addArgument("title");
074:                cmdLine.addArgument("table");
075:                cmdLine.addArgument("quotechar");
076:                cmdLine.addArgument("dateFormat");
077:                cmdLine.addArgument("timestampFormat");
078:                cmdLine.addArgument("decimal");
079:                cmdLine.addArgument("charFunc");
080:                cmdLine.addArgument("concat");
081:                cmdLine.addArgument("concatFunc");
082:                cmdLine.addArgument("header", ArgumentType.BoolArgument);
083:                cmdLine.addArgument("createTable", ArgumentType.BoolArgument);
084:                cmdLine.addArgument("keyColumns");
085:                cmdLine.addArgument("append", ArgumentType.BoolArgument);
086:                cmdLine.addArgument(WbXslt.ARG_STYLESHEET);
087:                cmdLine.addArgument(WbXslt.ARG_OUTPUT);
088:                cmdLine.addArgument("escapeHTML", ArgumentType.BoolArgument);
089:                cmdLine
090:                        .addArgument("createFullHTML",
091:                                ArgumentType.BoolArgument);
092:                cmdLine.addArgument("sourceTable", ArgumentType.TableArgument);
093:                cmdLine.addArgument("outputDir");
094:                cmdLine.addArgument("useCDATA", ArgumentType.BoolArgument);
095:                cmdLine.addArgument("escapeText", StringUtil
096:                        .stringToList("control,7bit,8bit,extended,none"));
097:                cmdLine.addArgument("quoteAlways", ArgumentType.BoolArgument);
098:                cmdLine.addArgument("lineEnding", StringUtil
099:                        .stringToList("crlf,lf"));
100:                cmdLine.addArgument("showEncodings");
101:                cmdLine.addArgument("writeOracleLoader",
102:                        ArgumentType.Deprecated);
103:                cmdLine.addArgument("formatFile", StringUtil
104:                        .stringToList("oracle,sqlserver"));
105:                cmdLine.addArgument("compress", ArgumentType.BoolArgument);
106:                cmdLine.addArgument("blobIdCols", ArgumentType.Deprecated);
107:                cmdLine.addArgument("lobIdCols");
108:                cmdLine.addArgument("filenameColumn");
109:                cmdLine.addArgument("blobType", BlobMode.getTypes());
110:                cmdLine.addArgument("clobAsFile", ArgumentType.BoolArgument);
111:                cmdLine.addArgument("continueOnError",
112:                        ArgumentType.BoolArgument);
113:                cmdLine.addArgument("sqlDateLiterals", Settings.getInstance()
114:                        .getLiteralTypeList());
115:                cmdLine.addArgument("createDir", ArgumentType.BoolArgument);
116:            }
117:
118:            public String getVerb() {
119:                return VERB;
120:            }
121:
122:            private void addWrongArgumentsMessage(StatementRunnerResult result) {
123:                if (WbManager.getInstance().isBatchMode())
124:                    return;
125:                String msg = getWrongArgumentsMessage();
126:                result.addMessageNewLine();
127:                result.addMessage(msg);
128:            }
129:
130:            private String getWrongArgumentsMessage() {
131:                String msg = ResourceMgr.getString("ErrExportWrongParameters");
132:                String header = "text="
133:                        + Boolean.toString(getHeaderDefault("text"));
134:                header += ", ods=" + Boolean.toString(getHeaderDefault("ods"));
135:                header += ", xls=" + Boolean.toString(getHeaderDefault("xls"));
136:                header += ", xlsx="
137:                        + Boolean.toString(getHeaderDefault("xlsx"));
138:
139:                msg = StringUtil.replace(msg, "%header_flag_default%", header);
140:                msg = StringUtil.replace(msg, "%verbose_default%", Boolean
141:                        .toString(getVerboseXmlDefault()));
142:                msg = StringUtil.replace(msg, "%date_literal_default%",
143:                        Settings.getInstance()
144:                                .getDefaultExportDateLiteralType());
145:                msg = StringUtil.replace(msg, "%default_encoding%", Settings
146:                        .getInstance().getDefaultDataEncoding());
147:                return msg;
148:            }
149:
150:            private boolean getVerboseXmlDefault() {
151:                return Settings.getInstance().getBoolProperty(
152:                        "workbench.export.xml.default.verbose", true);
153:            }
154:
155:            private boolean getHeaderDefault(String type) {
156:                return Settings.getInstance().getBoolProperty(
157:                        "workbench.export." + type + ".default.header", false);
158:            }
159:
160:            public StatementRunnerResult execute(String sql)
161:                    throws SQLException {
162:                StatementRunnerResult result = new StatementRunnerResult();
163:
164:                cmdLine.parse(getCommandLine(sql));
165:
166:                if (cmdLine.isArgPresent("showencodings")) {
167:                    result.addMessage(ResourceMgr
168:                            .getString("MsgAvailableEncodings"));
169:                    result.addMessage("");
170:                    String[] encodings = EncodingUtil.getEncodings();
171:                    for (int i = 0; i < encodings.length; i++) {
172:                        result.addMessage(encodings[i]);
173:                    }
174:                    return result;
175:                }
176:
177:                if (cmdLine.hasUnknownArguments()) {
178:                    setUnknownMessage(result, cmdLine,
179:                            getWrongArgumentsMessage());
180:                    return result;
181:                }
182:
183:                WbFile outputFile = evaluateFileArgument(cmdLine
184:                        .getValue("file"));
185:                String type = cmdLine.getValue("type");
186:
187:                if (type == null) {
188:                    type = findTypeFromFilename(outputFile);
189:                }
190:
191:                if (type == null) {
192:                    result.addMessage(ResourceMgr
193:                            .getString("ErrExportTypeRequired"));
194:                    addWrongArgumentsMessage(result);
195:                    result.setFailure();
196:                    return result;
197:                }
198:
199:                if (!isTypeValid(type)) {
200:                    result.addMessage(ResourceMgr
201:                            .getString("ErrExportWrongType"));
202:                    addWrongArgumentsMessage(result);
203:                    result.setFailure();
204:                    return result;
205:                }
206:
207:                this .exporter = new DataExporter(this .currentConnection);
208:
209:                String tables = cmdLine.getValue("sourcetable");
210:                String outputdir = cmdLine.getValue("outputdir");
211:
212:                if (outputFile == null && outputdir == null) {
213:                    result.addMessage(ResourceMgr
214:                            .getString("ErrExportFileRequired"));
215:                    addWrongArgumentsMessage(result);
216:                    result.setFailure();
217:                    return result;
218:                }
219:
220:                String updateTable = cmdLine.getValue("table");
221:                type = type.trim().toLowerCase();
222:                if ("txt".equals(type))
223:                    type = "text";
224:
225:                String encoding = cmdLine.getValue("encoding");
226:                if (encoding != null) {
227:                    exporter.setEncoding(encoding);
228:                }
229:                exporter.setAppendToFile(cmdLine.getBoolean("append"));
230:                exporter.setWriteClobAsFile(cmdLine.getBoolean("clobasfile",
231:                        false));
232:
233:                this .continueOnError = cmdLine.getBoolean("continueonerror",
234:                        false);
235:
236:                // Some properties used by more than one export type
237:                String format = cmdLine.getValue("dateformat");
238:                if (format != null)
239:                    exporter.setDateFormat(format);
240:
241:                format = cmdLine.getValue("timestampformat");
242:                if (format != null)
243:                    exporter.setTimestampFormat(format);
244:
245:                format = cmdLine.getValue("decimal");
246:                if (format != null)
247:                    exporter.setDecimalSymbol(format);
248:
249:                exporter.setPageTitle(cmdLine.getValue("title"));
250:
251:                exporter.setExportHeaders(cmdLine.getBoolean("header",
252:                        getHeaderDefault(type)));
253:
254:                if ("text".equals(type)) {
255:                    // Support old parameter Syntax
256:                    if (cmdLine.getBoolean("writeoracleloader", false)) {
257:                        exporter.addControlFileFormat(ControlFileFormat.oracle);
258:                    }
259:
260:                    exporter.addControlFileFormats(ControlFileFormat
261:                            .parseCommandLine(cmdLine.getValue("formatfile")));
262:
263:                    String delimiter = cmdLine.getValue("delimiter");
264:                    if (delimiter != null)
265:                        exporter.setTextDelimiter(delimiter);
266:
267:                    String quote = cmdLine.getValue("quotechar");
268:                    if (quote != null)
269:                        exporter.setTextQuoteChar(quote);
270:
271:                    String escape = cmdLine.getValue("escapetext");
272:                    if (escape != null) {
273:                        if ("control".equalsIgnoreCase(escape)
274:                                || "ctrl".equalsIgnoreCase(escape)) {
275:                            exporter
276:                                    .setEscapeRange(CharacterRange.RANGE_CONTROL);
277:                        } else if ("7bit".equalsIgnoreCase(escape)) {
278:                            exporter.setEscapeRange(CharacterRange.RANGE_7BIT);
279:                        } else if ("8bit".equalsIgnoreCase(escape)
280:                                || "true".equalsIgnoreCase(escape)) {
281:                            exporter.setEscapeRange(CharacterRange.RANGE_8BIT);
282:                        } else if ("extended".equalsIgnoreCase(escape)) {
283:                            exporter
284:                                    .setEscapeRange(CharacterRange.RANGE_8BIT_EXTENDED);
285:                        } else if ("none".equalsIgnoreCase(escape)
286:                                || "false".equalsIgnoreCase(escape)) {
287:                            exporter.setEscapeRange(null);
288:                        } else {
289:                            exporter.setEscapeRange(null);
290:                            String msg = ResourceMgr.getString(
291:                                    "ErrExportInvalidEscapeRangeIgnored")
292:                                    .replaceAll("%value%", escape);
293:                            result.addMessage(msg);
294:                        }
295:                    }
296:                    exporter.setQuoteAlways(cmdLine.getBoolean("quotealways"));
297:                    exporter.setQuoteEscaping(CommonArgs
298:                            .getQuoteEscaping(cmdLine));
299:
300:                    this .defaultExtension = ".txt";
301:                } else if (type.startsWith("sql")) {
302:                    exporter.setIncludeCreateTable(cmdLine
303:                            .getBoolean("createtable"));
304:                    exporter.setChrFunction(cmdLine.getValue("charfunc"));
305:                    exporter.setConcatFunction(cmdLine.getValue("concatfunc"));
306:                    exporter.setConcatString(cmdLine.getValue("concat"));
307:
308:                    CommonArgs.setCommitEvery(exporter, cmdLine);
309:
310:                    exporter.setAppendToFile(cmdLine.getBoolean("append"));
311:                    if (updateTable != null)
312:                        exporter.setTableName(updateTable);
313:                    String c = cmdLine.getValue("keycolumns");
314:                    if (c != null) {
315:                        List cols = StringUtil.stringToList(c, ",");
316:                        exporter.setKeyColumnsToUse(cols);
317:                    }
318:                    String bmode = cmdLine.getValue("blobtype");
319:                    exporter.setBlobMode(bmode);
320:                    this .defaultExtension = ".sql";
321:                    String literal = cmdLine.getValue("sqlDateLiterals");
322:                    if (literal != null) {
323:                        exporter.setDateLiteralType(literal);
324:                    }
325:                } else if ("xml".equals(type)) {
326:                    String xsl = cmdLine.getValue(WbXslt.ARG_STYLESHEET);
327:                    String output = cmdLine.getValue(WbXslt.ARG_OUTPUT);
328:
329:                    boolean verboseDefault = getVerboseXmlDefault();
330:                    boolean verbose = cmdLine.getBoolean(
331:                            CommonArgs.ARG_VERBOSE_XML, verboseDefault);
332:                    exporter.setUseVerboseFormat(verbose);
333:
334:                    if (xsl != null && output != null) {
335:                        File f = new File(xsl);
336:                        if (f.exists()) {
337:                            exporter.setXsltTransformation(xsl);
338:                            exporter.setXsltTransformationOutput(output);
339:                        } else {
340:                            String msg = ResourceMgr
341:                                    .getString("ErrSpoolXsltNotFound");
342:                            msg = msg.replaceAll("%xslt%", f.getAbsolutePath());
343:                            result.addMessage(msg);
344:                        }
345:                    }
346:                    this .exporter.setUseCDATA(cmdLine.getBoolean("usecdata"));
347:                    if (updateTable != null)
348:                        exporter.setTableName(updateTable);
349:                    this .defaultExtension = ".xml";
350:                    if (encoding == null) {
351:                        // Make sure to use UTF-8 as the default if no encoding is specified
352:                        this .exporter.setEncoding("UTF-8");
353:                    }
354:                } else if ("html".equals(type)) {
355:                    String value = cmdLine.getValue("escapehtml");
356:                    if (value != null) {
357:                        exporter.setEscapeHtml("true".equalsIgnoreCase(value));
358:                    }
359:                    value = cmdLine.getValue("createfullhtml");
360:                    if (value != null) {
361:                        exporter.setCreateFullHtmlPage("true"
362:                                .equalsIgnoreCase(value));
363:                    }
364:                    if (updateTable != null)
365:                        exporter.setTableName(updateTable);
366:                    this .defaultExtension = ".html";
367:                } else if (type.equalsIgnoreCase("xls")) {
368:                    if (!PoiHelper.isPoiAvailable()) {
369:                        result.setFailure();
370:                        result.addMessage(ResourceMgr
371:                                .getString("ErrExportNoPoi"));
372:                        return result;
373:                    }
374:                }
375:
376:                String ending = cmdLine.getValue("lineending");
377:                if (ending != null) {
378:                    if ("crlf".equalsIgnoreCase(ending)
379:                            || "dos".equalsIgnoreCase(ending)
380:                            || "win".equalsIgnoreCase(ending)
381:                            || "\\r\\n".equals(ending)) {
382:                        exporter.setLineEnding("\r\n");
383:                    } else if ("lf".equalsIgnoreCase(ending)
384:                            || "unix".equalsIgnoreCase(ending)
385:                            || "linux".equalsIgnoreCase(ending)
386:                            || "\\n".equals(ending)) {
387:                        exporter.setLineEnding("\n");
388:                    }
389:                }
390:
391:                String cols = cmdLine.getValue("lobidcols");
392:                if (cols == null) {
393:                    cols = cmdLine.getValue("blobidcols");
394:                    if (cols != null) {
395:                        result
396:                                .addMessage("The blobIdCols parameter is deprecated, please use lobIdCols");
397:                        result.setWarning(true);
398:                    }
399:                }
400:
401:                List<String> columns = StringUtil.stringToList(cols, ",", true,
402:                        true, false);
403:                this .exporter.setBlobIdColumns(columns);
404:                this .exporter.setCompressOutput(cmdLine.getBoolean("compress",
405:                        false));
406:
407:                this .exporter.setOutputFilename(outputFile != null ? outputFile
408:                        .getFullPath() : null);
409:
410:                // Setting the output type should be the last step in the configuration
411:                // of the exporter as this will trigger some initialization
412:                // that depends on the other properties
413:                setExportType(exporter, type);
414:
415:                List<TableIdentifier> tablesToExport = null;
416:                try {
417:                    SourceTableArgument argParser = new SourceTableArgument(
418:                            tables, this .currentConnection);
419:                    tablesToExport = argParser.getTables();
420:                    if (tablesToExport.size() == 0
421:                            && argParser.wasWildCardArgument()) {
422:                        result.addMessage(ResourceMgr.getFormattedString(
423:                                "ErrExportNoTablesFound", tables));
424:                        result.setFailure();
425:                        return result;
426:                    }
427:                } catch (SQLException e) {
428:                    LogMgr.logError("WbExport.runTableExports()",
429:                            "Could not retrieve table list", e);
430:                    result.addMessage(ExceptionUtil.getDisplay(e));
431:                    result.setFailure();
432:                    return result;
433:                }
434:
435:                this .directExport = (tablesToExport.size() > 0);
436:
437:                CommonArgs.setProgressInterval(this , cmdLine);
438:                this .showProgress = (this .progressInterval > 0);
439:
440:                boolean create = cmdLine.getBoolean("createdir", false);
441:
442:                if (create) {
443:                    WbFile dir = null;
444:                    if (outputFile != null) {
445:                        dir = new WbFile(outputFile.getParentFile());
446:                    } else if (!StringUtil.isEmptyString(outputdir)) {
447:                        dir = new WbFile(outputdir);
448:                    }
449:
450:                    if (!dir.exists()) {
451:                        if (!dir.mkdirs()) {
452:                            result.addMessage(ResourceMgr.getFormattedString(
453:                                    "ErrCreateDir", dir.getFullPath()));
454:                            result.setFailure();
455:                            return result;
456:                        } else {
457:                            result.addMessage(ResourceMgr.getFormattedString(
458:                                    "MsgDirCreated", dir.getFullPath()));
459:                        }
460:                    }
461:                }
462:
463:                if (outputFile != null) {
464:                    // For a single table export the definition of a
465:                    String extCol = cmdLine.getValue("filenameColumn");
466:                    exporter.setFilenameColumn(extCol);
467:
468:                    // Check the outputfile right now, so the user does not have
469:                    // to wait for a possible error message until the ResultSet
470:                    // from the SELECT statement comes in...
471:                    boolean canWrite = true;
472:                    String msg = null;
473:                    try {
474:                        // File.canWrite() does not work reliably. It will report
475:                        // an error if the file does not exist, but still could
476:                        // be written.
477:                        if (outputFile.exists()) {
478:                            msg = ResourceMgr.getString("ErrExportFileWrite");
479:                            canWrite = outputFile.canWrite();
480:                        } else {
481:                            // try to create the file
482:                            outputFile.tryCreate();
483:                        }
484:                    } catch (IOException e) {
485:                        canWrite = false;
486:                        msg = ResourceMgr.getString("ErrExportFileCreate")
487:                                + " " + e.getMessage();
488:                    }
489:
490:                    if (!canWrite) {
491:                        result.addMessage(msg);
492:                        result.setFailure();
493:                        return result;
494:                    }
495:                }
496:
497:                if (!this .directExport) {
498:                    // Waiting for the next SQL Statement...
499:                    this .exporter.setRowMonitor(this .rowMonitor);
500:                    this .exporter.setReportInterval(this .progressInterval);
501:
502:                    String msg = ResourceMgr.getString("MsgSpoolInit");
503:                    msg = StringUtil.replace(msg, "%type%", exporter
504:                            .getTypeDisplay());
505:                    msg = StringUtil.replace(msg, "%file%", outputFile
506:                            .getFullPath());
507:                    //msg = msg + " quote=" + exporter.getTextQuoteChar();
508:                    result.addMessage(msg);
509:                    if (this .maxRows > 0) {
510:                        msg = ResourceMgr.getString("MsgExportMaxRowsWarning")
511:                                .replaceAll("%maxrows%",
512:                                        Integer.toString(maxRows));
513:                        result.addMessage(msg);
514:                    }
515:                } else {
516:                    try {
517:                        File outdir = (StringUtil.isEmptyString(outputdir) ? null
518:                                : new File(outputdir));
519:                        exporter.setRowMonitor(this );
520:                        exporter.setReportInterval(this .progressInterval);
521:                        exporter.setContinueOnError(this .continueOnError);
522:                        runDirectExport(tablesToExport, result, outdir);
523:                        addMessages(result);
524:                    } catch (Exception e) {
525:                        LogMgr.logError("WbExport.execute()",
526:                                "Error when running table export", e);
527:                        addErrorInfo(result, sql, e);
528:                        result.setFailure();
529:                    }
530:                }
531:                return result;
532:            }
533:
534:            boolean isTypeValid(String type) {
535:                if (type == null)
536:                    return false;
537:                Collection<String> types = cmdLine.getAllowedValues("type");
538:                return types.contains(type);
539:            }
540:
541:            private void setExportType(DataExporter exporter, String type) {
542:                if (type.equals("sql") || type.equals("sqlinsert")) {
543:                    exporter.setOutputTypeSqlInsert();
544:                } else if (type.equals("sqlupdate")) {
545:                    exporter.setOutputTypeSqlUpdate();
546:                } else if (type.equals("sqldeleteinsert")) {
547:                    exporter.setOutputTypeSqlDeleteInsert();
548:                } else if (type.equals("xml")) {
549:                    exporter.setOutputTypeXml();
550:                } else if (type.equals("text") || type.equals("txt")) {
551:                    exporter.setOutputTypeText();
552:                } else if (type.equals("html")) {
553:                    exporter.setOutputTypeHtml();
554:                } else if (type.equals("ods")) {
555:                    exporter.setOutputTypeOds();
556:                } else if (type.equals("xls")) {
557:                    exporter.setOutputTypeXls();
558:                } else if (type.equals("xlsx")) {
559:                    exporter.setOutputTypeXlsXML();
560:                }
561:            }
562:
563:            private void runDirectExport(List<TableIdentifier> tableList,
564:                    StatementRunnerResult result, File outdir)
565:                    throws SQLException {
566:                if (tableList.size() > 1) {
567:                    exportTableList(tableList, result, outdir);
568:                } else {
569:                    exportSingleTable(tableList.get(0), result, outdir);
570:                }
571:            }
572:
573:            private void exportSingleTable(TableIdentifier table,
574:                    StatementRunnerResult result, File outdir)
575:                    throws SQLException {
576:                String outfile = this .exporter.getOutputFilename();
577:
578:                if (StringUtil.isEmptyString(outfile)) {
579:                    outfile = StringUtil.makeFilename(table.getTableName());
580:                    File f = new File(outdir, outfile + defaultExtension);
581:                    outfile = f.getAbsolutePath();
582:                }
583:                exporter.addTableExportJob(outfile, table);
584:                exporter.runJobs();
585:                if (exporter.isSuccess()) {
586:                    long rows = exporter.getTotalRows();
587:                    String msg = ResourceMgr
588:                            .getString("MsgExportTableExported");
589:                    msg = StringUtil.replace(msg, "%file%", exporter
590:                            .getFullOutputFilename());
591:                    msg = StringUtil.replace(msg, "%tablename%", table
592:                            .getTableExpression());
593:                    msg = StringUtil
594:                            .replace(msg, "%rows%", Long.toString(rows));
595:                    result.addMessage(msg);
596:                } else {
597:                    result.setFailure();
598:                }
599:            }
600:
601:            private void exportTableList(List<TableIdentifier> tableList,
602:                    StatementRunnerResult result, File outdir)
603:                    throws SQLException {
604:                result.setSuccess();
605:
606:                int tableCount = tableList.size();
607:
608:                // when more than one table is selected or no outputfile is specified
609:                // then we require an output directory
610:                if (outdir == null) {
611:                    result.setFailure();
612:                    result.addMessage(ResourceMgr
613:                            .getString("ErrExportOutputDirRequired"));
614:                    return;
615:                }
616:
617:                if (outdir == null || !outdir.exists()) {
618:                    String msg = ResourceMgr
619:                            .getString("ErrExportOutputDirNotFound");
620:                    msg = StringUtil.replace(msg, "%dir%", outdir
621:                            .getAbsolutePath());
622:                    result.addMessage(msg);
623:                    result.setFailure();
624:                    return;
625:                }
626:
627:                if (!outdir.isDirectory()) {
628:                    String msg = ResourceMgr
629:                            .getString("ErrExportOutputDirNotDir");
630:                    msg = StringUtil.replace(msg, "%dir%", outdir
631:                            .getAbsolutePath());
632:                    result.addMessage(msg);
633:                    result.setFailure();
634:                    return;
635:                }
636:
637:                for (TableIdentifier tbl : tableList) {
638:                    String fname = StringUtil.makeFilename(tbl
639:                            .getTableExpression());
640:                    File f = new File(outdir, fname + defaultExtension);
641:                    try {
642:                        exporter.addTableExportJob(f.getAbsolutePath(), tbl);
643:                    } catch (SQLException e) {
644:                        if (continueOnError) {
645:                            result.addMessage(ResourceMgr
646:                                    .getString("TxtWarning")
647:                                    + ": " + e.getMessage());
648:                            result.setWarning(true);
649:                        } else {
650:                            throw e;
651:                        }
652:                    }
653:                }
654:
655:                exporter.runJobs();
656:
657:                if (exporter.isSuccess()) {
658:                    tableCount = exporter.getNumberExportedTables();
659:                    String msg = ResourceMgr.getString("MsgExportNumTables");
660:                    msg = msg.replaceAll("%numtables%", Integer
661:                            .toString(tableCount));
662:                    msg = StringUtil.replace(msg, "%dir%", outdir
663:                            .getAbsolutePath());
664:                    result.addMessage(msg);
665:                    result.setSuccess();
666:                } else {
667:                    result.setFailure();
668:                }
669:            }
670:
671:            private void addMessages(StatementRunnerResult result) {
672:                result.addMessage(this .exporter.getErrors());
673:
674:                if (exporter.hasWarning()) {
675:                    result.addMessage(ResourceMgr.getString("TxtWarnings"));
676:                    result.addMessage(exporter.getWarnings());
677:                }
678:            }
679:
680:            public boolean isResultSetConsumer() {
681:                return !this .directExport;
682:            }
683:
684:            public void setMaxRows(int rows) {
685:                this .maxRows = rows;
686:            }
687:
688:            public void consumeResult(StatementRunnerResult aResult) {
689:                // Run an export that is defined by a SQL Statement
690:                // i.e. no sourcetable given in the initial wbexport command
691:                try {
692:                    if (aResult.hasResultSets()) {
693:                        String sql = aResult.getSourceCommand();
694:                        this .exporter.setSql(sql);
695:                        ResultSet toExport = aResult.getResultSets().get(0);
696:                        // The exporter has already closed the resultSet that it exported
697:                        // so we can remove it from the list of ResultSets in the StatementRunnerResult
698:                        // object. Thus the later call to clearResultSets() will only free any not used
699:                        // ResultSet
700:                        aResult.getResultSets().remove(0);
701:                        long rowCount = this .exporter.startExport(toExport);
702:
703:                        String msg = null;
704:
705:                        if (exporter.isSuccess()) {
706:                            msg = ResourceMgr.getString("MsgSpoolOk")
707:                                    .replaceAll("%rows%",
708:                                            Long.toString(rowCount));
709:                            aResult.addMessage(""); // force new line in output
710:                            aResult.addMessage(msg);
711:                            msg = ResourceMgr.getString("MsgSpoolTarget") + " "
712:                                    + this .exporter.getFullOutputFilename();
713:                            aResult.addMessage(msg);
714:                        }
715:                        addMessages(aResult);
716:
717:                        if (exporter.isSuccess()) {
718:                            aResult.setSuccess();
719:                        } else {
720:                            aResult.setFailure();
721:                        }
722:                    }
723:                } catch (Exception e) {
724:                    aResult.setFailure();
725:                    aResult.addMessage(ResourceMgr
726:                            .getString("ErrExportExecute"));
727:                    aResult.addMessage(ExceptionUtil.getAllExceptions(e));
728:                    LogMgr.logError("WbExportCommand.consumeResult()",
729:                            "Error spooling data", e);
730:                } finally {
731:                    aResult.clearResultSets();
732:                }
733:            }
734:
735:            public void done() {
736:                super .done();
737:                exporter = null;
738:                maxRows = 0;
739:                directExport = false;
740:                currentTable = null;
741:                defaultExtension = null;
742:            }
743:
744:            public void cancel() throws SQLException {
745:                if (this .exporter != null) {
746:                    this .exporter.cancelExecution();
747:                }
748:                super .cancel();
749:            }
750:
751:            public void jobFinished() {
752:            }
753:
754:            public void setCurrentObject(String object, long number, long total) {
755:                this .currentTable = object;
756:                if (!this .showProgress && this .rowMonitor != null) {
757:                    this .rowMonitor.setCurrentObject(this .currentTable, -1, -1);
758:                }
759:            }
760:
761:            public void setCurrentRow(long currentRow, long totalRows) {
762:                if (this .showProgress && this .rowMonitor != null) {
763:                    this .rowMonitor.setCurrentObject(this .currentTable,
764:                            currentRow, -1);
765:                }
766:            }
767:
768:            public void setReportInterval(int interval) {
769:                this .progressInterval = interval;
770:            }
771:
772:            public int getMonitorType() {
773:                return RowActionMonitor.MONITOR_PLAIN;
774:            }
775:
776:            public void setMonitorType(int aType) {
777:            }
778:
779:            public void saveCurrentType(String type) {
780:            }
781:
782:            public void restoreType(String type) {
783:            }
784:
785:            protected String findTypeFromFilename(WbFile f) {
786:                if (f == null)
787:                    return null;
788:                String fname = f.getFullPath();
789:                if (fname == null)
790:                    return null;
791:                if (fname.toLowerCase().endsWith(".txt"))
792:                    return "text";
793:                if (fname.toLowerCase().endsWith(".xml"))
794:                    return "xml";
795:                if (fname.toLowerCase().endsWith(".text"))
796:                    return "text";
797:                if (fname.toLowerCase().endsWith(".csv"))
798:                    return "text";
799:                if (fname.toLowerCase().endsWith(".htm"))
800:                    return "html";
801:                if (fname.toLowerCase().endsWith(".html"))
802:                    return "html";
803:                if (fname.toLowerCase().endsWith(".sql"))
804:                    return "sqlinsert";
805:                if (fname.toLowerCase().endsWith(".xls"))
806:                    return "xls";
807:                if (fname.toLowerCase().endsWith(".ods"))
808:                    return "ods";
809:                return null;
810:            }
811:
812:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.