Java command to show the processus - java

hi i want to show the jboss 7 as process information and the database sessions information in java code...
i try this code:
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
and this code:
Process p = Runtime.getRuntime().exec
("C:\\Users\\user\\Downloads\\PSTools\\pslist.exe -s 2");
and it works good but it works only on windows operating system .
so i want to a java code which work on each operating system, and not only on windows or linux ...
can u help me please?
thanks for everybody.

Finding java processes on the same host is fairly straight forward (some caveats listed later). Connecting to their JMX interfaces is also achievable. As far as tracking database sessions, you can conceptually acquire any data you want, as long as it is published through an accessible MBean.
The process requires using the Java Attach API. Here's a simple example where I will list all the JVM's running on my host, attempt to attach to them and list their heap usage.
First off, here's the imports:
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.util.List;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
The com.sun.tools.attach classes are in your JVM's tools.jar. Here's the code:
public class AttachAPIExample {
/**
* Uses the attach API to locate all JVMs accessible on this machine.
* #param args None
*/
public static void main(String[] args) {
// Get my PID
final String MYPID = ManagementFactory.getRuntimeMXBean().getName().split("#")[0];
log("Scanning for JVMs...");
// List all the Virtual Machine Descriptors
List<VirtualMachineDescriptor> descriptors = VirtualMachine.list();
for(VirtualMachineDescriptor vmd: descriptors) {
VirtualMachine vm = null;
// Do this in a catch block in case we run into a JVM that is not the same "bit" as we are
try {
vm = vmd.provider().attachVirtualMachine(vmd.id());
String display = vmd.displayName().trim().isEmpty() ? "Unknown" : vmd.displayName();
log("JVM%sPID: %s Display: %s", vmd.id().equals(MYPID) ? " (Me) " : " ", vmd.id(), display);
String connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress", null);
if(connectorAddress!=null) {
log("\tConnector Found Installed at [%s]", connectorAddress);
} else {
String javaHome = vm.getSystemProperties().getProperty("java.home");
File agentJarFile = new File(javaHome + File.separator + "lib" + File.separator + "management-agent.jar");
if(agentJarFile.exists()) {
log("I think we can find this JVM's management agent here: [%s]", agentJarFile.toString());
vm.loadAgent(agentJarFile.getAbsolutePath());
connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress", null);
log("\tConnector Installed at [%s]", connectorAddress);
} else {
log("Cannot find the agent jar for JVM [%s] at [%s]", vmd.id(), javaHome);
}
}
// Now lets try and connect and read some MBean values
if(connectorAddress!=null) {
log("Attaching to JVM [%s]...", vmd.id());
JMXServiceURL jmxUrl = new JMXServiceURL(connectorAddress);
JMXConnector connector = null;
try {
connector = JMXConnectorFactory.connect(jmxUrl);
MBeanServerConnection conn = connector.getMBeanServerConnection();
MemoryUsage heap = MemoryUsage.from((CompositeData)conn.getAttribute(new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME), "HeapMemoryUsage"));
log("Heap Usage: %s", heap);
} finally {
if(connector!=null) {
try { connector.close(); } catch (Exception ex) {/* No Op */}
}
}
}
} catch (Exception ex) {
/* No Op */
} finally {
if(vm!=null) try { vm.detach(); } catch (Exception ex) {/* No Op */}
log("======================================");
}
}
}
public static void log(String fmt, Object...args) {
System.out.println(String.format(fmt, args));
}
}
And here's some sample output:
Scanning for JVMs...
JVM PID: 27928 Display: sun.tools.jconsole.JConsole
Connector Found Installed at [service:jmx:rmi://127.0.0.1/stub/rO0ABXNyAC5qYXZheC5tYW5hZ2VtZW50LnJlbW90ZS5ybWkuUk1JU2VydmVySW1wbF9TdHViAAAAAAAAAAICAAB4cgAaamF2YS5ybWkuc2VydmVyLlJlbW90ZVN0dWLp/tzJi+FlGgIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHc3AAtVbmljYXN0UmVmMgAADDEwLjEyLjExNC4zNwAA9bhcC21U1Z9PMPLlR/0AAAFAxsF5moACAHg=]
Attaching to JVM [27928]...
Heap Usage: init = 8388608(8192K) used = 40242696(39299K) committed = 44236800(43200K) max = 5726666752(5592448K)
======================================
JVM PID: 25028 Display: org.jboss.Main -c ecseu -b 0.0.0.0
I think we can find this JVM's management agent here: [c:\java\jdk1.6.0_30\jre\lib\management-agent.jar]
Connector Installed at [service:jmx:rmi://127.0.0.1/stub/rO0ABXNyAC5qYXZheC5tYW5hZ2VtZW50LnJlbW90ZS5ybWkuUk1JU2VydmVySW1wbF9TdHViAAAAAAAAAAICAAB4cgAaamF2YS5ybWkuc2VydmVyLlJlbW90ZVN0dWLp/tzJi+FlGgIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHc4AAtVbmljYXN0UmVmMgAADVBQLVdLLU5XSEktMDEAAPjJTzYbxtjrUKazaPTEAAABQMuKX+6ABAB4]
Attaching to JVM [25028]...
Heap Usage: init = 1073741824(1048576K) used = 173876432(169801K) committed = 982581248(959552K) max = 982581248(959552K)
======================================
Caveats
JMVs can only attach to like bit JVMs (i.e. 32bit to 32bit, 64bit to 64bit)
The OS user launching the attach must have the OS authorization to access other processed. So same user, no problem. Other user... you should be root.
The attach api has mixed results when used across different JVM vendor implementations. ie. if it's Sun/Oracle/OpenJDK, you're probably good. If it's those, and you're trying to connect to an IBM JVM (or vice-versa) then I have no idea what will happen, although JRockit seems to be fairly friendly in this regard.
I don't know all the caveats.

Related

PHP - Serial Port (com port) access denied in WAMP server (Windows)

I have been trying to write a PHP script to send SMS messages via a GSM modem connected to the server machine.
Below is the aforesaid PHP script.
<?php
$device = "COM7";
exec("mode $device BAUD=9600 PARITY=n DATA=8");
$comport = fopen($device, "w");
fputs($comport,"AT+CMGF=1\n\r");
fputs($comport,"AT+cmgs=\"xxxxxxxxxx\"\n\r");
fputs($comport,"sms text\n\r");
fputs($comport,chr(26));
fclose($comport);
echo "done";
?>
When I try to run the above code I get the following error;
Warning: fopen(COM7): failed to open stream: Permission denied in
E:\wamp\www\sms\index.php on line 4
and
Warning: fclose() expects parameter 1 to be resource, boolean given in
E:\wamp\www\sms\index.php on line 9
I have tried changing the user permission in windows to allow WAMP server full access, which WAMP server already had by default.
As a workaround I have tried using the DIO extension which gave a similar error when trying to open a port. DIO also gave an permission denied error.
It was suggested here in stackoverflow to use the physical address of the GSM modem instead of "COM7", I tried it didn't work. Another answer had suggested to add the www-data to the dialout group, but that solution was for Linux.
I tried writing a Java servlet as a workaround for this issue. The Java program runs as a stand alone file, but when its run as a servlet via Tomcat, it again gives an "Access Violation" error. I used RXTX library for the Java servlet.
So I am guessing this error is caused by lack of permission assigned to whoever is trying to access the com port via the server. (I get "SYSTEM" when I ran echo get_current_user(); from the above PHP script)
I am trying to find the root cause of this error. Your help is much appreciated.
Below is the Java SMS sender class which uses the RXTX Library.
import java.io.*;
import java.util.*;
import gnu.io.*;
public class SMSsender {
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString1 = "AT";
static String messageString3 = "AT+CMGF=1";
static String messageString4 = "AT+CMGS=\"+xxxxxxxxxx\"";
static String messageString5 = "TESTY2";
static SerialPort serialPort;
static OutputStream outputStream;
static InputStream inputStream;
static char enter = 13;
static char CTRLZ = 26;
public void sendMessage(String[] args) throws InterruptedException {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM7")) {
try {
serialPort = (SerialPort) portId.open("COM7", 2000);
} catch (PortInUseException e) {
System.out.println("err");
}
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
outputStream.write((messageString1 + enter).getBytes());
Thread.sleep(100);
outputStream.flush();
// outputStream.write((messageString2 + enter).getBytes());
Thread.sleep(100);
outputStream.flush();
outputStream.write((messageString3 + enter).getBytes());
Thread.sleep(100);
outputStream.flush();
outputStream.write((messageString4 + enter).getBytes());
Thread.sleep(100);
outputStream.flush();
outputStream.write((messageString5 + CTRLZ).getBytes());
outputStream.flush();
Thread.sleep(100);
System.out.println("step 1");
Thread.sleep(3000);
outputStream.close();
serialPort.close();
System.out.println("step 2");
} catch (IOException e) {
e.printStackTrace();
serialPort.close();
} finally {
serialPort.close();
}
}
}
}
}
}
Above code works when its run outside of the server as a stand alone application.
Following is the servlet code which invokes the above class to send an SMS.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class sendSMS extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Set the response MIME type of the response message
response.setContentType("text/html");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
SMSsender obj = new SMSsender();
try {
obj.sendMessage(null);
}
catch(Exception e)
{
out.println(e.getMessage());
}
finally {
out.close(); // Always close the output writer
}
}
}
When this servlet is run through Apache Tomcat, the server automatically closes with the following error in the log.
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000001cf32174465, pid=5828, tid=2276
#
# JRE version: Java(TM) SE Runtime Environment (10.0.2+13) (build 10.0.2+13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (10.0.2+13, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)
# Problematic frame:
# C [rxtxSerial.dll+0x4465]
#
# No core dump will be written. Minidumps are not enabled by default on client versions of Windows
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
I was able to solve the issue.
Apparently, windows no longer allows to communicate with serial ports via virtual file names. In the case of PHP, I was trying to get in-touch with the com port via fopen("com7"). So this method is no longer viable it seems. This is according to David Gibson. View Source Here . I would love to read more on this if I could find the original source though.
According to David Gibson's post, PHP extensions like DIO is not very stable in the Windows environment. So I stopped trying to find a solution to my PHP code.
Now to the Java workaround
Earlier I was trying to use the RXTX java library. Although the code worked as a standalone application, it failed with an "Access Violation" error when run via tomcat.
I wonder if RXTX is still in active development.
Anyhow I tired out the platform independent solution jSerialComm. Pretty amazing, it doesn't require any DLLs or any other native libraries.
I was finally able to send a SMS via a servlet thanks to this awesome, easy to use library. I have posted my working Java code below for your reference.
I hope this will help someone who is facing the same problem! Cheers!
And thanks to Mehdi, Erwin and Sanguinary for the guidance given with regards to using this amazing Stackoverflow platform and of course to the developers!
Note: This code below is messy and not optimised. This code is for reference only.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import java.io.InputStream;
import java.util.Scanner;
import com.fazecast.jSerialComm.*;
public class sendSMS extends HttpServlet {
SerialPort ubxPort;
static String messageString1 = "AT";
static String messageString2 = "AT+CMGF=1";
static String messageString3 = "AT+CMGS=\"+xxxxxxxxxx\"";
static String messageString4 = "TESTY2";
static char enter = 13;
static char CTRLZ = 26;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response MIME type of the response message
response.setContentType("text/html");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
try {
ubxPort = SerialPort.getCommPort("com7");
boolean openedSuccessfully = ubxPort.openPort();
out.println("h1<br>");
if(openedSuccessfully)
{
out.println("Port Opened<br>");
byte[] buffer = (messageString1 + enter).getBytes();
ubxPort.writeBytes(buffer, buffer.length);
out.println("1 sent<br>");
InputStream in = ubxPort.getInputStream();
try
{
for (int j = 0; j < 1000; ++j)
System.out.print((char)in.read());
in.close();
} catch (Exception e) { e.printStackTrace(); }
buffer = (messageString2 + enter).getBytes();
ubxPort.writeBytes(buffer, buffer.length);
out.println("2 sent<br>");
try
{
for (int j = 0; j < 1000; ++j)
System.out.print((char)in.read());
in.close();
} catch (Exception e) { e.printStackTrace(); }
buffer = (messageString3 + enter).getBytes();
ubxPort.writeBytes(buffer, buffer.length);
out.println("3 sent<br>");
try
{
for (int j = 0; j < 1000; ++j)
System.out.print((char)in.read());
in.close();
} catch (Exception e) { e.printStackTrace(); }
buffer = (messageString4 + CTRLZ).getBytes();
ubxPort.writeBytes(buffer, buffer.length);
out.println("4 sent<br>");
try
{
for (int j = 0; j < 1000; ++j)
System.out.print((char)in.read());
in.close();
} catch (Exception e) { e.printStackTrace(); }
}
}
catch(Exception e)
{
out.println("here3");
out.println(e.getMessage());
}
finally {
ubxPort.closePort();
out.println("here4");
out.close(); // Always close the output writer
}
}
}

