1 package gov.nasa.pds.ltdt.gui.util;
2
3 import gov.nasa.pds.ltdt.gui.MainWindow;
4 import gov.nasa.pds.ltdt.gui.configuration.LTDTKeys;
5 import gov.nasa.pds.tools.dict.Dictionary;
6
7 import java.awt.Cursor;
8 import java.io.BufferedReader;
9 import java.io.BufferedWriter;
10 import java.io.File;
11 import java.io.FileInputStream;
12 import java.io.FileNotFoundException;
13 import java.io.FileOutputStream;
14 import java.io.FileReader;
15 import java.io.FileWriter;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.OutputStream;
19 import java.net.MalformedURLException;
20 import java.net.URL;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Properties;
29 import java.util.SortedSet;
30 import java.util.TreeSet;
31
32 import javax.swing.BorderFactory;
33 import javax.swing.BoxLayout;
34 import javax.swing.JPanel;
35
36 public class Utility {
37
38 /*** Create a panel to hold components vertically
39 * @return A panel with vertical box layout and opaque background
40 */
41 public static JPanel createVerticalBoxPanel() {
42 JPanel p = new JPanel();
43 p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
44 p.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
45 p.setOpaque(true);
46 return p;
47 }
48
49 /***
50 * @param in An integer to be formatted to right justified string
51 * @param targetLength The length of string after formatting
52 * @return formatted string wih input integer padded with blanks on lefthand-side (right justified)
53 */
54
55 public static String formatInt (int in, int targetLength) {
56 String str="";
57 String out=null;
58 StringBuffer target = new StringBuffer();
59
60 str= new Integer(in).toString();
61
62 if (str.length() <= targetLength) {
63
64 for (int i=0;i<(targetLength-str.length());i++) {
65
66 target.append(' ');
67
68 }
69
70 target.append(in);
71 out = target.toString();
72
73 }
74 else out = target.append(in).toString();
75 return out;
76 }
77
78 /***
79 * Convert a string to a URL.
80 * @param s The string to convert
81 * @return A URL of the input string
82 * @throws MalformedURLException
83 */
84 public static URL toURL(String s) throws MalformedURLException {
85 URL url = null;
86 try {
87 url = new URL(s);
88 } catch (MalformedURLException ex) {
89 url = new File(s).toURI().toURL();
90 }
91 return url;
92 }
93
94 /***
95 * Add carriage-return (\<CR\>) followed by linefeed (\<LF\>) at the end
96 * of a string.
97 * @param s
98 * @return The string appended with \<CR\>\<LF\>.
99 */
100 public static String addCRLF(String s) {
101 return s + "\r\n";
102 }
103
104 /***
105 * Adds leading whitespaces to a given string
106 *
107 * @param string The string to add whitespaces to.
108 * @param length The number of whitespaces to add to the line.
109 * @return The string with leading whitespaces added.
110 */
111 public static String addLeadingWhiteSpace(String string, int length) {
112 char[] spaces = new char[length];
113 Arrays.fill(spaces, ' ');
114 return new String(spaces) + string;
115 }
116
117 public static String addTrailingWhiteSpace(String string, int length) {
118 char[] spaces = new char[length];
119 Arrays.fill(spaces, ' ');
120 return string + new String(spaces);
121 }
122
123 /***
124 * Removes leading whitespaces in a string
125 *
126 * @param string The string
127 * @param length The number of whitespaces to delete
128 * @return The trimmed string
129 */
130 public static String trimLeadingWhiteSpace(String string, int length) {
131 StringBuffer sb = new StringBuffer(string);
132 for(int i=0; (i < length) && (Character.isWhitespace(sb.charAt(0))); i++) {
133 sb = sb.deleteCharAt(0);
134 }
135 return sb.toString();
136 }
137
138 /***
139 * Removes leading whitespaces in a string
140 * @param string The string
141 * @return The given string without the leading whitespaces
142 */
143 public static String trimLeadingWhiteSpace(String string) {
144 StringBuffer sb = new StringBuffer(string);
145 while(Character.isWhitespace(sb.charAt(0))) {
146 sb = sb.deleteCharAt(0);
147 }
148 return sb.toString();
149 }
150
151 /***
152 * Add surrounding quotes
153 *
154 * @param string
155 * @return The string surrounded with quotes
156 */
157 public static String addQuotes(String string) {
158 return '\"' + string + '\"';
159 }
160
161 /***
162 * Makes a string. For instance, if the given size is '3',
163 * the string returned will be 'ABC'.
164 *
165 * @param size The size of the string
166 * @return a string based on the given size
167 */
168 public static String makeTestString(int size) {
169 char letter = 'A';
170 String string = new String();
171 for(int i=0; i < size; i++) {
172 string = string + letter;
173 ++letter;
174 }
175 return string;
176 }
177
178 /***
179 * Get a list of key fields in a keyword=value type of file, for example
180 * LTDT tool profile, LTDT project property file, etc. The existence of input
181 * file should be checked prior to calling this method. Lines starts with # and
182 * lines does not have K=V pairs are ignored.
183 *
184 *
185 * @param inFile Input filename.
186 * @return An ArrayList containing valid project names.
187 * @throws IOException
188 *
189 */
190 public static ArrayList getKeyList (String inFile) throws IOException {
191
192 List projNameList=null;
193 BufferedReader reader=null;
194
195 reader = new BufferedReader (new FileReader(inFile));
196 projNameList = new ArrayList();
197
198
199
200 for (String line=reader.readLine(); line!=null; line=reader.readLine()) {
201
202 if (!line.trim().startsWith("#")) {
203 String[] str=line.split("=");
204
205 if (str.length==2) {
206 if (str[0].trim().length()>0 && str[1].trim().length()>0) {
207 if (new File(str[1].trim()).exists()) {
208 if (new File(str[1].trim()+System.getProperty("file.separator")+LTDTKeys.PROPERTYFILENAME).exists())
209 projNameList.add(str[0].trim());
210 }
211 }
212 }
213 }
214 }
215
216 try {
217 if (reader!=null) reader.close();
218 }
219 catch (IOException ie2) {
220
221 }
222
223 return (ArrayList)projNameList;
224 }
225
226 /***
227 * Return a sorted list of LTDT project names available on the system. The project names are included in this list
228 * only if their associating project property files exist.
229 * @param propFile The LTDT tool property file with project=path entries
230 * @return List of sorted project names
231 * @throws IOException , FileNotFoundException
232 */
233 public static ArrayList getSortedProjectList (String propFile) throws IOException {
234 List pn = new ArrayList();
235
236 SortedSet ss = new TreeSet(Utility.getKeyList(propFile));
237
238 for (Iterator it=ss.iterator(); it.hasNext();)
239 pn.add(it.next());
240
241 return (ArrayList)pn;
242 }
243
244 /***
245 * Given a proejct name, retrive the path of the project from LTDT property file HOME/.ltdt
246 * @param projectName
247 * @return Path where a project workarea is located
248 * @throws IOException
249 * @throws FileNotFoundException
250 */
251 public static String getProjectLocation(String projectName) throws IOException, FileNotFoundException {
252
253 String path=null;
254
255 BufferedReader reader = new BufferedReader (new FileReader(LTDTKeys.LTDTPROPFILE));
256 projectName = projectName.trim().toLowerCase();
257 for (String line=reader.readLine(); line!=null; line=reader.readLine()) {
258
259 if (!line.trim().startsWith("#")) {
260 String [] str = line.split("=");
261
262 if (str.length==2) {
263 if (str[0].trim().length()>0 && str[1].trim().length()>0) {
264
265 if (projectName.equals(str[0])) {
266 path=str[1].toString();
267 break;
268 }
269 }
270 }
271 }
272 }
273
274 try {
275 if (reader!=null) reader.close();
276 }
277 catch (IOException ie2) { }
278
279 return path;
280 }
281
282 /***
283 * Given a project location, search the LTDT tool property and find out the project registered with the location
284 * @param projectLocation
285 * @return Project Name
286 * @throws IOException
287 * @throws FileNotFoundException
288 */
289 public static String getProjectName (String projectLocation) throws IOException, FileNotFoundException {
290 String projectName = null;
291
292 BufferedReader reader = new BufferedReader (new FileReader(LTDTKeys.LTDTPROPFILE));
293
294 for (String line=reader.readLine(); line!=null; line=reader.readLine()) {
295
296 if (!line.trim().startsWith("#")) {
297 String [] str = line.split("=");
298
299 if (str.length==2) {
300 if (str[0].trim().length()>0 && str[1].trim().length()>0) {
301
302 if (projectLocation.equals(str[1])) {
303 projectName=str[0].toString();
304 break;
305 }
306 }
307 }
308 }
309 }
310
311 try {
312 if (reader!=null) reader.close();
313 }
314 catch (IOException ie2) { }
315
316 return projectName;
317 }
318
319 /***
320 * Examine if a directory is read/write permitted
321 * @param dir Directory
322 * @return true or false
323 */
324 public static boolean dirRWAllowed (String dir) {
325 File f = new File(dir);
326 if (f.canRead() && f.canWrite())
327 return true;
328 else
329 return false;
330 }
331
332 /***
333 * Append a timestamp and a message to a log file
334 * @param logfile
335 * @param message
336 * @throws IOException
337 */
338 public static void writeLogEntry(String logfile, String message) throws IOException {
339
340 java.text.DateFormat df = new java.text.SimpleDateFormat ("yyyy.MM.dd HH:mm:ss");
341
342 FileWriter fw = new FileWriter(logfile, true);
343 BufferedWriter out = new BufferedWriter(fw);
344 out.write("");
345 out.write(df.format(new java.util.Date()) + "==>"+message+"\n");
346 out.close();
347
348 fw.close();
349 }
350
351 /***
352 * Get fully qualified name for a project property file
353 * @param props
354 * @return Project Property File Name
355 */
356 public static String getProjectPropertyFileName (Properties props) {
357 return (String)props.getProperty(LTDTKeys.PROJECTDIR)+LTDTKeys.PROJECTPROPERTYFILESUFFIX;
358 }
359
360 /***
361 * Get fully qualified name for a project property file located at non-default path
362 * @param newProjectLocation
363 * @return Project property file name
364 */
365 public static String getNewProjectPropertyFileName (String newProjectLocation) {
366 return (String)newProjectLocation+LTDTKeys.PROJECTPROPERTYFILESUFFIX;
367 }
368
369 /***
370 * Get fully qualified name for a project template file
371 * @param props
372 * @return Template file name
373 */
374 public static String getProjectTemplateFileName (Properties props) {
375 return (String)props.getProperty(LTDTKeys.PROJECTDIR)+LTDTKeys.PROJECTTEMPLATESUFFIX;
376 }
377
378 /***
379 * Get fully qualified name for a project templae file located at non-default path
380 * @param newProjectLocation
381 * @return Template file name
382 */
383 public static String getNewProjectTemplateFileName (String newProjectLocation) {
384 return (String)newProjectLocation+LTDTKeys.PROJECTTEMPLATESUFFIX;
385 }
386
387 /***
388 * Get fully qualified name for a project WDD file
389 * @param props
390 * @return Project WDD file name in project path
391 */
392 public static String getProjectWDDFileName (Properties props) {
393 return (String)props.getProperty(LTDTKeys.PROJECTDIR)+LTDTKeys.PROJECTWDDSUFFIX;
394 }
395
396 /***
397 * Get fully qualified name for a project WDD file located at non-default path
398 * @param newProjectLocation
399 * @return Project WDD file name at a non-default path
400 */
401 public static String getNewProjectWDDFileName (String newProjectLocation) {
402 return (String)newProjectLocation+LTDTKeys.PROJECTWDDSUFFIX;
403 }
404
405 /***
406 * Get full path name for a project log file
407 * @param props
408 * @return Project log file name
409 */
410 public static String getProjectLogFileName (Properties props) {
411 return (String)props.getProperty(LTDTKeys.PROJECTDIR)+LTDTKeys.PROJECTLOGFILESUFFIX;
412 }
413
414 /***
415 * Get fully qualified name for a project log file located at non-default path
416 * @param newProjectLocation
417 * @return Project log file name
418 */
419 public static String getNewProjectLogFileName (String newProjectLocation) {
420 return (String)newProjectLocation+LTDTKeys.PROJECTLOGFILESUFFIX;
421 }
422
423 /***
424 * Copy a file from one location to another. Caller is expected to check the accessibility of srouce and target locations
425 *
426 * @param sourceFileName Fully qualified name of file to be copied from
427 * @param targetFileNmae Fully qualified name of file to be copied to
428 */
429 private static void copyFile (String sourceFileName, String targetFileNmae) throws IOException {
430
431 File infile = new File(sourceFileName);
432 File outfile = new File(targetFileNmae);
433
434 InputStream in = new FileInputStream(infile);
435 OutputStream out = new FileOutputStream(outfile);
436
437
438 byte[] buf = new byte[1024];
439 int len;
440 while ((len = in.read(buf)) > 0) {
441 out.write(buf, 0, len);
442 }
443 in.close();
444 out.close();
445 }
446
447 /***
448 * Clear windows and properties to get ready for the next project
449 * @param props
450 * @param window
451 */
452
453
454 public static void initializeEmptyProject (Properties props, MainWindow window) {
455
456
457 window.WDD = new Dictionary();
458 window.mDictionary = new Dictionary();
459 window.dictionaryMap.clear();
460
461 window.keywordFullLong=null;
462 window.keywordFullShort=null;
463 window.keywordSubLong=null;
464 window.keywordSubShort=null;
465 window.keywordDisplayLong=null;
466 window.keywordDisplayShort=null;
467
468 window.requestedType = LTDTKeys.ELEMENT_TYPE;
469 window.lastSelectedKeyword = "";
470
471 window.editorPane.jta.setText("");
472 window.statusPane.jta.setText("");
473 window.dictListPane.jtfSearchString.setText("");
474 window.dictListPane.displaySingleTypeList(window, LTDTKeys.ELEMENTONLY);
475
476 window.dictDefPane.jta.setText("");
477
478 props.setProperty(LTDTKeys.TEMPLATETYPE, "");
479 props.setProperty(LTDTKeys.TEMPLATEEXISTS, "false");
480 props.setProperty(LTDTKeys.WDDEXISTS, "false");
481 props.setProperty(LTDTKeys.DICTIONARIES, "");
482 props.setProperty(LTDTKeys.COMMANDLINEDICTIONARYADDED, "false");
483
484
485 props.setProperty(LTDTKeys.PROJECTNAME, LTDTKeys.UNTITLED);
486 props.setProperty(LTDTKeys.PROJECTDIR, "");
487
488 props.setProperty(LTDTKeys.PROJECTALTERED, "false");
489
490 window.setTitle("LTDTool (Project Name: "+props.getProperty(LTDTKeys.PROJECTNAME)+")");
491
492 }
493
494
495
496 /***
497 *Given a List object and return it as a String with a ',' and a line feed
498 * as delimiters ** with a leading line feed
499 * @param dlist
500 * @return concatenated string with elements from a list plus a leading line feed
501 */
502 public static String list2stringLF (List dlist) {
503 String defStr="";
504 boolean started=false;
505
506 if (dlist!=null) {
507
508 for (Iterator it=dlist.iterator(); it.hasNext();) {
509 if (started) {
510 defStr=defStr+","+System.getProperty("line.separator")+(String)it.next();
511 }
512 else {
513 defStr = System.getProperty("line.separator")+(String)it.next();
514 started=true;
515 }
516 }
517
518
519 }
520
521 return defStr;
522 }
523
524
525 /***
526 * Given a List object and return it as a String with a ',' and a line feed
527 * as delimiters, ** without leading line feed
528 * @param dlist
529 * @return concatenated string with elements from a list not including a leading line feed
530 */
531 public static String list2stringNLF (List dlist) {
532 String defStr="";
533 boolean started=false;
534
535 if (dlist!=null) {
536
537 for (Iterator it=dlist.iterator(); it.hasNext();) {
538 if (started) {
539 defStr=defStr+","+System.getProperty("line.separator")+(String)it.next();
540 }
541 else {
542 defStr = (String)it.next();
543 started=true;
544 }
545 }
546
547
548 }
549
550 return defStr;
551 }
552
553 /***
554 * Given a list object, this method constructs and returns
555 * a string contains element from the original list, with ","
556 * as delimiter and " around each element value.
557 * @param dlist
558 * @return string with concatenated list element values
559 */
560 public static String list2quotedSet (List dlist) {
561
562 StringBuffer buf= new StringBuffer().append("");
563
564
565 if (dlist!=null) {
566
567 boolean started=false;
568
569 for (Iterator it=dlist.iterator(); it.hasNext();) {
570
571 if (started) {
572 buf.append(",");
573 buf.append(System.getProperty("line.separator"));
574 buf.append("\""+(String)it.next()+"\"");
575
576 }
577 else {
578
579 buf.append("\""+(String)it.next()+"\"");
580 started=true;
581 }
582
583 }
584
585 }
586 return buf.toString();
587 }
588
589
590 /***
591 * Given a string, tokenize it, and create an ArrayList as result.
592 * The delimiters are blank space, carriage return (\r), line feed (\n),
593 * semicolon(;) or comma (,)
594 *
595 * @param instring
596 * @return list of string tokens
597 */
598 public static List rowstring2list (String instring) {
599
600 List outList = new ArrayList();
601 String delimiters = "//n|//r|,|//s|;";
602 String[] tokenized = instring.split(delimiters);
603 for (int i=0; i<tokenized.length; i++) {
604 tokenized[i].trim();
605 if (tokenized[i].length()>0) {
606 outList.add(tokenized[i]);
607 }
608 }
609
610 return outList;
611 }
612
613 /***
614 * Given a string with ; as delimeter, convert each elements into URL and stored in a list
615 * @param instring
616 * @return list of urls
617 * @throws MalformedURLException
618 */
619 public static List rowstring2urllist (String instring) throws MalformedURLException {
620
621 List outList = new ArrayList();
622 String delimiters = ";";
623 String[] tokenized = instring.split(delimiters);
624 for (int i=0; i<tokenized.length; i++) {
625 tokenized[i].trim();
626 if (tokenized[i].length()>0) {
627 outList.add(Utility.toURL(tokenized[i]));
628 }
629 }
630
631 return outList;
632 }
633
634
635 /***
636 * Given a string, tokenize it, and create an ArrayList as result.
637 * The delimiters are blank space, carriage return (\r), line feed (\n),
638 * semicolon(;) or comma (,)
639 * The process explicitly removes surrounding quotes on every value in
640 * the result list.
641 * @param instring
642 * @return list of string tokens
643 */
644 public static List rowstring2listNotQuoted (String instring) {
645
646 List outList = new ArrayList();
647 String str = "";
648
649 String delimiters = "//n|//r|,|//s|;";
650 String[] tokenized = instring.split(delimiters);
651 for (int i=0; i<tokenized.length; i++) {
652 str = tokenized[i].trim();
653 if (str.length()>0) {
654
655
656 if (str.startsWith("\"")) {
657 str = str.substring(1);
658 }
659
660 if (str.endsWith("\"")) {
661 str = str.substring(0, str.length()-1);
662 }
663
664 if (str.length()>0)
665 outList.add(str);
666 }
667 }
668
669 return outList;
670 }
671
672 /***
673 * Writes content in template editor to a file
674 * @param window
675 * @param filename
676 * @throws IOException
677 */
678 public static void writeTemplate (MainWindow window, String filename) throws IOException {
679
680 FileWriter fw = new FileWriter(filename);
681 fw.write(window.editorPane.jta.getText());
682 fw.close();
683
684 if (fw!=null)
685 try {
686 fw.close();
687 }
688 catch (IOException e) {
689
690 }
691
692 }
693
694 public static void startWait (MainWindow window) {
695 window.setCursor(new Cursor(Cursor.WAIT_CURSOR));
696 }
697
698 public static void stopWait (MainWindow window) {
699 window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
700 }
701
702 public static String reformatDescription (String origDescription) {
703
704 StringBuffer newDescription=new StringBuffer();
705
706 List outList = new ArrayList();
707
708 StringBuffer buf = new StringBuffer();
709
710 String delimiters = "//n|//r";
711 String[] tokenized = origDescription.split(delimiters);
712
713 for (int i=0; i<tokenized.length; i++) {
714
715 String currentToken = tokenized[i].trim();
716 int currentTokenSize = currentToken.length();
717
718
719
720 if (i==0) {
721
722
723 if (currentTokenSize >0)
724 buf.append(currentToken);
725 }
726
727
728
729 else if (i>0) {
730 String previousToken = tokenized[i-1].trim();
731 int previousTokenSize = previousToken.length();
732
733
734
735 if (currentTokenSize>0) {
736
737
738
739 if (previousTokenSize>0)
740 buf.append(" "+currentToken);
741
742
743 else
744
745
746 if (buf.length() >0) {
747 outList.add(buf.toString());
748 buf.delete(0, buf.length());
749 buf.append(System.getProperty("line.separator")+currentToken);
750 }
751
752
753 else {
754 buf.append(currentToken);
755 }
756 }
757
758 else {
759
760 if (previousTokenSize>0) {
761 buf.append(System.getProperty("line.separator"));
762 }
763
764 }
765 }
766 }
767
768
769 if (buf.length()>0) {
770 outList.add(buf.toString());
771 }
772
773 for (Iterator it=outList.iterator(); it.hasNext();) {
774 newDescription.append((String)it.next());
775 }
776 return newDescription.toString();
777
778 }
779
780 /***
781 * Bases on URL, load and return properties info
782 * @return Loaded properties
783 * @throws IOException
784 */
785 public static Properties getProperties(URL propFile) throws IOException {
786
787 String info = "";
788 Properties props = new Properties();
789 props.load(propFile.openStream());
790
791 return props;
792
793 }
794 }