How to get jboss7 version in java programatically through? [duplicate] - java

This question already has answers here:
How do I programmatically obtain the version in JBoss AS 5.1?
(2 answers)
Closed 8 years ago.
i have use j boss 4.2.2 to latest version.i have use java development kit 1.5 to 1.7 latest version all j boss version in get all java development kit. how to get j boss version in java code through.

With 5 there is a properties file: /org/jboss/version.properties where the keys version.major and version.minor looks for your case. Sust load the file to Properties and read. See link below:
http://grepcode.com/file/repository.jboss.org/nexus/content/repositories/releases/org.jboss.jbossas/jboss-as-main/5.0.0.CR2/org/jboss/version.properties
This file has been kept also in jboss6.1
http://grepcode.com/file/repository.jboss.org/nexus/content/repositories/releases/org.jboss.jbossas/jboss-as-main/6.1.0.Final/org/jboss/version.properties?av=f
I realized you asked for jboss7.... but I leave the work I did in case can be useful (it is anyway an approach valid for 5 and 6 versions)
For jboss7 I found two ways:
WAY 1
Checking out the code from github I cannot find anymore this Versoin.properties in the sources.
But I could find a Version.class which stores the version and release code name as properties; you can use Version.AS_VERSION to get what you want as you can see from the source code:
public class Version {
public static final String AS_VERSION;
public static final String AS_RELEASE_CODENAME;
public static final int MANAGEMENT_MAJOR_VERSION = 1;
public static final int MANAGEMENT_MINOR_VERSION = 4;
public static final int MANAGEMENT_MICRO_VERSION = 0;
static {
InputStream stream = Version.class.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF");
Manifest manifest = null;
try {
if (stream != null)
manifest = new Manifest(stream);
} catch (Exception e) {
}
String version = null, code = version;
if (manifest != null) {
version = manifest.getMainAttributes().getValue("JBossAS-Release- Version");
code = manifest.getMainAttributes().getValue("JBossAS-Release-Codename");
}
if (version == null) {
version = "Unknown";
}
if (code == null) {
code = "Unknown";
}
AS_VERSION = version;
AS_RELEASE_CODENAME = code;
}
}
WAY2
Another option that I found googling but I didn't verify personally is going through JMX (perhaps you prefer this approach):
ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9999);
ModelNode op = new ModelNode();
op.get(ClientConstants.OP).set("read-resource");
ModelNode returnVal = client.execute(op);
logger.info("release-version: " + returnVal.get("result").get("release-version").asString());
logger.info("release-codename: " + returnVal.get("result").get("release-codename").asString());
And from the jboss-admin command line interface, you can get the info from these commands:
/:read-attribute(name=release-version)
/:read-attribute(name=release-codename)
NOTE:
The source code are now under git clone https://github.com/wildfly/wildfly.git (the jboss website still send to an outdated link)

Try this tutorial: https://community.jboss.org/thread/176932?start=0&tstart=0
or this: How do I programmatically obtain the version in JBoss AS 5.1?

Related

java.awt.print.PrinterException: Printer is not accepting job

