Debian Codegraph @

src/footleg/cavesurvey/converter/CaveConverter.java

raw symbols SCIP
1 /**
2 * Copyright (C) 2009-2017 Paul Fretwell - aka 'Footleg' ([email protected])
3 *
4 * This file is part of Cave Converter.
5 *
6 * Cave Converter is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Cave Converter is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Cave Converter. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package footleg.cavesurvey.converter;
20
21 import java.io.File;
22 import java.text.DecimalFormat;
23 import java.text.ParseException;
24 import java.util.ArrayList;
25 import java.util.Calendar;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.TimeZone;
29
30 import footleg.cavesurvey.data.model.CaveSurvey;
31 import footleg.cavesurvey.data.reader.CompassParser;
32 import footleg.cavesurvey.data.reader.DxfParser;
33 import footleg.cavesurvey.data.reader.PocketTopoParser;
34 import footleg.cavesurvey.data.reader.SurvexParser;
35 import footleg.cavesurvey.data.writer.SurvexWriter;
36 import footleg.cavesurvey.data.writer.TopoRobotWriter;
37 import footleg.cavesurvey.tools.UtilityFunctions;
38
39 /**
40 * Command line application for converting cave survey data from one file format to another.
41 * Currently it can read some survex files, text export files from PocketTopo and DXF format
42 * data. It can write toporobot and survex files.
43 *
44 * @author Footleg
45 * @version 2017.01.12 (ISO 8601 YYYY.MM.DD)
46 * @since 1.6 (The Java version used)
47 *
48 * @to.do
49 * TODO Write Therion reader and writer
50 */
51 public class CaveConverter {
52 private static final String filePath = "./";
53 private static Date today;
54
55 public static String newline = System.getProperty("line.separator");
56
57 public static final String DATA_ORDER_CAT_FROMSTN = "FROM";
58 public static final String DATA_ORDER_CAT_TOSTN = "TO";
59 public static final String DATA_ORDER_CAT_LENGTH = "LENGTH";
60 public static final String DATA_ORDER_CAT_BEARING = "BEARING";
61 public static final String DATA_ORDER_CAT_CLINO = "GRADIENT";
62 public static final String DATA_ORDER_CAT_IGNOREALL = "IGNOREALL";
63 public static final String DATA_ORDER_CAT_FROMDEPTH = "FROMDEPTH";
64 public static final String DATA_ORDER_CAT_TODEPTH = "TODEPTH";
65 public static final String DATA_ORDER_CAT_DEPTHCHANGE = "DEPTHCHANGE";
66
67
68 /**
69 * Command line options for True, False or 'Use Default'
70 */
71 public static enum CmdlineOpt {
72 T, F, D
73 }
74
75 /**
76 * Command line options for splays output
77 */
78 public static enum CmdlineSplaysOpt {
79 Named, None, Default, Anon
80 }
81
82 /**
83 * Supported cave survey data formats for input (these are the formats the application can read)
84 */
85 public static enum SurveyDataInputFormats {
86 Compass,
87 DXF,
88 PocketTopo,
89 Survex
90 }
91
92 /**
93 * Supported cave survey data formats for output (these are the formats the application can write)
94 */
95 public static enum SurveyDataOutputFormats {
96 Survex,
97 Toporobot
98 }
99
100 private static String dataFormats[][] = {{"Compass","dat"},{"DXF","dxf"},{"PocketTopo","txt"},{"Survex","svx"},{"Toporobot","text"}};
101
102 /**
103 * Units for length measurements
104 */
105 public static enum LengthUnit {
106 Metres,
107 Feet,
108 Yards
109 }
110
111 /**
112 * Units for bearing measurements
113 */
114 public static enum BearingUnit {
115 Degrees,
116 Grads,
117 Minutes
118 }
119
120 /**
121 * Units for gradient measurements
122 */
123 public static enum GradientUnit {
124 Degrees,
125 Grads,
126 Minutes,
127 Percent
128 }
129
130 /**
131 * Supplies the display name for survey data input formats
132 * @param format The data format enum value
133 * @return Display name for this data format
134 */
135 public static String getFormatName(SurveyDataInputFormats format) {
136 String formatName = "";
137 switch (format) {
138 case Compass:
139 formatName = dataFormats[0][0];
140 break;
141 case DXF:
142 formatName = dataFormats[1][0];
143 break;
144 case PocketTopo:
145 formatName = dataFormats[2][0];
146 break;
147 case Survex:
148 formatName = dataFormats[3][0];
149 break;
150 }
151 return formatName;
152 }
153
154 /**
155 * Supplies the display name for survey data output formats
156 * @param format The data format enum value
157 * @return Display name for this data format
158 */
159 public static String getFormatName(SurveyDataOutputFormats format) {
160 String formatName = "";
161 switch (format) {
162 case Survex:
163 formatName = dataFormats[3][0];
164 break;
165 case Toporobot:
166 formatName = dataFormats[4][0];
167 break;
168 }
169 return formatName;
170 }
171
172 /**
173 * Returns the file format for a specified file name extension
174 * @param fileExtn The filename extension
175 * @return The survey data input format matching the file extn (or null if no match)
176 */
177 public static SurveyDataInputFormats inputFormatFromFileExtn( String fileExtn ) {
178 SurveyDataInputFormats format = null;
179
180 if ( fileExtn.equalsIgnoreCase( dataFormats[0][1] ) ) {
181 format = SurveyDataInputFormats.Compass;
182 }
183 else if ( fileExtn.equalsIgnoreCase( dataFormats[1][1] ) ) {
184 format = SurveyDataInputFormats.DXF;
185 }
186 else if ( fileExtn.equalsIgnoreCase( dataFormats[2][1] ) ) {
187 format = SurveyDataInputFormats.PocketTopo;
188 }
189 else if ( fileExtn.equalsIgnoreCase( dataFormats[3][1] ) ) {
190 format = SurveyDataInputFormats.Survex;
191 }
192
193 return format;
194 }
195
196 /**
197 * @param args Command line arguments
198 */
199 public static void main( String[] args ) {
200 //Default input and output filenames
201 String inputFilename = "input.svx";
202 String outputFilename = "output.text";
203 SurveyDataInputFormats inputFormat = null;
204 SurveyDataOutputFormats outputFormat = null;
205 CmdLineLogger logger = new CmdLineLogger();
206
207 //Set date if not already set
208 if ( today == null ) {
209 //Set date to todays datetime
210 Calendar cal = Calendar.getInstance(TimeZone.getDefault());
211 today = cal.getTime();
212 }
213 //Check for arguments
214 if (args.length > 0) {
215 //Set input filename from 1st argument
216 inputFilename = args[0];
217 if (args.length > 1) {
218 //Set output filename from 2nd argument
219 outputFilename = args[1];
220 if (args.length > 2) {
221 //Set input format from 3rd argument
222 try {
223 inputFormat = UtilityFunctions.inputDataFormatFromLetterCode( parseSingleCharacterArgument( args[2] ) );
224 if (args.length > 3) {
225 //Set output format from 4th argument
226 outputFormat = UtilityFunctions.outputDataFormatFromLetterCode( parseSingleCharacterArgument( args[3] ) );
227
228 //Set options flags from 5th argument onwards
229 CmdlineSplaysOpt splaysOpt = CmdlineSplaysOpt.Default;
230 boolean anonSplaysOpt = false;
231 CmdlineOpt genLRUDOpt = CmdlineOpt.F;
232 String charSetEncoding = "UTF8";
233 for (int iOpts = 4; iOpts < args.length; iOpts++ ) {
234 if ( args[iOpts].compareToIgnoreCase("nosplays") == 0 ) {
235 splaysOpt = CmdlineSplaysOpt.None;
236 }
237 else if ( args[iOpts].compareToIgnoreCase("splays") == 0 ) {
238 splaysOpt = CmdlineSplaysOpt.Named;
239 }
240 if ( args[iOpts].compareToIgnoreCase("anonsplays") == 0 ) {
241 anonSplaysOpt = true;
242 }
243 if ( args[iOpts].compareToIgnoreCase("lrud") == 0 ) {
244 genLRUDOpt = CmdlineOpt.T;
245 }
246 if ( args[iOpts].compareToIgnoreCase("charset") == 0 ) {
247 if ( iOpts + 1 < args.length ) {
248 charSetEncoding = args[iOpts + 1];
249 }
250 }
251 }
252
253 //Set splays to anonymous if option was set and splays are being output
254 if ( ( splaysOpt != CmdlineSplaysOpt.None ) && ( anonSplaysOpt == true ) ) {
255 splaysOpt = CmdlineSplaysOpt.Anon;
256 }
257 //Call file convert method
258 convertFile(inputFilename, outputFilename, inputFormat, outputFormat, splaysOpt,
259 genLRUDOpt, charSetEncoding, logger );
260
261 //Write log file
262 logger.writeLogToFile( filePath + "CaveConverter.log", charSetEncoding );
263 }
264 } catch (ParseException e) {
265 //Log error
266 e.printStackTrace();
267 }
268 }
269 }
270 }
271 }
272
273 public static void setToday(Date date) {
274 CaveConverter.today = date;
275 }
276
277 /**
278 * Parses a string argument into a single character.
279 *
280 * @param argument String to be converting into a single character
281 * @return The char which was contained in the string argument
282 * @throws ParseException If the argument is not a single character length string
283 */
284 private static char parseSingleCharacterArgument( String argument ) throws ParseException {
285 char[] chars = argument.toCharArray();
286 char argChar = 'x';
287
288 if ( chars.length == 1 ) {
289 argChar = chars[0];
290 }
291 else {
292 ParseException e = new ParseException("Failed to parse argument to single character. " +
293 "Argument was '" + argument + "'.", 1);
294 throw e;
295 }
296
297 return argChar;
298 }
299
300 /**
301 * Reads in a survey data file and converts it to another format which is written out to a file.
302 *
303 * @param inputFilename Name and location of file to be converted
304 * @param outputFilename Name and location of file to be output
305 * @param inputFormat Format of input file
306 * @param outputFormat Format of file to be generated
307 * @param splaysOpt Indicates if a splays output option was set to True, False or to use default for writer (T,F,D)
308 * @param generateLRUDOpt Indicates whether to generate LRUD data from splays before writing out data
309 * @param charSetEncoding Character set encoding to be used when reading and writing files
310 * @param logger Logging class to output information, warning and error messages to
311 * @throws ParseException Exception raised when information in a survey data file is not supported or valid for the format
312 */
313 public static void convertFile( String inputFilename, String outputFilename, SurveyDataInputFormats inputFormat,
314 SurveyDataOutputFormats outputFormat, CmdlineSplaysOpt splaysOpt, CmdlineOpt generateLRUDOpt,
315 String charSetEncoding, Logger logger ) throws ParseException {
316 //Declare structure to hold survey data
317 CaveSurvey surveyData = null;
318 List<String> multiFileRefs = null;
319 boolean multifile = false;
320
321 //Prepare log message
322 String msg = "Reading data file '" + inputFilename + "' with format " + getFormatName( inputFormat )
323 + ". Splays option: ";
324 switch ( splaysOpt ) {
325 case None:
326 msg += "None";
327 break;
328 case Anon:
329 msg += "Anonymous";
330 break;
331 case Default:
332 msg += "Default";
333 break;
334 case Named:
335 msg += "Named to Stations";
336 break;
337 }
338 if ( inputFormat == SurveyDataInputFormats.Survex ) {
339 multifile = true;
340 multiFileRefs = new ArrayList<String>();
341 }
342 //Read input data file
343 logger.logMessage( msg );
344 List<String> fileData = UtilityFunctions.readTextFile( new File( inputFilename ), charSetEncoding,
345 multifile, multiFileRefs, logger );
346
347 //Parse file data
348 if ( inputFormat == SurveyDataInputFormats.Survex ) {
349 //Parse Survex data
350 SurvexParser parser = new SurvexParser(logger);
351 surveyData = parser.parseFile( fileData, multiFileRefs );
352 }
353 else if ( inputFormat == SurveyDataInputFormats.PocketTopo ) {
354 //Parse PocketTopo data
355 PocketTopoParser parser = new PocketTopoParser(logger);
356 surveyData = parser.parseFile( fileData );
357 }
358 else if ( inputFormat == SurveyDataInputFormats.DXF ) {
359 //Parse Autocad DXF data polylines into survey series
360 DxfParser parser = new DxfParser(logger);
361 surveyData = parser.parseFile(fileData, 0);
362 }
363 else if ( inputFormat == SurveyDataInputFormats.Compass ) {
364 //Parse Compass data file
365 CompassParser parser = new CompassParser(logger);
366 surveyData = parser.parseFile(fileData);
367 }
368 else {
369 //Unsupported input format argument
370 logger.logMessage("Unsupported input format argument: " + inputFormat + " is not a valid input format.");
371 }
372
373 //Set options flag for generating LRUD data
374 boolean generateLRUD = false;
375 if (generateLRUDOpt == CmdlineOpt.T) {
376 generateLRUD = true;
377 }
378
379 //Generate LRUD data if required
380 if ( generateLRUD ) {
381 logger.logMessage("Generating LRUD data from splays...");
382 surveyData.generateLRUDfromSplays();
383 }
384
385 //Convert data to output format
386 List<String> outputData = null;
387 if ( surveyData != null ) {
388 if ( outputFormat == SurveyDataOutputFormats.Survex ) {
389 //Set options flag for splays (default to true)
390 SurvexWriter.SplayFormats outputSplays = SurvexWriter.SplayFormats.Flagged;
391 if ( splaysOpt == CmdlineSplaysOpt.None ) {
392 outputSplays = SurvexWriter.SplayFormats.None;
393 }
394 else if ( splaysOpt == CmdlineSplaysOpt.Anon ) {
395 outputSplays = SurvexWriter.SplayFormats.Anonymous;
396 }
397 //Generate Survex format data
398 SurvexWriter writer = new SurvexWriter(logger);
399 outputData = writer.generateSurvexData( surveyData, outputSplays );
400 }
401 else if ( outputFormat == SurveyDataOutputFormats.Toporobot ) {
402 //Set options flag for splays (default to false)
403 boolean outputSplays = false;
404 if ( ( splaysOpt == CmdlineSplaysOpt.Named ) || ( splaysOpt == CmdlineSplaysOpt.Anon ) ) {
405 outputSplays = true;
406 }
407 //Generate Toporobot format data
408 TopoRobotWriter writer = new TopoRobotWriter(logger);
409 outputData = writer.generateToporobotData( surveyData, today, outputSplays );
410 }
411 // else if ( outputFormat == SurveyDataOutputFormats.Compass ) {
412 // //Generate Compass format data
413 // CompassWriter writer = new CompassWriter();
414 // outputData = writer.generateCompassData( surveyData );
415 // }
416 else {
417 //Unsupported output format argument
418 logger.logMessage("Unsupported output format argument: " + outputFormat + " is not a valid output format.");
419 }
420 }
421
422 //Write output file
423 if ( outputData.size() > 0 ) {
424 String outputFilePath = filePath + outputFilename;
425 logger.logMessage( "Writing output file: " + outputFilePath );
426 String error = UtilityFunctions.writeTextFile( outputData, outputFilePath, charSetEncoding );
427 if ( error.length() > 0 ) {
428 logger.logMessage( error );
429 }
430 }
431 }
432
433 public static String padNumber(int num, int padWidth) {
434 String numStr = "" + num;
435
436 return padString(numStr,padWidth);
437 }
438
439 /**
440 * Generates a string from a number with specified number of decimal places and padded with spaces
441 * to a specified length string
442 * @param num Number to convert to string
443 * @param decPlaces Number of decimal places to represent the number to
444 * @param padWidth Minimum length of string to return
445 * @return Formatted string representation of number
446 */
447 public static String padNumber(double num, int decPlaces, int padWidth) {
448 String formatStr = "0.";
449 for (int i = 0; i < decPlaces; i++) {
450 formatStr += '0';
451 }
452 DecimalFormat formatter = new DecimalFormat(formatStr);
453
454 return padString(formatter.format(num), padWidth);
455 }
456
457 /**
458 * Prefixes a string with space characters to make the string a minimum length if
459 * the string is shorter than the specified minimum length
460 *
461 * @param data The string to pad with spaces
462 * @param padWidth The minimum length the string should have
463 * @return The string padded with space characters to make it at least the specified length
464 */
465 public static String padString(String data, int padWidth) {
466 String padded;
467 //Pad number with spaces if not already as wide as pad width
468 if ( data.length() < padWidth ) {
469 //Pad with lots of spaces
470 padded = " " + data;
471 //then trim to padded width
472 padded = padded.substring(padded.length() - padWidth);
473 }
474 else {
475 //Already wide enough, so just return as is
476 padded = data;
477 }
478
479 return padded;
480 }
481
482 }