1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 /*
25  * the main Class
26  *
27  * Command Line arguments are reviewed
28  * and a Converter is constructed
29  */
30 package com.sun.star.tooling.converter;
31 
32 import java.io.BufferedWriter;
33 import java.io.File;
34 import java.io.FileWriter;
35 import java.io.IOException;
36 import java.util.Calendar;
37 
38 import com.sun.star.tooling.DirtyTags.DirtyTagWrapper;
39 
40 /**
41  * The main class of the converter tool
42  *
43  * The converter tool is command line based.
44  * Its classes allow the converting between the
45  * file formats sdf, gsi and <a href="http://www.oasis-open.org/committees/xliff/documents/cs-xliff-core-1.1-20031031.htm">xliff</a>.
46  *
47  * Those file formats are used in localization
48  * of Star-Office and OpenOffice.
49  *
50  * Information about the whole localization process can be found in
51  * <a href="http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf">http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf</a>
52  *
53  * @author Christian Schmidt 2005
54  *
55  */
56 public class Convert {
57 
58     private static Calendar     cal;
59 
60     private static final String EMPTY              = "";
61 
62     /**
63      * The name of the  file containing the debug information
64      * that where found while converting (every output goes here too)
65      */
66     private static String       dbgName            = EMPTY;
67 
68     /**
69      * the character that separates the extension from the file name
70      */
71     private static final char   extensionSeperator = '.';
72 
73     /**
74      * the log File
75      */
76     private static File         log;
77 
78     /**
79      * the name of the log file
80      */
81     private static String       logString          = EMPTY;
82 
83     /**
84      * indicates whether existing sources should be overwritten
85      * without asking
86      */
87     private static boolean      overwrite          = false;
88 
89     /**
90      * A second Source File needed for GSI Merging
91      */
92     private static File secondSource;
93 
94     //private static final char   pathSeperator      = '\\';
95 
96     /**
97      * The language that should be the source language
98      * that means the language to translate from
99      */
100     private static String       sourceLanguage     = "en-US";
101 
102     /**
103      * the name of the source file
104      */
105     private static String       sourceName         = EMPTY;
106 
107     /**
108      * the type of the source file (sdf,xliff,...)
109      */
110     private static String       sourceType         = EMPTY;
111 
112     /**
113      * The time when converting started
114      */
115     private static String       startTime          = EMPTY;
116     /**
117     * The language that should be the target language
118     * that means the language to translate to
119     */
120     private static String       TargetLanguage     = EMPTY;
121 
122     /**
123      * the name of the target file
124      */
125     private static String       targetName         = EMPTY;
126 
127     /**
128      * the type of the target file (sdf,xliff,...)
129      */
130     private static String       targetType         = EMPTY;
131 
132     /**
133      * Store the current version ID and number of this tool
134      */
135     final static String         version            = " Prod.20050710:1255 ";
136 
137     /**
138      * The name of the (original) sdf file used as second source for gsi->sdf merging
139      */
140     private static String secondSourceName=EMPTY;
141     /**
142      * Indicate whether strings in xliff files should
143      * be wrapped with ept/bpt or sub tags to enable translation tools
144      * to synchronize source language string with there translation
145      *
146      * @see <a href="http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf">http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf</a>
147      */
148     private static boolean doWrap=true;
149 
150 
151 
main(String[] args)152             public static void main(String[] args) throws IOException, Exception {
153                 try{
154 
155                     //go, parse and check the command line parameters
156                     ParameterChecker.checkClParameters(args);
157                     ParameterChecker.createContentOfClParameters();
158                     //Initialize the tagWrapper
159                     DirtyTagWrapper.setWrapping(doWrap);
160                     //create an instance of converter
161                     Converter conv = new Converter(sourceType, sourceName, sourceLanguage,
162                             targetType, targetName, TargetLanguage,secondSourceName, overwrite);
163                     // get actual time
164                     cal = Calendar.getInstance();
165                     startTime = cal.getTime().toString();
166                     //show infos
167                     printPreamble();
168                     //do the job
169                     conv.convert();
170 
171                     showStatistic();
172 
173                     //close log, debug...
174                     OutputHandler.closeAll();
175 
176                 } catch(Exception e){
177                     System.out.print("An EXCEPTION occurred, please check your commad line settings \n"+e.getMessage());
178                     System.exit(-1);
179                 }catch(Throwable t){
180                     System.out.print("A FATAL ERROR occurred, please check your commad line settings \n"+t.getMessage());
181                     System.exit(-1);
182                 }
183 
184     }
185 
186     /**
187      * show the command line help
188      */
printHelp()189     private static void printHelp() {
190 
191         final String ls = System.getProperty("line.separator");
192         System.out
193                 .println(
194 
195                 "File Converting Tool 'converter' Version "
196                         + Convert.version
197                         + ls
198                         + "Converts SDF files to wellformed XLIFF or GSI files and vice versa" + ls
199                         + ls
200                         + "Use: " + ls
201                         + "convert [-h]|[SourcePath [TargetPath] [-T Type] [[-S Type [secondSourcePath]]  " + ls
202                         + "        [-s LanguageID] [-t LanguageID] [-l [LogPath]] [-o]]" + ls
203                         + ls
204                         + "-h               show this help." + ls
205                         + "SourcePath       path of the file to convert." + ls
206                         + "secondSourcePath path of the SDF file to merge to (GSI -> SDF only!)." + ls
207                         + "TargetPath       path where to store the result." + ls
208                         + "LogPath          path of the log file" + ls
209                         + "-T Type          the type of the target file (xliff,sdf,gsi)" + ls
210                         + "-S Type          the type of the source file (xliff,sdf,gsi)" + ls
211                         + "-s LanguageID    the ISO language code of the source language (de, fr...)." + ls
212                         + "                 Default is 'en-US' " + ls
213                         + "-t LanguageID    the language code of the target language (de, fr...)." + ls
214                         + "                 Default is first found Language other than source language." + ls
215                         + "-l [LogPath]     write a log file, you can name the file." + ls
216                         + "-o               overwrite existing files without asking." + ls
217                         + "-nw              disable the wrapping with ept/bpt tags." + ls
218                         + ls
219                         + "The created files were stored in the SourceFile Path if nothing else is given. " + ls
220                         + "The extension is '.xliff','.sdf' depending on the source file and '.log' " + ls
221                         + "for the logfile." + ls);
222     }
223 
224     /**
225      * show the parameters the converter starts with
226      *
227      * @throws IOException
228      */
printPreamble()229     final private static void printPreamble() throws IOException {
230         OutputHandler.out(EMPTY);
231         OutputHandler.out("Source File is: " + sourceName);
232         OutputHandler.out("Target File is: " + targetName);
233         if (OutputHandler.doLog) {
234             OutputHandler.out("Log File    is: " + logString);
235         } else {
236             OutputHandler.out("Log File    is: disabled");
237         }
238 
239         OutputHandler.out(EMPTY);
240 
241     }
242 
243     /**
244      * show some statistic data
245      *
246      * @throws IOException
247      */
showStatistic()248     final private static void showStatistic() throws IOException {
249         OutputHandler.dbg(EMPTY);
250         OutputHandler
251                 .out((targetType.equalsIgnoreCase("xliff") ? "TransUnits written:   "
252                         : "Lines written :         ")
253                         + Converter.getLineCounter());
254         OutputHandler.dbg(EMPTY);
255         OutputHandler.out("Started    at :         " + Convert.startTime);
256         Convert.cal = Calendar.getInstance();
257         OutputHandler.out("Finished   at :         " + Convert.cal.getTime());
258         OutputHandler.dbg(EMPTY);
259 
260     }
261 
262     /**
263      * Get the extension of a file name
264      * (sdf,xliff,gsi)
265      *
266      * @param sourceString     the file name
267      * @return                 the extension
268      */
extractExtension(String sourceString)269     static protected String extractExtension(String sourceString) {
270         String ext = sourceString.substring(sourceString
271                 .lastIndexOf(Convert.extensionSeperator) + 1);
272         return ext;
273     }
274 
275 //    static protected String extractFileName(String sourceString) {
276 //        String sName = EMPTY;
277 //        sName = (sourceString.substring(sourceString
278 //                .lastIndexOf(File.separator) + 1, sourceString
279 //                .lastIndexOf(Convert.extensionSeperator)));
280 //
281 //        return sName;
282 //    }
283 //
284 //    static protected String extractPath(String sourceString) {
285 //        String sPath = sourceString.substring(0, sourceString
286 //                .lastIndexOf(File.separator) + 1);
287 //        return sPath;
288 //    }
289 
290     /**
291      *
292      */
Convert()293     public Convert() {
294     }
295 
296     /**
297      *
298      * Verify a parameter array and create content usable by the program
299      * from the switches and attributes set at command line
300      *
301      * @author Christian Schmidt 2005
302      */
303     private static class ParameterChecker {
304 
305         /**
306          * Holds the path of the source file
307          */
308         private static String filePath;
309         /**
310          * Holds the name of the source file
311          */
312         private static String fileName;
313 
314         /**
315          * Create a new Instance of ParameterChecker
316          *
317          *
318          */
ParameterChecker()319         public ParameterChecker(){};
320         /**
321          * Checks the command line parameters
322          *
323          * @param args          the parameters to check and to parse
324          * @throws IOException
325          */
checkClParameters(String[] args)326         private static void checkClParameters(String[] args) throws IOException {
327             try {
328                 // show help if no attributes...
329                 if (args.length == 0) {
330                     printHelp();
331                     System.exit(-1);
332                 }
333                 //...or attribute is -h
334                 if (args[0].equals("-h")) {
335                     printHelp();
336                     System.exit(0);
337                 }
338                 if (args[0].equals("-ver")) {
339                     System.out.println("File Converting Tool Version "+version);
340                     System.exit(0);
341                 }
342                 //source file Location and path is always first attribute
343                 sourceName = new String(args[0]);
344 
345                 File source = new File(sourceName);
346                 //break if there is no source to convert
347                 if (!source.exists())
348                     throw new IOException("ERROR: Can not find Source File '"
349                             + sourceName + "'. Aborting...");
350 
351     //            String name=source.getName();
352     //            String parent=source.getParent();
353     //            String path=source.getPath();
354 
355                 filePath = (source.getParent()==null)?"":source.getParent()+File.separator; //extractPath(sourceName);
356                 fileName = source.getName().substring(0,source.getName().lastIndexOf(extensionSeperator));
357 
358                 for (int i = 1; i < args.length; i++) {
359 
360 
361                         if ("-s".equals(args[i])) {
362                             if (args.length > i + 1) {
363                                 sourceLanguage = args[++i];
364 
365                             } else {
366                                 throw new ConverterException(
367                                         "missing argument for -s source language");
368                             }
369                             continue;
370                         }
371 
372                         if ("-S".equals(args[i])) {
373                             if (args.length > i + 1) {
374                                 sourceType = args[++i];
375                                 if (args.length > i +1 &&!args[i+1].startsWith("-")) {
376                                     secondSourceName = args[++i];
377                                 }
378 
379                             } else {
380                                 throw new ConverterException(
381                                         "missing argument for -S  source type");
382                             }
383                             continue;
384                         }
385 
386                         if ("-T".equals(args[i])) {
387                             if (args.length > i + 1) {
388                                 targetType = args[++i];
389 
390 
391                             } else {
392                                 throw new ConverterException(
393                                         "missing argument for -T  target type");
394                             }
395                             continue;
396                         }
397 
398                         if ("-l".equals(args[i])) {
399                             OutputHandler.doLog = true;
400                             if (args.length > i + 1
401                                     && (!args[i + 1].startsWith("-"))) {
402                                 logString = args[++i];
403                             } else {
404                                 logString = EMPTY;
405                             }
406                             continue;
407                         }
408 
409                         if ("-o".equals(args[i])) {
410                             overwrite = true;
411                             continue;
412                         }
413 
414                         if ("-nw".equals(args[i])) {
415                             doWrap = false;
416                             continue;
417                         }
418 
419                         if ("-h".equals(args[i])) {
420                             printHelp();
421                             System.exit(0);
422                         }
423 
424                         if ("-dbg".equals(args[i])) {
425                             OutputHandler.doDebug = true;
426                             continue;
427                         }
428 
429                         if ("-t".equals(args[i])) {
430                             if (args.length > i + 1) {
431                                 TargetLanguage = args[++i];
432                             } else {
433                                 throw new ConverterException(
434                                         "missing argument for -t  target language");
435                             }
436                             continue;
437                         }
438 
439                         if (i == 1 && !args[i].startsWith("-")) { //target file
440                             // found
441                             targetName = args[i];
442                             continue;
443                         }
444                         // if we come here we
445                         // can not match the attribute
446                         throw new ConverterException("unknown Attribute: "
447                                 + args[i]);
448 
449 
450                 }//end for
451             } catch (ConverterException e) {
452                 OutputHandler.out("ERROR: "+e.getMessage());
453                 System.exit(-1);
454             } catch (Throwable t){
455                 System.out.print("An Error occurred while parsing the command line,\nplease check your command line settings.\n "+t.getMessage());
456                 System.exit(-1);
457             }
458 
459         }//end checkClParameters
460 
461         /**
462          * Creates the appropriate content of whatever data
463          * we found in the command line
464          *
465          * @throws IOException
466          */
createContentOfClParameters()467         private static void createContentOfClParameters() throws IOException {
468 
469             try {
470                 if (OutputHandler.doDebug) {
471                     // if the -dbg switch is set, we
472                     // create
473                     // a file that gets all information
474                     // produced by this tool
475 
476                     OutputHandler.dbgFile = new BufferedWriter(new FileWriter(
477                             new File(new String(filePath + fileName + ".dbg"))));
478                 }
479 
480                 if (OutputHandler.doLog) {// create a logfile?
481                     // given at command line?
482                     if (EMPTY.equals(logString) || logString == null) {
483                         logString = new String(filePath + fileName + ".log");
484                     }
485                     log = FileMaker.newFile(logString, overwrite);
486                     OutputHandler.logFile = (new BufferedWriter(new FileWriter(
487                             log)));
488                 }
489 
490                 if (EMPTY.equals(sourceType) || sourceType == null) {
491                     // not given at command line?
492                     if (!(EMPTY.equals(sourceName) || sourceName == null)) {
493                         sourceType = extractExtension(sourceName);
494                     } else {
495                         throw new ConverterException("Source type is missing");
496                     }
497                 }
498 
499                 if(sourceType.equalsIgnoreCase("gsi")){
500 
501                     if(EMPTY.equals(Convert.secondSourceName)){
502                         Convert.secondSourceName=filePath+fileName+".sdf";
503                     }
504                     //secondSource=new File(Convert.secondSourceName);
505 
506                 }
507 
508                 if (EMPTY.equals(sourceName)) {
509                     sourceName = filePath + fileName + "." + sourceType;
510                 }
511                 // no target type given at command line?
512                 if (EMPTY.equals(targetType) || targetType == null) {
513                     if (!(EMPTY.equals(targetName) || targetName == null)) {
514                         targetType = extractExtension(targetName);
515                     } else {
516                         throw new ConverterException("Target type is missing");
517 
518                     }
519                 }
520                 // no target File specified at command line
521                 if (EMPTY.equals(targetName) || targetName == null) {
522                     targetName = filePath + fileName + "." + targetType;
523                     if (targetName.equals(Convert.secondSourceName)){
524                         OutputHandler.out("ERROR: \nSource '"+Convert.secondSourceName+"' and \nTarget'"+targetName+"' are the same");
525                         System.exit(0);
526                     }else if (targetName.equals(Convert.sourceName)){
527                         OutputHandler.out("ERROR: \nSource '"+Convert.sourceName+"' and \nTarget'"+targetName+"' are the same");
528                         System.exit(0);
529                     }
530                 }else if (targetName.equals(Convert.secondSourceName)){
531                     OutputHandler.out("ERROR: \nSource '"+Convert.secondSourceName+"' and \nTarget'"+targetName+"' are the same");
532                     System.exit(0);
533                 }else if (targetName.equals(Convert.sourceName)){
534                     OutputHandler.out("ERROR: \nSource '"+Convert.sourceName+"' and \nTarget'"+targetName+"' are the same");
535                     System.exit(0);
536                 }
537 
538 
539             } catch (ConverterException e) {
540                 OutputHandler.out(e.getMessage());
541             }
542 
543         }
544 
545     }
546 
547 }
548 
549