提交 97f5238f 编写于 作者: R roo00

删除旧的scratch代码

上级 7caad7ab
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="x_program_center" metadata-complete="false"
version="3.0">
<display-name>x_program_center</display-name>
</web-app>
\ No newline at end of file
package com.x.program.center.test;
import java.util.Random;
import org.junit.Test;
public class A {
public static String sss = "aaaaa";
@Test
public void test1() {
Random random = new Random();
System.out.println(random.nextInt());
}
}
package com.x.program.center.test;
import java.util.TimerTask;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;
public class ATimerTask extends TimerTask {
@Test
public void run() {
System.out.println(NumberUtils.isNumber(null));
// TODO Auto-generated method stub
}
@Test
public void test1() {
}
}
package com.x.program.center.test;
public class B extends A {
}
package com.x.program.center.test;
import java.util.TimerTask;
public class BTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("BBBBBBBBBBBBBBBBB");
// TODO Auto-generated method stub
}
}
[
{
"containerType": "tomcat8",
"host": "127.0.0.1",
"port": 80,
"username": "xadmin",
"password": "xpfadmin",
"order": 0,
"name": "xw01"
}
]
\ No newline at end of file
package com.x.program.center.test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.x.base.core.project.gson.XGsonBuilder;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
public class TestClient {
@Test
public void test7() throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("javascript");
String str = "function aaa(){";
str += StringUtils.LF;
str += "var list = [{},{}]";
str += StringUtils.LF;
str += "return list";
str += StringUtils.LF;
str += "}";
str += StringUtils.LF;
str += "aaa()";
Object obj = engine.eval(str);
System.out.println(obj);
System.out.println(obj.getClass().getName());
ScriptObjectMirror som = (ScriptObjectMirror) obj;
System.out.println(som.isArray());
Object[] os = new Object[] {};
ScriptObjectMirror.unwrapArray(os, som);
System.out.println(os);
for (Object o : os) {
System.out.println(o);
}
}
@Test
public void test3() {
Pattern REGEX = Pattern.compile("^\\/\\*(\\s|.)*?\\*\\/");
String COMMENT = "/*" + StringUtils.LF;
COMMENT += "* resources.getEntityManagerContainer(); // 实体管理容器." + StringUtils.LF;
COMMENT += "* resources.getContext(); //上下文根." + StringUtils.LF;
COMMENT += "* resources.getOrganization(); //组织访问接口." + StringUtils.LF;
COMMENT += "* requestText //请求内容." + StringUtils.LF;
COMMENT += "* request //请求对象." + StringUtils.LF;
COMMENT += "*/adfasdfasdfasdf";
Matcher m = REGEX.matcher(COMMENT);
System.out.println(m.find());
System.out.println(m.replaceFirst(""));
}
@Test
public void test4() {
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(4);
list.add(8);
list.add(5);
list.add(5);
list.add(9);
list = list.stream()
.sorted(Comparator.comparing(Integer::intValue, Comparator.nullsLast(Integer::compareTo)).reversed())
.collect(Collectors.toList());
System.out.println(XGsonBuilder.toJson(list));
}
}
package com.x.program.center.test.appstyle;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
public class TestClient {
@Test
public void test_bas64_launch_logo() throws IOException {
URL url = this.getClass().getClassLoader().getResource("launch_logo.png");
File file = FileUtils.toFile(url);
String icon = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
System.out.print(icon);
}
@Test
public void test_bas64_login_avatar() throws IOException {
URL url = this.getClass().getClassLoader().getResource("login_avatar.png");
File file = FileUtils.toFile(url);
String icon = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
System.out.print(icon);
}
@Test
public void test_bas64_index_bottom_menu_logo_blur() throws IOException {
URL url = this.getClass().getClassLoader().getResource("index_bottom_menu_logo_blur.png");
File file = FileUtils.toFile(url);
String icon = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
System.out.print(icon);
}
@Test
public void test_bas64_index_bottom_menu_logo_focus() throws IOException {
URL url = this.getClass().getClassLoader().getResource("index_bottom_menu_logo_focus.png");
File file = FileUtils.toFile(url);
String icon = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
System.out.print(icon);
}
@Test
public void test_bas64_people_avatar_default() throws IOException {
URL url = this.getClass().getClassLoader().getResource("people_avatar_default.png");
File file = FileUtils.toFile(url);
String icon = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
System.out.print(icon);
}
@Test
public void test_bas64_process_default() throws IOException {
URL url = this.getClass().getClassLoader().getResource("process_default.png");
File file = FileUtils.toFile(url);
String icon = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
System.out.print(icon);
}
@Test
public void test_bas64_index_setup_about_logo() throws IOException {
URL url = this.getClass().getClassLoader().getResource("setup_about_logo.png");
File file = FileUtils.toFile(url);
String icon = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
System.out.print(icon);
}
}
package com.x.program.center.test.ca;
import org.apache.commons.io.FilenameUtils;
import org.junit.Test;
public class TestClient {
@Test
public void test1() {
System.out.println(FilenameUtils.getExtension("hh"));
}
}
/**
*
*/
/**
* @author zhour
*
*/
package com.x.program.center.test.ca;
\ No newline at end of file
/*
* Copyright (c) 2006-2008 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarLoader;
/**
* Display cpu information for each cpu found on the system.
*/
public class CpuInfo extends SigarCommandBase {
public boolean displayTimes = true;
public CpuInfo(Shell shell) {
super(shell);
}
public CpuInfo() {
super();
}
public String getUsageShort() {
return "Display cpu information";
}
private void output(CpuPerc cpu) {
println("User Time....." + CpuPerc.format(cpu.getUser()));
println("Sys Time......" + CpuPerc.format(cpu.getSys()));
println("Idle Time....." + CpuPerc.format(cpu.getIdle()));
println("Wait Time....." + CpuPerc.format(cpu.getWait()));
println("Nice Time....." + CpuPerc.format(cpu.getNice()));
println("Combined......" + CpuPerc.format(cpu.getCombined()));
println("Irq Time......" + CpuPerc.format(cpu.getIrq()));
if (SigarLoader.IS_LINUX) {
println("SoftIrq Time.." + CpuPerc.format(cpu.getSoftIrq()));
println("Stolen Time...." + CpuPerc.format(cpu.getStolen()));
}
println("");
}
public void output(String[] args) throws SigarException {
org.hyperic.sigar.CpuInfo[] infos = this.sigar.getCpuInfoList();
CpuPerc[] cpus = this.sigar.getCpuPercList();
org.hyperic.sigar.CpuInfo info = infos[0];
long cacheSize = info.getCacheSize();
println("Vendor........." + info.getVendor());
println("Model.........." + info.getModel());
println("Mhz............" + info.getMhz());
println("Total CPUs....." + info.getTotalCores());
if ((info.getTotalCores() != info.getTotalSockets()) || (info.getCoresPerSocket() > info.getTotalCores())) {
println("Physical CPUs.." + info.getTotalSockets());
println("Cores per CPU.." + info.getCoresPerSocket());
}
if (cacheSize != Sigar.FIELD_NOTIMPL) {
println("Cache size...." + cacheSize);
}
println("");
if (!this.displayTimes) {
return;
}
for (int i = 0; i < cpus.length; i++) {
println("CPU " + i + ".........");
output(cpus[i]);
}
println("Totals........");
output(this.sigar.getCpuPerc());
}
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("java.library.path"));
new CpuInfo().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
* Copyright (c) 2010 VMware, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.ArrayList;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemMap;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.NfsFileSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.shell.FileCompleter;
import org.hyperic.sigar.util.GetlineCompleter;
/**
* Report filesytem disk space usage.
*/
public class Df extends SigarCommandBase {
private static final String OUTPUT_FORMAT =
"%-15s %4s %4s %5s %4s %-15s %s";
//like df -h -a
private static final String[] HEADER = new String[] {
"Filesystem",
"Size",
"Used",
"Avail",
"Use%",
"Mounted on",
"Type"
};
//df -i
private static final String[] IHEADER = new String[] {
"Filesystem",
"Inodes",
"IUsed",
"IFree",
"IUse%",
"Mounted on",
"Type"
};
private GetlineCompleter completer;
private boolean opt_i;
public Df(Shell shell) {
super(shell);
setOutputFormat(OUTPUT_FORMAT);
this.completer = new FileCompleter(shell);
}
public Df() {
super();
setOutputFormat(OUTPUT_FORMAT);
}
public GetlineCompleter getCompleter() {
return this.completer;
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getSyntaxArgs() {
return "[filesystem]";
}
public String getUsageShort() {
return "Report filesystem disk space usage";
}
public void printHeader() {
printf(this.opt_i ? IHEADER : HEADER);
}
public void output(String[] args) throws SigarException {
this.opt_i = false;
ArrayList sys = new ArrayList();
if (args.length > 0) {
FileSystemMap mounts = this.proxy.getFileSystemMap();
for (int i=0; i<args.length; i++) {
String arg = args[i];
if (arg.equals("-i")) {
this.opt_i = true;
continue;
}
String name = FileCompleter.expand(arg);
FileSystem fs = mounts.getMountPoint(name);
if (fs == null) {
throw new SigarException(arg +
" No such file or directory");
}
sys.add(fs);
}
}
if (sys.size() == 0) {
FileSystem[] fslist = this.proxy.getFileSystemList();
for (int i=0; i<fslist.length; i++) {
sys.add(fslist[i]);
}
}
printHeader();
for (int i=0; i<sys.size(); i++) {
output((FileSystem)sys.get(i));
}
}
public void output(FileSystem fs) throws SigarException {
long used, avail, total, pct;
try {
FileSystemUsage usage;
if (fs instanceof NfsFileSystem) {
NfsFileSystem nfs = (NfsFileSystem)fs;
if (!nfs.ping()) {
println(nfs.getUnreachableMessage());
return;
}
}
usage = this.sigar.getFileSystemUsage(fs.getDirName());
if (this.opt_i) {
used = usage.getFiles() - usage.getFreeFiles();
avail = usage.getFreeFiles();
total = usage.getFiles();
if (total == 0) {
pct = 0;
}
else {
long u100 = used * 100;
pct = u100 / total +
((u100 % total != 0) ? 1 : 0);
}
}
else {
used = usage.getTotal() - usage.getFree();
avail = usage.getAvail();
total = usage.getTotal();
pct = (long)(usage.getUsePercent() * 100);
}
} catch (SigarException e) {
//e.g. on win32 D:\ fails with "Device not ready"
//if there is no cd in the drive.
used = avail = total = pct = 0;
}
String usePct;
if (pct == 0) {
usePct = "-";
}
else {
usePct = pct + "%";
}
ArrayList items = new ArrayList();
items.add(fs.getDevName());
items.add(formatSize(total));
items.add(formatSize(used));
items.add(formatSize(avail));
items.add(usePct);
items.add(fs.getDirName());
items.add(fs.getSysTypeName() + "/" + fs.getTypeName());
printf(items);
}
private String formatSize(long size) {
return this.opt_i ? String.valueOf(size) : Sigar.formatSize(size * 1024);
}
public static void main(String[] args) throws Exception {
new Df().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.DirUsage;
import org.hyperic.sigar.SigarException;
/**
* Display usage for a directory recursively
*/
public class Du extends SigarCommandBase {
//like du -s -b
public Du(Shell shell) {
super(shell);
}
public Du() {
super();
}
public String getUsageShort() {
return "Display usage for a directory recursively";
}
protected boolean validateArgs(String[] args) {
return args.length == 1;
}
public void output(String[] args) throws SigarException {
String dir = args[0];
DirUsage du = this.sigar.getDirUsage(dir);
println(du.getDiskUsage() + "\t" + dir);
}
public static void main(String[] args) throws Exception {
new Du().processCommand(args);
}
}
/*
* Copyright (c) 2007, 2009 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.win32.EventLog;
import org.hyperic.sigar.win32.EventLogNotification;
import org.hyperic.sigar.win32.EventLogRecord;
import org.hyperic.sigar.win32.EventLogThread;
import org.hyperic.sigar.win32.Win32Exception;
public class EventLogTail {
private static void tail(String name, Tail tail) throws Win32Exception {
EventLog log = new EventLog();
log.open(name);
int max = log.getNumberOfRecords();
if (tail.number < max) {
max = tail.number;
}
int last = log.getNewestRecord()+1;
int first = last - max;
for (int i=first; i<last; i++) {
EventLogRecord record = log.read(i);
System.out.println(record);
}
log.close();
}
private static class TailNotification implements EventLogNotification {
public void handleNotification(EventLogRecord event) {
System.out.println(event);
}
public boolean matches(EventLogRecord event) {
return true;
}
}
public static void main(String[] args) throws Exception {
Tail tail = new Tail();
tail.parseArgs(args);
if (tail.files.size() == 0) {
tail.files.add(EventLog.SYSTEM);
}
for (int i=0; i<tail.files.size(); i++) {
String name = (String)tail.files.get(i);
tail(name, tail);
if (tail.follow) {
TailNotification notifier = new TailNotification();
EventLogThread thread =
EventLogThread.getInstance(name);
thread.add(notifier);
thread.doStart();
}
}
if (tail.follow) {
System.in.read();
}
}
}
/*
* Copyright (c) 2008-2009 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.win32.FileVersion;
import org.hyperic.sigar.win32.Win32;
/**
* Display process file information.
*/
public class FileVersionInfo extends SigarCommandBase {
public FileVersionInfo(Shell shell) {
super(shell);
}
public FileVersionInfo() {
super();
}
protected boolean validateArgs(String[] args) {
return args.length >= 1;
}
public String getUsageShort() {
return "Display file version info";
}
public void output(String[] args) throws SigarException {
for (int i=0; i<args.length; i++) {
String exe = args[i];
if (new File(exe).exists()) {
output(exe);
}
else {
long[] pids = this.shell.findPids(exe);
for (int j=0; j<pids.length; j++) {
try {
output(sigar.getProcExe(pids[j]).getName());
} catch (SigarException e) {
println(exe + ": " + e.getMessage());
}
}
}
}
}
private void output(String key, String val) {
final int max = 20;
int len = max - key.length();
StringBuffer sb = new StringBuffer();
sb.append(" ").append(key);
while (len-- > 0) {
sb.append('.');
}
sb.append(val);
println(sb.toString());
}
public void output(String exe) throws SigarException {
FileVersion info = Win32.getFileVersion(exe);
if (info == null) {
return;
}
println("Version info for file '" + exe + "':");
output("FileVersion", info.getFileVersion());
output("ProductVersion", info.getProductVersion());
for (Iterator it = info.getInfo().entrySet().iterator();
it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
output((String)entry.getKey(), (String)entry.getValue());
}
}
public static void main(String[] args) throws Exception {
new FileVersionInfo().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Swap;
/**
* Display amount of free and used memory in the system.
*/
public class Free extends SigarCommandBase {
public Free(Shell shell) {
super(shell);
}
public Free() {
super();
}
public String getUsageShort() {
return "Display information about free and used memory";
}
private static Long format(long value) {
return new Long(value / 1024);
}
public void output(String[] args) throws SigarException {
Mem mem = this.sigar.getMem();
Swap swap = this.sigar.getSwap();
Object[] header = new Object[] { "total", "used", "free" };
Object[] memRow = new Object[] {
format(mem.getTotal()),
format(mem.getUsed()),
format(mem.getFree())
};
Object[] actualRow = new Object[] {
format(mem.getActualUsed()),
format(mem.getActualFree())
};
Object[] swapRow = new Object[] {
format(swap.getTotal()),
format(swap.getUsed()),
format(swap.getFree())
};
printf("%18s %10s %10s", header);
printf("Mem: %10ld %10ld %10ld", memRow);
//e.g. linux
if ((mem.getUsed() != mem.getActualUsed()) ||
(mem.getFree() != mem.getActualFree()))
{
printf("-/+ buffers/cache: " + "%10ld %10d", actualRow);
}
printf("Swap: %10ld %10ld %10ld", swapRow);
printf("RAM: %10ls", new Object[] { mem.getRam() + "MB" });
}
public static void main(String[] args) throws Exception {
new Free().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.Arrays;
import java.util.Collection;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Display network interface configuration and metrics.
*/
public class Ifconfig extends SigarCommandBase {
public Ifconfig(Shell shell) {
super(shell);
}
public Ifconfig() {
super();
}
protected boolean validateArgs(String[] args) {
return args.length <= 1;
}
public String getSyntaxArgs() {
return "[interface]";
}
public String getUsageShort() {
return "Network interface information";
}
public Collection getCompletions() {
String[] ifNames;
try {
ifNames = this.proxy.getNetInterfaceList();
} catch (SigarException e) {
return super.getCompletions();
}
return Arrays.asList(ifNames);
}
public void output(String[] args) throws SigarException {
String[] ifNames;
if (args.length == 1) {
ifNames = args;
}
else {
ifNames = this.proxy.getNetInterfaceList();
}
for (int i=0; i<ifNames.length; i++) {
try {
output(ifNames[i]);
} catch (SigarException e) {
println(ifNames[i] + "\t" + e.getMessage());
}
}
}
public void output(String name) throws SigarException {
NetInterfaceConfig ifconfig =
this.sigar.getNetInterfaceConfig(name);
long flags = ifconfig.getFlags();
String hwaddr = "";
if (!NetFlags.NULL_HWADDR.equals(ifconfig.getHwaddr())) {
hwaddr = " HWaddr " + ifconfig.getHwaddr();
}
if (!ifconfig.getName().equals(ifconfig.getDescription())) {
println(ifconfig.getDescription());
}
println(ifconfig.getName() + "\t" +
"Link encap:" + ifconfig.getType() +
hwaddr);
String ptp = "";
if ((flags & NetFlags.IFF_POINTOPOINT) > 0) {
ptp = " P-t-P:" + ifconfig.getDestination();
}
String bcast = "";
if ((flags & NetFlags.IFF_BROADCAST) > 0) {
bcast = " Bcast:" + ifconfig.getBroadcast();
}
println("\t" +
"inet addr:" + ifconfig.getAddress() +
ptp + //unlikely
bcast +
" Mask:" + ifconfig.getNetmask());
println("\t" +
NetFlags.getIfFlagsString(flags) +
" MTU:" + ifconfig.getMtu() +
" Metric:" + ifconfig.getMetric());
try {
NetInterfaceStat ifstat =
this.sigar.getNetInterfaceStat(name);
println("\t" +
"RX packets:" + ifstat.getRxPackets() +
" errors:" + ifstat.getRxErrors() +
" dropped:" + ifstat.getRxDropped() +
" overruns:" + ifstat.getRxOverruns() +
" frame:" + ifstat.getRxFrame());
println("\t" +
"TX packets:" + ifstat.getTxPackets() +
" errors:" + ifstat.getTxErrors() +
" dropped:" + ifstat.getTxDropped() +
" overruns:" + ifstat.getTxOverruns() +
" carrier:" + ifstat.getTxCarrier());
println("\t" + "collisions:" +
ifstat.getTxCollisions());
long rxBytes = ifstat.getRxBytes();
long txBytes = ifstat.getTxBytes();
println("\t" +
"RX bytes:" + rxBytes +
" (" + Sigar.formatSize(rxBytes) + ")" +
" " +
"TX bytes:" + txBytes +
" (" + Sigar.formatSize(txBytes) + ")");
} catch (SigarException e) {
}
println("");
}
public static void main(String[] args) throws Exception {
new Ifconfig().processCommand(args);
}
}
/*
* Copyright (c) 2006-2008 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.ArrayList;
import org.hyperic.sigar.DiskUsage;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemMap;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.shell.FileCompleter;
import org.hyperic.sigar.util.GetlineCompleter;
/**
* Report filesytem disk space usage.
*/
public class Iostat extends SigarCommandBase {
private static final String OUTPUT_FORMAT =
"%-15s %-15s %10s %10s %7s %7s %5s %5s";
private static final String[] HEADER = new String[] {
"Filesystem",
"Mounted on",
"Reads",
"Writes",
"R-bytes",
"W-bytes",
"Queue",
"Svctm",
};
private GetlineCompleter completer;
public Iostat(Shell shell) {
super(shell);
setOutputFormat(OUTPUT_FORMAT);
this.completer = new FileCompleter(shell);
}
public Iostat() {
super();
setOutputFormat(OUTPUT_FORMAT);
}
public GetlineCompleter getCompleter() {
return this.completer;
}
protected boolean validateArgs(String[] args) {
return args.length <= 1;
}
public String getSyntaxArgs() {
return "[filesystem]";
}
public String getUsageShort() {
return "Report filesystem disk i/o";
}
public void printHeader() {
printf(HEADER);
}
private String svctm(double val) {
return sprintf("%3.2f", new Object[] { new Double(val) });
}
public void output(String[] args) throws SigarException {
if (args.length == 1) {
String arg = args[0];
if ((arg.indexOf('/') != -1) || (arg.indexOf('\\') != -1)) {
outputFileSystem(arg);
}
else {
outputDisk(arg);
}
}
else {
FileSystem[] fslist = this.proxy.getFileSystemList();
printHeader();
for (int i=0; i<fslist.length; i++) {
if (fslist[i].getType() == FileSystem.TYPE_LOCAL_DISK) {
output(fslist[i]);
}
}
}
}
public void outputFileSystem(String arg) throws SigarException {
FileSystemMap mounts = this.proxy.getFileSystemMap();
String name = FileCompleter.expand(arg);
FileSystem fs = mounts.getMountPoint(name);
if (fs != null) {
printHeader();
output(fs);
return;
}
throw new SigarException(arg +
" No such file or directory");
}
public void outputDisk(String name) throws SigarException {
DiskUsage disk =
this.sigar.getDiskUsage(name);
ArrayList items = new ArrayList();
printHeader();
items.add(name);
items.add("-");
items.add(String.valueOf(disk.getReads()));
items.add(String.valueOf(disk.getWrites()));
if (disk.getReadBytes() == Sigar.FIELD_NOTIMPL) {
items.add("-");
items.add("-");
}
else {
items.add(Sigar.formatSize(disk.getReadBytes()));
items.add(Sigar.formatSize(disk.getWriteBytes()));
}
if (disk.getQueue() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(disk.getQueue()));
}
if (disk.getServiceTime() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(disk.getServiceTime()));
}
printf(items);
}
public void output(FileSystem fs) throws SigarException {
FileSystemUsage usage =
this.sigar.getFileSystemUsage(fs.getDirName());
ArrayList items = new ArrayList();
items.add(fs.getDevName());
items.add(fs.getDirName());
items.add(String.valueOf(usage.getDiskReads()));
items.add(String.valueOf(usage.getDiskWrites()));
if (usage.getDiskReadBytes() == Sigar.FIELD_NOTIMPL) {
items.add("-");
items.add("-");
}
else {
items.add(Sigar.formatSize(usage.getDiskReadBytes()));
items.add(Sigar.formatSize(usage.getDiskWriteBytes()));
}
if (usage.getDiskQueue() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(usage.getDiskQueue()));
}
if (usage.getDiskServiceTime() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(usage.getDiskServiceTime()));
}
printf(items);
}
public static void main(String[] args) throws Exception {
new Iostat().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.SigarException;
/**
* Send a signal to a process.
*/
public class Kill extends SigarCommandBase {
public Kill(Shell shell) {
super(shell);
}
public Kill() {
super();
}
protected boolean validateArgs(String[] args) {
return args.length == 1 || args.length == 2;
}
public String getSyntaxArgs() {
return "[signal] <query|pid>";
}
public String getUsageShort() {
return "Send signal to a process";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
String signal = "SIGTERM";
long[] pids;
String query;
if (args.length == 2) {
signal = args[0];
query = args[1];
}
else {
query = args[0];
}
pids = this.shell.findPids(new String[] { query });
for (int i=0; i<pids.length; i++) {
println("kill " + signal + " " + pids[i]);
this.sigar.kill(pids[i], signal);
}
}
public static void main(String[] args) throws Exception {
new Kill().processCommand(args);
}
}
/*
* Copyright (c) 2008 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hyperic.sigar.FileInfo;
import org.hyperic.sigar.SigarException;
public class Ls extends SigarCommandBase {
public Ls(Shell shell) {
super(shell);
}
public Ls() {
super();
}
public String getUsageShort() {
return "simple FileInfo test at the moment (like ls -l)";
}
protected boolean validateArgs(String[] args) {
return args.length == 1;
}
private String getDate(long mtime) {
final String fmt = "MMM dd yyyy";
return new SimpleDateFormat(fmt).format(new Date(mtime));
}
public void output(String[] args) throws SigarException {
String file = args[0];
FileInfo link = this.sigar.getLinkInfo(file);
FileInfo info = this.sigar.getFileInfo(file);
if (link.getType() == FileInfo.TYPE_LNK) {
try {
file = file + " -> " + new File(file).getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
}
println(link.getTypeChar() +
info.getPermissionsString() + "\t" +
info.getUid() + "\t" + info.getGid() + "\t" +
info.getSize() + "\t" +
getDate(info.getMtime()) + "\t" +
file);
}
public static void main(String[] args) throws Exception {
new Ls().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.Sigar;
/**
* Watch for changes in program memory usage.
*/
public class MemWatch {
static final int SLEEP_TIME = 1000 * 10;
public static void main(String[] args) throws Exception {
Sigar sigar = new Sigar();
if (args.length != 1) {
throw new Exception("Usage: MemWatch pid");
}
long pid = Long.parseLong(args[0]);
long lastTime = System.currentTimeMillis();
ProcMem last = sigar.getProcMem(pid);
while (true) {
ProcMem cur = sigar.getProcMem(pid);
StringBuffer diff = diff(last, cur);
if (diff.length() == 0) {
System.out.println("no change " +
"(size=" +
Sigar.formatSize(cur.getSize()) +
")");
}
else {
long curTime = System.currentTimeMillis();
long timeDiff = curTime - lastTime;
lastTime = curTime;
diff.append(" after " + timeDiff + "ms");
System.out.println(diff);
}
last = cur;
Thread.sleep(SLEEP_TIME);
}
}
private static StringBuffer diff(ProcMem last, ProcMem cur) {
StringBuffer buf = new StringBuffer();
long diff;
diff = cur.getSize() - last.getSize();
if (diff != 0) {
buf.append("size=" + diff);
}
diff = cur.getResident() - last.getResident();
if (diff != 0) {
buf.append(", resident=" + diff);
}
diff = cur.getShare() - last.getShare();
if (diff != 0) {
buf.append(", share=" + diff);
}
return buf;
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.MultiProcCpu;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Show multi process status.
*/
public class MultiPs extends SigarCommandBase {
public MultiPs(Shell shell) {
super(shell);
}
public MultiPs() {
super();
}
protected boolean validateArgs(String[] args) {
return args.length == 1;
}
public String getSyntaxArgs() {
return "query";
}
public String getUsageShort() {
return "Show multi process status";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
String query = args[0];
MultiProcCpu cpu = this.proxy.getMultiProcCpu(query);
println("Number of processes: " + cpu.getProcesses());
println("Cpu usage: " + CpuPerc.format(cpu.getPercent()));
println("Cpu time: " + Ps.getCpuTime(cpu.getTotal()));
ProcMem mem = this.proxy.getMultiProcMem(query);
println("Size: " + Sigar.formatSize(mem.getSize()));
println("Resident: " + Sigar.formatSize(mem.getResident()));
println("Share: " + Sigar.formatSize(mem.getShare()));
}
public static void main(String[] args) throws Exception {
new MultiPs().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.SigarException;
/**
* Display network info.
*/
public class NetInfo extends SigarCommandBase {
public NetInfo(Shell shell) {
super(shell);
}
public NetInfo() {
super();
}
public String getUsageShort() {
return "Display network info";
}
public void output(String[] args) throws SigarException {
NetInterfaceConfig config = this.sigar.getNetInterfaceConfig(null);
println("primary interface....." +
config.getName());
println("primary ip address...." +
config.getAddress());
println("primary mac address..." +
config.getHwaddr());
println("primary netmask......." +
config.getNetmask());
org.hyperic.sigar.NetInfo info =
this.sigar.getNetInfo();
println("host name............." +
info.getHostName());
println("domain name..........." +
info.getDomainName());
println("default gateway......." +
info.getDefaultGateway());
println("primary dns..........." +
info.getPrimaryDns());
println("secondary dns........." +
info.getSecondaryDns());
}
public static void main(String[] args) throws Exception {
new NetInfo().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.hyperic.sigar.NetConnection;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Tcp;
/**
* Display network connections.
*/
public class Netstat extends SigarCommandBase {
private static final int LADDR_LEN = 20;
private static final int RADDR_LEN = 35;
private static final String[] HEADER = new String[] {
"Proto",
"Local Address",
"Foreign Address",
"State",
""
};
private static boolean isNumeric, wantPid, isStat;
public Netstat(Shell shell) {
super(shell);
}
public Netstat() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Display network connections";
}
//poor mans getopt.
public static int getFlags(String[] args, int flags) {
int proto_flags = 0;
isNumeric = false;
wantPid = false;
isStat = false;
for (int i=0; i<args.length; i++) {
String arg = args[i];
int j = 0;
while (j<arg.length()) {
switch (arg.charAt(j++)) {
case '-':
continue;
case 'l':
flags &= ~NetFlags.CONN_CLIENT;
flags |= NetFlags.CONN_SERVER;
break;
case 'a':
flags |= NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT;
break;
case 'n':
isNumeric = true;
break;
case 'p':
wantPid = true;
break;
case 's':
isStat = true;
break;
case 't':
proto_flags |= NetFlags.CONN_TCP;
break;
case 'u':
proto_flags |= NetFlags.CONN_UDP;
break;
case 'w':
proto_flags |= NetFlags.CONN_RAW;
break;
case 'x':
proto_flags |= NetFlags.CONN_UNIX;
break;
default:
System.err.println("unknown option");
}
}
}
if (proto_flags != 0) {
flags &= ~NetFlags.CONN_PROTOCOLS;
flags |= proto_flags;
}
return flags;
}
private String formatPort(int proto, long port) {
if (port == 0) {
return "*";
}
if (!isNumeric) {
String service = this.sigar.getNetServicesName(proto, port);
if (service != null) {
return service;
}
}
return String.valueOf(port);
}
private String formatAddress(int proto, String ip,
long portnum, int max) {
String port = formatPort(proto, portnum);
String address;
if (NetFlags.isAnyAddress(ip)) {
address = "*";
}
else if (isNumeric) {
address = ip;
}
else {
try {
address = InetAddress.getByName(ip).getHostName();
} catch (UnknownHostException e) {
address = ip;
}
}
max -= port.length() + 1;
if (address.length() > max) {
address = address.substring(0, max);
}
return address + ":" + port;
}
private void outputTcpStats() throws SigarException {
Tcp stat = this.sigar.getTcp();
final String dnt = " ";
println(dnt + stat.getActiveOpens() + " active connections openings");
println(dnt + stat.getPassiveOpens() + " passive connection openings");
println(dnt + stat.getAttemptFails() + " failed connection attempts");
println(dnt + stat.getEstabResets() + " connection resets received");
println(dnt + stat.getCurrEstab() + " connections established");
println(dnt + stat.getInSegs() + " segments received");
println(dnt + stat.getOutSegs() + " segments send out");
println(dnt + stat.getRetransSegs() + " segments retransmited");
println(dnt + stat.getInErrs() + " bad segments received.");
println(dnt + stat.getOutRsts() + " resets sent");
}
private void outputStats(int flags) throws SigarException {
if ((flags & NetFlags.CONN_TCP) != 0) {
println("Tcp:");
try {
outputTcpStats();
} catch (SigarException e) {
println(" " + e);
}
}
}
//XXX currently weak sauce. should end up like netstat command.
public void output(String[] args) throws SigarException {
//default
int flags = NetFlags.CONN_CLIENT | NetFlags.CONN_PROTOCOLS;
if (args.length > 0) {
flags = getFlags(args, flags);
if (isStat) {
outputStats(flags);
return;
}
}
NetConnection[] connections = this.sigar.getNetConnectionList(flags);
printf(HEADER);
for (int i=0; i<connections.length; i++) {
NetConnection conn = connections[i];
String proto = conn.getTypeString();
String state;
if (conn.getType() == NetFlags.CONN_UDP) {
state = "";
}
else {
state = conn.getStateString();
}
ArrayList items = new ArrayList();
items.add(proto);
items.add(formatAddress(conn.getType(),
conn.getLocalAddress(),
conn.getLocalPort(),
LADDR_LEN));
items.add(formatAddress(conn.getType(),
conn.getRemoteAddress(),
conn.getRemotePort(),
RADDR_LEN));
items.add(state);
String process = null;
if (wantPid &&
//XXX only works w/ listen ports
(conn.getState() == NetFlags.TCP_LISTEN))
{
try {
long pid =
this.sigar.getProcPort(conn.getType(),
conn.getLocalPort());
if (pid != 0) { //XXX another bug
String name =
this.sigar.getProcState(pid).getName();
process = pid + "/" + name;
}
} catch (SigarException e) {
}
}
if (process == null) {
process = "";
}
items.add(process);
printf(items);
}
}
public static void main(String[] args) throws Exception {
new Netstat().processCommand(args);
}
}
/*
* Copyright (c) 2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.lang.reflect.Method;
import org.hyperic.sigar.SigarException;
public class Nfsstat extends SigarCommandBase {
public Nfsstat(Shell shell) {
super(shell);
}
public Nfsstat() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Display nfs stats";
}
private String getValue(Object obj, String attr) {
if (attr == "") return "";
String name =
"get" + Character.toUpperCase(attr.charAt(0)) +
attr.substring(1);
try {
Method method =
obj.getClass().getMethod(name, new Class[0]);
return method.invoke(obj, new Object[0]).toString();
} catch (Exception e) {
return "EINVAL";
}
}
private void printnfs(Object nfs, String[] names) {
String[] values = new String[names.length];
for (int i=0; i<names.length; i++) {
values[i] = getValue(nfs, names[i]);
}
printf(names);
printf(values);
}
private void outputNfsV2(String header, Object nfs) {
println(header + ":");
printnfs(nfs,
new String[] { "null", "getattr", "setattr", "root", "lookup", "readlink" });
printnfs(nfs,
new String[] { "read", "writecache", "write", "create", "remove", "rename" });
printnfs(nfs,
new String[] { "link", "symlink", "mkdir", "rmdir", "readdir", "fsstat" });
println("");
flush();
}
private void outputNfsV3(String header, Object nfs) {
println(header + ":");
printnfs(nfs,
new String[] { "null", "getattr", "setattr", "lookup", "access", "readlink" });
printnfs(nfs,
new String[] { "read", "write", "create", "mkdir", "symlink", "mknod" });
printnfs(nfs,
new String[] { "remove", "rmdir", "rename", "link", "readdir", "readdirplus" });
printnfs(nfs,
new String[] { "fsstat", "fsinfo", "pathconf", "commit", "", "" });
println("");
flush();
}
public void output(String[] args) throws SigarException {
try {
outputNfsV2("Client nfs v2",
this.sigar.getNfsClientV2());
} catch (SigarException e) {}
try {
outputNfsV2("Server nfs v2",
this.sigar.getNfsServerV2());
} catch (SigarException e) {}
try {
outputNfsV3("Client nfs v3",
this.sigar.getNfsClientV3());
} catch (SigarException e) {}
try {
outputNfsV3("Server nfs v3",
this.sigar.getNfsServerV3());
} catch (SigarException e) {}
}
}
/*
* Copyright (c) 2008 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.SigarException;
public class Pidof extends SigarCommandBase {
public Pidof(Shell shell) {
super(shell);
}
public Pidof() {
super();
}
protected boolean validateArgs(String[] args) {
return args.length > 0;
}
public String getSyntaxArgs() {
return "query";
}
public String getUsageShort() {
return "Find the process ID of a running program";
}
public void output(String[] args) throws SigarException {
long[] pids = this.shell.findPids(args);
for (int i=0; i<pids.length; i++) {
this.out.print(pids[i]);
this.out.print(' ');
}
this.out.println();
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.ProcExe;
import org.hyperic.sigar.ProcFd;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarPermissionDeniedException;
/**
* Display process file information.
*/
public class ProcFileInfo extends SigarCommandBase {
public ProcFileInfo(Shell shell) {
super(shell);
}
public ProcFileInfo() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Display process file info";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
long[] pids = this.shell.findPids(args);
for (int i=0; i<pids.length; i++) {
try {
output(pids[i]);
} catch (SigarPermissionDeniedException e) {
println(this.shell.getUserDeniedMessage(pids[i]));
} catch (SigarException e) {
println("(" + e.getMessage() + ")");
}
println("\n------------------------\n");
}
}
public void output(long pid) throws SigarException {
println("pid=" + pid);
try {
ProcFd fd = sigar.getProcFd(pid);
println("open file descriptors=" + fd.getTotal());
} catch (SigarNotImplementedException e) {}
ProcExe exe = sigar.getProcExe(pid);
String name = exe.getName();
if (name.length() == 0) {
name = "unknown";
}
println("name=" + name);
println("cwd=" + exe.getCwd());
}
public static void main(String[] args) throws Exception {
new ProcFileInfo().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarPermissionDeniedException;
/**
* Display all process information.
*/
public class ProcInfo extends SigarCommandBase {
private boolean isSingleProcess;
public ProcInfo(Shell shell) {
super(shell);
}
public ProcInfo() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Display all process info";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
this.isSingleProcess = false;
if ((args.length != 0) && args[0].startsWith("-s")) {
this.isSingleProcess = true;
}
if (this.isSingleProcess) {
for (int i=1; i<args.length; i++) {
try {
output(args[i]);
} catch (SigarException e) {
println("(" + e.getMessage() + ")");
}
println("\n------------------------\n");
}
}
else {
long[] pids = this.shell.findPids(args);
for (int i=0; i<pids.length; i++) {
try {
output(String.valueOf(pids[i]));
} catch (SigarPermissionDeniedException e) {
println(this.shell.getUserDeniedMessage(pids[i]));
} catch (SigarException e) {
println("(" + e.getMessage() + ")");
}
println("\n------------------------\n");
}
}
}
public void output(String pid) throws SigarException {
println("pid=" + pid);
try {
println("state=" + sigar.getProcState(pid));
} catch (SigarException e) {
if (this.isSingleProcess) {
println(e.getMessage());
}
}
try {
println("mem=" + sigar.getProcMem(pid));
} catch (SigarException e) {}
try {
println("cpu=" + sigar.getProcCpu(pid));
} catch (SigarException e) {}
try {
println("cred=" + sigar.getProcCred(pid));
} catch (SigarException e) {}
try {
println("credname=" + sigar.getProcCredName(pid));
} catch (SigarException e) {}
}
public static void main(String[] args) throws Exception {
new ProcInfo().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.List;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
/**
* Display process module info.
*/
public class ProcModuleInfo extends SigarCommandBase {
public ProcModuleInfo(Shell shell) {
super(shell);
}
public ProcModuleInfo() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Display process module info";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
long[] pids = this.shell.findPids(args);
for (int i=0; i<pids.length; i++) {
try {
output(pids[i]);
} catch (SigarException e) {
println("(" + e.getMessage() + ")");
}
println("\n------------------------\n");
}
}
public void output(long pid) throws SigarException {
println("pid=" + pid);
try {
List modules = this.sigar.getProcModules(pid);
for (int i=0; i<modules.size(); i++) {
println(i + "=" + modules.get(i));
}
} catch (SigarNotImplementedException e) {
throw e;
} catch (SigarException e) {
println("[" + e.getMessage() + "]");
}
}
public static void main(String[] args) throws Exception {
new ProcModuleInfo().processCommand(args);
}
}
package com.x.program.center.test.examples;
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/*
Example to show the process state for a given pid.
Compile the example:
% javac -classpath sigar-bin/lib/sigar.jar ProcessState.java
State of the java process running the example:
% java -classpath sigar-bin/lib/sigar.jar:. ProcessState
java: Running
State of the bash shell when invoking the example is running:
% java -classpath sigar-bin/lib/sigar.jar:. ProcessState $$
bash: Sleeping
State of emacs editor used to write the example:
% java -classpath sigar-bin/lib/sigar.jar:. ProcessState 2673
emacs: Suspended
See also: examples/Ps.java, examples/Top.java
*/
public class ProcessState {
private static String getStateString(char state) {
switch (state) {
case ProcState.SLEEP:
return "Sleeping";
case ProcState.RUN:
return "Running";
case ProcState.STOP:
return "Suspended";
case ProcState.ZOMBIE:
return "Zombie";
case ProcState.IDLE:
return "Idle";
default:
return String.valueOf(state);
}
}
public static void main(String[] args)
throws SigarException {
String pid;
if (args.length == 0) {
pid = "$$"; //default to this process
}
else {
pid = args[0];
}
Sigar sigar = new Sigar();
ProcState procState = sigar.getProcState(pid);
String state;
System.out.println(procState.getName() + ": " +
getStateString(procState.getState()));
sigar.close();
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hyperic.sigar.ProcCredName;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.ProcTime;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
/**
* Show process status.
*/
public class Ps extends SigarCommandBase {
public Ps(Shell shell) {
super(shell);
}
public Ps() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getSyntaxArgs() {
return "[pid|query]";
}
public String getUsageShort() {
return "Show process status";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
long[] pids;
if (args.length == 0) {
pids = this.proxy.getProcList();
}
else {
pids = this.shell.findPids(args);
}
for (int i=0; i<pids.length; i++) {
long pid = pids[i];
try {
output(pid);
} catch (SigarException e) {
this.err.println("Exception getting process info for " +
pid + ": " + e.getMessage());
}
}
}
public static String join(List info) {
StringBuffer buf = new StringBuffer();
Iterator i = info.iterator();
boolean hasNext = i.hasNext();
while (hasNext) {
buf.append((String)i.next());
hasNext = i.hasNext();
if (hasNext)
buf.append("\t");
}
return buf.toString();
}
public static List getInfo(SigarProxy sigar, long pid)
throws SigarException {
ProcState state = sigar.getProcState(pid);
ProcTime time = null;
String unknown = "???";
List info = new ArrayList();
info.add(String.valueOf(pid));
try {
ProcCredName cred = sigar.getProcCredName(pid);
info.add(cred.getUser());
} catch (SigarException e) {
info.add(unknown);
}
try {
time = sigar.getProcTime(pid);
info.add(getStartTime(time.getStartTime()));
} catch (SigarException e) {
info.add(unknown);
}
try {
ProcMem mem = sigar.getProcMem(pid);
info.add(Sigar.formatSize(mem.getSize()));
info.add(Sigar.formatSize(mem.getRss()));
info.add(Sigar.formatSize(mem.getShare()));
} catch (SigarException e) {
info.add(unknown);
}
info.add(String.valueOf(state.getState()));
if (time != null) {
info.add(getCpuTime(time));
}
else {
info.add(unknown);
}
String name = ProcUtil.getDescription(sigar, pid);
info.add(name);
return info;
}
public void output(long pid) throws SigarException {
println(join(getInfo(this.proxy, pid)));
}
public static String getCpuTime(long total) {
long t = total / 1000;
return t/60 + ":" + t%60;
}
public static String getCpuTime(ProcTime time) {
return getCpuTime(time.getTotal());
}
private static String getStartTime(long time) {
if (time == 0) {
return "00:00";
}
long timeNow = System.currentTimeMillis();
String fmt = "MMMd";
if ((timeNow - time) < ((60*60*24) * 1000)) {
fmt = "HH:mm";
}
return new SimpleDateFormat(fmt).format(new Date(time));
}
public static void main(String[] args) throws Exception {
new Ps().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.ArrayList;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetRoute;
import org.hyperic.sigar.SigarException;
public class Route extends SigarCommandBase {
private static final String OUTPUT_FORMAT =
"%-15s %-15s %-15s %-5s %-6s %-3s %-s";
//like route -n
private static final String[] HEADER = new String[] {
"Destination",
"Gateway",
"Genmask",
"Flags",
"Metric",
"Ref",
"Iface"
};
public Route(Shell shell) {
super(shell);
setOutputFormat(OUTPUT_FORMAT);
}
public Route() {
super();
setOutputFormat(OUTPUT_FORMAT);
}
private static String flags(long flags) {
StringBuffer sb = new StringBuffer();
if ((flags & NetFlags.RTF_UP) != 0) {
sb.append('U');
}
if ((flags & NetFlags.RTF_GATEWAY) != 0) {
sb.append('G');
}
return sb.toString();
}
public String getUsageShort() {
return "Kernel IP routing table";
}
//netstat -r
public void output(String[] args) throws SigarException {
NetRoute[] routes = this.sigar.getNetRouteList();
printf(HEADER);
for (int i=0; i<routes.length; i++) {
NetRoute route = routes[i];
ArrayList items = new ArrayList();
items.add(route.getDestination());
items.add(route.getGateway());
items.add(route.getMask());
items.add(flags(route.getFlags()));
items.add(String.valueOf(route.getMetric()));
items.add(String.valueOf(route.getRefcnt()));
items.add(route.getIfname());
printf(items);
}
}
public static void main(String[] args) throws Exception {
new Route().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2010 VMware, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarLoader;
public class Runner {
private static HashMap wantedJars = new HashMap();
private static final String JAR_EXT = ".jar";
static {
wantedJars.put("junit", Boolean.FALSE);
wantedJars.put("log4j", Boolean.FALSE);
}
private static void printMissingJars() {
for (Iterator it = wantedJars.entrySet().iterator();
it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
String jar = (String)entry.getKey();
if (wantedJars.get(jar) == Boolean.FALSE) {
System.out.println("Unable to locate: " + jar + JAR_EXT);
}
}
}
private static boolean missingJars() {
for (Iterator it = wantedJars.entrySet().iterator();
it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
String jar = (String)entry.getKey();
if (wantedJars.get(jar) == Boolean.FALSE) {
return true;
}
}
return false;
}
public static URL[] getLibJars(String dir) throws Exception {
File[] jars = new File(dir).listFiles(new FileFilter() {
public boolean accept(File file) {
String name = file.getName();
int jarIx = name.indexOf(JAR_EXT);
if (jarIx == -1) {
return false;
}
int ix = name.indexOf('-');
if (ix != -1) {
name = name.substring(0, ix); //versioned .jar
}
else {
name = name.substring(0, jarIx);
}
if (wantedJars.get(name) != null) {
wantedJars.put(name, Boolean.TRUE);
return true;
}
else {
return false;
}
}
});
if (jars == null) {
return new URL[0];
}
URL[] urls = new URL[jars.length];
for (int i=0; i<jars.length; i++) {
URL url =
new URL("jar", null,
"file:" + jars[i].getAbsolutePath() + "!/");
urls[i] = url;
}
return urls;
}
private static void addURLs(URL[] jars) throws Exception {
URLClassLoader loader =
(URLClassLoader)Thread.currentThread().getContextClassLoader();
//bypass protected access.
Method addURL =
URLClassLoader.class.getDeclaredMethod("addURL",
new Class[] {
URL.class
});
addURL.setAccessible(true); //pound sand.
for (int i=0; i<jars.length; i++) {
addURL.invoke(loader, new Object[] { jars[i] });
}
}
private static boolean addJarDir(String dir) throws Exception {
URL[] jars = getLibJars(dir);
addURLs(jars);
return !missingJars();
}
private static String getenv(String key) {
try {
return System.getenv("ANT_HOME"); //check for junit.jar
} catch (Error e) {
/*1.4*/
Sigar sigar = new Sigar();
try {
return sigar.getProcEnv("$$", "ANT_HOME");
} catch (Exception se) {
return null;
}
finally { sigar.close(); }
}
}
public static void main(String[] args) throws Exception {
if (args.length < 1) {
args = new String[] { "Shell" };
}
else {
//e.g. convert
// "ifconfig", "eth0"
// to:
// "Shell", "ifconfig", "eth0"
if (Character.isLowerCase(args[0].charAt(0))) {
String[] nargs = new String[args.length + 1];
System.arraycopy(args, 0, nargs, 1, args.length);
nargs[0] = "Shell";
args = nargs;
}
}
String name = args[0];
String[] pargs = new String[args.length - 1];
System.arraycopy(args, 1, pargs, 0, args.length-1);
String sigarLib = SigarLoader.getLocation();
String[] dirs = { sigarLib, "lib", "." };
for (int i=0; i<dirs.length; i++) {
if (addJarDir(dirs[i])) {
break;
}
}
if (missingJars()) {
File[] subdirs = new File(".").listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
for (int i=0; i<subdirs.length; i++) {
File lib = new File(subdirs[i], "lib");
if (lib.exists()) {
if (addJarDir(lib.getAbsolutePath())) {
break;
}
}
}
if (missingJars()) {
String home = getenv("ANT_HOME"); //check for junit.jar
if (home != null) {
addJarDir(home + "/lib");
}
}
}
Class cmd = null;
String[] packages = {
"org.hyperic.sigar.cmd.",
"org.hyperic.sigar.test.",
"org.hyperic.sigar.",
"org.hyperic.sigar.win32.",
"org.hyperic.sigar.jmx.",
};
for (int i=0; i<packages.length; i++) {
try {
cmd = Class.forName(packages[i] + name);
break;
} catch (ClassNotFoundException e) {}
}
if (cmd == null) {
System.out.println("Unknown command: " + args[0]);
return;
}
Method main = cmd.getMethod("main",
new Class[] {
String[].class
});
try {
main.invoke(null, new Object[] { pargs });
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof NoClassDefFoundError) {
System.out.println("Class Not Found: " +
t.getMessage());
printMissingJars();
}
else {
t.printStackTrace();
}
}
}
}
package com.x.program.center.test.examples;
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
import java.util.Arrays;
import java.util.List;
import org.hyperic.sigar.win32.Service;
import org.hyperic.sigar.win32.Win32Exception;
/*
Example to show the status of a Windows services.
Compile the example:
% javac -classpath sigar-bin/lib/sigar.jar ServiceStatus.java
Status of all services:
% java -classpath sigar-bin/lib/sigar.jar:. ServiceStatus
Alerter: Stopped
ALG: Running
Apache Tomcat 4.1: Stopped
Apache2: Running
...
Status of a specific service:
% java -classpath sigar-bin/lib/sigar.jar:. ServiceStatus Eventlog
Eventlog: Running
See also: examples/Win32Service.java
*/
public class ServiceStatus {
private static void printStatus(String name)
throws Win32Exception {
Service service = new Service(name);
System.out.println(name + ": " +
service.getStatusString());
service.close();
}
public static void main(String[] args)
throws Exception {
List services;
String name;
if (args.length == 0) {
services = Service.getServiceNames();
}
else {
services = Arrays.asList(args);
}
for (int i=0; i<services.size(); i++) {
printStatus((String)services.get(i));
}
}
}
/*
* Copyright (c) 2006-2008 Hyperic, Inc.
* Copyright (c) 2010 VMware, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.SigarPermissionDeniedException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
import org.hyperic.sigar.ptql.ProcessFinder;
import org.hyperic.sigar.shell.ShellBase;
import org.hyperic.sigar.shell.ShellCommandExecException;
import org.hyperic.sigar.shell.ShellCommandHandler;
import org.hyperic.sigar.shell.ShellCommandInitException;
import org.hyperic.sigar.shell.ShellCommandUsageException;
import org.hyperic.sigar.util.Getline;
/**
* The Sigar Shell provides a command shell for running the example
* commands and Sigar tests.
*/
public class Shell extends ShellBase {
public static final String RCFILE_NAME = ".sigar_shellrc";
private static final String CLEAR_SCREEN = "\033[2J";
private Sigar sigar = new Sigar();
private SigarProxy proxy = SigarProxyCache.newInstance(this.sigar);
private long[] foundPids = new long[0];
private boolean isInteractive = false;
public Shell() {
}
public static void clearScreen() {
System.out.print(CLEAR_SCREEN);
}
public SigarProxy getSigarProxy() {
return this.proxy;
}
public Sigar getSigar() {
return this.sigar;
}
public boolean isInteractive() {
return this.isInteractive;
}
public void setInteractive(boolean value) {
this.isInteractive = value;
}
public void registerCommands() throws ShellCommandInitException {
registerCommandHandler("df", new Df(this));
registerCommandHandler("du", new Du(this));
registerCommandHandler("ls", new Ls(this));
registerCommandHandler("iostat", new Iostat(this));
registerCommandHandler("free", new Free(this));
registerCommandHandler("pargs", new ShowArgs(this));
registerCommandHandler("penv", new ShowEnv(this));
registerCommandHandler("pfile", new ProcFileInfo(this));
registerCommandHandler("pmodules", new ProcModuleInfo(this));
registerCommandHandler("pinfo", new ProcInfo(this));
registerCommandHandler("cpuinfo", new CpuInfo(this));
registerCommandHandler("ifconfig", new Ifconfig(this));
registerCommandHandler("uptime", new Uptime(this));
registerCommandHandler("ps", new Ps(this));
registerCommandHandler("pidof", new Pidof(this));
registerCommandHandler("kill", new Kill(this));
registerCommandHandler("netstat", new Netstat(this));
registerCommandHandler("netinfo", new NetInfo(this));
registerCommandHandler("nfsstat", new Nfsstat(this));
registerCommandHandler("route", new Route(this));
registerCommandHandler("version", new Version(this));
registerCommandHandler("mps", new MultiPs(this));
registerCommandHandler("sysinfo", new SysInfo(this));
registerCommandHandler("time", new Time(this));
registerCommandHandler("ulimit", new Ulimit(this));
registerCommandHandler("who", new Who(this));
if (SigarLoader.IS_WIN32) {
registerCommandHandler("service", new Win32Service(this));
registerCommandHandler("fversion", new FileVersionInfo(this));
}
try {
//requires junit.jar
registerCommandHandler("test", "org.hyperic.sigar.test.SigarTestRunner");
} catch (NoClassDefFoundError e) { }
catch (Exception e) { }
}
private void registerCommandHandler(String name, String className) throws Exception {
Class cls = Class.forName(className);
Constructor con = cls.getConstructor(new Class[] { this.getClass() });
registerCommandHandler(name, (ShellCommandHandler)con.newInstance(new Object[] { this }));
}
public void processCommand(ShellCommandHandler handler, String args[])
throws ShellCommandUsageException, ShellCommandExecException
{
try {
super.processCommand(handler, args);
if (handler instanceof SigarCommandBase) {
((SigarCommandBase)handler).flush();
}
} finally {
SigarProxyCache.clear(this.proxy);
}
}
public static long[] getPids(SigarProxy sigar, String[] args)
throws SigarException {
long[] pids;
switch (args.length) {
case 0:
pids = new long[] { sigar.getPid() };
break;
case 1:
if (args[0].indexOf("=") > 0) {
pids = ProcessFinder.find(sigar, args[0]);
}
else if (args[0].equals("$$")) {
pids = new long[] { sigar.getPid() };
}
else {
pids = new long[] {
Long.parseLong(args[0])
};
}
break;
default:
pids = new long[args.length];
for (int i=0; i<args.length; i++) {
pids[i] = Long.parseLong(args[i]);
}
break;
}
return pids;
}
public long[] findPids(String[] args) throws SigarException {
if ((args.length == 1) && args[0].equals("-")) {
return this.foundPids;
}
this.foundPids = getPids(this.proxy, args);
return this.foundPids;
}
public long[] findPids(String query) throws SigarException {
return findPids(new String[] { query });
}
public void readCommandFile(String dir) {
try {
File rc = new File(dir, RCFILE_NAME);
readRCFile(rc, false);
if (this.isInteractive && Getline.isTTY()) {
this.out.println("Loaded rc file: " + rc);
}
} catch (IOException e) { }
}
public String getUserDeniedMessage(long pid) {
return
SigarPermissionDeniedException.getUserDeniedMessage(this.proxy,
pid);
}
public void shutdown() {
this.sigar.close();
//cleanup for dmalloc
//using reflection incase junit.jar is not present
try {
//SigarTestCase.closeSigar();
Class.forName("org.hyperic.sigar.test.SigarTestCase").
getMethod("closeSigar", new Class[0]).invoke(null, new Object[0]);
} catch (ClassNotFoundException e) {
//SigarTestCase.java not compiled w/o junit.jar
} catch (Exception e) {
e.printStackTrace();
} catch (NoClassDefFoundError e) {
//avoiding possible Class Not Found: junit/framework/TestCase
}
super.shutdown();
}
public static void main(String[] args) {
Shell shell = new Shell();
try {
if (args.length == 0) {
shell.isInteractive = true;
}
shell.init("sigar", System.out, System.err);
shell.registerCommands();
shell.readCommandFile(System.getProperty("user.home"));
shell.readCommandFile(".");
shell.readCommandFile(SigarLoader.getLocation());
if (shell.isInteractive) {
shell.initHistory();
Getline.setCompleter(shell);
shell.run();
}
else {
shell.handleCommand(null, args);
}
} catch (Exception e) {
System.err.println("Unexpected exception: " + e);
} finally {
shell.shutdown();
}
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
/**
* Show process command line arguments.
*/
public class ShowArgs extends SigarCommandBase {
public ShowArgs(Shell shell) {
super(shell);
}
public ShowArgs() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Show process command line arguments";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
long[] pids = this.shell.findPids(args);
for (int i=0; i<pids.length; i++) {
try {
println("pid=" + pids[i]);
output(pids[i]);
} catch (SigarException e) {
println(e.getMessage());
}
println("\n------------------------\n");
}
}
public void output(long pid) throws SigarException {
String[] argv = this.proxy.getProcArgs(pid);
try {
String exe = this.proxy.getProcExe(pid).getName();
println("exe=" + exe);
} catch (SigarNotImplementedException e) {
} catch (SigarException e) {
println("exe=???");
}
try {
String cwd = this.proxy.getProcExe(pid).getCwd();
println("cwd=" + cwd);
} catch (SigarNotImplementedException e) {
} catch (SigarException e) {
println("cwd=???");
}
for (int i=0; i<argv.length; i++) {
println(" " + i + "=>" + argv[i] + "<=");
}
}
public static void main(String[] args) throws Exception {
new ShowArgs().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.Iterator;
import java.util.Map;
import org.hyperic.sigar.SigarException;
/**
* Show process environment.
*/
public class ShowEnv extends SigarCommandBase {
public ShowEnv(Shell shell) {
super(shell);
}
public ShowEnv() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Show process environment";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
long[] pids = this.shell.findPids(args);
for (int i=0; i<pids.length; i++) {
try {
println("pid=" + pids[i]);
output(pids[i]);
} catch (SigarException e) {
println(e.getMessage());
}
println("\n------------------------\n");
}
}
public void output(long pid) throws SigarException {
Map env = this.proxy.getProcEnv(pid);
for (Iterator it = env.entrySet().iterator();
it.hasNext();)
{
Map.Entry ent = (Map.Entry)it.next();
println(ent.getKey() + "=" + ent.getValue());
}
}
public static void main(String[] args) throws Exception {
new ShowEnv().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.pager.PageControl;
import org.hyperic.sigar.pager.PageFetchException;
import org.hyperic.sigar.pager.StaticPageFetcher;
import org.hyperic.sigar.shell.CollectionCompleter;
import org.hyperic.sigar.shell.ProcessQueryCompleter;
import org.hyperic.sigar.shell.ShellCommandBase;
import org.hyperic.sigar.shell.ShellCommandExecException;
import org.hyperic.sigar.shell.ShellCommandUsageException;
import org.hyperic.sigar.util.GetlineCompleter;
import org.hyperic.sigar.util.PrintfFormat;
public abstract class SigarCommandBase
extends ShellCommandBase
implements GetlineCompleter {
protected Shell shell;
protected PrintStream out = System.out;
protected PrintStream err = System.err;
protected Sigar sigar;
protected SigarProxy proxy;
protected List output = new ArrayList();
private CollectionCompleter completer;
private GetlineCompleter ptqlCompleter;
private Collection completions = new ArrayList();
private PrintfFormat formatter;
private ArrayList printfItems = new ArrayList();
public SigarCommandBase(Shell shell) {
this.shell = shell;
this.out = shell.getOutStream();
this.err = shell.getErrStream();
this.sigar = shell.getSigar();
this.proxy = shell.getSigarProxy();
//provide simple way for handlers to implement tab completion
this.completer = new CollectionCompleter(shell);
if (isPidCompleter()) {
this.ptqlCompleter = new ProcessQueryCompleter(shell);
}
}
public SigarCommandBase() {
this(new Shell());
this.shell.setPageSize(PageControl.SIZE_UNLIMITED);
}
public void setOutputFormat(String format) {
this.formatter = new PrintfFormat(format);
}
public PrintfFormat getFormatter() {
return this.formatter;
}
public String sprintf(String format, Object[] items) {
return new PrintfFormat(format).sprintf(items);
}
public void printf(String format, Object[] items) {
println(sprintf(format, items));
}
public void printf(Object[] items) {
PrintfFormat formatter = getFormatter();
if (formatter == null) {
//see flushPrintfItems
this.printfItems.add(items);
}
else {
println(formatter.sprintf(items));
}
}
public void printf(List items) {
printf((Object[])items.toArray(new Object[0]));
}
public void println(String line) {
if (this.shell.isInteractive()) {
this.output.add(line);
}
else {
this.out.println(line);
}
}
private void flushPrintfItems() {
if (this.printfItems.size() == 0) {
return;
}
//no format was specified, just line up the columns
int[] max = null;
for (Iterator it=this.printfItems.iterator();
it.hasNext();)
{
Object[] items = (Object[])it.next();
if (max == null) {
max = new int[items.length];
Arrays.fill(max, 0);
}
for (int i=0; i<items.length; i++) {
int len = items[i].toString().length();
if (len > max[i]) {
max[i] = len;
}
}
}
StringBuffer format = new StringBuffer();
for (int i=0; i<max.length; i++) {
format.append("%-" + max[i] + "s");
if (i < max.length-1) {
format.append(" ");
}
}
for (Iterator it=this.printfItems.iterator();
it.hasNext();)
{
printf(format.toString(), (Object[])it.next());
}
this.printfItems.clear();
}
public void flush() {
flushPrintfItems();
try {
this.shell.performPaging(new StaticPageFetcher(this.output));
} catch(PageFetchException e) {
this.err.println("Error paging: " + e.getMessage());
} finally {
this.output.clear();
}
}
public abstract void output(String[] args)
throws SigarException;
protected boolean validateArgs(String[] args) {
return args.length == 0;
}
public void processCommand(String[] args)
throws ShellCommandUsageException, ShellCommandExecException
{
if (!validateArgs(args)) {
throw new ShellCommandUsageException(getSyntax());
}
try {
output(args);
} catch (SigarException e) {
throw new ShellCommandExecException(e.getMessage());
}
}
public Collection getCompletions() {
return this.completions;
}
public GetlineCompleter getCompleter() {
return null;
}
public boolean isPidCompleter() {
return false;
}
public String completePid(String line) {
if ((line.length() >= 1) &&
Character.isDigit(line.charAt(0)))
{
return line;
}
return this.ptqlCompleter.complete(line);
}
public String complete(String line) {
if (isPidCompleter()) {
return completePid(line);
}
GetlineCompleter c = getCompleter();
if (c != null) {
return c.complete(line);
}
this.completer.setCollection(getCompletions());
return this.completer.complete(line);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.Arrays;
import org.hyperic.sigar.SigarException;
/**
* Display System Information
*/
public class SysInfo extends SigarCommandBase {
public SysInfo(Shell shell) {
super(shell);
}
public SysInfo() {
super();
}
public String getUsageShort() {
return "Display system information";
}
public void output(String[] args) throws SigarException {
//sigar/os info
Version.printInfo(this.out);
println("");
//uptime
new Uptime(this.shell).output(args);
println("");
//cpu info
CpuInfo cpuinfo = new CpuInfo(this.shell);
cpuinfo.displayTimes = false;
cpuinfo.output(args);
println("");
//memory info
new Free(this.shell).output(args);
println("");
println("File Systems........." +
Arrays.asList(this.sigar.getFileSystemList()));
println("");
println("Network Interfaces..." +
Arrays.asList(this.sigar.getNetInterfaceList()));
println("");
//system resource limits
println("System resource limits:");
new Ulimit(this.shell).output(args);
}
public static void main(String[] args) throws Exception {
new SysInfo().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.hyperic.sigar.FileInfo;
import org.hyperic.sigar.FileTail;
import org.hyperic.sigar.FileWatcherThread;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Display the last part of files to the standard output.
*/
public class Tail {
public boolean follow;
public int number = 10;
public List files = new ArrayList();
public void parseArgs(String args[]) throws SigarException {
for (int i=0; i<args.length; i++) {
String arg = args[i];
if (arg.charAt(0) != '-') {
this.files.add(arg);
continue;
}
arg = arg.substring(1);
if (arg.equals("f")) {
this.follow = true;
}
else if (Character.isDigit(arg.charAt(0))) {
this.number = Integer.parseInt(arg);
}
else {
throw new SigarException("Unknown argument: " + args[i]);
}
}
}
public static void main(String[] args) throws SigarException {
Sigar sigar = new Sigar();
FileWatcherThread watcherThread =
FileWatcherThread.getInstance();
watcherThread.doStart();
watcherThread.setInterval(1000);
FileTail watcher =
new FileTail(sigar) {
public void tail(FileInfo info, Reader reader) {
String line;
BufferedReader buffer =
new BufferedReader(reader);
if (getFiles().size() > 1) {
System.out.println("==> " +
info.getName() +
" <==");
}
try {
while ((line = buffer.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}
}
};
for (int i=0; i<args.length; i++) {
watcher.add(args[i]);
}
watcherThread.add(watcher);
try {
System.in.read();
} catch (IOException e) { }
watcherThread.doStop();
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.CpuTimer;
import org.hyperic.sigar.SigarException;
public class Time extends SigarCommandBase {
public Time(Shell shell) {
super(shell);
}
public Time() {
super();
}
protected boolean validateArgs(String[] args) {
return args.length >= 1;
}
public String getSyntaxArgs() {
return "[command] [...]";
}
public String getUsageShort() {
return "Time command";
}
public void output(String[] args) throws SigarException {
boolean isInteractive = this.shell.isInteractive();
//turn off paging.
this.shell.setInteractive(false);
CpuTimer cpu = new CpuTimer(this.sigar);
int num;
if (Character.isDigit(args[0].charAt(0))) {
num = Integer.parseInt(args[0]);
String[] xargs = new String[args.length-1];
System.arraycopy(args, 1, xargs, 0, xargs.length);
args = xargs;
}
else {
num = 1;
}
cpu.start();
try {
for (int i=0; i<num; i++) {
this.shell.handleCommand("time " + args[0], args);
}
} finally {
this.shell.setInteractive(isInteractive);
}
cpu.stop();
cpu.list(this.out);
}
public static void main(String[] args) throws Exception {
new Time().processCommand(args);
}
}
/*
* Copyright (c) 2006-2008 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.List;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/**
* Display system resource utilization summaries and process information.
* <p>
* This version of the top command requires a ptql query to select which
* processes to display.
*
* Example to display java processes only:<br>
* <code>% java -jar sigar-bin/lib/sigar.jar Top State.Name.eq=java</code>
*/
public class Top {
private static final int SLEEP_TIME = 1000 * 5;
private static final String HEADER =
"PID\tUSER\tSTIME\tSIZE\tRSS\tSHARE\tSTATE\tTIME\t%CPU\tCOMMAND";
private static String toString(ProcStat stat) {
return
stat.getTotal() + " processes: " +
stat.getSleeping() + " sleeping, " +
stat.getRunning() + " running, " +
stat.getZombie() + " zombie, " +
stat.getStopped() + " stopped... " + stat.getThreads() + " threads";
}
public static void main(String[] args) throws Exception {
Sigar sigarImpl = new Sigar();
SigarProxy sigar =
SigarProxyCache.newInstance(sigarImpl, SLEEP_TIME);
while (true) {
Shell.clearScreen();
System.out.println(Uptime.getInfo(sigar));
System.out.println(toString(sigar.getProcStat()));
System.out.println(sigar.getCpuPerc());
System.out.println(sigar.getMem());
System.out.println(sigar.getSwap());
System.out.println();
System.out.println(HEADER);
long[] pids = Shell.getPids(sigar, args);
for (int i=0; i<pids.length; i++) {
long pid = pids[i];
String cpuPerc = "?";
List info;
try {
info = Ps.getInfo(sigar, pid);
} catch (SigarException e) {
continue; //process may have gone away
}
try {
ProcCpu cpu = sigar.getProcCpu(pid);
cpuPerc = CpuPerc.format(cpu.getPercent());
} catch (SigarException e) {
}
info.add(info.size()-1, cpuPerc);
System.out.println(Ps.join(info));
}
Thread.sleep(SLEEP_TIME);
SigarProxyCache.clear(sigar);
}
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import org.hyperic.sigar.ResourceLimit;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.jmx.SigarInvokerJMX;
/**
* Display system resource limits.
*/
public class Ulimit extends SigarCommandBase {
private SigarInvokerJMX invoker;
private String mode;
public Ulimit(Shell shell) {
super(shell);
}
public Ulimit() {
super();
}
public String getUsageShort() {
return "Display system resource limits";
}
protected boolean validateArgs(String[] args) {
return true;
}
private static String format(long val) {
if (val == ResourceLimit.INFINITY()) {
return "unlimited";
}
else {
return String.valueOf(val);
}
}
private String getValue(String attr)
throws SigarException {
Long val = (Long)this.invoker.invoke(attr + this.mode);
return format(val.longValue());
}
public void output(String[] args) throws SigarException {
this.mode = "Cur";
this.invoker =
SigarInvokerJMX.getInstance(this.proxy, "Type=ResourceLimit");
for (int i=0; i<args.length; i++) {
String arg = args[i];
if (arg.equals("-H")) {
this.mode = "Max";
}
else if (arg.equals("-S")) {
this.mode = "Cur";
}
else {
throw new SigarException("Unknown argument: " + arg);
}
}
println("core file size......." + getValue("Core"));
println("data seg size........" + getValue("Data"));
println("file size............" + getValue("FileSize"));
println("pipe size............" + getValue("PipeSize"));
println("max memory size......" + getValue("Memory"));
println("open files..........." + getValue("OpenFiles"));
println("stack size..........." + getValue("Stack"));
println("cpu time............." + getValue("Cpu"));
println("max user processes..." + getValue("Processes"));
println("virtual memory......." + getValue("VirtualMemory"));
}
public static void main(String[] args) throws Exception {
new Ulimit().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.util.PrintfFormat;
/**
* Display how long the system has been running and the current load averages.
*/
public class Uptime extends SigarCommandBase {
private static Object[] loadAvg = new Object[3];
private static PrintfFormat formatter =
new PrintfFormat("%.2f, %.2f, %.2f");
public Uptime(Shell shell) {
super(shell);
}
public Uptime() {
super();
}
public String getUsageShort() {
return "Display how long the system has been running";
}
public void output(String[] args) throws SigarException {
System.out.println(getInfo(this.sigar));
}
public static String getInfo(SigarProxy sigar) throws SigarException {
double uptime = sigar.getUptime().getUptime();
String loadAverage;
try {
double[] avg = sigar.getLoadAverage();
loadAvg[0] = new Double(avg[0]);
loadAvg[1] = new Double(avg[1]);
loadAvg[2] = new Double(avg[2]);
loadAverage = "load average: " +
formatter.sprintf(loadAvg);
} catch (SigarNotImplementedException e) {
loadAverage = "(load average unknown)";
}
return
" " + getCurrentTime() +
" up " + formatUptime(uptime) +
", " + loadAverage;
}
private static String formatUptime(double uptime) {
String retval = "";
int days = (int)uptime / (60*60*24);
int minutes, hours;
if (days != 0) {
retval += days + " " + ((days > 1) ? "days" : "day") + ", ";
}
minutes = (int)uptime / 60;
hours = minutes / 60;
hours %= 24;
minutes %= 60;
if (hours != 0) {
retval += hours + ":" + minutes;
}
else {
retval += minutes + " min";
}
return retval;
}
private static String getCurrentTime() {
return new SimpleDateFormat("h:mm a").format(new Date());
}
//pretty close to uptime command, but we don't output number of users yet
public static void main(String[] args) throws Exception {
new Uptime().processCommand(args);
}
}
/*
* Copyright (c) 2006-2009 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.File;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.win32.LocaleInfo;
/**
* Display Sigar, java and system version information.
*/
public class Version extends SigarCommandBase {
public Version(Shell shell) {
super(shell);
}
public Version() {
super();
}
public String getUsageShort() {
return "Display sigar and system version info";
}
private static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "unknown";
}
}
private static void printNativeInfo(PrintStream os) {
String version =
"java=" + Sigar.VERSION_STRING +
", native=" + Sigar.NATIVE_VERSION_STRING;
String build =
"java=" + Sigar.BUILD_DATE +
", native=" + Sigar.NATIVE_BUILD_DATE;
String scm =
"java=" + Sigar.SCM_REVISION +
", native=" + Sigar.NATIVE_SCM_REVISION;
String archlib =
SigarLoader.getNativeLibraryName();
os.println("Sigar version......." + version);
os.println("Build date.........." + build);
os.println("SCM rev............." + scm);
String host = getHostName();
String fqdn;
Sigar sigar = new Sigar();
try {
File lib = sigar.getNativeLibrary();
if (lib != null) {
archlib = lib.getName();
}
fqdn = sigar.getFQDN();
} catch (SigarException e) {
fqdn = "unknown";
} finally {
sigar.close();
}
os.println("Archlib............." + archlib);
os.println("Current fqdn........" + fqdn);
if (!fqdn.equals(host)) {
os.println("Hostname............" + host);
}
if (SigarLoader.IS_WIN32) {
LocaleInfo info = new LocaleInfo();
os.println("Language............" + info);
os.println("Perflib lang id....." +
info.getPerflibLangId());
}
}
public static void printInfo(PrintStream os) {
try {
printNativeInfo(os);
} catch (UnsatisfiedLinkError e) {
os.println("*******ERROR******* " + e);
}
os.println("Current user........" +
System.getProperty("user.name"));
os.println("");
OperatingSystem sys = OperatingSystem.getInstance();
os.println("OS description......" + sys.getDescription());
os.println("OS name............." + sys.getName());
os.println("OS arch............." + sys.getArch());
os.println("OS machine.........." + sys.getMachine());
os.println("OS version.........." + sys.getVersion());
os.println("OS patch level......" + sys.getPatchLevel());
os.println("OS vendor..........." + sys.getVendor());
os.println("OS vendor version..." + sys.getVendorVersion());
if (sys.getVendorCodeName() != null) {
os.println("OS code name........" + sys.getVendorCodeName());
}
os.println("OS data model......." + sys.getDataModel());
os.println("OS cpu endian......." + sys.getCpuEndian());
os.println("Java vm version....." +
System.getProperty("java.vm.version"));
os.println("Java vm vendor......" +
System.getProperty("java.vm.vendor"));
os.println("Java home..........." +
System.getProperty("java.home"));
}
public void output(String[] args) {
printInfo(this.out);
}
public static void main(String[] args) throws Exception {
new Version().processCommand(args);
}
}
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Date;
import org.hyperic.sigar.DirStat;
import org.hyperic.sigar.FileInfo;
import org.hyperic.sigar.FileWatcher;
import org.hyperic.sigar.FileWatcherThread;
import org.hyperic.sigar.ProcFileMirror;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Watch a file or directory displaying attribute changes.
*/
public class Watch {
private static void printHeader(Sigar sigar, FileInfo info)
throws SigarException {
String file = info.getName();
FileInfo link = sigar.getLinkInfo(file);
if (link.getType() == FileInfo.TYPE_LNK) {
try {
System.out.println(file + " -> " +
new File(file).getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(link.getTypeChar() +
info.getPermissionsString() + "\t" +
info.getUid() + "\t" + info.getGid() + "\t" +
info.getSize() + "\t" +
new Date(info.getMtime()) + "\t" +
file);
if (info.getType() == FileInfo.TYPE_DIR) {
info.enableDirStat(true);
DirStat stats = sigar.getDirStat(file);
System.out.println(" Files......." + stats.getFiles());
System.out.println(" Subdirs....." + stats.getSubdirs());
System.out.println(" Symlinks...." + stats.getSymlinks());
System.out.println(" Chrdevs....." + stats.getChrdevs());
System.out.println(" Blkdevs....." + stats.getBlkdevs());
System.out.println(" Sockets....." + stats.getSockets());
System.out.println(" Total......." + stats.getTotal());
System.out.println(" Disk Usage.." + stats.getDiskUsage());
}
}
private static void add(Sigar sigar,
FileWatcher watcher,
String file,
boolean recurse)
throws SigarException {
FileInfo info = watcher.add(file);
printHeader(sigar, info);
if (!recurse) {
return;
}
if (info.getType() == FileInfo.TYPE_DIR) {
File[] dirs =
new File(info.getName()).listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() && file.canRead();
}
});
for (int i=0; i<dirs.length; i++) {
add(sigar, watcher, dirs[i].getAbsolutePath(), recurse);
}
}
}
public static void main(String[] args) throws SigarException {
boolean recurse = false;
Sigar sigar = new Sigar();
FileWatcherThread watcherThread =
FileWatcherThread.getInstance();
watcherThread.setInterval(1000);
FileWatcher watcher =
new FileWatcher(sigar) {
public void onChange(FileInfo info) {
System.out.println(info.getName() +
" Changed:\n" +
info.diff());
}
public void onNotFound(FileInfo info) {
System.out.println(info.getName() + " no longer exists");
remove(info.getName());
}
public void onException(FileInfo info, SigarException e) {
System.out.println("Error checking " + info.getName() + ":");
e.printStackTrace();
}
};
ProcFileMirror mirror =
new ProcFileMirror(sigar, "./proc");
watcher.setInterval(watcherThread.getInterval());
mirror.setInterval(watcherThread.getInterval());
mirror.setExpire(60);
for (int i=0; i<args.length; i++) {
String arg = args[i];
if (arg.startsWith("/proc/")) {
mirror.add(arg);
arg = mirror.getProcFile(arg);
add(sigar, watcher, arg, false);
}
else if (arg.equals("-r")) {
recurse = true;
}
else {
add(sigar, watcher, arg, recurse);
}
}
watcherThread.add(mirror);
watcherThread.add(watcher);
watcherThread.doStart();
System.out.println("Press any key to stop");
try {
System.in.read();
} catch (IOException e) { }
watcherThread.doStop();
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hyperic.sigar.SigarException;
public class Who extends SigarCommandBase {
public Who(Shell shell) {
super(shell);
}
public Who() {
super();
}
public String getUsageShort() {
return "Show who is logged on";
}
private String getTime(long time) {
if (time == 0) {
return "unknown";
}
String fmt = "MMM dd HH:mm";
return new SimpleDateFormat(fmt).format(new Date(time));
}
public void output(String[] args) throws SigarException {
org.hyperic.sigar.Who[] who = this.sigar.getWhoList();
for (int i=0; i<who.length; i++) {
String host = who[i].getHost();
if (host.length() != 0) {
host = "(" + host + ")";
}
printf(new String[] {
who[i].getUser(),
who[i].getDevice(),
getTime(who[i].getTime() * 1000),
host
});
}
}
public static void main(String[] args) throws Exception {
new Who().processCommand(args);
}
}
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* 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.
*/
package com.x.program.center.test.examples;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.win32.Service;
import org.hyperic.sigar.win32.Win32Exception;
public class Win32Service extends SigarCommandBase {
private static final List COMMANDS =
Arrays.asList(new String[] {
"state",
"start",
"stop",
"pause",
"resume",
"restart",
});
public Win32Service() {
super();
}
public Win32Service(Shell shell) {
super(shell);
}
public String getSyntaxArgs() {
return "[name] [action]";
}
public String getUsageShort() {
return "Windows service commands";
}
protected boolean validateArgs(String[] args) {
return (args.length == 1) || (args.length == 2);
}
public Collection getCompletions() {
try {
return Service.getServiceNames();
} catch (Win32Exception e) {
return null;
}
}
public void output(String[] args) throws SigarException {
Service service = null;
String name = args[0];
String cmd = null;
if (args.length == 2) {
cmd = args[1];
}
try {
service = new Service(name);
if ((cmd == null) || cmd.equals("state")) {
service.list(this.out);
}
else if (cmd.equals("start")) {
service.start();
}
else if (cmd.equals("stop")) {
service.stop();
}
else if (cmd.equals("pause")) {
service.pause();
}
else if (cmd.equals("resume")) {
service.resume();
}
else if (cmd.equals("delete")) {
service.delete();
}
else if (cmd.equals("restart")) {
service.stop(0);
service.start();
}
else {
println("Unsupported service command: " + args[1]);
println("Valid commands: " + COMMANDS);
}
} finally {
if (service != null) {
service.close();
}
}
}
}
package com.x.program.center.test.nlp;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.google.gson.JsonObject;
import com.x.base.core.project.bean.NameValuePair;
import com.x.base.core.project.connection.HttpConnection;
public class TestClient {
@Test
public void test() {
String url = "http://api.cuobiezi.net/spellcheck/json_check/json_phrase";
String sentence = "测试文本中国人民共和国张可诺雷非科技2018年23月35号习近平国家主席李克强总理这根邮寄达老旧烟囱已走到生命进头,中国人民解军雷落科技中国特色会社主义马少黄股票她的离去让哦们很悲伤, 客户侧中华人民共和李洪志台万第二大金融控股公司富邦金控已与腾讯谈成合作,上述保险产品将由富邦金控旗下内地子公司富邦财险开发或引进。";
sentence = "习近平离京对西班牙、阿根廷、巴拿马和葡萄牙进行国事访问 并出仙二十国集团领导人第十三次峰会";
// sentence = "华为云专业名词测试:对像存储服务是稳定、安全、高效、易用的云存储服务,具备标准Restful
// API接口,可存储任意数量和形式的非结构化数据,提供99.999999999%的数据可靠性。";
JsonObject json = new JsonObject();
json.addProperty("content", sentence);// 固定 参数
json.addProperty("username", "zhourui");// 可替换参数 --> 请注册账号后,向管理员申请权限, :-)
json.addProperty("password", "1234abcd");// 固定测试参数
json.addProperty("biz_type", "show");// 固定参数
json.addProperty("mode", "advanced");// 固定参数
// json.put("is_return_sentence",true);// 是否返回句子 , 具体说明,可以参考文档。
json.addProperty("user_channel", "api.cuobiezi.net"); // 固定参数
// json.put("check_sensitive_word",true); // 敏感词检测
List<NameValuePair> heads = new ArrayList<>();
heads.add(new NameValuePair("", ""));
System.out.println(json.toString());
String str = null;
try {
str = HttpConnection.postAsString(url, null, json.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
}
}
/**
*
*/
/**
* @author zhour
*
*/
package com.x.program.center.test.nlp;
\ No newline at end of file
package com.x.program.center.test.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
package com.x.program.center.test.quartz;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import org.junit.Test;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
public class TestClient {
@Test
public void test() throws Exception {
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
Scheduler sched = schedFact.getScheduler();
// sched.getListenerManager().addJobListener(arg0);
sched.start();
// define the job and tie it to our
JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("myJob", "group1").build();
// Trigger the job to run now, andthen every 40 seconds
Trigger trigger = newTrigger().withIdentity("myTrigger", "group2").startNow()
.withSchedule(simpleSchedule().withIntervalInSeconds(1).repeatForever()).build();
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
Thread.sleep(2000);
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册