Hi i want to obtain from java classes infos on JBoss like the status and the version and then manage him by starting/stopping/resatring him.
For the version i do this :
String fileSeparator = System.getProperty("file.separator");
String runJarFile = jbossHomeDir + fileSeparator + "bin" + fileSeparator + "run.jar";
System.out.println("JBOSSDIR est :" + runJarFile);
jarInputStream = new JarInputStream(new FileInputStream(runJarFile));
System.out.println("Pigmalion" + jarInputStream.getNextEntry().getName());
Manifest manifest = jarInputStream.getManifest();
Attributes attributes = manifest.getMainAttributes();
jbossVersion = attributes.getValue(Attributes.Name.SPECIFICATION_VERSION);
which works fine, now for the status, i saw some people doing it by checking the port, but isn't there another way of doing it ?
As for the start/stop/restart commands i saw this script
package com.sudipta.jboss.conf;
import org.jboss.Main;
public class JbossOperation {
public static Main ob;
static Class jbossMain;
static{
try {
jbossMain=Class.forName("org.jboss.Main");
ob = (Main)jbossMain.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* START JBOSS SERVER
* #return true if started successfully
*/
public static boolean startServer(){
boolean status=true;
String str[]={"-c","default"};
try {
ob.boot(str);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return status;
}
/**
* STOP JBOSS SERVER
* #return true if started successfully
*/
public static boolean stopServer(){
boolean status=true;
try {
ob.shutdown();
} catch (Throwable e) {
e.printStackTrace();
}
return status;
}
/**
* Main method
* #param args
*/
public static void main(String args[]){
System.out.println("---------------------Strating the server------------------");
startServer();
System.out.println("---------------------Stoping the server------------------");
stopServer();
System.out.println("---------------------SERVER STOPPED------------------");
}
}
I downloaded the jboss-system 4.0.2 jar and it tells me the shutdown method doesn't exist. Do i have to download other jboss jars ?
If you are looking for something more enterprisy (but still open source). You may want to use RHQ for it. It allows to run operations on managed resources and it can start/restart/stop JBoss server, deploy a war to it and far more. But the learning curve may be quite steep.
Have you considered to use JMX Console?. Moreover, if you really need to manage the server from a Java program you could write a JMX client that invoke specific server operations like shutdown. Additionaly, different kind of server information can be obtained this way. (ofcourse JMX wont be useful for start the server).
Related
I'm working on a text-based RPG with some friends using Netbeans. It works all fine and dandy in Netbeans but when I export it to a .jar file I get this error.
Jan 28, 2019 2:27:15 PM Operator.DragonsHead startActionPerformed
SEVERE: null
java.io.FileNotFoundException: File "src\Operator\files\Opening.mid" does not exist!
This happens when the game starts, as we have a "theme" that plays at boot up.
The song plays on Netbeans but not when exported.
I'm relatively new to Java programming, I took a course on it last year.
I've tried looking around the web for people having the same issue, but I can't quite get it to duplicate with my code.
Here's the midi class:
import javax.sound.midi.*;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
public class MIDI {
private File file = null;
private Sequencer sequencer = null;
public MIDI (String midiFile) throws FileNotFoundException {
this.file = new File(midiFile);
if (!file.isFile()) {
throw new FileNotFoundException("File \"" + midiFile + "\" does not exist!");
}
try{
sequencer = MidiSystem.getSequencer();
if (sequencer == null){
System.err.println("Error: Sequencer not supported");
return;
}
sequencer.open();
Sequence sequence = MidiSystem.getSequence(file);
sequencer.setSequence(sequence);
}
catch (MidiUnavailableException | InvalidMidiDataException | IOException ex){
}
}
public void play(){
sequencer.start();
}
public void stop() {
sequencer.stop();
}
public void waitAndStop(int millis) {
Runnable song = () -> {
try {
Thread.sleep(millis);
}
catch (InterruptedException e) {
System.err.println("MIDI playback interrupted");
}
stop();
};
Thread t = new Thread(song);
t.start();
}
public long songLengthMicroseconds() {
return sequencer.getMicrosecondLength();
}
public Sequence getSequence(String resource) {
try {
return MidiSystem.getSequence(new File(resource));
}
catch (InvalidMidiDataException | IOException ex) {
return null;
}
}
}
Here's the lines that initialize it and call the song to play:
MIDI midiTest;
midiTest = new MIDI("src\\Operator\\files\\Opening.mid");
midiTest.play();
I'm not sure what the API is of 'MIDI', but unless you want to go through the rigamarole of writing an installer, you cannot use direct file access for resources like icons, pictures, music, and datafiles.
Instead, use the getResource/getResourceAsStream mechanism, which returns URLs/InputStreams. Well written libraries take these just as well as files.
Basic format:
try (InputStream resource = MyClassName.class.getResourceAsStream("Opening.mid")) {
// do something with resource here.
}
where Opening.mid is in the exact same place that MyClassName.class is (so, if you are shipping as a jar, it's in the jar, in the same folder structure as myClassName.class. If you prefer to have a root dir 'music' in your jar, you can pass for example: /music/Opening.mid, with the leading slash to indicate you're going off of the jar root.
secondary observation, if you don't know what to do with an exception, best solution is to add the exception(s) you cannot handle to your method's 'throws' line. If that is somehow not possible, the proper body for a catch block is:
throw new RuntimeException("unhandled checked exception", e);
because right now if an error occurs, your code will silently just keep going. If that was your intent (because, hey, music is optional I guess), I'd still log it SOMEWHERE, right now if an error occurs, you just won't know about it.
I decided to write RMI (from the book) took code from the book too. i created the Stub with rmic, and started rmiregistry but when i dedided to write java Start Server i got the problem, actually here is my problem i faced with:
java -classpath D:\RMI AddServer
Exception:java.rmi.ServerException: RemoteException occurred in server thread; n
ested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested excep
tion is:
java.lang.ClassNotFoundException: AddServerImpl_Stub
PLease i need help, i lost lot of time because of this :(
AddServerIntf.java
package rmi.app;
import java.rmi.*;
public interface AddServerIntf extends Remote {
double add(double d1,double d2) throws RemoteException;}
AddServerImpl
package rmi.app;
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf {
public AddServerImpl() throws RemoteException {}
public double add(double d1, double d2) throws RemoteException {
return d1+d2;
}
}
AddServer
package rmi.app;
import java.net.*;
import java.rmi.*;
public class AddServer {
public static void main(String[] args) {
try {
AddServerImpl addServerImpl = new AddServerImpl();
Naming.rebind("AddServer", addServerImpl);
}
catch (Exception e){
System.out.println("Exception:"+e);
}
}
}
AddClient
package rmi.app;
import java.rmi.Naming;
public class AddClient {
public static void main(String[] args) {
try{
String addServerURL= "rmi://"+args[0]+ "/AddServer";
AddServerIntf addServer =(AddServerIntf)Naming.lookup(addServerURL);
System.out.println("The first number is:"+args[1]);
double d1= Double.valueOf(args[1]).doubleValue();
System.out.println("The second number is:"+args[2]);
double d2= Double.valueOf(args[2]).doubleValue();
System.out.println("the sum is:"+ addServer.add(d1,d2));
}
catch(Exception e){
System.out.println("Exception : "+ e);
}
}
}
I am writing a Java RMI application too and I went through a lot before being able to make it work. After a lot of research and try and error I got this "recipe":
Don't install SecurityManager;
Don't use policy files;
Make sure the classes you're moving from one VM to another are in
both client and server classpath (or in the same jar/war).
If you're using hibernate to make database access, put the jars in the
client too. Hibernate "changes" the original classes and the client
will need this to deserialize it;
If you're also using Spring on the server side you might include the spring-orm and spring-data-jpa jars in the client, if you experience ClassNotFoundException followed by JpaObjectRetrievalFailureException;
I am not running anything outside the jars (no rmi services at all);
I didn't create the stubs as I am using Java 6.
My server is purely doing this:
try {
try {
LocateRegistry.createRegistry(SERVER_PORT);
} catch (RemoteException e) {
LocateRegistry.getRegistry(SERVER_PORT);
e.printStackTrace();
}
System.setProperty("java.rmi.server.hostname", SERVER_HOST);
connectionRequestHandler = new ConnectionRequestHandlerImpl();
dataRequestHandler = new DataRequestHandlerImpl();
String rmiUrl = "rmi://" + SERVER_HOST + ":" + SERVER_PORT + "/";
Naming.rebind(rmiUrl + "ConnectionRequestHandler", connectionRequestHandler);
Naming.rebind(rmiUrl + "DataRequestHandler", dataRequestHandler);
} catch (RemoteException e1) {
e1.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Then on client I am doing:
String rmiUrl = "rmi://" + SERVER_HOST + ":" + SERVER_PORT + "/";
try {
connectionRequestHandler = (ConnectionRequestHandler)Naming.lookup(rmiUrl + "ConnectionRequestHandler");
dataRequestHandler = (DataRequestHandler)Naming.lookup(rmiUrl + "DataRequestHandler");
} catch (MalformedURLException e) {
throw new RmiServicesDownException(e.getMessage());
} catch (RemoteException e) {
throw new RmiServicesDownException(e.getMessage());
} catch (NotBoundException e) {
throw new RmiServicesDownException(e.getMessage());
} catch (Exception e ){
e.printStackTrace();
return;
}
This is how it's working for me. Any other problems you may have are easy to solve compared to the first setup.
Short answer: the registry needs to have the stubs on its classpath.
Long answer: find an rmi tutorial from within the last 10 years which doesn't use rmic, cause you haven't need to do all that for a long time.
Change the AddServerImpl constructor to call super(0). Then you don't even need to generate a stub, let alone deploy it. See the preamble to the Javadoc of UnicastRemoteObject.
start rmiregistry from the server code directory. (or) Execute with -j option Please refer How do I set the classpath that rmiregistry uses? and javadoc reference [here]
I am currently working on a project about calculations.I have done the main part of my project,Also integrated SVN Commit function to my code (using .ini file to read the specific address etc. )
I can easily Commit the files, what I am trying is I want to implement the real-time log to my console. Is there any way to implement the log to the console ? Not the general log but the commit log which should be real time.
I am using eclipse for mac, I've heard about SVNKit but I am really poor about SVN.
Thanks in advance for any information
--- EDIT ---
This is the code for reading the svn commands from .ini file
public static String iniSVNOkut(String deger, String getObje, String fetchObje){
Ini uzantilariAlIni = null;
try
{
String uzantiAyarlari = "Uzantilar.ini";
try
{
uzantilariAlIni = new Ini(new FileReader(uzantiAyarlari));
}
catch (InvalidFileFormatException e)
{
System.err.print("Hata InvalidFileFormat : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch(FileNotFoundException e)
{
System.err.print("Hata FileNotFoundException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch (IOException e)
{
System.err.print("Hata IOException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
return deger = uzantilariAlIni.get(getObje).fetch(fetchObje);
}
finally
{
}
}
This is what .ini includes
[svnAdresi]
svnAdresiniAl = svn co http://svn.svnkit.com/repos/svnkit/trunk/ /Users/sample/Documents/workspace/SatirHesaplaGUI/svnTestMAC
This is how I call it
String svnAdresi;
svnAdresi = IniFonksiyon.iniSVNOkut(svnAdresi, "svnAdresi", "svnAdresiniAl");
Runtime cmdCalistir = Runtime.getRuntime();
try
{
Process islem = cmdCalistir.exec(svnAdresi);
}
catch (Exception e)
{
e.printStackTrace();
}
If I understand your question correctly, you want to read the Subversion commit log into your console application.
The easiest way is to use SVNKit.
Here's how I did it.
private static List<SVNLogEntry> logEntryList;
/*
* Gets the Subversion log records for the directory
*/
LogHandler handler = new LogHandler();
String[] paths = { directory };
try {
repository.log(paths, latestRevision, 1L, false, true, handler);
} catch (SVNException svne) {
if (svne.getMessage().contains("not found")) {
logEntryList = new ArrayList<SVNLogEntry>();
} else {
CobolSupportLog.logError(
"Error while fetching the repository history: "
+ svne.getMessage(), svne);
return false;
}
}
logEntryList = handler.getLogEntries();
directory - string pointing to a particular directory or module
latestRevision - largest revision number from Subversion. Placing the latestRevision second in the log method invocation returns the log records in most recent order.
If you want the log records in sequential order, from 1 to latestRevision, then the 1L would be placed second, and the latestRevision would be placed third.
repository - Subversion repository that you've already authenticated.
Here's LogHandler.
public class LogHandler implements ISVNLogEntryHandler {
protected static final int REVISION_LIMIT = 5;
protected List<SVNLogEntry> logEntryList;
public LogHandler() {
logEntryList = new ArrayList<SVNLogEntry>();
}
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
logEntryList.add(logEntry);
}
public List<SVNLogEntry> getLogEntries() {
if (logEntryList.size() <= REVISION_LIMIT) {
return logEntryList;
} else {
return logEntryList.subList(0, REVISION_LIMIT);
}
}
}
I'm trying to find a way to detect when a flash drive has been plugged into my computer. So far, the solution I found was to poll FileSystem#getFileStores for changes. This does indeed tell me when the flash drive has been inserted, but as far as I can tell there is no way to retrieve the location for it. FileStore#type and FileStore#name both seem highly unreliable as their return value is implementation specific, but they appear to be the only methods that might return any relevant information that might help find the directory for the FileStore.
With that in mind, the following code:
public class Test {
public static void main(String[] args) throws IOException {
for (FileStore store : FileSystems.getDefault().getFileStores()) {
System.out.println(store);
System.out.println("\t" + store.name());
System.out.println("\t" + store.type());
System.out.println();
}
}
}
Gave me this output:
/ (/dev/sda5)
/dev/sda5
ext4
/* snip */
/media/TI103426W0D (/dev/sda2)
/dev/sda2
fuseblk
/media/flashdrive (/dev/sdb1)
/dev/sdb1
vfat
As it turns out, FileStore#type returns the format of the drive and FileStore#name returns the location of the device file for the drive. As far as I can tell, the only method which has the location of the drive is the toString method, but extracting the path name out of it seems dangerous because I'm not sure how well that particular solution would hold up on other operating systems and future versions of Java.
Is there something I'm missing here or is this simply not possible purely with Java?
System Information:
$ java -version
java version "1.7.0_03"
OpenJDK Runtime Environment (IcedTea7 2.1.1pre) (7~u3-2.1.1~pre1-1ubuntu2)
OpenJDK Client VM (build 22.0-b10, mixed mode, sharing)
$ uname -a
Linux jeffrey-pc 3.2.0-24-generic-pae #37-Ubuntu SMP Wed Apr 25 10:47:59 UTC 2012 i686 athlon i386 GNU/Linux
Here's a temporary work around until a better solution is found:
public Path getRootPath(FileStore fs) throws IOException {
Path media = Paths.get("/media");
if (media.isAbsolute() && Files.exists(media)) { // Linux
try (DirectoryStream<Path> stream = Files.newDirectoryStream(media)) {
for (Path p : stream) {
if (Files.getFileStore(p).equals(fs)) {
return p;
}
}
}
} else { // Windows
IOException ex = null;
for (Path p : FileSystems.getDefault().getRootDirectories()) {
try {
if (Files.getFileStore(p).equals(fs)) {
return p;
}
} catch (IOException e) {
ex = e;
}
}
if (ex != null) {
throw ex;
}
}
return null;
}
As far as I know, this solution will only work for Windows and Linux systems.
You have to catch the IOException in the Windows loop because if there is no CD in the CD drive an exception is thrown when you try to retrieve the FileStore for it. This might happen before you iterate over every root.
This is what I have ended up doing. This is limited to Windows + UNIX but avoids using external tools or additional library calls. It steals the information Java already has in the FileStore objects
LinuxFileStore definitely extends UnixFileStore, so it will work. Same deal for Solaris. Since Mac OS X is UNIX, it probably works there but I'm not sure because I couldn't see its subclass in any place I was looking.
public class FileStoreHacks {
/**
* Stores the known hacks.
*/
private static final Map<Class<? extends FileStore>, Hacks> hacksMap;
static {
ImmutableMap.Builder<Class<? extends FileStore>, Hacks> builder =
ImmutableMap.builder();
try {
Class<? extends FileStore> fileStoreClass =
Class.forName("sun.nio.fs.WindowsFileStore")
.asSubclass(FileStore.class);
builder.put(fileStoreClass, new WindowsFileStoreHacks(fileStoreClass));
} catch (ClassNotFoundException e) {
// Probably not running on Windows.
}
try {
Class<? extends FileStore> fileStoreClass =
Class.forName("sun.nio.fs.UnixFileStore")
.asSubclass(FileStore.class);
builder.put(fileStoreClass, new UnixFileStoreHacks(fileStoreClass));
} catch (ClassNotFoundException e) {
// Probably not running on UNIX.
}
hacksMap = builder.build();
}
private FileStoreHacks() {
}
/**
* Gets the path from a file store. For some reason, NIO2 only has a method
* to go in the other direction.
*
* #param store the file store.
* #return the path.
*/
public static Path getPath(FileStore store) {
Hacks hacks = hacksMap.get(store.getClass());
if (hacks == null) {
return null;
} else {
return hacks.getPath(store);
}
}
private static interface Hacks {
Path getPath(FileStore store);
}
private static class WindowsFileStoreHacks implements Hacks {
private final Field field;
public WindowsFileStoreHacks(Class<?> fileStoreClass) {
try {
field = fileStoreClass.getDeclaredField("root");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("file field not found", e);
}
}
#Override
public Path getPath(FileStore store) {
try {
String root = (String) field.get(store);
return FileSystems.getDefault().getPath(root);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Denied access", e);
}
}
}
private static class UnixFileStoreHacks implements Hacks {
private final Field field;
private UnixFileStoreHacks(Class<?> fileStoreClass) {
try {
field = fileStoreClass.getDeclaredField("file");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("file field not found", e);
}
}
#Override
public Path getPath(FileStore store) {
try {
return (Path) field.get(store);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Denied access", e);
}
}
}
}
I've not really explored this area of java, but I found this, which seems to be related. It uses File.listRoots()
There also seems to be a number of related questions linked there too.
This works for Windows:
public Path getFileStoreRootPath(FileStore fs) throws Exception {
for (Path root : FileSystems.getDefault().getRootDirectories()) {
if (Files.isDirectory(root) && Files.getFileStore(root).equals(fs)) {
return root;
}
}
throw new RuntimeException("Root directory for filestore " + fs + " not found");
}
Basically, by filtering by condition Files.isDirectory(root) we are excluding all CD/DVD drives which will throw IOException when compact-disc is not inserted.
I am trying to use Reflection on the server side only of a GWT app. I have a basic example working in a non-GWT example which can be seen below.
package com.xyz.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class EntryPoint {
/**
* #param args
*/
public static void main(String[] args) {
ClassLoader dynClassLoader = ClassLoader.getSystemClassLoader();
Class<?> dynClass = null;
try {
dynClass = dynClassLoader.loadClass("com.xyz.reflection.RunMe");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Object dynInstance = null;
try {
dynInstance = dynClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Method dynMethod = null;
try {
try {
dynMethod = dynInstance.getClass().getMethod("returnSid",
new Class[] { PassMe.class });
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
String returnValue = (String) dynMethod.invoke(dynInstance,
new Object[] { new PassMe() });
System.out.println("Return Value: " + returnValue.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
using the aptly named:
package com.xyz.reflection;
public class PassMe {
private String sid = "DEFAULT_SID";
public PassMe() {
this.sid = "INITIATED_SID";
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
}
and:
package com.xyz.reflection;
public class RunMe {
public String returnSid(PassMe s) {
return s.getSid();
}
}
This runs fine. When I try running this from a GWT server side class it doesn't work, and instead returns
java.lang.NoSuchMethodException: com.xyz.reflection.RunMe.returnSid(com.xyz.reflection.PassMe)
If I change the parameter to a String (instead of the 'PassMe' class) it works fine. Why does it not like passing my 'PassMe' class? I thought it might be an issue with serialization despite being 100% server code, but I haven't had any luck with this either.
Thanks in advance for any help anyone can give me with this.
In addition to finrod's solution, you can also change your class loader to something like:
ClassLoader dynClassLoader = PassMe.class.getClassLoader();
And you can use the PassMe.class style lookup again. The class used to find a loader doesn't seem to matter though. Just not the system loader.
Weird stuff. I wouldn't doubt if GWT is doing something weird with the class loader though.
Edit: Yep. GWT sets the system class loader to com.google.appengine.tools.development.IsolatedAppClassLoader in dev mode.
I think this could be related to Class loading - but it is just a hunch as I cannot experiment with it in context similar to yours.
Here are some suggestions to try:
You use:
ClassLoader dynClassLoader = ClassLoader.getSystemClassLoader();
dynClass = dynClassLoader.loadClass("com.xyz.reflection.RunMe");
To load the RunMe Class.
However to load the PassMe class you use:
PassMe.class
Try to load the PassMe Class through the dynClassLoader and use that instance in the getMethod() instead of the PassMe.class.
I wonder, do you need to use the dynClassLoader?
This is pretty much a shot in the dark, but does it help if you replace
dynMethod = dynInstance.getClass().getMethod("returnSid",
new Class[] { PassMe.class });
with
dynMethod = dynInstance.getClass().getMethod("returnSid", PassMe.class );
?
It doesn't make a difference outside of a GWT server, but it may exercise the container's VM differently.
Did you put your reflection file in the server side package?
For example:
org.myproject.client - your gwt client package (put here your java files that are able to be complied into java script NO REFLECTION)
org.myproject.server - put here any java files including reflection
org.myproject.shared - put here java classes that are able to be compiled into java script