KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > impl > load > ExportWriteData


1 /*
2
3    Derby - Class org.apache.derby.impl.load.ExportWriteData
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derby.impl.load;
23
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.BufferedOutputStream JavaDoc;
26 import java.io.OutputStreamWriter JavaDoc;
27 import java.net.MalformedURLException JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.util.Date JavaDoc;
30 import java.io.IOException JavaDoc;
31
32 //this class takes the passed row and writes it into the data file using the
33
//properties from the control file
34
//FIXED FORMAT: if length of nullstring is greater than column width, throw execption
35

36 final class ExportWriteData extends ExportWriteDataAbstract
37     implements java.security.PrivilegedExceptionAction JavaDoc {
38
39   private String JavaDoc outputFileName;
40   // i18n support - instead of using DataOutputStream.writeBytes - use
41
// OutputStreamWriter.write with the correct codeset.
42
private OutputStreamWriter JavaDoc aStream;
43
44   //writes data into the o/p file using control file properties
45
ExportWriteData(String JavaDoc outputFileName, ControlInfo controlFileReader)
46   throws Exception JavaDoc {
47     this.outputFileName = outputFileName;
48     this.controlFileReader = controlFileReader;
49     loadPropertiesInfo();
50
51     try {
52         java.security.AccessController.doPrivileged(this);
53     } catch (java.security.PrivilegedActionException JavaDoc pae) {
54         throw pae.getException();
55     }
56
57   }
58
59   public final Object JavaDoc run() throws Exception JavaDoc {
60       openFile();
61       return null;
62   }
63
64   //prepares the o/p file for writing
65
private void openFile() throws Exception JavaDoc {
66     try {
67       URL JavaDoc url = new URL JavaDoc(outputFileName);
68       outputFileName = url.getFile();
69     } catch (MalformedURLException JavaDoc ex) {}
70     FileOutputStream JavaDoc anOutputStream = new FileOutputStream JavaDoc(outputFileName);
71     BufferedOutputStream JavaDoc buffered = new BufferedOutputStream JavaDoc(anOutputStream);
72     
73     aStream = dataCodeset == null ?
74             new OutputStreamWriter JavaDoc(buffered) :
75             new OutputStreamWriter JavaDoc(buffered, dataCodeset);
76   }
77
78   /**if control file says true for column definition, write it as first line of the
79   * data file
80     * @exception Exception if there is an error
81     */

82   void writeColumnDefinitionOptionally(String JavaDoc[] columnNames,
83                                               String JavaDoc[] columnTypes)
84                                                         throws Exception JavaDoc {
85     boolean ignoreColumnTypes=true;
86
87     //do uppercase because the ui shows the values as True and False
88
if (columnDefinition.toUpperCase(java.util.Locale.ENGLISH).equals(ControlInfo.INTERNAL_TRUE.toUpperCase(java.util.Locale.ENGLISH))) {
89        String JavaDoc tempStr=new String JavaDoc();
90        //put the start and stop delimiters around the column name and type
91
for (int i=0; i<columnNames.length; i++) {
92          // take care at adding fieldSeparator at the
93
// end of the field if needed
94
if (i>0) {
95              tempStr=fieldSeparator;
96          } else {
97              tempStr="";
98          }
99
100          tempStr=tempStr+
101                  fieldStartDelimiter+columnNames[i]+fieldStopDelimiter;
102          if (ignoreColumnTypes==false) {
103              tempStr=tempStr+fieldSeparator+
104                  fieldStartDelimiter+columnTypes[i]+fieldStopDelimiter;
105          }
106
107          aStream.write(tempStr, 0, tempStr.length());
108        }
109        aStream.write(recordSeparator, 0, recordSeparator.length());
110     }
111   }
112
113   //puts the start and stop delimiters only if column value contains field/record separator
114
//in it
115
private void writeNextColumn(String JavaDoc oneColumn, boolean isNumeric) throws Exception JavaDoc {
116     if (oneColumn != null) {
117        //put the start and end delimiters always
118
//because of the bug 2045, I broke down following
119
//aStream.writeBytes(fieldStartDelimiter+oneColumn+fieldStopDelimiter);
120
//into 3 writeBytes. That bug had a table with long bit varying datatype and while
121
//writing data from that column using the stream, it would run out of memory.
122
// i18n - write using the write method of OutputStreamWriter
123
if (!isNumeric)
124            aStream.write(fieldStartDelimiter, 0, fieldStartDelimiter.length());
125        //convert the string to double character delimiters format if requred.
126
if(doubleDelimiter)
127            oneColumn = makeDoubleDelimiterString(oneColumn , fieldStartDelimiter);
128        aStream.write(oneColumn, 0, oneColumn.length());
129        if (!isNumeric)
130          aStream.write(fieldStopDelimiter, 0, fieldStopDelimiter.length());
131     }
132   }
133
134   /**write the passed row into the data file
135     * @exception Exception if there is an error
136     */

