-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsole.java
More file actions
285 lines (248 loc) · 9.21 KB
/
Console.java
File metadata and controls
285 lines (248 loc) · 9.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package javaxt.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.lang.reflect.Array;
import java.util.HashMap;
//******************************************************************************
//** Console
//******************************************************************************
/**
* Various command line utilities used to print debug messages and collect
* user inputs.
*
******************************************************************************/
public class Console {
private static final String indent = " "; // 25 spaces
private static final DecimalFormat df = new DecimalFormat("#.##");
/** Static instance of the this class that can be called directly via a
* static import. Example:
<pre>
import static javaxt.utils.Console.console;
public class Test {
public Test(){
console.log("Hello!");
}
}
</pre>
*/
public static Console console = new Console();
//**************************************************************************
//** log
//**************************************************************************
/** Prints a message to the standard output stream, along with the class
* name and line number where the log() function is called. This function
* is intended to help debug applications and is inspired by the JavaScript
* console.log() function.
* @param any Accepts any Java object (e.g. string, number, null, classes,
* arrays, etc). You can pass in multiple objects separated by a comma.
* Example:
<pre>
console.log("Hello");
console.log("Date: ", new Date());
console.log(1>0, 20/5, new int[]{1,2,3});
</pre>
*/
public void log(Object... any){
//Get source
String source = getSource();
source = "[" + source + "]";
if (source.length()<indent.length()){
source += indent.substring(0, indent.length() - source.length());
}
else{
source += " ";
}
//Get string representation of the object
StringBuilder out = new StringBuilder(source);
if (any!=null){
int n = 0;
for (Object obj : any){
String str = null;
if (obj!=null){
if (obj.getClass().isArray()){
StringBuilder sb = new StringBuilder("[");
for (int i=0; i<Array.getLength(obj); i++) {
Object o = Array.get(obj, i);
String s = format(o);
if (i>0) sb.append(",");
sb.append(s);
}
sb.append("]");
str = sb.toString();
}
else{
str = format(obj);
}
}
if (n>0) out.append(" ");
out.append(str);
n++;
}
}
else{
out.append(any);
}
System.out.println(out);
}
//**************************************************************************
//** format
//**************************************************************************
private String format(Object obj){
String str = null;
if (obj!=null){
if (obj instanceof Double){
df.setMaximumFractionDigits(8);
str = df.format((Double) obj);
}
else{
str = obj.toString();
}
}
return str;
}
//**************************************************************************
//** getSource
//**************************************************************************
/** Returns the class name and line number that was used to call the log()
* method.
*/
private String getSource(){
//Create an exception and get the stack trace
Exception e = new Exception();
StackTraceElement[] stackTrace = e.getStackTrace();
//Find first element in the stack trace that is not an instance of this class
StackTraceElement target = null;
boolean foundConsole = false;
for (int i=1; i<stackTrace.length; i++){
StackTraceElement el = stackTrace[i];
try{
Class c = Class.forName(el.getClassName());
if (c.isAssignableFrom(this.getClass())){
foundConsole = true;
}
else{
if (foundConsole){
target = stackTrace[i];
break;
}
}
}
catch(Exception ex){
}
}
if (target==null) return "";
//Parse target classname and append line number
String className = target.getClassName();
int idx = className.lastIndexOf(".");
if (idx>0) className = className.substring(idx+1);
idx = className.indexOf("$");
if (idx>0) className = className.substring(0, idx);
return className + ":" + target.getLineNumber();
}
//**************************************************************************
//** getInput
//**************************************************************************
/** Used to prompt a user for an input
*/
public static String getInput(String prompt){
String input = null;
System.out.print(prompt);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
input = br.readLine();
}
catch (IOException e) {
System.out.println("Failed to read input");
//System.exit(1);
}
return input;
}
//**************************************************************************
//** getUserName
//**************************************************************************
/** Used to prompt a user for a username
*/
public static String getUserName(String prompt){
return getInput(prompt);
}
//**************************************************************************
//** getPassword
//**************************************************************************
/** Used to prompt a user for a password. The password is hidden as is it
* entered.
*/
public static String getPassword(String prompt) {
return new String(System.console().readPassword(prompt));
}
//**************************************************************************
//** parseArgs
//**************************************************************************
/** Converts command line inputs into key/value pairs. Assumes keys start
* with a "-" character (e.g. "-version" or "--version") followed by a
* value (or nothing at all).
*/
public static HashMap<String, String> parseArgs(String[] args){
HashMap<String, String> map = new HashMap<>();
for (int i=0; i<args.length; i++){
String key = args[i];
if (key.startsWith("-")){
if (i<args.length-1){
String nextArg = args[i+1];
if (nextArg.startsWith("-")){
map.put(key, null);
}
else{
i++;
map.put(key, nextArg);
}
}
else{
map.put(key, null);
}
}
}
return map;
}
//**************************************************************************
//** getValue
//**************************************************************************
/** Returns a value for a given set of command line arguments
* @param args HashMap of command line inputs generated by parseArgs()
* @param keys One or more keywords to search (e.g. "--threads", "-t")
*/
public static Value getValue(HashMap<String, String> args, String ...keys){
for (String key : keys){
if (args.containsKey(key)){
return new Value(args.get(key));
}
else{
//Fuzzy match (user passed one hyphen instead of two)
if (key.startsWith("-")){
String k = key.substring(1);
if (k.startsWith("-") && args.containsKey(k)){
return new Value(args.get(k));
}
}
}
}
return new Value(null);
}
//**************************************************************************
//** main
//**************************************************************************
/** Used to print the JavaXT version number when this jar is called from the
* command line. Example:
<pre>
java -jar javaxt-core.jar
JavaXT: 1.11.3
</pre>
* Under the hood, this simple command line application uses the
* getVersion() method in the javaxt.io.Jar class.
*/
public static void main(String[] args) {
javaxt.io.Jar jar = new javaxt.io.Jar(javaxt.io.Jar.class);
System.out.println("JavaXT: " + jar.getVersion());
}
}