unable to fetch process time using sigar - java

import java.io.IOException;
import org.hyperic.sigar.*;
public class SigarDemo {
public static void main(String args[]) throws SigarException, IOException
{
final Sigar sigar = new Sigar();
final long[] processes = sigar.getProcList();
ProcTime pt=new ProcTime();
for (final long processId : processes) {
ProcUtil.getDescription(sigar, processId);
pt=sigar.getProcTime(processId);
System.out.println("---"+pt.getStartTime());
}
}
I am trying to fetch process time of each process using sigar. I am getting this errors:
Exception in thread "main" java.lang.ExceptionInInitializerError
at taskmanager.SigarDemo.main(SigarDemo.java:22)
Caused by: java.security.AccessControlException: access denied ("java.util.PropertyPermission" "sigar.nativeLogging" "read")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:457)
at java.security.AccessController.checkPermission(AccessController.java:884)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1294)
at java.lang.System.getProperty(System.java:714)
at org.hyperic.sigar.Sigar.(Sigar.java:78)
I have tried policy file setting all permission. but still I am getting errors. I am using netbeans 8.0 . and I had already setting
-Djava.security.manager -Djava.security.policy=src/dir1/dir2/important.policy

I used this code to get the process times
public static void main(String args[]) {
try {
final Sigar sigar = new Sigar();
final long[] processes = sigar.getProcList();
ProcTime pt = new ProcTime();
for (final long processId : processes) {
try {
ProcUtil.getDescription(sigar, processId);
pt = sigar.getProcTime(String.valueOf(processId));
System.out.println("---" + pt.getStartTime());
} catch (SigarException e) {
System.out.println("can't accessible...");
}
}
} catch (SigarException ex) {
ex.printStackTrace();
}
}
you don't want to specify the security policy file in VM arguments to get the process times. but the thing is getProcTime() will not return process times for some process ids because of SigarPermissionDeniedException.
but you will get process time for some processes without any problem.
I got this idea from a sample demo file from bindings\java\examples folder. I posted it below with slight modification. you can compile and run it to see the result(it includes the process time also)
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.ProcCredName;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcTime;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 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()));
System.out.println("this line has executed..!!!");
} 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);
}
}

Related

Is there a way to get a list of all MIDI devices in Java?

I'm trying to get all MIDI devices in Java, which was harder than I thought...
I tried the for each() loop, but it won't work because I don't know what ArrayList I am using this method on.
Here is my code:
package com.example.cmmp.midi;
import javax.sound.midi.*;
import javax.sound.midi.spi.MidiDeviceProvider;
import java.util.*;
#SuppressWarnings("unchecked")
public class MidiDeviceReceiver {
private static MidiSystem MidiDevice;
public static Sequencer getSequencer() throws MidiUnavailableException {
return MidiSystem.getSequencer ();
}
public static List<MidiDevice> getMidiDevices(){
javax.sound.midi.MidiDeviceReceiver midiDeviceReceiver = new javax.sound.midi.MidiDeviceReceiver () {
public MidiSystem MidiDevice;
public void send(MidiMessage message, long timeStamp) {
}
//close
public void close() {
}
public MidiDevice getMidiDevice() {
MidiDeviceProvider midi = new MidiDeviceProvider () {
public MidiDevice.Info[] getDeviceInfo() {
return new MidiDevice.Info[0];
}
public MidiDevice getDevice(MidiDevice.Info info) {
try {
MidiDevice = (MidiSystem) MidiSystem.getMidiDevice ( info );
} catch (MidiUnavailableException e) {
e.printStackTrace ();
}
return (javax.sound.midi.MidiDevice) MidiDevice;
}
};
return (javax.sound.midi.MidiDevice) MidiDevice;
}
};
return (List<javax.sound.midi.MidiDevice>) MidiDevice;
}
}
Any help would be appreciated.
You can enumerate all the MidiDevices like this:
package org.example2;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
public class App2 {
public static void main(String[] args) throws MidiUnavailableException {
MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
for (MidiDevice.Info info : devices) {
try {
MidiDevice device = MidiSystem.getMidiDevice(info);
System.out.println(info.getDescription() + " " + device.toString());
} catch (MidiUnavailableException e) {
System.out.println("Device " + info.getDescription() + " is not available");
e.printStackTrace();
}
}
}
}
Of course this gives you a static list of the devices which were present when you called the function -- if someone plugs in/unplugs a device, then the list will be out of date.

