Is there any way I can get a system process and listen to it so I can get what it's doing? An example of what Im looking for is this:
RunningProcess proc = new RunningProcess("notepad.exe");
ProcListener procListener = new ProcListener(proc);
Listener class example:
public class ProcListener implements ProcessListener {
public ProcListener(...) {
}
#Override
public void started() {
}
#Override
public void terminated() {
}
#Override
public void ioOperation(IOoperation iop){
}
}
Is there something like that? I haven't found yet.
If you just want to run your jar whenever another program is started or terminated, I recommend using Bill2's Process Manager. Although this is not a Java way to do, it can launch a program or batch file when some processes started/terminated, and you can execute the jar using batch file. After installing, you may want to change the language in Options first. The software is simple and quite easy to use.
Related
What I am trying to achieve:
I want to make a dropwizard client that polls Amazon SQS.
Whenever a message is found in the queue, it is processed and stored.
Some information about the processed messages will be available through an API.
Why I chose Dropwizard:
Seemed like a good choice to make a REST client. I need to have metrics, DB connections and integrate with some Java services.
What I need help with:
It is not very clear how and where the SQS polling will fit in a typical dropwizard application.
Should it be a managed resource? Or a console reporter console-reporter? Or something else.
You can use com.google.common.util.concurrent.AbstractScheduledService to create a consumer thread and add it to the dropwizard's environment lifecycle as ManagedTask. Following is the pseudocode -
public class YourSQSConsumer extends AbstractScheduledService {
#Override
protected void startUp() {
// may be print something
}
#Override
protected void shutDown() {
// may be print something
}
#Override
protected void runOneIteration() {
// code to poll on SQS
}
#Override
protected Scheduler scheduler() {
return newFixedRateSchedule(5, 1, SECONDS);
}
}
In Main do this -
YourSQSConsumer consumer = new YourSQSConsumer();
Managed managedTask = new ManagedTask(consumer);
environment.lifecycle().manage(managedTask);
As an alternative to RishikeshDhokare's answer, one can also go ahead with the following code which does not need to include additional jar as a dependency in your project to keep the uber jar as much lightweight as possible.
public class SQSPoller implements Managed, Runnable {
private ScheduledExecutorService mainRunner;
#Override
public void start() throws Exception {
mainRunner = Executors.newSingleThreadScheduledExecutor()
mainRunner.scheduleWithFixedDelay(this, 0, 100, TimeUnit.MILLISECONDS);
}
#Override
public void run() {
// poll SQS here
}
#Override
public void stop() throws Exception {
mainRunner.shutdown();
}
}
And in the run() of your Application class, you can register the above class as follows.
environment.lifecycle().manage(new SQSPoller());
You can use either scheduleWithFixedDelay() or scheduleAtFixedRate() depending upon your use case.
I am looking for a blocking version of AtomicReference to avoid such active waiting:
AtomicReference<Object> ref = new AtomicReference<Object>();
// execute some code in a different thread and set the reference
Object o;
while ((o = ref.get()) == null);
// continue execution
Java provides a Future interface, which blocks in get() method. But I cannot use that part of concurrent package because the reference should be set by a framework where the usage of a simple listener is expected.
To be more precise I work with the launching framework in Eclipse. I fire a maven launch via org.eclipse.m2e.actions.ExecutePomAction but I don't have a directly access to its process because it's hidden deeply in JDT. That's why I'm using Eclipse's launch manager for that purpose:
final ILaunchManager launchMan = DebugPlugin.getDefault().getLaunchManager();
launchMan.addLaunchListener(new ILaunchListener() {
public void launchRemoved(ILaunch launch) {
ILaunchConfiguration conf = launch.getLaunchConfiguration();
if (("Executing install in "+proj.getLocation().toOSString().replace('\\', '-')).equals(conf.getName()))
{
IProcess[] processes = launch.getProcesses();
if (processes.length == 1)
procRef.set(processes[0]);
}
launchMan.removeLaunchListener(this);
}
});
I think there is no other way to use active waiting afterwards, because IProcess provides no possibility to listen on its termination. Kinda like this:
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
while (!proc.isTerminated())
Thread.sleep(500);
}
});
This question has basically something common with [eclipse pde]How to catch the event that a launch is terminated? but it's quite old and I provided here more information on my investigations.
You can use DebugPlugin.getDefault().addDebugEventFilter(filter) to set up an IDebugEventFilter class.
This is given all the debug / run events include the DebugEvent.TERMINATE event when a launch terminates.
I also found another way to do it with a launch manager. I just had to use another listener interface:
final ILaunchManager launchMan = DebugPlugin.getDefault().getLaunchManager();
launchMan.addLaunchListener(new ILaunchesListener2()
{
public void launchesTerminated(ILaunch[] launches)
{
for (ILaunch launch : launches) {
ILaunchConfiguration conf = launch.getLaunchConfiguration();
if (("Executing install in "+proj.getLocation().toOSString().replace('\\', '-')).equals(conf.getName()))
{
//my maven launch is terminated!
}
}
}
});
I need to make a program, which can be executed in single instance. I tried to create a temporary file and delete it before exit program.
public static boolean isLocked() {
File f = new File("lock.txt");
return f.exists();
}
public static void lock() {
String fname = "lock.txt";
File f = new File(fname);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void unlock() {
File f = new File("lock.txt");
f.delete();
}
In frame
private void initialize() {
lock();
}
private void setFrameHandler() {
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
unlock();
}
});
}
Problem occurs if program is finished with emergency (e.g. electricity cuts). File does not remove, and running a new instance is impossible.
How to make a reliable single-instance verification?
You could check for another instance of the program at startup using the GetProcesses method as described here
But that only works depending on the scenario you have (might not see all processes of other users)
Another thing you could do is simply checking, if a specific file is locked via File.Open
File.Open ("path.lock", FileMode.OpenOrCreate, FileAccess.ReadWrite);
As long as you keep the resulting FileStream open in your program no other program can open the file in that mode either. This is basically how Unix lock files work too. Of course you have to catch an IOException (hinting you to a locked file).
Disclaimer: I did not try that code out so please check if I gave you the right parameters.
Edit: You could also check out this Code-Project article on how to do it with the win32 API
Another attempt using windows messaging has been done here
A simple approach to this on a single machine is to write a 'PID file', which is literally a file containing the operating system's ID of the process currently running. You create this when you start your "critical" work, and remove it on successful completion.
Since it is unlikely that the process would be started again with the same PID, you can simply check to see if the PID file already exists, and if so, if that process is still running.
Sorry if this was asked, but I keep wondering and weren't able to google up solution and not for luck of trying.
When implementing Command pattern inside one class, this one-method interface keeps popping up in all places.
public interface Command {
void execute();
}
Then it gets reused plenty of times like this:
public void doAction1()
{
perform(new Command () {
#Override
public void execute()
{
//do some crazy stuff
}
});
}
public void doAction2()
{
perform(new Command () {
#Override
public void execute()
{
//do some event crazier stuff
}
});
}
public void doAction3()
{
perform(new Command () {
#Override
public void execute()
{
//do a barrel roll
}
});
}
private void perform(Command command)
{
command.execute();
}
Different namings, different modules, different software even --- but this one gets reimplemented over and over, cluttering source and doing essentially nothing new.
Is there any generic, OOB one-method interface that's OK to use instead of creating my own every time I need lambda-like sentence? Is it OK to use Runnable in this way? Wouldn't it create confusion in the mind of some future source code-reader?
PS: Now, I know, that there's java 1.8 with lambdas and all, but at my work we're stuck with 1.6 for the moment (enterprise customers are so enterprise), so I'd appreciate some archeological help here.
Yes, Runnable or Callable (if you need to return a result) are perfectly fine to use.
The class example below MyAppender is called from the logback.xml file.
When the append() is called by logback i have no reference to the
class MyAppenderso i cannot attach any Observer or register a Listener
Does logback have some Listener the Swing gui can register or what should i do?
Have been reading the logback manual but i cannot figure this out.
public class MongoAppender extends AppenderBase<ILoggingEvent> {
public MongoAppender () {
}
#Override
public void start() {
super.start();
}
public void append(ILoggingEvent event) {
// Inserting log event into MongoDb
// just got an error...
// how do i send this error back to Swing Gui?
}
}
In the append i did not make and call to the gui.
I ended up writing to the DB whatever needed to be saved.
This of course is cleaner and safer then having classes trying to
address each other.