137   public void writeData(String JavaDoc[] oneRow, boolean[] isNumeric) throws Exception JavaDoc {
138     if (format.equals(ControlInfo.DEFAULT_FORMAT)) {
139        //if format is delimited, write column data and field separator and then the record separator
140
//if a column's value is null, write just the column separator
141
writeNextColumn(oneRow[0], isNumeric[0]);
142        for (int i = 1; i < oneRow.length; i++) {
143          aStream.write(fieldSeparator, 0, fieldSeparator.length());
144          writeNextColumn(oneRow[i], isNumeric[i]);
145        }
146        if (hasDelimiterAtEnd){ //write an additional delimeter if user wants one at the end of each row
147
aStream.write(fieldSeparator, 0, fieldSeparator.length());
148        }
149     }
150     aStream.write(recordSeparator, 0, recordSeparator.length());
151   }
152
153   /**if nothing more to write, then close the file and write a message of completion
154   * in message file
155     *@exception Exception if there is an error
156     */

157   public void noMoreRows() throws IOException JavaDoc {
158     aStream.flush();
159     aStream.close();
160 // System.err.print(new Date(System.currentTimeMillis()) + " ");
161
// System.err.println("Export finished");
162
// System.setErr(System.out);
163
}
164
165
166     /*
167      * Convert the input string into double delimiter format for export.
168      * double character delimiter recognition in delimited format
169      * files applies to the export and import utilities. Character delimiters are
170      * permitted within the character-based fields of a file. This applies to
171      * fields of type CHAR, VARCHAR, LONGVARCHAR, or CLOB. Any pair of character
172      * delimiters found between the enclosing character delimiters is imported
173      * into the database. For example with doble quote(") as character delimiter
174      *
175      * "What a ""nice""day!"
176      *
177      * will be imported as:
178      *
179      * What a "nice"day!
180      *
181      * In the case of export, the rule applies in reverse. For example,
182      *
183      * I am 6"tall.
184      *
185      * will be exported to a file as:
186      *
187      * "I am 6""tall."
188
189      */

190     private String JavaDoc makeDoubleDelimiterString(String JavaDoc inputString , String JavaDoc charDelimiter)
191     {
192         int start = inputString.indexOf(charDelimiter);
193         StringBuffer JavaDoc result;
194         //if delimeter is not found inside the string nothing to do
195
if(start != -1)
196         {
197             result = new StringBuffer JavaDoc(inputString);
198             int current;
199             int delLength = charDelimiter.length();
200             while(start!= -1)
201             {
202                 //insert delimter character
203
result = result.insert(start, charDelimiter);
204                 current = start + delLength +1 ;
205                 start = result.toString().indexOf(charDelimiter, current);
206             }
207             return result.toString();
208         }
209         return inputString;
210     }
211 }
212
213
Popular Tags