1 package fri.patterns.interpreter.parsergenerator.builder; 2 3 import java.io.*; 4 import java.util.*; 5 import fri.util.props.ConfigDir; 6 import fri.patterns.interpreter.parsergenerator.syntax.*; 7 import fri.patterns.interpreter.parsergenerator.syntax.builder.*; 8 9 14 15 class SerializedObject 16 { 17 18 public SerializedObject() { 19 } 20 21 25 protected Object read(String fileName) { 26 fileName = makeFilePath(fileName); 27 System.err.println("deserializing object from "+fileName); 28 ObjectInputStream oin = null; 29 try { 30 FileInputStream in = new FileInputStream(fileName); 31 oin = new ObjectInputStream(in); 32 return oin.readObject(); 33 } 34 catch (Exception e) { 35 System.err.println(e.getMessage()); return null; 37 } 38 finally { 39 try { oin.close(); } catch (Exception e) {} 40 } 41 } 42 43 47 protected boolean write(String fileName, Object o) { 48 fileName = makeFilePath(fileName); 49 System.err.println("serializing object to "+fileName); 50 ObjectOutputStream oout = null; 51 try { 52 ensureDirectory(fileName); 53 FileOutputStream out = new FileOutputStream(fileName); 54 oout = new ObjectOutputStream(out); 55 oout.writeObject(o); 56 return true; 57 } 58 catch (IOException e) { 59 e.printStackTrace(); 60 return false; 61 } 62 finally { 63 try { oout.flush(); oout.close(); } catch (Exception e) {} 64 } 65 } 66 67 68 73 public static String baseNameFromSyntax(Object syntaxInput) { 74 String name; 75 if (syntaxInput instanceof File) { 76 File f = (File) syntaxInput; 77 name = f.getName(); 78 int i = name.indexOf("."); 79 if (i > 0) 80 name = name.substring(0, i); 81 } 82 else { 83 name = "Unknown"; 84 } 85 return name; 86 } 87 88 89 90 public static Syntax toSyntax(Object syntaxInput) 91 throws Exception 92 { 93 Syntax syntax; 94 if (syntaxInput instanceof Syntax) 95 syntax = (Syntax) syntaxInput; 96 else 97 if (syntaxInput instanceof String [][]) 98 syntax = new Syntax((String [][]) syntaxInput); 99 else 100 if (syntaxInput instanceof List) 101 syntax = new Syntax((List)syntaxInput); 102 else 103 syntax = new SyntaxBuilder(syntaxInput).getSyntax(); 104 105 syntax.resolveSingulars(); 106 return syntax; 107 } 108 109 110 111 protected String makeFilePath(String fileName) { 112 return ConfigDir.dir()+"parsers"+File.separator+fileName; 113 } 114 115 116 protected String ensureDirectory(String fileName) { 117 File file = new File(fileName); 118 String dir = file.getParent(); 119 120 if (dir != null) { 121 File directory = new File(dir); 122 if (directory.exists() == false) 123 directory.mkdirs(); 124 } 125 126 return dir; 127 } 128 129 } | Popular Tags |