View Javadoc

1   /*
2    * #%L
3    * prolobjectlink-jpi
4    * %%
5    * Copyright (C) 2019 Prolobjectlink Project
6    * %%
7    * Permission is hereby granted, free of charge, to any person obtaining a copy
8    * of this software and associated documentation files (the "Software"), to deal
9    * in the Software without restriction, including without limitation the rights
10   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11   * copies of the Software, and to permit persons to whom the Software is
12   * furnished to do so, subject to the following conditions:
13   * 
14   * The above copyright notice and this permission notice shall be included in
15   * all copies or substantial portions of the Software.
16   * 
17   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23   * THE SOFTWARE.
24   * #L%
25   */
26  package io.github.prolobjectlink.prolog;
27  
28  import java.io.BufferedReader;
29  import java.io.FileNotFoundException;
30  import java.io.IOException;
31  import java.io.InputStream;
32  import java.io.InputStreamReader;
33  import java.io.PrintWriter;
34  import java.net.URI;
35  import java.net.URISyntaxException;
36  import java.security.ProtectionDomain;
37  import java.util.HashMap;
38  import java.util.Iterator;
39  import java.util.List;
40  import java.util.Map;
41  import java.util.Map.Entry;
42  import java.util.Set;
43  import java.util.logging.Level;
44  import java.util.logging.Logger;
45  
46  /**
47   * Partial implementation of {@link PrologConsole} interface.
48   * 
49   * @author Jose Zalacain
50   * @since 1.0
51   */
52  public abstract class AbstractConsole implements PrologConsole {
53  
54  	private static final String PROLOBJECTLINK = "Prolobjectlink";
55  	private static final String COPYRIHT = " (C)";
56  
57  	private static final InputStream STDIN = System.in;
58  //	private static final OutputStream STDOUT = System.out
59  
60  	// default input stream
61  	private final InputStreamReader input = new InputStreamReader(STDIN);
62  
63  	// buffered reader for read from standard input stream
64  	private final BufferedReader reader = new BufferedReader(input);
65  
66  	// standard output stream
67  //	private final PrintWriter output = System.console().writer()
68  	private final PrintWriter output = new PrintWriter(System.out, true);
69  
70  	//
71  	private final PrologEngine engine;
72  
73  	public AbstractConsole(PrologProvider provider) {
74  		this.engine = provider.newEngine();
75  	}
76  
77  	public final Map<String, String> getArguments(String[] args) {
78  		final Map<String, String> map = new HashMap<String, String>();
79  		if (args.length > 0) {
80  			Iterator<String> i = new ArrayIterator<String>(args);
81  			String name = i.next();
82  			if (i.hasNext()) {
83  				String value = i.next();
84  				map.put(name, value);
85  			} else {
86  				map.put(name, "");
87  			}
88  		}
89  		return map;
90  	}
91  
92  	public final void printUsage() {
93  		output.println("Usage: pllink option [file]");
94  		output.println("options:");
95  		output.println("	-r	consult/run a prolog file");
96  		output.println("	-v	print the prolog engine version");
97  		output.println("	-n	print the prolog engine name");
98  		output.println("	-l	print the prolog engine license");
99  		output.println("	-i	print the prolog engine information");
100 		output.println("	-a	print the prolog engine about");
101 		output.println("	-e	print the prolog engine enviroment paths");
102 		output.println("	-x	start the prolog engine execution");
103 		output.println("	-w	print the current work directory ");
104 		output.println("	-f	consult a prolog file and save formatted code");
105 		output.println("	-t	test and report integration conditions");
106 		output.println("	-p	print in a file a snapshot of currents predicates");
107 		output.println("	-s	generate .project file for Prolog Development Tool");
108 
109 	}
110 
111 	public final void run(String[] args) {
112 
113 		Map<String, String> m = getArguments(args);
114 		if (!m.isEmpty()) {
115 			if (m.containsKey("-v")) {
116 				output.println(engine.getVersion());
117 			} else if (m.containsKey("-n")) {
118 				output.println(engine.getName());
119 			} else if (m.containsKey("-l")) {
120 				output.println(engine.getLicense());
121 			} else if (m.containsKey("-i")) {
122 				output.print(PROLOBJECTLINK);
123 				output.print(COPYRIHT);
124 				output.print(" ");
125 				output.print(engine.getName());
126 				output.print(" v");
127 				output.println(engine.getVersion());
128 				output.println(engine.getLicense());
129 				output.println(System.getProperty("java.vm.name"));
130 				output.println(System.getProperty("java.vendor"));
131 				output.println(System.getProperty("java.version"));
132 				output.println();
133 			} else if (m.containsKey("-w")) {
134 				try {
135 					output.println("Working directory");
136 					ProtectionDomain p = getClass().getProtectionDomain();
137 					URI d = p.getCodeSource().getLocation().toURI();
138 					output.println(d);
139 				} catch (URISyntaxException e) {
140 					Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
141 				}
142 			} else if (m.containsKey("-e")) {
143 				output.println("Enviroment");
144 				output.println("Class path");
145 				output.println(System.getenv("java.class.path"));
146 				output.println("System path");
147 				output.println(System.getenv("Path"));
148 			} else if (m.containsKey("-a")) {
149 				output.print(PROLOBJECTLINK);
150 				output.print(COPYRIHT);
151 			} else if (m.containsKey("-r")) {
152 				String file = m.get("-r");
153 				output.print("Consult ");
154 				output.println(file);
155 				engine.consult(file);
156 			} else if (m.containsKey("-x")) {
157 				// do nothing silently execution
158 			} else if (m.containsKey("-f")) {
159 				String file = m.get("-r");
160 				output.print("Format ");
161 				output.println(file);
162 				engine.consult(file);
163 				engine.persist(file);
164 			} else if (m.containsKey("-t")) {
165 				List<String> status = engine.verify();
166 				for (String string : status) {
167 					output.println(string);
168 				}
169 			} else if (m.containsKey("-p")) {
170 				String file = m.get("-p");
171 				try {
172 					PrintWriter writter = new PrintWriter(file);
173 					Set<PrologIndicator> set = engine.currentPredicates();
174 					for (PrologIndicator prologIndicator : set) {
175 						writter.println(prologIndicator);
176 					}
177 					writter.close();
178 				} catch (FileNotFoundException e) {
179 					Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
180 					System.exit(1);
181 				}
182 			} else if (m.containsKey("-h")) {
183 				System.exit(1);
184 				printUsage();
185 			} else {
186 				printUsage();
187 				System.exit(1);
188 			}
189 
190 			try {
191 
192 				String queryString;
193 				output.print("?- ");
194 				output.flush();
195 				queryString = reader.readLine();
196 
197 				while (true) {
198 
199 					if (!queryString.equals("")) {
200 						output.println();
201 
202 						if (queryString.lastIndexOf('.') == queryString.length() - 1) {
203 							queryString = queryString.substring(0, queryString.length() - 1);
204 						}
205 
206 						PrologQuery query = engine.query(queryString);
207 						if (query.hasSolution()) {
208 							Map<String, PrologTerm> s = query.oneVariablesSolution();
209 							for (Entry<String, PrologTerm> e : s.entrySet()) {
210 								output.println(e.getKey() + " = " + e.getValue());
211 							}
212 							output.println();
213 							output.println("Yes.");
214 						}
215 
216 						else {
217 							output.println("No.");
218 						}
219 
220 						output.println();
221 						output.println();
222 
223 					} else {
224 						output.println("Emty query");
225 						output.println();
226 					}
227 
228 					output.print("?- ");
229 					output.flush();
230 					queryString = reader.readLine();
231 
232 				}
233 
234 			} catch (UnsatisfiedLinkError e) {
235 				output.println("Prolog engine link conditions:");
236 				List<String> status = engine.verify();
237 				for (String string : status) {
238 					output.println(string);
239 				}
240 			} catch (IOException e) {
241 				Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
242 				System.exit(1);
243 			}
244 
245 		} else {
246 			printUsage();
247 			System.exit(1);
248 		}
249 
250 	}
251 
252 }