I am facing java.awt.print.PrinterException: Printer is not accepting job..Exception in my jsp page when sending documents to print dyanamically................
String pdfFile = "D://Records.pdf";
boolean silentPrint = false;
String printerindx = "1";
String password = "";
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
if (pdfFile == null) {
System.out.println("No PDF file available");
}
PDDocument document = null;
try {
document = PDDocument.load(pdfFile);
if (document.isEncrypted()) {
document.decrypt(password);
}
PrinterJob printJob = PrinterJob.getPrinterJob();
if (printerindx != null) {
PrintService[] printServices = PrinterJob.lookupPrintServices();
for (PrintService printService : printServices) {
if (printService.getName().equals("HP LaserJet P1007") {
System.out.println("Printer found ....");
printJob.setPrintService(printService);
System.out.println(printService);
}
}
}
document.print(printJob);
} finally {
if (document != null) {
document.close();
}
}
System.out.println("Printing Completed...");
whats going wrong ?
According to this: openjdk bug it is an error in printing libraries, and you have some options:
Use different JRE where error is fixed.
Repeat printing until it will not throw, people with similar problem say it often worked on first repeat.
Use hack from here: hack, see ForcedAcceptPrintService class
What Failed
I've previously attempted the solution from Piro's third suggestion, but I received the same error that the succeeding poster (post #10) experienced.
What Worked
I performed the bytecode hack, which overwrites the Win32PrintService getPrinterIsAcceptingJobs() method to always return a status of "ACCEPTING_JOBS." This worked perfectly for my needs: The printer is always seen as available and even if it's actually offline, print jobs are queued for whenever it comes back online. The only thing I had to do differently was grab an older version of Javassist (3.18) from GitHub since I'm compiling with Java 7. Attempting to compile with the latest version (3.20) -- which is built with Java 8 -- gave me the following error:
java.lang.UnsupportedClassVersionError: sun/print/Win32PrintService : Unsupported major.minor version 52.0
For anyone else unfamiliar with the compilations necessary to create the PrintServiceFixer.jar, here are the steps I took:
Copied javassist.jar to <JAVA_HOME>\jre\lib\ext
Compiled Win32PrintServiceFixer.java (from within <JAVA_HOME>\jre\lib)
javac -classpath .\rt.jar -bootclasspath ext\javassist.jar Win32PrintServiceFixer.java
Created PrintServiceFixer.jar file:
java -cp .;.\ext\javassist.jar Win32PrintServiceFixer
Copied PrintServiceFixer.jar from <JAVA_HOME>\jre\lib\target to the directory where I store my program's library/JAR files.
Ran my program
java -jar -Xbootclasspath/p:path\to\my\program's\libs\PrintServiceFixer.jar MyPrintingProgram.jar

Java - Deploying RXTX

I am on Windows Seven 64-bit. I wrote a little application that uses RXTX to communication through serial port. I used the rxtxSerial.dll for Windows 64-bit and it works pretty well on both Eclispe and NetBeans.
At the root of the project, I placed RXTXComm.jar and rxtxSerial.dll.
The problem appears when I want to deploy the application. I used the Export function on Eclipse or I accessed the bin/ folder from NetBeans. I placed again RXTXComm.jar and rxtxSerial.dll at the root of the folders but when I execute the Application.jar, RXTX doesn't seem working. The scan seems to stay stuck whereas it shouldn't last more than a second.
[Sorry, I "need at least 10 reputation to post images."]
I tried all the suggestions I found on the internet:
installing the dlls and RXTXComm.jar in the JRE folder
placing the dlls in Windows32 folder
tried all the different export options of Export from Eclipse
I must be missing something. Has anyone already been successful in deploying RXTX for Windows 32/64bit and MAC? Could you describe what you did and what is necessary to do so?
Please find below the piece of code executing when scanning for ports:
private void scanButtonAction()
{
if(scanState == ST_FREE)
{
scanState = ST_SCANNING;
redrawComponents();
scan = new Thread(new ScanPorts());
scan.start();
}
}
// Thread run to scan the ports
private class ScanPorts implements Runnable {
public void run()
{
try
{
UARTConnection connection = new UARTConnection();
// listPort() is a long blocking call
String[][] list = connection.listPorts();
// Display the ports in the ComboBox
comboBoxModel.removeAllElements();
if(list.length == 0) comboBoxModel.addElement( new Item(-1, "No port scanned", "" ) );
else
{
for(int i = 0; i < list.length; i++)
{
// Id, Description (user's display), PortName (for serial connection)
comboBoxModel.addElement( new Item(i, list[i][1], list[i][0]) );
}
// To select the first item of the list. Necessary with custom Rendered
portNumberBox.setSelectedIndex(0);
}
scanState = ST_FREE;
redrawComponents();
// The connect button is enabled only after a first scan
connectButton.setEnabled(true);
}
catch(Exception ex)
{
scanState = ST_FREE;
redrawComponents();
}
}
}
public class UARTConnection {
public UARTConnection()
{
}
public String[][] listPorts() throws Exception
{
Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
Enumeration<CommPortIdentifier> tmpPortEnum = portEnum;
ArrayList<String[]> list = new ArrayList<String[]>();
int i = 0;
while ( portEnum.hasMoreElements() )
{
String port[] = new String[2];
CommPortIdentifier portIdentifier = portEnum.nextElement();
System.out.println(portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()));
port[0] = portIdentifier.getName();
port[1] = portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType());
list.add(port);
i++;
}
String listOfPort[][] = new String[list.size()][2];
for(i = 0; i < list.size(); i++)
{
String[] port = list.get(i);
listOfPort[i][0] = port[0];
listOfPort[i][1] = port[1];
}
return listOfPort;
}
private String getPortTypeName ( int portType )
{
switch ( portType )
{
case CommPortIdentifier.PORT_I2C:
return "I2C";
case CommPortIdentifier.PORT_PARALLEL:
return "Parallel";
case CommPortIdentifier.PORT_RAW:
return "Raw";
case CommPortIdentifier.PORT_RS485:
return "RS485";
case CommPortIdentifier.PORT_SERIAL:
return "Serial";
default:
return "unknown type";
}
}
}
Thank you for your help.
I found the solution, for those it might help.
When running the application from Eclipse or NetBean, the app is running in 64-bit. Hence, I used the 64bit rxtxSerial.dll. It was working properly.
But I realized when running the compiled .jar outside of the IDE, the Windows process list was displaying javaw.exe *32 for the application. For some reason I ignore, the compiled .jar was in 32bit. Hence, the driver required was for Windows 32bit, not the 64bit. It works well from now on.
Note: in order to be able to work on my MAC, I had to compile the application in Java 1.6 (not 1.7) and to provide the MAC driver of course.