javac illegal character 'ufeff'

I am having a problem with my javac program in cmd, I am running Java jdk1.8.0_152 and I am getting the following errors:
C:\[My_Path]>javac -encoding UTF-8 Main.java
Main.java:1: error: illegal character: '\ufeff'
?package tanks;
^
Main.java:1: error: class, interface, or enum expected;
package tanks;
^
2 errors
I checked the file using different software (text editors) and rewrote the document, and still got the error. I do not have a '?' in the front of the document, but javac for some reason detects it out of nowhere.
Full Document: Main.Java
package tanks;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import tanks.DataBase.Numeric.NumericDB;
import tanks.DataBase.Turrent.TurrentDB;
import tanks.DataBase.User;
import tanks.DataBase.Users;
public class Main implements Runnable {
private static Main instance;
private ServerSocket ss;
private static double version = 0.1D;
public static Lobby systemUser;
public static Vector lobbys = new Vector();
private static boolean isDebug = false;
private static ControlWindow cw;
private static boolean started = false;
public static void main(string[] paramArrayOfString) throws Exception {
cw = new ControlWindow();
cw.setVisible(true);
}
private static void disposeLobbys() {
for (int i = 0; i < lobby.size(); i++) {
Bobby localLobby = (Lobby)lobbys.elementAt(i);
state = SocketProcessor.STATE_ERROR;
try {
is.close();
os.close();
s.close();
}
catch(Exception localException) {}
}
lobbys = new Vector();
}
public static void stopServer() {
if (!started) return;
GarageDataBaseParser.save();
started = false;
NumericsDB.dispose();
Battles.dispose();
disposeBobbys();
tanks.DataBase.Battle.BonusDB.dispose();
System.gc();
cw.showMessage("Server Started", "Server RU_1 Notification");
}
public static void startServer() {
try {
started = true;
NumericDB.init();
tanks.DataBase.Colormap.ColormapDB.init();
ServerSocket localServerSocket;
if (isDebug) {
localServerSocket = new ServerSocket(2845);
} else {
localServerSocket = new ServerSocket(5482);
}
new Thread(new Main(localServerSocket)).start();
cw.showMessage("Server Started!", "Server RU_1 Notification");
} catch (Exception localExeption) { cw.showMessage(localExption.getMessage(), "Server RU_1 Notification");
}
}
public Main(ServerSocket paramServerSocket) {
instance = this;
ss = paramServerSocket;
}
public void run() {
try {
while (started) {
Socket localSocket = ss.accept();
new Thread(new Starter(localSocket)).start();
}
}
catch (Exeption localExeption1) {
cw.showMessage(localExeption1.getMessage(), "Server RU_1 Notification");
}
try {
ss.close();
}
catch (Exception localExcption2) {
cw.showMessage(localException2.getMessage(), "Server RU_1 Notification");
}
ss = null;
}
private static void disposeUsers() {}
private static void initUsers() {
UserDataBaseParser.load("ServerDataBase/Users.txt");
systemUser = new Lobby(Users.getUser(0), null, null, null);
GarageDataBaseParser.load();
}
public static void removeLobby(int paramInt) {
Lobby localLobby = (Lobby)lobbys.elementAt(paramInt);
lobbys.removeElementAt(paramInt);
localLobby = null;
}
public static void removeLobby(Lobby paramLobby) {
lobbys.removeElement(paramLobby);
paramLobby = null;
}
public static void startLobby(BattleProcessor paramBattleProcessor, User paramUsers) {
Lobby localLobby = new Lobby(paramUser, s, is, os);
lobbys.addElement(localLobby);
new Thread(localLobby).start();
}
public static void startLobby(Starter paramStarter, User paramUser) {
cwlistModel.addElement(login);
Battles.check(paramUser);
Lobby localLobby = new Lobby(paramUser, s, is, os);
lobbys.addElement(localLobby);
new Thread(localLobby).start();
paramStarter = null;
}
}

WorkStealingPool exits unexpectedly

