View Javadoc

1   /* ===================================================================
2    * Copyright 2002-06 SRI International.
3    * Released under the MOZILLA PUBLIC LICENSE Version 1.1
4    * which can be obtained at http://www.mozilla.org/MPL/MPL-1.1.html
5    * This software is distributed on an "AS IS"
6    * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
7    * See the License for the specific language governing rights and
8    * limitations under the License.
9    * =================================================================== */
10  package com.sri.emo.commandline;
11  
12  import java.io.*;
13  import java.util.ArrayList;
14  import java.util.List;
15  import java.util.StringTokenizer;
16  
17  import com.jcorporate.expresso.core.db.DBConnectionPool;
18  import com.jcorporate.expresso.core.db.DBException;
19  import com.sri.emo.annotations.NodeTag;
20  import com.sri.emo.commandline.defaults.DefaultSQLGenerator;
21  import com.sri.emo.commandline.defaults.DefaultTreeExporter;
22  import com.sri.emo.commandline.defaults.InMemoryNodeTracker;
23  import com.sri.emo.commandline.defaults.WizardExporter;
24  import com.sri.emo.dbobj.Node;
25  import com.sri.emo.dbobj.selectiontree.TagSelectionFactory;
26  
27  /***
28   *
29   * @author Michael Rimov
30   * @version 1.0
31   */
32  public class Export extends AbstractEmoUtility {
33  	
34  	private final NodeTracker nodeTracker;
35  	
36  	private final TagSelectionFactory selectionFactory;
37  	
38  	private SqlRowGenerator generator;
39  	
40      public Export(NodeTracker nodeTracker, SqlRowGenerator generator, TagSelectionFactory selectionFactory) {
41          super();
42          this.nodeTracker = nodeTracker;
43          this.selectionFactory = selectionFactory;
44          this.generator = generator;
45      }
46  
47      public static void main(String[] args) throws Exception {
48      	if (!AbstractEmoUtility.checkArgs(args)) {
49      		usage();
50      		System.exit(-1);
51      	}
52      	
53      	setupExpresso("default");
54      	
55      	long startTime = System.currentTimeMillis();
56      	int numExported = 0;
57      	try {
58              numExported = exportTaggedTree(args);
59          } finally {
60      		DBConnectionPool.getInstance(System.getProperty("junit.argv.testContext","default")).disconnectAll();
61      	}
62          
63          System.out.println(
64          		"Export Complete.  Exported " 
65          		+ numExported 
66          		+ " records in " 
67          		+ ( (System.currentTimeMillis() - startTime) /1000 )         		
68          		+ "seconds.");
69          
70          System.out.println("Current total memory: "  + (Runtime.getRuntime().totalMemory() / 1000000l) + "Mb");
71          System.exit(0);
72      }
73  
74      /***
75       * @param args first string in array is tags
76       * @return number exported
77       */
78      private static int exportTaggedTree(String[] args) throws DBException, IOException {
79          int numExported = 0;
80          //
81          //Verify propery expresso instantiation.
82          //
83          NodeTag nodeTag = new NodeTag();
84          int tagCounts = nodeTag.count();
85          if (tagCounts == 0) {
86              throw new IllegalStateException("Could not find _any_ node tags in the database -- check database settings.");
87          }
88  
89          //Set up services and objects for use in the Export.
90  
91          String[] tagsToParse = parseTags(args[0]);
92  
93          StringBuffer tags = new StringBuffer();
94          boolean needComma = false;
95          for (int i =0; i < tagsToParse.length; i++) {
96              if (needComma) {
97                  tags.append(',');
98              } else {
99                  needComma = true;
100             }
101 
102             tags.append(tagsToParse[i]);
103 
104         }
105 
106         System.out.println("Exporting nodes marked with tag(s): " + tags.toString());
107         File f = new File(args[1]);
108         if (!f.exists()) {
109             System.out.println("Creating new file " + args[1] + " for export");
110         }
111 
112         TagSelectionFactory selectionFactory = new TagSelectionFactory(tagsToParse );
113 
114         FileWriter fileWriter = new FileWriter(f);
115         BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
116         PrintWriter writer = new PrintWriter(bufferedWriter);
117 
118 
119         try {
120             //Change the constructor to DefaultSQLGenerator.SKIP_IGNORE_SYNTAX when using hsqldb.
121             SqlRowGenerator sqlGenerator = new DefaultSQLGenerator(DefaultSQLGenerator.USE_IGNORE_SYNTAX);
122             Export treewriter = new Export(new InMemoryNodeTracker(), sqlGenerator, selectionFactory);
123             numExported = treewriter.exportNodes(writer);
124 
125         } finally {
126             writer.close();
127             bufferedWriter.close();
128             fileWriter.close();
129         }
130         return numExported;
131     }
132 
133     public int exportNodes(final PrintWriter writer) throws DBException  {
134         Node[] taggedNodes = selectionFactory.getTaggedNodes();
135 
136         TreeExporter exporter = new DefaultTreeExporter(nodeTracker, generator);
137 
138         System.out.println("Found " + taggedNodes.length + " node trees marked ready for export");
139         int totalRecordCount = 0;
140 
141         for (int i = 0; i < taggedNodes.length; i++) {
142             Node eachNode = taggedNodes[i];
143             try {
144                 totalRecordCount += exporter.exportNodeTree(writer, eachNode);
145                 //WE catch exception so things like out of memory ERRORS can
146                 //pass through.
147             } catch (Exception e) {
148                 System.err.println("Error adding node ID " + eachNode.getNodeId() + ": "
149                         + eachNode.getNodeTitle() + " to export file.");
150                 e.printStackTrace();
151                 //We continue on anyway --
152             }
153         }
154         
155         WizardExporter wizardExporter = new WizardExporter(nodeTracker, generator, selectionFactory.getTags());
156         totalRecordCount += wizardExporter.exportAllWizards(writer);
157 
158         return totalRecordCount;
159     }
160 	
161     protected static String[] parseTags(String commandLineArg) {
162 		if (!commandLineArg.startsWith("--tags")) {
163 			usage();
164 			System.exit(-1);
165 		}
166 		String tagsToParse = commandLineArg.substring("--tags".length() + 1);
167 		List result = new ArrayList();
168 		StringTokenizer stok = new StringTokenizer(tagsToParse,",");
169 		while (stok.hasMoreTokens()) {
170 			result.add(stok.nextToken());
171 		}
172 		if (result.size() == 0) {
173 			throw new IllegalArgumentException("Couldn't find any tags to parse in arg " + commandLineArg);
174 		}
175 		
176 		return (String[])result.toArray(new String[result.size()] );
177 	}    
178 	
179 	/***
180 	 * Ok, so I need to come up with a better usage statement.  Especially
181 	 * since this will probably be run from an ANT task.
182 	 */
183 	protected static void usage() {
184 		System.out.println("Usage: ");
185 		System.out.println("\t --tags=[tag1],[tag2],...,[tagN] <export filename>");
186 		System.out.println();
187 		System.out.println("Example args:  -tags=NSF export.sql");
188 	}
189 
190 	
191 }