JNetPcap in eclipse does not print error... Ubuntu 12.04

Have some problems with JNetPcap.
I uses Ubuntu 12.04, and trying to make packet snipper that based in java language.
What I did is below.
I have downloaded JNetPcap 1.3.0.
And as tutorial said built a java project.
http://jnetpcap.com/examples/dumper <- this is the link.
I typed just like that link and I got my first problem.
PcapHandler Class is deprecated. So I find the document and replace it with ByteBufferHandler.
Now I compile this project and got an unsatifiedLinked Error.
I have tried with static block to load that library.
After some attempts I copied "libjnetpcap.so" to /usr/lib/
now I remove unsatisfiedLinked Error. but somehow it stops in 1st Error check.
It prints "1st error check : ", then exit automatically.
public static void main(String[] args) {
List<PcapIf> alldevs = new ArrayList<PcapIf>();
StringBuilder errbuff = new StringBuilder();
int r = Pcap.findAllDevs(alldevs, errbuff);
//============1st check
if(r == Pcap.NOT_OK || alldevs.isEmpty()){
System.err.printf("1st error check : %s\n", errbuff.toString());
return;
}
PcapIf device = alldevs.get(1);
//===================== END
int snaplen = 64 * 1024;
int flags = Pcap.MODE_PROMISCUOUS;
int timeout = 10 * 1000;
Pcap pcap = Pcap.openLive(device.getName(),snaplen, flags, timeout, errbuff);
//============2nd check
if(pcap == null){
System.err.printf("2nd error check : %s\n", errbuff.toString());
return;
}
//===================== END
String ofile = "/home/juneyoungoh/tmp_capture_file.cap";
final PcapDumper dumper = pcap.dumpOpen(ofile);
ByteBufferHandler<PcapDumper> handler = new ByteBufferHandler<PcapDumper>() {
#Override
public void nextPacket(PcapHeader arg0, ByteBuffer arg1, PcapDumper arg2) {
dumper.dump(arg0, arg1);
}
};
pcap.loop(10,handler, dumper);
File file = new File(ofile);
System.out.printf("%s file has %d bytes in it!\n", ofile, file.length());
dumper.close();
pcap.close();
if(file.exists()){
file.delete();
}
}
if is there any good reference or wonderful idea, please share.
Thanks.
On Linux, a program will probably have to run as root, or with sufficient privileges granted in some other fashion, in order to be able to open any devices, and, currently, pcap_findalldevs(), which is presumably what the Pcap.findAllDevs method uses, tries to open each of the devices it finds, and only returns the devices it can open.
So you'll have to run your Java program as root, or will somehow have to arrange that it have sufficient privileges (CAP_NET_RAW and CAP_NET_ADMIN) to get a list of network adapters and open those adapters.

java.lang.nosuchfielderror in j2me app