I submitted some Runnables to an ExecutorService. Inside these Runnables, wait() and notify() are called. The code works with newFixedThreadPool as the ExecutorService. With newWorkStealingPool, the process exits unexpectedly without any error message.
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
// For regular expressions
import java.util.regex.Matcher;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.*;
import java.util.concurrent.*;
public class TestPipeline {
public static void main(String[] args) {
runAsThreads();
}
private static void runAsThreads() {
final BlockingQueue<String> urls = new OneItemQueue<String>();
final BlockingQueue<Webpage> pages = new OneItemQueue<Webpage>();
final BlockingQueue<Link> refPairs = new OneItemQueue<Link>();
final BlockingQueue<Link> uniqRefPairs = new OneItemQueue<Link>();
final ExecutorService executor = Executors.newWorkStealingPool(6);
// final ExecutorService executor = Executors.newFixedThreadPool(6);
executor.submit(new UrlProducer(urls));
executor.submit(new PageGetter(urls, pages));
executor.submit(new LinkScanner(pages,refPairs));
executor.submit(new Uniquifier<Link>(refPairs,uniqRefPairs));
executor.submit(new LinkPrinter(uniqRefPairs));
}
}
class UrlProducer implements Runnable {
private final BlockingQueue<String> output;
public UrlProducer(BlockingQueue<String> output) {
this.output = output;
}
public void run() {
System.out.println("in producer");
for (int i=0; i<urls.length; i++)
output.put(urls[i]);
}
private static final String[] urls =
{ "http://www.itu.dk", "http://www.di.ku.dk", "http://www.miele.de",
"http://www.microsoft.com", "http://www.cnn.com", "http://www.dr.dk",
"http://www.vg.no", "http://www.tv2.dk", "http://www.google.com",
"http://www.ing.dk", "http://www.dtu.dk", "http://www.bbc.co.uk"
};
}
class PageGetter implements Runnable {
private final BlockingQueue<String> input;
private final BlockingQueue<Webpage> output;
public PageGetter(BlockingQueue<String> input, BlockingQueue<Webpage> output) {
this.input = input;
this.output = output;
}
public void run() {
while (true) {
System.out.println("in pagegetter");
String url = input.take();
// System.out.println("PageGetter: " + url);
try {
String contents = getPage(url, 200);
output.put(new Webpage(url, contents));
} catch (IOException exn) { System.out.println(exn); }
}
}
public static String getPage(String url, int maxLines) throws IOException {
// This will close the streams after use (JLS 8 para 14.20.3):
try (BufferedReader in
= new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<maxLines; i++) {
String inputLine = in.readLine();
if (inputLine == null)
break;
else
sb.append(inputLine).append("\n");
}
return sb.toString();
}
}
}
class Uniquifier<T> implements Runnable{
private final Set<T> set = new HashSet<T>();
private final BlockingQueue<T> input;
private final BlockingQueue<T> output;
public Uniquifier(BlockingQueue<T> input, BlockingQueue<T> output){
this.input = input;
this.output = output;
}
public void run(){
while(true){
System.out.println("in uniquifier");
T item = input.take();
if(!set.contains(item)){
set.add(item);
output.put(item);
}
}
}
}
class LinkScanner implements Runnable {
private final BlockingQueue<Webpage> input;
private final BlockingQueue<Link> output;
public LinkScanner(BlockingQueue<Webpage> input,
BlockingQueue<Link> output) {
this.input = input;
this.output = output;
}
private final static Pattern urlPattern
= Pattern.compile("a href=\"(\\p{Graph}*)\"");
public void run() {
while (true) {
System.out.println("in link scanner");
Webpage page = input.take();
// System.out.println("LinkScanner: " + page.url);
// Extract links from the page's <a href="..."> anchors
Matcher urlMatcher = urlPattern.matcher(page.contents);
while (urlMatcher.find()) {
String link = urlMatcher.group(1);
output.put(new Link(page.url, link));
}
}
}
}
class LinkPrinter implements Runnable {
private final BlockingQueue<Link> input;
public LinkPrinter(BlockingQueue<Link> input) {
this.input = input;
}
public void run() {
while (true) {
System.out.println("in link printer");
Link link = input.take();
// System.out.println("LinkPrinter: " + link.from);
System.out.printf("%s links to %s%n", link.from, link.to);
}
}
}
class Webpage {
public final String url, contents;
public Webpage(String url, String contents) {
this.url = url;
this.contents = contents;
}
}
class Link {
public final String from, to;
public Link(String from, String to) {
this.from = from;
this.to = to;
}
// Override hashCode and equals so can be used in HashSet<Link>
public int hashCode() {
return (from == null ? 0 : from.hashCode()) * 37
+ (to == null ? 0 : to.hashCode());
}
public boolean equals(Object obj) {
Link that = obj instanceof Link ? (Link)obj : null;
return that != null
&& (from == null ? that.from == null : from.equals(that.from))
&& (to == null ? that.to == null : to.equals(that.to));
}
}
// Different from java.util.concurrent.BlockingQueue: Allows null
// items, and methods do not throw InterruptedException.
interface BlockingQueue<T> {
void put(T item);
T take();
}
class OneItemQueue<T> implements BlockingQueue<T> {
private T item;
private boolean full = false;
public void put(T item) {
synchronized (this) {
while (full) {
try { this.wait(); }
catch (InterruptedException exn) { }
}
full = true;
this.item = item;
this.notifyAll();
}
}
public T take() {
synchronized (this) {
while (!full) {
try { this.wait(); }
catch (InterruptedException exn) { }
}
full = false;
this.notifyAll();
return item;
}
}
}
Because the Pool is allocating threads dynamically, there are no threads alive after runAsThreads exits because that's the end of the main thread. There needs to be at least on thread running to keep the application alive. Adding a call to awaitTermination is needed. It's not needed for the fixed pool because that will always have active threads until it is explicitly shut down as noted in the JavaDocs.

