01: /*
02: * FileNameSorter.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.db.importer;
13:
14: import java.io.File;
15: import java.io.FileFilter;
16: import java.util.ArrayList;
17: import java.util.HashMap;
18: import java.util.LinkedList;
19: import java.util.List;
20: import java.util.Map;
21: import workbench.db.TableIdentifier;
22: import workbench.db.WbConnection;
23: import workbench.util.WbFile;
24:
25: /**
26: *
27: * @author support@sql-workbench.net
28: */
29: public class FileNameSorter {
30: private List<WbFile> toProcess;
31: private WbConnection dbConn;
32: private TablenameResolver resolver;
33:
34: public FileNameSorter(WbConnection con, File sourceDir,
35: final String extension, TablenameResolver resolve) {
36: toProcess = new ArrayList<WbFile>();
37: this .resolver = resolve;
38: dbConn = con;
39: FileFilter ff = new FileFilter() {
40: public boolean accept(File pathname) {
41: if (pathname.isDirectory())
42: return false;
43: String fname = pathname.getName();
44: if (fname == null)
45: return false;
46: return (fname.toLowerCase().endsWith(extension
47: .toLowerCase()));
48: }
49: };
50:
51: File[] files = sourceDir.listFiles(ff);
52:
53: for (File f : files) {
54: toProcess.add(new WbFile(f));
55: }
56: }
57:
58: public List<WbFile> getFiles() {
59: return toProcess;
60: }
61:
62: public List<WbFile> getSortedList() throws CycleErrorException {
63: Map<String, WbFile> fileMapping = new HashMap<String, WbFile>(
64: toProcess.size());
65:
66: List<TableIdentifier> tables = new LinkedList<TableIdentifier>();
67: for (WbFile f : toProcess) {
68: String tablename = this .resolver.getTableName(f);
69: tables.add(new TableIdentifier(tablename));
70: fileMapping.put(tablename.toLowerCase(), f);
71: }
72:
73: TableDependencySorter sorter = new TableDependencySorter(dbConn);
74: List<TableIdentifier> sorted = sorter.sortForInsert(tables);
75: if (sorter.hasErrors()) {
76: throw new CycleErrorException(sorter.getErrorTables()
77: .get(0));
78: }
79:
80: List<WbFile> result = new LinkedList<WbFile>();
81: for (TableIdentifier tbl : sorted) {
82: String t = tbl.getTableName().toLowerCase();
83: WbFile f = fileMapping.get(t);
84: if (f != null) {
85: result.add(f);
86: }
87: }
88: return result;
89: }
90: }
|