Hey Hi Friends I am created one j2me app. it runs perfectly in Emulator but in Mobile it showing error like java.lang.nosuchfielderror:No such field HEADERS.[[Ljava/lang/String;.
Why this happening with mobile, it runs good in emulator......
Please help me to remove this error......
public String connectPhoneName() throws Exception{
String url = "http://122.170.122.186/Magic/getPhonetype.jsp";
String phoneType;
if ((conn = connectHttp.connect(url, HEADERS)) != null) {
if ((in = connectHttp.getDataInputStream(conn)) != null) {
byte[] data = connectHttp.readDATA(in, 100);
phoneType = new String(data);
System.out.println("DATA : " + phoneType);
} else {
throw new Exception("ERROR WHILE OPENING INPUTSTREAM");
}
} else {
throw new Exception("COULD NOT ESTABLISH CONNECTION TO THE SERVER");
}
return phoneType;
}
In this code i have used HEADERS.
It looks like your app is using some (I guess) or static final or final field of some library class that does not exist in the profile of Java ME your mobile device implements.
But I can't figure out where that field comes from. Perhaps you should search your codebase for use of "HEADER" as an identifier ...
If the HEADER field is properly declared in your codebase (your MagiDEF interface) and the code you showed is using the HEADER from that interface, then you must have something wrong with your build or deployment process. Specifically, you are not deploying the version of MagiDEF that your code (above) has been compiled against. Maybe you've got an old version of something in some JAR file?
Basically, the error indicates that you have a binary incompatibility between some of the classes / interfaces that make up your app.

How can a Java program get its own process ID?

How do I get the id of my Java process?
I know there are several platform-dependent hacks, but I would prefer a more generic solution.
There exists no platform-independent way that can be guaranteed to work in all jvm implementations.
ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use.
On linux+windows it returns a value like "12345#hostname" (12345 being the process id). Beware though that according to the docs, there are no guarantees about this value:
Returns the name representing the running Java virtual machine. The
returned name string can be any arbitrary string and a Java virtual
machine implementation can choose to embed platform-specific useful
information in the returned name string. Each running virtual machine
could have a different name.
In Java 9 the new process API can be used:
long pid = ProcessHandle.current().pid();
You could use JNA. Unfortunately there is no common JNA API to get the current process ID yet, but each platform is pretty simple:
Windows
Make sure you have jna-platform.jar then:
int pid = Kernel32.INSTANCE.GetCurrentProcessId();
Unix
Declare:
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);
int getpid ();
}
Then:
int pid = CLibrary.INSTANCE.getpid();
Java 9
Under Java 9 the new process API can be used to get the current process ID. First you grab a handle to the current process, then query the PID:
long pid = ProcessHandle.current().pid();
Here's a backdoor method which might not work with all VMs but should work on both linux and windows (original example here):
java.lang.management.RuntimeMXBean runtime =
java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt =
(sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method =
mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);
int pid = (Integer) pid_method.invoke(mgmt);
Try Sigar . very extensive APIs. Apache 2 license.
private Sigar sigar;
public synchronized Sigar getSigar() {
if (sigar == null) {
sigar = new Sigar();
}
return sigar;
}
public synchronized void forceRelease() {
if (sigar != null) {
sigar.close();
sigar = null;
}
}
public long getPid() {
return getSigar().getPid();
}
The following method tries to extract the PID from java.lang.management.ManagementFactory:
private static String getProcessId(final String fallback) {
// Note: may fail in some JVM implementations
// therefore fallback has to be provided
// something like '<pid>#<hostname>', at least in SUN / Oracle JVMs
final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
final int index = jvmName.indexOf('#');
if (index < 1) {
// part before '#' empty (index = 0) / '#' not found (index = -1)
return fallback;
}
try {
return Long.toString(Long.parseLong(jvmName.substring(0, index)));
} catch (NumberFormatException e) {
// ignore
}
return fallback;
}
Just call getProcessId("<PID>"), for instance.
For older JVM, in linux...
private static String getPid() throws IOException {
byte[] bo = new byte[256];
InputStream is = new FileInputStream("/proc/self/stat");
is.read(bo);
for (int i = 0; i < bo.length; i++) {
if ((bo[i] < '0') || (bo[i] > '9')) {
return new String(bo, 0, i);
}
}
return "-1";
}
Since Java 9 there is a method Process.getPid() which returns the native ID of a process:
public abstract class Process {
...
public long getPid();
}
To get the process ID of the current Java process one can use the ProcessHandle interface:
System.out.println(ProcessHandle.current().pid());
You can check out my project: JavaSysMon on GitHub. It provides process id and a bunch of other stuff (CPU usage, memory usage) cross-platform (presently Windows, Mac OSX, Linux and Solaris)
java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("#")[0]
In Scala:
import sys.process._
val pid: Long = Seq("sh", "-c", "echo $PPID").!!.trim.toLong
This should give you a workaround on Unix systems until Java 9 will be released.
(I know, the question was about Java, but since there is no equivalent question for Scala, I wanted to leave this for Scala users who might stumble into the same question.)
For completeness there is a wrapper in Spring Boot for the
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
return jvmName.split("#")[0];
solution. If an integer is required, then this can be summed up to the one-liner:
int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("#")[0]);
If someone uses Spring boot already, she/he might use org.springframework.boot.ApplicationPid
ApplicationPid pid = new ApplicationPid();
pid.toString();
The toString() method prints the pid or '???'.
Caveats using the ManagementFactory are discussed in other answers already.
public static long getPID() {
String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
if (processName != null && processName.length() > 0) {
try {
return Long.parseLong(processName.split("#")[0]);
}
catch (Exception e) {
return 0;
}
}
return 0;
}
I am adding this, in addition to other solutions.
with Java 10, to get process id
final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
final long pid = runtime.getPid();
out.println("Process ID is '" + pid);
The latest I have found is that there is a system property called sun.java.launcher.pid that is available at least on linux. My plan is to use that and if it is not found to use the JMX bean.
It depends on where you are looking for the information from.
If you are looking for the information from the console you can use the jps command. The command gives output similar to the Unix ps command and comes with the JDK since I believe 1.5
If you are looking from the process the RuntimeMXBean (as said by Wouter Coekaerts) is probably your best choice. The output from getName() on Windows using Sun JDK 1.6 u7 is in the form [PROCESS_ID]#[MACHINE_NAME]. You could however try to execute jps and parse the result from that:
String jps = [JDK HOME] + "\\bin\\jps.exe";
Process p = Runtime.getRuntime().exec(jps);
If run with no options the output should be the process id followed by the name.
This is the code JConsole, and potentially jps and VisualVM uses. It utilizes classes from
sun.jvmstat.monitor.* package, from tool.jar.
package my.code.a003.process;
import sun.jvmstat.monitor.HostIdentifier;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;
public class GetOwnPid {
public static void main(String[] args) {
new GetOwnPid().run();
}
public void run() {
System.out.println(getPid(this.getClass()));
}
public Integer getPid(Class<?> mainClass) {
MonitoredHost monitoredHost;
Set<Integer> activeVmPids;
try {
monitoredHost = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));
activeVmPids = monitoredHost.activeVms();
MonitoredVm mvm = null;
for (Integer vmPid : activeVmPids) {
try {
mvm = monitoredHost.getMonitoredVm(new VmIdentifier(vmPid.toString()));
String mvmMainClass = MonitoredVmUtil.mainClass(mvm, true);
if (mainClass.getName().equals(mvmMainClass)) {
return vmPid;
}
} finally {
if (mvm != null) {
mvm.detach();
}
}
}
} catch (java.net.URISyntaxException e) {
throw new InternalError(e.getMessage());
} catch (MonitorException e) {
throw new InternalError(e.getMessage());
}
return null;
}
}
There are few catches:
The tool.jar is a library distributed with Oracle JDK but not JRE!
You cannot get tool.jar from Maven repo; configure it with Maven is a bit tricky
The tool.jar probably contains platform dependent (native?) code so it is not easily
distributable
It runs under assumption that all (local) running JVM apps are "monitorable". It looks like
that from Java 6 all apps generally are (unless you actively configure opposite)
It probably works only for Java 6+
Eclipse does not publish main class, so you will not get Eclipse PID easily
Bug in MonitoredVmUtil?
UPDATE: I have just double checked that JPS uses this way, that is Jvmstat library (part of tool.jar). So there is no need to call JPS as external process, call Jvmstat library directly as my example shows. You can aslo get list of all JVMs runnin on localhost this way.
See JPS source code:
I know this is an old thread, but I wanted to call out that API for getting the PID (as well as other manipulation of the Java process at runtime) is being added to the Process class in JDK 9: http://openjdk.java.net/jeps/102
Based on Ashwin Jayaprakash's answer (+1)
about the Apache 2.0 licensed SIGAR, here is how I use it to get only the PID of the current process:
import org.hyperic.sigar.Sigar;
Sigar sigar = new Sigar();
long pid = sigar.getPid();
sigar.close();
Even though it does not work on all platforms, it does work on Linux, Windows, OS X and various Unix platforms as listed here.
You can try getpid() in JNR-Posix.
It has a Windows POSIX wrapper that calls getpid() off of libc.
I found a solution that may be a bit of an edge case and I didn't try it on other OS than Windows 10, but I think it's worth noticing.
If you find yourself working with J2V8 and nodejs, you can run a simple javascript function returning you the pid of the java process.
Here is an example:
public static void main(String[] args) {
NodeJS nodeJS = NodeJS.createNodeJS();
int pid = nodeJS.getRuntime().executeIntegerScript("process.pid;\n");
System.out.println(pid);
nodeJS.release();
}
Here is my solution:
public static boolean isPIDInUse(int pid) {
try {
String s = null;
int java_pid;
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("#")));
if (java_pid == pid) {
System.out.println("In Use\n");
return true;
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return false;
}
This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux
netstat -tupln | grep portNumber

Categories