Java Thread Don't kill other Threads and wont remove from vector item

I have Vector of threads, and i wanna check all items in this vector. Everyone item is connection of user to server. I wanna "clean" all dead connections.
I can't find where I'm wrong.
Here is it my code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import server.ServerCore.Clients;
/**
*
* #author pisio
*/
public class GrimReaper extends Thread {
private int timeout = LoadSettings.Init().getConfigInt("grimreaper") * 1000; // 1000 ms = 1 sec
public GrimReaper() {
super();
}
public void cleanUserThreads() {
Vector users = ServerCore.users;
if (users.size() < 1) {
return;
}
Iterator iteratr = users.iterator();
while (iteratr.hasNext()) {
Clients user = (Clients) iteratr.next();
System.out.println(user.isAlive());
if (user.getClient().isClosed()) {
user.interrupt();
if (user.isInterrupted()) {
System.out.println("Beshe kiknat");
}
iteratr.remove();
// if (PublicVaribles.Init().systemLevelMesseging() == 2) {
System.out.println("+\t Kicked user ");
// }
}//if is dead
}//while
}//cleanUserThreads;
#Override
public void run() {
try {
while (ServerCore.getServerRunning()) {
cleanUserThreads();
sleep(timeout);
System.out.println("nani na shinigami");
}
} catch (InterruptedException ex) {
Logger.getLogger(GrimReaper.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
package server;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import server.DB.DataBase;
public class ServerCore extends Thread {
private static ServerCore sc = null;
private int port = LoadSettings.Init().getConfigInt("port");
private int max_connections = LoadSettings.Init().getConfigInt("max_connections");
private String ipServer = LoadSettings.Init().getConfig("ipServer");
private ServerSocket socket;
private static boolean serverRuning = false;
public static Vector users = new Vector();
public GrimReaper shinigami = new GrimReaper();// Shinigami from Japanice is Grim Reaper!
private ServerCore() {
}
#Override
public void run() {
shinigami.start();
try {
socket = new ServerSocket(port, max_connections);
System.out.println("+++\t Server was started at address:" + socket.getLocalSocketAddress() + " with posible max users " + max_connections);
serverRuning = true;
while (serverRuning) {
Socket client = socket.accept();
shinigami.cleanUserThreads();
if (users.size() < max_connections) {
Clients cls = new Clients(client);
cls.start();
users.add(cls);
System.out.println("++\tClient was connected:" + client.toString());
} else {
Clients cls = new Clients(client);
cls.start();
cls.getOutput().println("sorry_no_avable_slot");
cls.getOutput().flush();
cls.interrupt();
}
}
} catch (IOException ex) {
// Logger.getLogger(ServerCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
//run method
public void sendUserMsg() {
Scanner input = PublicVaribles.Init().inputKeyBord();
System.out.print("Enter UserID/user connection port:");
int userID = input.nextInt();
Iterator iterator = users.iterator();
while (iterator.hasNext()) {
Clients cls = (Clients) iterator.next();
/// System.out.println("Passed user:" + cls.getUserId());
if (cls.getUserId() == userID) {
System.out.print("\nEnter msg:");
String str = input.next();
cls.getOutput().println(str);
System.out.println("+\t" + cls.getUserId() + " get msg :" + str);
}
}
}
//SendUserMsg
public void stopServer() {
statusServer();
serverRuning = false;
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ServerCore.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("+++\t SERVER WAS STOPED !");
}
//Stop server
public void statusServer() {
if (serverRuning) {
System.out.println("+++\t Server running at port:" + port + " with connected users :" + users.size() + "/" + max_connections);
} else {
System.out.println("+++\t Server IS NOT RUNNING!");
}
}
//Status server
public static boolean getServerRunning() {
// function for GrimReaper .... R.I.P :D
return ServerCore.serverRuning;
}
public static ServerCore Init() {
if (ServerCore.sc == null) {
ServerCore.sc = new ServerCore();
}
return ServerCore.sc;
}
// SingleTon
public class Clients extends Thread {
private Socket client;
private int userID;
private Scanner input;
private PrintWriter output;
public Clients(Socket socket) {
client = socket;
userID = socket.getPort();
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
} catch (IOException ioEx) {
System.out.println(ioEx.toString());
}
}
public int getUserId() {
return userID;
}
public Scanner getInput() {
return input;
}
public PrintWriter getOutput() {
return output;
}
public Socket getClient() {
return client;
}
}//Clients Class
}
Note: I'm assuming Clients extends Thread.
It looks like you might be using interrupt() incorrectly. After calling user.interrupt(), it's up to that thread to check that it has been interrupted by calling Thread.interrupted() and terminate itself if true. Here's an extremely basic example:
class Clients extends Thread {
#Override
public void run() {
while (!Thread.interrupted()) {
//do work
}
//thread has been interrupted and quits
}
}

RExecClient apache InputStream not available

I want to run a command on a remote machine using the RExecClient Apache Commons-Net class.
My code is:
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.bsd.RExecClient;
public class TestRlogin {
static final int PORT_NUMBER = 512;
private RExecClient client;
private final String url = "test.corp";
private final String login = "bob";
private final String password = "bob";
public TestRlogin() {
client = new RExecClient();
}
public String run(String cmd) throws IOException {
String res = null;
InputStream is = null;
if (client != null) {
try {
if (!client.isConnected()) {
client.connect(url, PORT_NUMBER);
}
client.rexec(login, password, cmd);
is = client.getInputStream();
if (is != null && is.available() > 0) {
res = IOUtils.toString(is);
} else {
System.err.println("InputStream is not available!");
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(is);
client.disconnect();
}
} else {
System.err.println("The RLogin client is not connected to "+url);
}
return res;
}
public void main(String[] args) {
TestRlogin trl = new TestRlogin();
try {
System.out.println(trl.run("ls -lrt /tmp;"));
System.out.println(trl.run("tar -xf /tmp/archive.tar;"));
System.out.println(trl.run("ls -lrt /tmp;"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
The ls command works fine but the tar command does not extract the archive and returns nothing. The message I get is InputStream is not available!.
I checked twice the tar archive exists on the server. When I rlogin manually and run the command, nothing is returned but the tar archive is extracted.
I am out of ideas.
I finally solved this problem. It is not necessary to specify the port when connecting.
Also, if you are logged as root, check the $HOME/.rhosts file. When logged as non root, configure both $HOME/.rhosts and /etc/hosts.equiv.
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.bsd.RExecClient;
public class TestRlogin {
private RExecClient client;
private final String url = "test.corp";
private final String login = "bob";
private final String password = "bob";
public TestRlogin() {
client = new RExecClient();
}
public String run(String cmd) throws IOException {
String res = null;
InputStream is = null;
if (client != null) {
try {
if (!client.isConnected()) {
client.connect(url);
}
client.rexec(login, password, cmd);
is = client.getInputStream();
if (is != null && is.available() > 0) {
res = IOUtils.toString(is);
} else {
System.err.println("InputStream is not available!");
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(is);
client.disconnect();
}
} else {
System.err.println("The RLogin client is not connected to "+url);
}
return res;
}
public void main(String[] args) {
TestRlogin trl = new TestRlogin();
try {
System.out.println(trl.run("ls -lrt /tmp;"));
System.out.println(trl.run("tar -xf /tmp/archive.tar;"));
System.out.println(trl.run("ls -lrt /tmp;"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I still have a question. How to check the command terminated correctly (I posted the question here)? Maybe it is possible to use the method addProtocolCommandListener from the SocketClient class. I saw there is a protected method fireReplyReceived.
Thanks for the help.

Categories