Java Runtime not capturing STDOUT on Mac

Mac OS here, but looking for a solution that is platform agnostic. Also please note, even though Consul is mentioned here, it is just arbitrary and the solution should have nothing to do with, nor require knowledge of, Consul.
When I open a shell and run consul -v (to determine if Consul is installed locally), I get the following STDOUT:
Consul v0.5.2
Consul Protocol: 2 (Understands back to: 1)
When I run the following code:
public class VerifyConsul {
public static void main(String[] args) {
PrintStream oldPS = System.out;
try {
Runtime runtime = Runtime.getRuntime();
Process proc;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream newPS = new PrintStream(baos);
System.setOut(newPS);
proc = runtime.exec(“consul -v”);
proc.waitFor();
String capturedOut = baos.toString();
if(capturedOut.isEmpty()) {
throw new IllegalArgumentException(“Consul not found.”);
}
} catch(Throwable t) {
System.out.println(t.getMessage());
System.setOut(oldPS);
}
}
}
I get the IllegalArgumentException stating that Consul [is] not found.
What is wrong with my code? Why isn’t it “hooking”/capturing STDOUT?
Use Process#getInputStream() to read STDOUT or Process#getErrorStream() to read STDERR
Here's an example (using java process and reading STDERR):
package so32589604;
import org.apache.commons.io.IOUtils;
public class App {
public static void main(String[] args) throws Exception {
final Runtime runtime = Runtime.getRuntime();
final Process proc = runtime.exec("java -version");
proc.waitFor();
// IOUtils from apache commons-io
final String capturedOut = IOUtils.toString(proc.getErrorStream());
System.out.println("output = " + capturedOut);
if(capturedOut.isEmpty()) {
throw new IllegalArgumentException("Java not found.");
}
}
}

