forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSysUtilAdmin.java
More file actions
382 lines (343 loc) · 12.2 KB
/
SysUtilAdmin.java
File metadata and controls
382 lines (343 loc) · 12.2 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package act;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import act.cli.*;
import act.sys.Env;
import act.util.PropertySpec;
import org.joda.time.LocalDateTime;
import org.osgl.$;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.storage.impl.SObject;
import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.IO;
import org.osgl.util.S;
import javax.validation.constraints.Min;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unused")
public class SysUtilAdmin {
private CliContext context;
public SysUtilAdmin() {
context = CliContext.current();
}
@Command(name = "act.pid", help = "Print current process ID")
public String pid() {
return Env.PID.get();
}
@Command(name = "act.meminfo, act.mi", help = "Print memory info")
public void memInfo(
@Optional("monitor memory usage") boolean monitor,
@Optional("human readable") boolean human,
CliContext context
) {
final int factor = human ? 1024 * 1024 : 1;
Runtime runtime = Runtime.getRuntime();
if (monitor) {
context.session().dameon(true);
long ts0 = $.ms();
long lastUsed = 0;
context.println();
context.println(" ====== MEMORY INFO ======");
context.println();
context.flush();
int count = 0;
while (true) {
long ts = ($.ms() - ts0) / 1000;
if (count % 6 == 0) {
context.println("");
context.println("%7s%15s%12s%12s%12s%12s", "time(s)", "cached(cls#)", "total", "free", "used", "delta");
}
long total = runtime.totalMemory() / factor;
long free = runtime.freeMemory() / factor;
long used = total - free;
long delta = 0 == count++ ? 0L : used - lastUsed;
lastUsed = used;
int cached = Act.classCacheSize();
context.println("%7d%15d%12d%12d%12d%12d", ts, cached, total, free, used, delta);
context.flush();
if (context.disconnected()) {
context.session().dameon(false);
break;
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
break;
}
}
} else {
long total = runtime.totalMemory() / factor;
long free = runtime.freeMemory() / factor;
int cached = Act.classCacheSize();
context.println("====== MEMORY INFO ======");
context.println("%12s: %11d", "total", total);
context.println("%12s: %11d", "free", free);
context.println("%12s: %11d", "used", total - free);
context.println("%12s: %11d", "cached(cls#)", cached);
context.flush();
}
}
@Command(name = "act.gc", help = "Run GC")
public void gc(CliContext context) {
System.gc();
context.println("GC executed");
memInfo(false, false, context);
}
@GetAction("version")
@Command(name = "act.version, act.ver", help = "Print app/actframework version")
@JsonView
public Object version() {
Map<String, Object> retVal = new HashMap<>();
retVal.put("act", Act.VERSION);
retVal.put("app", Act.appVersion());
return retVal;
}
@Command(name = "act.pwd", help = "Print name of the current working directory")
public String pwd() {
return pwd(context).getAbsolutePath();
}
@Command(name = "act.ls, act.dir, act.ll", help = "List files in the current working directory")
@PropertySpec("path as name,size,timestamp")
public List<FileInfo> ls(
@Optional("specify the path to be listed") String path,
@Optional(lead = "-a", help = "display hidden files") boolean showHidden,
String path2,
CliContext ctx
) {
if (S.blank(path) && S.notBlank(path2)) {
path = path2;
}
if (S.blank(path)) {
ctx.println(pwd());
return dir(curDir(), showHidden, context);
} else {
ctx.println(path);
File file = getFile(path);
if (!file.exists()) {
ctx.println("%s is not a file or directory", path);
return null;
} else {
if (file.isDirectory()) {
return dir(file, showHidden, context);
} else {
return C.list(new FileInfo(file.getParentFile(), file));
}
}
}
}
@Command(name = "act.cd", help = "Change working directory")
public void cd(@Required("specify the path to which the working directory to be changed") String path) {
if (S.blank(path)) {
context.println(pwd());
return;
}
File file = getFile(path);
if (path.contains("..")) {
try {
file = new File(file.getCanonicalPath());
} catch (IOException e) {
throw E.ioException(e);
}
}
if (!file.isDirectory()) {
context.println("path is not a directory");
return;
}
context.chDir(file);
context.println("current working directory changed to %s", file.getAbsolutePath());
}
@Command(name = "act.cat", help = "print file content")
public void cat(
@Required(lead = "-f --url", help = "specify the file/resource URL to be printed out", errorTemplate = "error accessing file/resource at %s") SObject sobj,
@Optional(help = "specify the maximum lines to be printed out") int limit,
@Optional(help = "specify the begin line to be printed out", defVal = "0") @Min(0) int begin,
@Optional(help = "specify the end line to be printed out") int end,
@Optional(help = "specify begin end as range, e.g. 5-8") String range,
@Optional(lead = "-n,--line-number", help = "print line number") boolean printLineNumber,
@Optional(lead = "-q,--grep", help = "specify search criteria") String q,
CliContext context
) {
if (S.notBlank(range)) {
range = range.trim();
String[] sa = range.split("[\\s,\\-:]+");
try {
begin = Integer.parseInt(sa[0]);
end = Integer.parseInt(sa[1]);
} catch (Exception e) {
context.println("Invalid range: %s. Try something like '3-6'", range);
return;
}
} else {
final int defLimit = S.blank(q) ? 20 : Integer.MAX_VALUE;
if (begin <= 0) {
begin = 1;
}
if (end <= 0) {
end = begin + (limit <= 0 ? defLimit : limit) - 1;
}
}
List<String> lines = IO.readLines(sobj.asInputStream(), end);
int len = lines.size();
context.println("");
for (int i = begin - 1; i < len; ++i) {
String line = lines.get(i);
if (S.notBlank(q) && !line.contains(q)) {
continue;
}
if (printLineNumber) {
context.print("%5s | ", i + 1);
}
context.println(line);
}
context.println("");
}
private File getFile(String path) {
return context.getFile(path);
}
private File curDir() {
return pwd(context);
}
private static File pwd(CliContext context) {
return context.curDir();
}
private static List<FileInfo> dir(File file, boolean showHidden, CliContext context) {
C.List<FileInfo> list = C.newList();
File[] files = file.listFiles();
if (null == files) {
context.println("Invalid dir: %s", file.getAbsolutePath());
return C.list();
}
File parent = file.getAbsoluteFile();
for (File f0 : files) {
if (!showHidden && f0.isHidden()) {
continue;
}
list.add(new FileInfo(parent, f0));
}
list = list.sorted();
return list;
}
public static class FileInfo implements Comparable<FileInfo> {
String context;
String path;
String size;
boolean hidden;
LocalDateTime timestamp;
boolean isDir;
private FileInfo(File parent, File file) {
this.isDir = file.isDirectory();
this.context = null == parent ? "/" : parent.getAbsolutePath();
this.path = printPath(file);
this.size = printSize(file);
this.timestamp = LocalDateTime.fromDateFields(new Date(file.lastModified()));
this.hidden = file.isHidden();
}
public String getContext() {
return context;
}
public String getPath() {
return path;
}
public String getSize() {
return size;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public boolean isHidden() {
return hidden;
}
@Override
public int compareTo(FileInfo that) {
if (this.isDir) {
return that.isDir ? this.path.compareTo(that.path) : -1;
} else {
return that.isDir ? 1 : this.path.compareTo(that.path);
}
}
private String printPath(File file) {
if (isDir) {
return S.newBuffer("[").append(file.getName()).append("]").toString();
} else {
return file.getName();
}
}
private String printSize(File file) {
String unit;
long len = file.length();
if (len < 1024L) {
unit = "B";
} else {
len /= 1024L;
if (len < 1024L) {
unit = "KB";
} else {
len /= 1024L;
if (len < 1024L) {
unit = "MB";
} else {
len /= 1024L;
if (len < 1024L) {
unit = "GB";
} else {
len /= 1024L;
unit = "TB";
}
}
}
}
return S.newBuffer(len).append(unit).toString();
}
}
/**
* Guess whether given file is binary. Just checks for anything under 0x09.
*/
private static boolean isBinary(InputStream in) {
try {
int size = in.available();
if (size > 1024) size = 1024;
byte[] data = new byte[size];
in.read(data);
in.close();
int ascii = 0;
int other = 0;
for (int i = 0; i < data.length; i++) {
byte b = data[i];
if (b < 0x09) return true;
if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++;
else if (b >= 0x20 && b <= 0x7E) ascii++;
else other++;
}
return other != 0 && 100 * other / (ascii + other) > 95;
} catch (IOException e) {
throw E.ioException(e);
}
}
@Command(value = "act.zen", help = "give me the zen words")
public static String zen() {
return Zen.wordsOfTheDay();
}
}