java code--how to detect if a browser is opened - java

I would like to know any java method can be used to check if the browser is closed.
I used the following code to open a default browser:
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
}
Then I want to perform some user actions on the opened website to capture the web traffic. After the browser is closed the web traffic will be saved.
So how can I determine if the browser is closed by using java code?

The best you can do is use Process builder:
public class Main {
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("C:\\Windows\\System32\\calc.exe");
Process p1 = pb.start();
p1.waitFor();
System.out.println(p1.exitValue());
} catch (Exception e) {
System.out.print(e);
}
}
}
You can launch a browser with the webpage as an argument and keep track of it like that.

Related

Desktop.getDesktop().open(file) on Ubuntu not working

I have a Java application, and when I use java.awt.Desktop:
Desktop.getDesktop().open(file);
It works fine on Windows (opens a file in my default program), but on Ubuntu (with openJdk 13), the Java application gets stuck and I do not even get any log error or anything. I have to force quit the app in order to recover.
The file path it correct, otherwise I would actually get an Exception. Also, isDesktopSupported a isSupported(Action.OPEN) returns true.
What can I do? Can I check some system settings or logs? Or perhaps get some logs from java.awt.Desktop? Or does this not work on Ubuntu/Linux?
Are there any alternatives?
From here:
In order to use the API, you have to call java.awt.EventQueue.invokeLater() and call methods of the Desktop class from a runnable passed to the invokeLater():
void fxEventHandler() {
EQ.invokeLater(() -> {
Desktop.open(...);
});
}
I am just going to add an example function
private static void OpenFile(String filePath){
try
{
//constructor of file class having file as argument
File file = new File(filePath);
if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not
{
System.out.println("not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) { //checks file exists or not
EventQueue.invokeLater(() -> {
try {
desktop.open(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

I want to open the same link multiple times, all in different browser sessions

This way it opens all the url in different tabs. All I want to do is open them in different sessions/windows.
import java.io.IOException;
public class For1 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
String url_open ="www.google.com";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The java.awt.Desktop.browse method uses the default browser of your user profile, as the Javadoc says:
Launches the default browser to display a URI. If the default browser
is not able to handle the specified URI, the application registered
for handling URIs of the specified type is invoked. The application is
determined from the protocol and path of the URI, as defined by the
URI class.
What you can do however, is to start the browser process using the java.lang.ProcessBuilder to start the browser process. That way you can set parameters to the browser's process such as the URL and the command to start as a new window. The following code starts firefox and chrome. You should change the filepath of each browser to match with your browser installation. If you use a different browser you should check what command line parameter it requires to start a new window.
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
String url_open ="www.google.com";
try {
new ProcessBuilder("C:\\Program Files (x86)\\Firefox Developer Edition\\firefox.exe", "-new-window", url_open).start();
new ProcessBuilder("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "/new-window", url_open).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
you should try this solution
String[] args = new String[] { "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", "http://www.google.com" };
Runtime.getRuntime().exec( args );

Jar file working when running standalone but doesn't work under Windows service

I have a java project, which complied into an executable jar file v-agent-exe.jar. This jar is a log server, log rows is sent to it for processing.
I can execute it by using this command:
`java -jar v-agent-exe.jar -a watch -f config.ini`.
After executed, this jar file will create a ServerSocket at port 1235 and listen for incoming data from clients. After data received, the program will process the data and send the result back to the client. When I execute the jar from CMD windows, the processing is working perfect.
Now I am trying to wrap the Jar file as a Windows service (I am using Windows 10). I created a "Windows service project"
in Visual studio like below:
- Caller class have call() method to execute the jar file using process.
- AgentService is the service, which execute Caller->call() in another thread.
- Program is the main entry to load AgentService.
Caller.cs
public class Caller
{
static Process proc;
public Process GetProcess(){
return proc;
}
public void call() {
try
{
String dir = AppDomain.CurrentDomain.BaseDirectory;
proc = new Process
{
StartInfo = new ProcessStartInfo
{
WorkingDirectory = dir,
FileName = "java.exe",
Arguments = #"-jar v-agent-exe.jar -a watch -f config.ini",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardError.EndOfStream)
{
string line = proc.StandardError.ReadLine();
}
}
catch (Exception ex) {
VAgentService.writeLog("Error when call process: " + ex.Message);
}
}
}
AgentService
public partial class AgentService : ServiceBase
{
private string jarPath;
private string iniPath;
static Process proc;
Caller caller;
public AgentService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
writeLog("On start");
try
{
caller = new Caller();
writeLog("Prepare to launch thread");
Thread t = new Thread(new ThreadStart(caller.call));
t.Start();
}
catch (Exception ex)
{
EventLog.WriteEntry("Demo error: " + ex.Message);
}
}
protected override void OnStop()
{
proc = caller.GetProcess();
if (proc != null && !proc.HasExited)
{
proc.Kill();
}
else
{
...
}
}
}
Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(String[] args)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new AgentService()
};
ServiceBase.Run(ServicesToRun);
}
}
After build the the service project, I have AgentService.exe.
I install it to my system using:
sc create VAgentLogging binpath= %CD%\AgentService.exe depend= lmhosts start= auto
After start the service in service.msc, I can telnet to port "1235" which the java process is listening (I am sure about
only the jar running in this port). According to the
log of java program, it still can received some part of data but seem like it cannot send back to client or something,
which cause the followed process cannot be done.
I think my problem is: the jar file can executed as standalone but somehow it sucks when wrapped under my service project.
I haven't posted the jar's code yet because I think the error is related to the Windows service project. If you need the java code, please tell me and I will update it here.
Any help would be appreciated.

Opening print dialog using java.awt.Desktop

I am trying to print an HTML file using java.awt.Desktop.print but the print dialog throws an IOException.
menuPrint.setOnAction((ActionEvent t) -> {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.PRINT)) {
try {
File output = new File(System.getProperty("java.io.tmpdir")+"/Preview.html");
desktop.print(output);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
java.io.IOException: Failed to print C:\Users\XXX\AppData\Local\Temp\Preview.html.
Error message: A device attached to the system is not functioning.
I have a PDF printer installed and can open the print dialog using Ctrl+P. Though this same code is working on a separate machine which is connected to an actual printer.
Any clues appreciated. How to make it work?

Tesseract implementing a web service to trigger OCR actions

I am trying to implement a web service which triggers OCR actions of the server side.
Client code:
...
sy = belgeArsivle(testServisIstegi, ab);
...
private static ServisYaniti belgeArsivle(com.ocr.ws.ServiceRequest serviceRequest,com.ocr.ws.Document document) {
com.ocr.ws.ServiceRequest service = new com.ocr.ws.OCRArsivWSService();
com.ocr.ws.OCRArsivWS port = service.getOCRArsivWSPort();
return port.docArchive(serviceRequest, document);
}
When I run the code on the server side there is no problem. But whenever I call the web service method from the client I got this error code:
Exception: javax.xml.ws.soap.SOAPFaultException: Unable to load library 'libtesseract302': The specified module could not be found.
The working server-side code is:
public static void main(String[] args) {
// TODO code application logic here
File imageFile = new File("...OCR\\testTurWithBarcodeScanned.png");
Tesseract instance = Tesseract.getInstance();
try {
String lang = "tur";
instance.setLanguage(lang);
String result = instance.doOCR(imageFile);
System.out.println(result);
// write in a file
try {
File file = new File("...MyOutputWithBarcode.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(result);
out.close();
} catch (IOException ex) {
}
} catch (TesseractException ep) {
System.err.println(ep.getMessage());
}
}
I know that this error code is about Tesseract libraries. I put the corresponding .dll files (liblept168 and libtesseract302) under the client project's folder, added corresponding libraries (jna, jai_imageio, ghost4j_0.3.1), did neccessary changes in classpath but still getting this error.
I run a test code on the server side, it works fine. But the client side code is not working. Do I need to make some extra adjustment on the client side to run this web service?
I found out that the actual problem was with the Tomcat Server. I had to put the jar files to the Tomcat's Sources under Properties, than voila!

Categories

Resources