Mismatched RXTX Versions

I found a code to communicate in Java via Serial Port to an Arduino and wanted to try and get it working in order to expand on it for a project idea, but I keep getting this error
Stable Library
=========================================
Native lib Version = RXTX-2.2-20081207 Cloudhopper Build rxtx.cloudhopper.net
Java lib Version = RXTX-2.1-7
WARNING: RXTX Version mismatch
Jar version = RXTX-2.1-7
native lib Version = RXTX-2.2-20081207 Cloudhopper Build rxtx.cloudhopper.net
Could not find COM port.
Started
I think that it means there is jar mismatch for the RXTX library, but the link to the build in the native lib is a website is no longer there. I'm not exactly sure how to fix the problem. My code is below if you believe that is the issue. Any help would be appreciated.
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.InputStream;
import java.util.Enumeration;
public class AraInterface {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM35", // Windows //shin: ardu com port here
};
private InputStream input;
private OutputStream output;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
serialPort.addEventListener((SerialPortEventListener) this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
byte chunk[] = new byte[available];
input.read(chunk, 0, available);
String temp = new String (chunk);
String ref = "Hel";
if(temp.compareTo(ref)==0){
System.out.println("Hello World request received");
}
else{
System.out.println("lala" + temp);
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
public static void main(String[] args) throws Exception {
AraInterface main = new AraInterface();
main.initialize();
System.out.println("Started");
}
}
Check if you have installed the library. If not, in case of Ubuntu,
sudo apt-get install librxtx-java
If already installed,
go to the path of the installation --- in my case /usr/share/java/RXTXcomm.jar
If you are using Ubuntu or any Linux distro, remove any downloaded rxtx library from Eclipse build path, and add the path of the installed rxtx library in step 2. You can also copy it into your project.
Check your java library property (System.getProperty("java.library.path")) to know the folder.
Copy the librxtxSerial.so to the Java library path - in my case
sudo cp -r /usr/lib/jni/librxtxSerial.so /usr/lib/x86_64-linux-gnu
After that try your code again.
For 32/64 bit processors, installing RXTX taken from jlog websites leads to
rxtx version mismatch error
The most stable rxtx java library is taken from the following RXTX for Windows page and resolves the "version mismatch error".
RXTX (download) is only for 32 bit operating systems
Here rxtx-2.1-7 bins-r2.zip (binary column) is the right one to take.
Let's hope these websites will not be taken down.
I had the same problem on the exact same code, here's what I did to make it work. I am on MacOS.
The reason is because the version of "RXTXcomm.jar" library you've installed does not match the version that is needed (I believe from Arduino). Therefore, you need to install a matching version (2.2). You can download it from here (http://rxtx.qbang.org/wiki/index.php/Download), binary "rxtx 2.2pre2 (prerelease)".
Then you want to move this new version into your Java directory, which is hidden by default, but can be open easily with Terminal (MacOS) by the following code.
cd /Library/Java/Extension
open .
Move the file into the Extension folder. (Admin password will be required)
Restart BlueJ (the Java IDE i used), compile the code, and right click on the "mouse" module -> void main (string[] args) -> "OK". It should work by now.
For the second error, "could not find COM port". You just have to make sure you type in the correct COM port in your Java code. You can find the correct COM port at the bottom right corner of the Arduino window when the device is plugged in.
You can build RXTX from Sources, e.g. GitHub-Arduino
and decide for yourself, how to deal with versions.
Binaries are here

PeerUnavailableException using JAIN SIP API on Android

I'm trying to build SIP application using JAIN SIP 1.2 and the NIST implementation on android.
I have rebuilt jain-sip-api-1.2.jar and jain-sip-ri-1.2.1111.jar from source, and renamed javax -> jain_javax and gov.nist.javax -> jain_gov.nist.jain_javax. I tested the jar files on textclient example on standard java without problem. However, when I run it on Android I still get the error:
"The Peer SIP Stack: jain_gov.nist.jain_javax.sip.SipstackImpl could not be instantiated. Ensure the Path Name has been set".
Did I miss anything here?
It is not sufficient to rename the packages. JAIN-SIP has internal references to some classes by their original package name "gov.nist". You should also double check all your code to rename any "gov.nist" references such as the prefix for the stack classes.
Android has built-in an older version of JAIN-SIP which is taking over some of the existing references to those "gov.nist" classes. It's not an exported API, so not quite obvious. That's why it may behave differently on desktop machines. Post you code and full error messages/debug logs if you need more help.
Sovled. Jain Sip is using log4i-1.2.x.jar which does not work properly on Android. There are lots of discussion on Internet how to make log4j working on Android but none of them works for me. I have removed all log4j related code from Jain Sip source and now the sip stack is working properly on Android.
I am using JAIN-SIP-1-2-164. Here is the app code:
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.*;
import android.os.Handler;
import jain_javax.sip.*;
import jain_javax.sip.address.*;
import jain_javax.sip.header.*;
import jain_javax.sip.message.*;
public class SipLayer implements SipListener {
private SipStack sipStack;
private SipFactory sipFactory;
private Properties properties;
private String local_ip;
int listen_port;
/** Here we initialize the SIP stack. */
public SipLayer(int listen_port) {
try {
setUsername(username);
this.local_ip = InetAddress.getLocalHost().getHostAddress();;
this.listen_port = listen_port;
// Create the SIP factory and set the path name.
this.sipFactory = SipFactory.getInstance();
this.sipFactory.setPathName("jain_gov.nist");
// Create and set the SIP stack properties.
this.properties = new Properties();
this.properties.setProperty("jain_javax.sip.STACK_NAME", "stack");
this.properties.setProperty("jain_javax.sip.IP_ADDRESS", local_ip);
if(proxy != null)
this.properties.setProperty("jain_javax.sip.OUTBOUND_PROXY", proxy + ':' + server_port + '/' + protocol);
//DEBUGGING: Information will go to files textclient.log and textclientdebug.log
this.properties.setProperty("jain_gov.nist.javax.sip.TRACE_LEVEL", "32");
// this.properties.setProperty("jain_gov.nist.javax.sip.SERVER_LOG", "textclient.txt");
// this.properties.setProperty("jain_gov.nist.javax.sip.DEBUG_LOG", "textclientdebug.log");
// Create the SIP stack.
this.sipStack = this.sipFactory.createSipStack(properties);
}
catch (Exception e) {
msgProc.processError("SipLayer failed: " + e.getMessage() + "\n");
}
}
}
Same code runs ok on java on a windows machine, but android emulator I got above mentioned error message.
I found that it failed in following Jain SIP 1.2 routine at "SipStack sipStack = (SipStack) sipStackConstructor.newInstance(conArgs);"
private SipStack createStack(Properties properties)
throws PeerUnavailableException {
try {
// create parameters argument to identify constructor
Class[] paramTypes = new Class[1];
paramTypes[0] = Class.forName("java.util.Properties");
// get constructor of SipStack in order to instantiate
Constructor sipStackConstructor = Class.forName(
getPathName() + ".jain_javax.sip.SipStackImpl").getConstructor(
paramTypes);
// Wrap properties object in order to pass to constructor of
// SipSatck
Object[] conArgs = new Object[1];
conArgs[0] = properties;
// Creates a new instance of SipStack Class with the supplied
// properties.
SipStack sipStack = (SipStack) sipStackConstructor.newInstance(conArgs);
sipStackList.add(sipStack);
String name = properties.getProperty("jain_javax.sip.STACK_NAME");
this.sipStackByName.put(name, sipStack);
return sipStack;
} catch (Exception e) {
String errmsg = "The Peer SIP Stack: "
+ getPathName()
+ ".jain_javax.sip.SipStackImpl"
+ " could not be instantiated. Ensure the Path Name has been set.";
throw new PeerUnavailableException(errmsg, e);
}
}
Any suggestion or how to debug further?

How to open the default webbrowser using java

Can someone point me in the right direction on how to open the default web browser and set the page to "www.example.com" thanks
java.awt.Desktop is the class you're looking for.
import java.awt.Desktop;
import java.net.URI;
// ...
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
For me solution with Desktop.isDesktopSupported() doesn't work (windows 7 and ubuntu). Please try this to open browser from java code:
Windows:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
Mac
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("open " + url);
Linux:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
String[] browsers = { "google-chrome", "firefox", "mozilla", "epiphany", "konqueror",
"netscape", "opera", "links", "lynx" };
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
if(i == 0)
cmd.append(String.format( "%s \"%s\"", browsers[i], url));
else
cmd.append(String.format(" || %s \"%s\"", browsers[i], url));
// If the first didn't work, try the next browser and so on
rt.exec(new String[] { "sh", "-c", cmd.toString() });
If you want to have multiplatform application, you need to add operation system checking(for example):
String os = System.getProperty("os.name").toLowerCase();
Windows:
os.indexOf("win") >= 0
Mac:
os.indexOf("mac") >= 0
Linux:
os.indexOf("nix") >=0 || os.indexOf("nux") >=0
Here is my code. It'll open given url in default browser (cross platform solution).
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
As noted in the answer provided by Tim Cooper, java.awt.Desktop has provided this capability since Java version 6 (1.6), but with the following caveat:
Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false.
For platforms which do not support or provide java.awt.Desktop, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.
Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:
This code is Copyright 1999-2001 by Eric Albert (ejalbert#cs.stanford.edu) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.
Credits:
Steven Spencer, JavaWorld magazine (Java Tip 66)
Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.
You can also use the Runtime to create a cross platform solution:
import java.awt.Desktop;
import java.net.URI;
public class App {
public static void main(String[] args) throws Exception {
String url = "http://stackoverflow.com";
if (Desktop.isDesktopSupported()) {
// Windows
Desktop.getDesktop().browse(new URI(url));
} else {
// Ubuntu
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
}
}
}
Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MultiBrowPop {
public static void main(String[] args) {
OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");
String url = "http://www.birdfolk.co.uk/cricmob";
OUT("We're going to this page: "+ url);
String myOS = System.getProperty("os.name").toLowerCase();
OUT("(Your operating system is: "+ myOS +")\n");
try {
if(Desktop.isDesktopSupported()) { // Probably Windows
OUT(" -- Going with Desktop.browse ...");
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} else { // Definitely Non-windows
Runtime runtime = Runtime.getRuntime();
if(myOS.contains("mac")) { // Apples
OUT(" -- Going on Apple with 'open'...");
runtime.exec("open " + url);
}
else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours
OUT(" -- Going on Linux with 'xdg-open'...");
runtime.exec("xdg-open " + url);
}
else
OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
}
OUT("\nThings have finished.\nI hope you're OK.");
}
catch(IOException | URISyntaxException eek) {
OUT("**Stuff wrongly: "+ eek.getMessage());
}
}
private static void OUT(String str) {
System.out.println(str);
}
}
Its very simple just write below code:
String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
or if you don't want to load URL then just write your browser name into string values like,
String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
it will open browser automatically with empty URL after executing a program
I recast Brajesh Kumar's answer above into Clojure as follows:
(defn open-browser
"Open a new browser (window or tab) viewing the document at this `uri`."
[uri]
(if (java.awt.Desktop/isDesktopSupported)
(let [desktop (java.awt.Desktop/getDesktop)]
(.browse desktop (java.net.URI. uri)))
(let [rt (java.lang.Runtime/getRuntime)]
(.exec rt (str "xdg-open " uri)))))
in case it's useful to anyone.
on windows invoke "cmd /k start http://www.example.com"
Infact you can always invoke "default" programs using the start command.
For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.
JavaFX bundles a cross-platform solution inside its StandaloneHostService that is independent of AWT, which is somehow similar to krzysiek.ste's answer.
I rewrote it to include some xdg-open alternatives (which are actually used by xdg-open by the way).
private static final String[][] commands = new String[][]{
{"xdg-open", "$1"},
{"gio", "open", "$1"},
{"gvfs-open", "$1"},
{"gnome-open", "$1"}, // Gnome
{"mate-open", "$1"}, // Mate
{"exo-open", "$1"}, // Xfce
{"enlightenment_open", "$1"}, // Enlightenment
{"gdbus", "call", "--session", "--dest", "org.freedesktop.portal.Desktop",
"--object-path", "/org/freedesktop/portal/desktop",
"--method", "org.freedesktop.portal.OpenURI.OpenURI",
"", "$1", "{}"}, // Flatpak
{"open", "$1"}, // Mac OS fallback
{"rundll32", "url.dll,FileProtocolHandler", "$1"}, // Windows fallback
};
Here is the final Java snippet, avoiding string concatenation and escape character issues.
public static void showDocument(final String uri) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Runtime.getRuntime().exec(new String[]{"open", uri});
} else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec(new String[]{"rundll32", "url.dll,FileProtocolHandler", uri});
} else { //assume Unix or Linux
new Thread(() -> {
try {
for (String[] browser : commands) {
try {
String[] command = new String[browser.length];
for (int i = 0; i < browser.length; i++)
if (browser[i].equals("$1"))
command[i] = uri;
else
command[i] = browser[i];
if (Runtime.getRuntime().exec(command).waitFor() == 0)
return;
} catch (IOException ignored) {
}
}
String browsers = System.getenv("BROWSER") == null ? "x-www-browser:firefox:iceweasel:seamonkey:mozilla:" +
"epiphany:konqueror:chromium:chromium-browser:google-chrome:" +
"www-browser:links2:elinks:links:lynx:w3m" : System.getenv("BROWSER");
for (String browser : browsers.split(":")) {
try {
Runtime.getRuntime().exec(new String[]{browser, uri});
return;
} catch (IOException ignored) {
}
}
} catch (Exception ignored) {
}
}).start();
}
} catch (Exception e) {
// should not happen
// dump stack for debug purpose
e.printStackTrace();
}
}
There is also
BrowserUtil.browse(uri);
(source code) that seems to be a more compatible with some more exotic setups. I recently had a client where Desktop.getDesktop().browse(uri) was failing in Fedora Linux, but BrowserUtil.browse(uri) worked.
I also believe this is now the preferred way by JetBrains to open a browser (for example, see this thread)
As I had this same problem and found no decent solution for our case so I ported the https://www.npmjs.com/package/open npm package to Java https://github.com/vaadin/open and released it into Maven central. Can be used as
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>open</artifactId>
<version>8.4.0.2</version>
</dependency>
Open.open("https://stackoverflow.com/")
or for a specific browser
Open.open("https://stackoverflow.com/", App.FIREFOX);

Categories

Resources