Check for open GUI Instance - java

I was wondering if it is possible to check whether there is an instance of an object(my gui) open in Java and if so how I would be able to find it?

You can use following code if this question is for swing window like JFrame or JDialog,
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
if (win[i].getName().equals("YourWindowName"))
isOpen = true;
break;
}
For this ypu need to give name to your JFrame and if that matches with open windows it will set true and return.

I used RMI to solve the same problem. My application creates Registry and places a lock object there after start. If lock object is already there at that time then it sends message via RMI to existing application and terminates. The sent message triggers existing application to move its window on top. Here is the code
public static void main(String[] args) {
RmiManager rmiManager = new RmiManager();
rmiManager.createRmiRegistry();
if(rmiManager.isAlreadyRunning()) {
logger.error("Another application instance is running! Exit");
System.exit(0);
return;
}
rmiManager.registerApplication();
}
RmiManager.java which is actually responsible for all the stuff
package myapp;
import java.rmi.AccessException;
import java.rmi.AlreadyBoundException;
import java.io.File;
import java.io.IOException;
import java.rmi.registry.LocateRegistry;
import java.rmi.NotBoundException;
import java.rmi.registry.Registry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import org.apache.log4j.Logger;
public class RmiManager {
private static final String LOCK_OBJECT_NAME = "myapp";
private static final Logger logger = Logger.getLogger(RmiManager.class);
public void createRmiRegistry() {
try {
logger.debug("Creating RMI registry...");
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
logger.debug("RMI registry was created");
} catch (RemoteException e) {
logger.debug("RMI registry is already created");
}
}
public boolean isAlreadyRunning() {
try {
logger.debug("Checking if application is already running. Looking for RMI registry...");
Registry registry = LocateRegistry.getRegistry();
logger.debug("RMI registry obtained. Looking for RmiListener: " + LOCK_OBJECT_NAME + "...");
try {
IRmiListener rmiListener = (IRmiListener) registry.lookup(LOCK_OBJECT_NAME);
logger.debug("RmiListener got. Checking...");
boolean isAlreadyRunning = rmiListener.isAlreadyRunning();
logger.debug("IsAlreadyRunning result: " + isAlreadyRunning);
return isAlreadyRunning;
} catch (AccessException e) {
logger.error("Error accessing RMI registry!", e);
return false;
} catch (NotBoundException e) {
logger.debug("RMI listener wasn't found. There are no other application instances running");
return false;
}
} catch (RemoteException e) {
logger.error("RemoteException!", e);
return false;
}
}
public void registerApplication() {
try {
logger.debug("Registering application...");
RmiListenerImpl rmiListenerImpl = new RmiListenerImpl();
logger.debug("Exporting RmiListener object...");
IRmiListener rmiListener = (IRmiListener) UnicastRemoteObject.exportObject(rmiListenerImpl, Registry.REGISTRY_PORT);
logger.debug("RmiListener object was exported. Looking for RMI registry...");
Registry registry = LocateRegistry.getRegistry();
logger.debug("RMI registry found");
try {
logger.debug("Binding RmiListener to " + LOCK_OBJECT_NAME + "...");
registry.bind(LOCK_OBJECT_NAME, rmiListener);
logger.debug("RmiListener binding was done. Application registration complete.");
} catch (AccessException e) {
logger.error("AccessException!", e);
} catch (AlreadyBoundException e) {
logger.error("RmiListener object is already bind", e);
}
} catch (RemoteException e) {
logger.error("RemoteException!", e);
}
}
}
IRmiListener.java
package myapp;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IRmiListener extends Remote {
boolean isAlreadyRunning() throws RemoteException;
}
RmiListenerImpl.java
package myapp;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
public class RmiListenerImpl implements IRmiListener {
private static final Logger logger = Logger.getLogger( RmiListenerImpl.class );
#Override
public boolean isAlreadyRunning() throws RemoteException {
// here I notify my GUI class to pop up the window
return true;
}
}
It can be more simple I think.

Assuming that by "open UI objects" you mean Swing dialogs and frames, it is better to design the application in a way that would remove the need to look for open instances all together.
This can be achieved by providing a factory that would produce application dialogs and frames instead of using something like new JFrame. This factory would register the produced instances internally and would serve as a single point of reference for all "open UI objects".
Although, be careful when implementing such solution as every registered object would have one additional reference preventing GC from collecting the allocated memory as intended. Please used weak references (weak reference map) for caching. A good blog post about different kinds of Java references can be found here.
This way if you need to find an open UI object, simply request your factory to provide a list of open instances.

Related

NotBoundException when I'm trying to connect with RMI server

