Using Java program I am opening an external application( for example: notepad). How can i get coordinates/location of external application for screen capture/screen-shots.
I can take screen-shots of the whole window, but not for a particular application.
I have already tried "Robot" for screen capturing but not able to capture a particular area as I am not able to find the location and size of the application window.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
public class AppCheck {
public static void main(String[] args) {
System.out.println("***********************");
try {
System.out.println("Opening notepad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("notepad");
try {
int count=0;
while(process.isAlive())
{
System.out.println("process name : " + process.getClass().getName());
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
System.out.println("Process ID : " + handl);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing notepad");
process.destroy();
} catch (Exception ex) {
System.out.println(ex);
}
System.out.println("************************************");
}
}
Related
I try to run the *.bat files of derby, but I can't do this.
I want to run the "startNetworkServer.bat" and "ij.bat" using by java code.
I try to write some simple code but it not working.
package dbconnect;
import java.io.IOException;
public class RunDerbyTools {
public static void main(String[] args) {
String pathIj, pathStartNetwork, pathStopNetwork;
pathIj = "C:/MyWorkSpace/MyDBProject/db/bin/ij.bat"; // running ij tool
// running network
pathStartNetwork = "C:/MyWorkSpace/MyDBProject/db/bin/startNetworkServer.bat";
// stop network
pathStopNetwork = "C:/MyWorkSpace/MyDBProject/db/bin/stopNetworkServer.bat";
try {
Process pStartNetwork = Runtime.getRuntime().exec(pathStartNetwork);
} catch (IOException e) {
e.printStackTrace();
}
try {
Process pPathIj = Runtime.getRuntime().exec(pathStartNetwork);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am doing a small project for my girlfriends grandparents, that have a hard time using a computer so I thought I would be able to write something that might fix their problem. Here is the code first off:
import java.io.IOException;
public class OpenWordPad {
public static void main(String[] args) {
try {
System.out.println("Opening WordPad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("wordpad");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing WordPad");
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(had to indent some so sorry if it is a little wonky)
When I put notepad in the process line it works fine but when I put in wordpad it freaks out. I want to be able to open wordpad so I can put it on their computer. Any suggestions?
For that you can use runTime.exec("write"):
import java.io.IOException;
public class OpenWordPad {
public static void main(String[] args) {
try {
System.out.println("Opening WordPad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("write"); // <--- here
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing WordPad");
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
opens WordPad.
How to release process resource??
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.StringTokenizer;
public class RuntimeSample{
public RuntimeSample() {
}
private void execCmd1() throws IOException {
InputStream in = null;
Process process = null;
String[] cmd = { "java", "-version" };
try {
process = Runtime.getRuntime().exec(cmd);
in = process.getInputStream();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
}
private void execCmd2() throws IOException {
Process process = null;
String[] cmd = { "java", "-version" };
try {
process = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
why it is throwing process.getError stream is not closed,I tried to close process resource by using following
if (process != null) {
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
even it is showing process.getError stream is not closed.may i know the reason y it is showing that stream is not closed and how to close the process resource.Thanks in advance
I know this answer is somewhat late, but maybe someone else runs into the same issue.
In my project the Server runs some utility (I call it winps.exe here) regularly and it was easy to see (using RAMMAP resp. Handles) that the Java process kept a handle to each of the (terminated) child processes. Restarting the Server removed all entries from the process table.
After some experimenting, I found that explicitly calling the Garbage Collector resolved the issue.
Below you find my Java test program which I used to investigate the matter.
Note that this test program has been copied from the Server source code and isn't 100% as cleanly written as possible.
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.text.*;
import java.lang.reflect.*;
import java.util.concurrent.TimeUnit;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class StartPS
{
static Long STARTTIME_JITTER = 5000L;
synchronized public static HashMap<String,Long> getStartTimes()
{
HashMap<String,Long> result = new HashMap<String, Long>();;
final File tmp_file = new File("/tmp/starttimes.out");
String tmpfilename = null;
try {
tmpfilename = tmp_file.getCanonicalPath();
} catch (Exception e) {}
try {
ProcessBuilder pb = new ProcessBuilder(".\\winps.exe");
pb.redirectOutput(new File(tmpfilename));
pb.redirectErrorStream(true);
Process p = pb.start();
p.getOutputStream().close();
p.getInputStream().close();
p.getErrorStream().close();
try {
p.waitFor();
} catch (InterruptedException ie) {
// maybe some cleanup here
}
try {
while (p.isAlive()) { // <- most likely unnecessary ;-)
Thread.sleep(100);
p.destroy();
System.gc();
}
p = null; // should help the garbage collector (eliminates a reference to the object p points to)
System.gc(); // <- most likely the key to success !
} catch (Exception e) {
System.out.println("Warning: " + e.toString());
}
} catch (Exception e) {
throw new RuntimeException("(02310251044) Process start times : " + e.toString());
}
return result;
}
public static void main(String[] argv)
{
String sMax;
int iMax = 500;
if (argv.length > 0) {
sMax = argv[0];
try {
iMax = Integer.parseInt(sMax);
} catch (Exception e) {
System.out.println("Oops : " + e.toString());
System.exit(1);
}
}
for (int i = 0; i < iMax; ++i) {
System.out.print("\r" + i);
getStartTimes();
try {
Thread.sleep(1000);
} catch (Exception e) {
// do nothing
}
}
}
}
I'm trying to prevent the launching multiple instances of a java application by binding a ServerSocket.
Currently I'm executing it in my main as seen below:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(65535, 10);
showFrame();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
It isn't working as in Eclipse I can still open two instances of the application.
There are some crons of using network socket.
What if the socket is used by other apps?
What if there is warning from firewall, which comes with some anti-virus?
Using an exclusive locked file seems to be more reliable.
AppLock.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// http://jimlife.wordpress.com/2008/07/21/java-application-make-sure-only-singleone-instance-running-with-file-lock-ampampampampamp-shutdownhook/
public class AppLock {
private static File f;
private static FileChannel channel;
private static FileLock lock;
public static boolean lock() {
try {
String directory = Utils.getUserDataDirectory();
String fileName = "jstock.lock";
Utils.createCompleteDirectoryHierarchyIfDoesNotExist(directory);
f = new File(directory + fileName);
// Do we need these code?
//if (f.exists()) {
// f.delete();
//}
channel = new RandomAccessFile(f, "rw").getChannel();
lock = channel.tryLock();
if(lock == null) {
channel.close();
return false;
}
} catch (FileNotFoundException ex) {
log.error(null, ex);
} catch (IOException ex) {
log.error(null, ex);
}
return true;
}
public static void unlock() {
// release and delete file lock
try {
if (lock != null) {
lock.release();
channel.close();
f.delete();
}
} catch(IOException e) {
log.error(null, e);
}
}
private static final Log log = LogFactory.getLog(AppLock.class);
}
An usage example
public static void main(String args[]) {
if (false == AppLock.lock()) {
System.exit(0);
}
installShutdownHook();
...
}
private static void installShutdownHook() {
Runnable runner = new Runnable() {
#Override
public void run() {
AppLock.unlock();
}
};
Runtime.getRuntime().addShutdownHook(new Thread(runner, "Window Prefs Hook"));
}
Note, I pick the code snippet from an open source project : AppLock.java
Enforce one instance of a program running with a ServerSocket Lock
Java Code. Put this into a file called Main.java:
import java.net.*;
import java.io.*;
public class Main{
public static void main(String args[]){
ServerSocket socket = null;
try {
socket = new ServerSocket(34567);
System.out.println("Doing hard work for 100 seconds");
try{ Thread.sleep(100000); } catch(Exception e){ }
socket.close();
}
catch (IOException ex) {
System.out.println("App already running, exiting...");
}
finally {
if (socket != null)
try{ socket.close(); } catch(Exception e){}
}
}
}
Compile and run it
javac Main.java
java Main
Test it in a normal case:
Run the program. You have 100 seconds to run the program again in another terminal, it will fall through saying its already running. Then wait 100 seconds, it should allow you to run it in the 2nd terminal.
Test it after force halting the program with a kill -9
Start the program in terminal 1.
kill -9 that process from another terminal within 100 seconds.
Run the program again, it is allowed to run.
Conclusion:
The socket occupation is cleaned up by the operating system when your program is no longer operating. So you can be sure that the program will not run twice.
Drawbacks
If some sneaky person, or some naughty process were to bind all of the ports, or just your port, then your program will not run because it thinks its already running.
I want to use ttorent java lib in my project. I am tried to figure out how it works. When I want to use it as a standalone program and call
./client -o ~ ~/file.torrent -i eth3
there is always 0%. When I tried to use it as a library with simple code like this:
import java.io.File;
import java.net.InetAddress;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.BasicConfigurator;
import com.turn.ttorrent.client.Client;
import com.turn.ttorrent.client.Client.ClientState;
import com.turn.ttorrent.client.SharedTorrent;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
BasicConfigurator.configure();
// Get options
File output = new File("/home/user");
// Get the .torrent file path
File torrentPath = new File("/home/user/file.torrent");
// Start downloading file
try {
SharedTorrent torrent = SharedTorrent.fromFile(torrentPath, output);
System.out.println("Starting client for torrent: "
+ torrent.getName());
Client client = new Client(InetAddress.getLocalHost(),
torrent);
try {
System.out.println("Start to download: " + torrent.getName());
client.download(); // DONE for completion signal
while (!ClientState.SEEDING.equals(client.getState())) {
// Check if there's an error
if (ClientState.ERROR.equals(client.getState())) {
throw new Exception("ttorrent client Error State");
}
// Display statistics
System.out
.printf("%f %% - %d bytes downloaded - %d bytes uploaded\n",
torrent.getCompletion(),
torrent.getDownloaded(),
torrent.getUploaded());
// Wait one second
TimeUnit.SECONDS.sleep(1);
}
System.out.println("download completed.");
} catch (Exception e) {
System.err.println("An error occurs...");
e.printStackTrace(System.err);
} finally {
System.out.println("stop client.");
client.stop();
}
} catch (Exception e) {
System.err.println("An error occurs...");
e.printStackTrace(System.err);
}
}
}
It is always 0% too. I tried to download with this torrent file using some other client and it was ok, so I assume this is no lack of seeds.