I try to launch this app using RMI client-server.
Firstly, I ran it and had the error "Connection refused to host: localhost".
After that I went go system32/drivers/etc/hosts and fix it, added line:
127.0.0.1 localhost
It wasn't led me to problem solution.
Then I looked up same questions in stackoverflow about how to fix this problem, then solved it with (ran in cmd):
start rmiregistry
So, rmiregistry ran and i had got a new error - NotBoundException (but I could fix "Connection refusal" problem).
servicebrowser.java:
package servicebrowser;
import java.awt.*;
import javax.swing.*;
import java.rmi.*;
import java.awt.event.*;
public class ServiceBrowser {
JPanel mainPanel;
JComboBox serviceList;
ServiceServer server;
public void buildGUI() {
Object[] services = getServicesList();
}
Object[] getServicesList() {
Object obj = null;
Object[] services = null;
try {
obj = Naming.lookup("rmi://127.0.0.1/ServiceServer");
}
catch (Exception ex) { ex.printStackTrace(); }
server = (ServiceServer) obj;
try {
services = server.getServiceList();
}
catch (Exception ex) { ex.printStackTrace(); }
return services;
}
class MyListListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
Object selection = serviceList.getSelectedItem();
loadService(selection);
}
}
public static void main(String[] args) {
new ServiceBrowser().buildGUI();
}
}
class ServiceServerImpl:
import java.rmi.*;
import java.util.*;
import java.rmi.server.*;
public class ServiceServerImpl extends UnicastRemoteObject
implements ServiceServer {
HashMap serviceList;
public ServiceServerImpl() throws RemoteException {
setUpServices();
}
private void setUpServices() {
serviceList = new HashMap();
}
public Object[] getServiceList() {
System.out.println("in remote");
return serviceList.keySet().toArray();
}
public Service getService(Object serviceKey) throws RemoteException {
Service theService = (Service) serviceList.get(serviceKey);
return theService;
}
public static void main (String[] args) {
try {
Naming.rebind("ServiceServer", new ServiceServerImpl());
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Remote service is running");
}
}
What is wrong with it? I turned off firewall too, certaintly.
Thanks a lot!
I solved my problem right this way.
Firstly, I edited classes servicebrowser, ServiceServerImpl.
class servicebrowser:
Before:
try {
obj = Naming.lookup("rmi://127.0.0.1/ServiceServer");
}
Now (plus I added import java.rmi.registry.LocateRegistry, import java.rmi.registry.Registry in top part of code):
try {
Registry registry = LocateRegistry.getRegistry("127.0.0.1", 10001);
obj = registry.lookup("ServiceServer");
}
class ServiceServerImpl:
Before:
try {
Naming.rebind("ServiceServer", new ServiceServerImpl());
}
Now (like a previous class I added import classes in top part of code):
try {
Registry registry = LocateRegistry.createRegistry(10001);
registry.bind("ServiceServer", new ServiceServerImpl());
}
Secondly, I try to ran project (F6) in Netbeans, where servicebrowser marked as main class. It was refusal connection again. After that I only ran class ServiceServerImpl (Shift + F6) then ran entire projecе. So, it works.
P.S. I didn't use cmd and try to
"start rmiregistry"
because the app works without it.

Bukkit Register Commands in Runtime

I am trying to register a bukkit Command on the other Command.
So I want to make "/command1" to register "/command2" so command 2 only can execute after I executed command 1.
I tried for like 10 hours by now to do that, at the moment I am able to register a command without making it into the plugin.yml and that works, just the second command does not get registered.
Main class:
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap;
import org.bukkit.plugin.SimplePluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
public class Main extends JavaPlugin {
#Getter
CommandMap commandMap;
#Override
public void onEnable() {
loadCommandMap();
this.commandMap.register("command1", new FirstCommand(this));
}
private void loadCommandMap() {
try {
if (Bukkit.getPluginManager() instanceof SimplePluginManager) {
Field f = SimplePluginManager.class.getDeclaredField("commandMap");
f.setAccessible(true);
this.commandMap = (CommandMap) f.get(Bukkit.getPluginManager());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
FirstCommand:
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public class FirstCommand extends Command {
private Main plugin;
public FirstCommand(Main plugin) {
super("command1");
this.plugin = plugin;
}
#Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
plugin.getCommandMap().register("command2", new SecondCommand());
sender.sendMessage("Command 1.");
return true;
}
}
Second Command:
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public class SecondCommand extends Command {
public SecondCommand() {
super("command2");
}
#Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
sender.sendMessage("Command 2");
return true;
}
}
I really hope someone knows why the first command gets registered but the second one does not.
You could try to not register them at runtime, but enable them at runtime.
You can use global, static variables (for example in the main class of your app), e.g.
// in your class "Main"
public static boolean isCommand2Enabled = false;
and when command1 is called, you set it to true
Main.isCommand2Enabled = true;
Your command2 must now only check whether it has already been activated and can be executed:
if(!Main.isCommand2Enabled) {
// I am not activated yet and must return
return false;
}
But I am not quite sure if you might try to define the name of command2 first when command1 is executed (variable command name). You should then maybe use a fixed command and only make the corresponding argument variable.
I don't really understand what you are talking about, but I think this may help you...
Bukkit Tutorial - Registering Commands At Runtime

Wildfly 10.x remote EJB client hangs when sending an enum value with CONNECT in the name

I've got a simple stateless EJB with a method that takes a basic enum as an argument and returns the same enum.
#Stateless
#LocalBean
public class SerialBean implements RemoteSerial {
#Override
public Whatever enumTest(Whatever type) {
return type;
}
}
Here's the simple enum:
public enum Whatever {
TEST,
CONNECT_TEST
}
And a simple client:
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
jndiProps.put("jboss.naming.client.ejb.context", true);
try {
Context ctx = new InitialContext(jndiProps);
RemoteSerial serial = (RemoteSerial)ctx.lookup("rmi_test/rmi_ejb/SerialBean!test.RemoteSerial");
System.out.println(serial.enumTest(Whatever.TEST));
System.out.println(serial.enumTest(Whatever.CONNECT_TEST));
} catch (NamingException ex) {
ex.printStackTrace();
}
When I run this code, the client successfully connects to WildFly and returns the first result (TEST). However, the client then freezes when performing the second method call (CONNECT_TEST). No response is received.
If I change the name of CONNECT_TEST to something that doesn't have CONNECT in it, the code works. I can even change CONNECT to cONNECT and that works.
I've tried this in both 10.0 and 10.1 on Windows 7 using jdk1.8.0_102 and 121.
What could possibly be going on here?
I was unable to reproduce your results. For comparison, here's my code, in full.
Server (ejb module rmi_test):
TestEnum.java
package com.example.rmitest;
public enum TestEnum {
TEST, CONNECT_TEST
}
SerialBean.java
package com.example.rmitest;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
#Stateless
#LocalBean
public class SerialBean implements RemoteSerial {
#Override
public TestEnum enumTest(TestEnum input) {
return input;
}
}
RemoteSerial.java
package com.example.rmitest;
import javax.ejb.Remote;
#Remote
public interface RemoteSerial {
TestEnum enumTest(TestEnum input);
}
Client (standalone JSE app, with wildfly-10.1.0.Final/bin/client/jboss-client.jar on it's classpath):
Client.java
package com.example.rmitest;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class Client {
public static void main(String... args) {
RemoteSerial remoteSerial = lookupRemoteService();
System.out.println(remoteSerial.enumTest(TestEnum.TEST));
System.out.println(remoteSerial.enumTest(TestEnum.CONNECT_TEST));
}
private static RemoteSerial lookupRemoteService() {
try {
return (RemoteSerial) jndiConnect().lookup("/rmi_ejb/SerialBean!com.example.rmitest.RemoteSerial");
} catch (NamingException e) {
throw new RuntimeException("Failed to lookup a remote interface", e);
}
}
private static Context jndiConnect() {
try {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
properties.setProperty(Context.PROVIDER_URL, "http-remoting://localhost:8080");
properties.setProperty("jboss.naming.client.ejb.context", "true");
return new InitialContext(properties);
} catch (NamingException e) {
throw new RuntimeException("Failed to establish a connection", e);
}
}
}
And finally, my console output:
TEST
CONNECT_TEST

java.lang.NoClassDefFoundError

I have no idea of why this is having a runtime error, I have googled the problem and it says that a class that was available during compile time is no longer available at run time.
This is the code:
package examples.RMIShape;
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
//import java.rmi.server.UnicastRemoteObject;
public class ShapeListServer {
public static void main(String args[]){
// System.setSecurityManager(new RMISecurityManager());
System.out.println("Main OK");
try{
ShapeList aShapelist = new ShapeListServant();
System.out.println("After create");
String registryURL = "rmi://localhost:" + "/ShapeList";
startRegistry();
Naming.rebind(registryURL, aShapelist);
System.out.println("ShapeList server ready");
}catch(Exception e) {
System.out.println("ShapeList server main " + e.getMessage());
}
}
// This method starts a RMI registry on the local host, if it
// does not already exists at the specified port number.
private static void startRegistry()throws RemoteException{
Registry registry;
try {
registry = LocateRegistry.getRegistry();
registry.list( ); // This call will throw an exception
// if the registry does not already exist
}
catch (RemoteException e) {
// No valid registry at that port.
System.out.println ("RMI registry cannot be located at port " + Registry.REGISTRY_PORT );
registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
System.out.println("RMI registry created at port " + Registry.REGISTRY_PORT);
}
} // end startRegistry
}
I have googled the problem and it says that a class that was available during compile time is no longer available at run time.
That's not correct. That would cause ClassNotFoundException. This one has several causes, but the most common one is that the class in the file isn the class implied by the filename and directory hierarchy.
Basicall java.lang.NoClassDefFoundError thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
following links will be helpful. This links will guide you slove issue.
http://javarevisited.blogspot.in/2011/06/noclassdeffounderror-exception-in.html
http://javaeesupportpatterns.blogspot.in/2012/06/javalangnoclassdeffounderror-how-to.html
Hope this will be helpful

Android Phone as Realtime MJPEG Video Server

I'm trying to use my phone as a realtime MJPEG video source. So far, capturing frames and converting them into JPEGs is no big deal. My real issue is sending the multipart response properly. There's tons of documentation about sending multipart responses out there, but the issue with them is that they all expect that all of the images are available at the time the HTTP request comes in (such as would be used for a multi-image upload). In order to stream in realtime, of course, I need to be able to begin to send the multipart response while continually adding jpegs in the body. I'm by no means a HTTP buff, so it's not desirable for me be required to roll my own HTTP response and write directly to a socket. Is there a library out there that supports this kind of behavior? I've scoured the internet for solutions, but I really don't see anything useful out there.
Any ideas? Worst case scenario, I'd be willing to look at human-readable documentation of how to write a multipart response by hand, but I'd really just rather use a library if that's possible.
Thanks in advance.
edit: got it working using the orielly servlet library as per sigmavirus' suggestion. Note that the MJPEG stream is more or less implicitly inferred from the fact that I'm sending a multipart/x-mixed-replace that only has image/jpeg's in it. Check out the comment in my code for a tutorial that shows what jetty libraries you'll need to get this running. Of course, you'll additionally need cos.jar, the Orielly servlet library. The code follows:
package edu.stevens.arpac.webclient;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.conn.util.InetAddressUtils;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.Request;
import com.oreilly.servlet.MultipartResponse;
import com.oreilly.servlet.ServletUtils;
import android.os.Environment;
import android.util.Log;
// holla at http://puregeekjoy.blogspot.com/2011/06/running-embedded-jetty-in-android-app.html
public class JettyServer extends Thread
{
private static final String TAG = "JettyServer";
private Server webServer;
private Boolean isStarted = false;
public JettyServer()
{
super();
Log.i(TAG, "Initializing server to port 8080");
webServer = new Server(8080);
Handler handler = new AbstractHandler() {
public void handle(String target, Request request, HttpServletRequest servletRequest,
HttpServletResponse servletResponse) throws IOException, ServletException {
ServletOutputStream out = servletResponse.getOutputStream();
MultipartResponse multi = new MultipartResponse(servletResponse);
Boolean go = true;
while( go )
{
try
{
multi.startResponse("image/jpeg");
ServletUtils.returnFile(Environment.getExternalStorageDirectory().getPath() + "/ARPac/twi.jpg", out);
multi.endResponse();
}
catch(IOException ex)
{
go = false;
Log.i(TAG, "IO Failed with exception " + ex.getMessage());
}
}
request.setHandled(true);
}
};
webServer.setHandler(handler);
try {
webServer.start();
Log.d(TAG, "started Web server # " + getIPAddress());
isStarted = true;
}
catch (Exception e) {
Log.d(TAG, "unexpected exception starting Web server: " + e);
}
}
/**
* Get IP address from first non-localhost interface
* #return address or empty string
*/
private String getIPAddress()
{
try
{
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces)
{
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs)
{
if (!addr.isLoopbackAddress())
{
String sAddr = addr.getHostAddress().toUpperCase();
if (InetAddressUtils.isIPv4Address(sAddr))
{
//Log.d(TAG, "IP address is: " + sAddr);
return sAddr;
}
}
}
}
}
catch (Exception ex)
{
Log.e(TAG, "could not get IP address: " + ex.getMessage());
} // for now eat exceptions
Log.e(TAG, "Could not find a non-loopback IPv4 address!");
return "";
}
public void teardown()
{
if( isStarted )
{
try {
webServer.stop();
isStarted = false;
} catch (Exception e) {
Log.e(TAG, "Couldn't stop server. Probably was called when server already stopped.");
}
}
}
public void run()
{
}
}
Have you seen this? http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartResponse.html It looks like the example sends each part individually and waits a specified time limit before sending the next or receiving an interrupt.

Categories

Resources