Runtime.getRuntime() restart mac Java IM - java

My os is MAC OS 10.11.3.
I using Spark as our IM(Instant messaging),but when the IM log out,IM give an error,said:
java.io.IOException: Cannot run program "open": error=2, No such file or directory .
But when Eclipse runs it, it worked well,and when I wrapped it a mac package and installed it and run it, click "log out" button, it throws errors.
In program, when I log out,I launch a new IM,meanwhile,I killed the old IM application.
Furthermore,in terminal,no matter what I run how many times “open -a Spark”,it just open the same IM,
The source as follows:
public boolean restartApplicationWithScript() {
String command = null;
try {
if (Spark.isMac()) {
command = "open -a " + Default.getString(Default.SHORT_NAME);
}
String commands[] = {"open", "/Applications/Spark.app"};
Runtime.getRuntime().exec(commands);
System.exit(0);
return true;
} catch (IOException e) {
Log.error("Error trying to restart application with script", e);
return false;
}
}

The exception seems to be saying that it cannot find the open command. That seems a bit odd, since it is a standard MacOS command. So I suspect that the reason that it cannot be found is that it is not on the PATH.
Try giving the absolute pathname for the open command. Running which open should tell you what it is.
If open is a shell builtin on MacOS, then you will need to create a subshell to run the command.

Thanks for all, i solved it by 2 step :
1, cmdline = { "open", "-na", "Microsoft Excel" }; this add a "n" ,otherwise,it will open the same app 。
2,chmod -R 777 youAppPath,if not do this ,the app can't issue the command

Related

Open webpage from a Java application doesn't work when run from task scheduler

I wrote a Java program some time ago that automatically opens a webpage before I get to work in the morning. I do this by calling a batch file from Java, which opens the webpage. This program worked great for about three or four months without any problems, but one day it just stopped working. I have tried opening the webpage from within Java as well instead of the batch file, but I consistently run into a problem. This is the process I use:
I exported my program as a runnable JAR and converted it to an EXE using Launch4j. In my Windows task scheduler I schedule it to run at 5:30am every morning.
My Java program calls the batch file that is stored on my desktop
The batch file opens Chrome and calls the webpage to open
When I run the Java program EXE manually (double-click from the desktop) it runs correctly, calls the batch file, and opens the webpage. However, when I try running the EXE from the Windows task scheduler it does not (visibly) open the webpage. It does appear to run Chrome in the background (according to the task manager/Process Explorer) but the webpage itself doesn't seem to open (I can tell because the webpage I open should be playing music, but I hear nothing).
This is the Java function I use to run the batch file:
public static void openWebpage() throws Exception {
String[] startupBat = {"cmd", "/c", "start", "/B", System.getProperty("user.home") + "\\Desktop\\WebpageStart.bat"};
ProcessBuilder pb = new ProcessBuilder(startupBat);
try {
webpage = pb.start();
} catch (IOException e) {
logWriter.write(tf.format(new Date()).toString() + " - Unable to start webpage");
}
if (webpage != null) {
try {
webpage.waitFor();
} catch (InterruptedException e) {
logWriter.write(tf.format(new Date()).toString() + " - Webpage startup interrupted");
} finally {
webpage.destroy();
}
}
}
And here are the contents of the batch file I use to start the webpage:
#echo off
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.myWebpage.com
Once again, everything works fine when I run the Java EXE manually, but when I try to run it from the task scheduler the webpage doesn't appear to open. What could cause this sort of behavior? What changes when the task scheduler runs a program vs. when it is manually run?
A few things to check
Which user is the scheduled task running as? Is it the same user as the one double clicking on the icon?
Have you changed your password recently? You might need to update the password on the scheduled task
Go to the windows event viewer, are there any errors in there?

Open a file using Java application

I'm trying to open the file using Runtime. This is similar to opening windows command prompt, and then executing the command.
Here is the code:
import java.io.IOException;
public class OpenFile {
public static void main(String[] args) {
String fileName = "E:\\Myfile.txt";
try {
Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd.exe", "/c", "start"});
rt.exec(new String[]{fileName});
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
The command prompt is opening successfully. But the file Myfile.txt is not opening. I'm getting the below error in console:
java.io.IOException: CreateProcess: E:\Myfile.txt error=193
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:464)
at OpenFile.main(OpenFile.java:10)
How to open the file successfully?
Not really an answer, but I think it's important to describe what exactly is happening in the current version of the application.
In this part of your code;
rt.exec(new String[]{"cmd.exe", "/c", "start"});
rt.exec(new String[]{fileName});
You are executing an external command. To quote the question,
similar to opening windows command prompt, and then executing the
command
What you need to realize is that whatever you've given as the string gets executed. It isn't queued or anything. Thus, re-reading your code, you are asking your program to execute 2 different commands. The first would look like;
cmd.exe /c start
Which if run on the windows command prompt executes without issues. The second "command" your program attempts to execute looks like this;
E:\Myfile.txt
Try typing that into the command prompt - it will produce an error. Probably something like "command not found". This is what the exception java.io.IOException: CreateProcess is telling you. That Java was not able to create the new process you asked it to.
Now, as for actually answering the OP, I suggest this;
rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});
Which, unfortunately looks exactly like an earlier answer.
You are trying to execute fileName in Runtime object, which is wrong! Try like below:
rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});

Connecting to Quality Center v11 using COM4J

I am trying to connect to HP Quality Center V11 using Java code and com4j but i keep getting following error. Can someone please take a look at the error?
When I use the URL in my browser and log-in with same credentials, I was able to login. I double checked all the spelling of my domain, url, Id and password..
Error I get:
com4j.ComException: 800403ea (Unknown error) : Failed to Login : .\invoke.cpp:517
at com4j.Wrapper.invoke(Wrapper.java:166)
at $Proxy5.connectProjectEx(Unknown Source)
at com.testpack.TestClass.main(TestClass.java:23)
Caused by: com4j.ComException: 800403ea (Unknown error) : Failed to Login : .\invoke.cpp:517
at com4j.Native.invoke(Native Method)
at com4j.StandardComMethod.invoke(StandardComMethod.java:35)
at com4j.Wrapper$InvocationThunk.call(Wrapper.java:340)
at com4j.Task.invoke(Task.java:51)
at com4j.ComThread.run0(ComThread.java:153)
at com4j.ComThread.run(ComThread.java:134)
Code I use to connect
public static void main(String[] args) {
String url="http://XXXX/qcbin/";
String domain="ACTIVE";
String project="QC_2013_Projects";
String username="XXXX";
String password="XXXXX";
try{
ITDConnection itd=ClassFactory.createTDConnection();
itd.initConnectionEx(url);
System.out.println("Test1:"+ itd.connected());
itd.connectProjectEx(domain,project,username,password);
//System.out.println(itd.connected());
}catch(Exception e){
e.printStackTrace();
}
}
I followed these steps for getting connected to HP QC 11 from Java code using com4j on windows 7 32 bit machine
Download Com4j artefacts com4j-20120426-2.zip from https://github.com/downloads/kohsuke/com4j/com4j-20120426-2.zip
Unzip it. Open a command prompt and navigate to the unzipped folder. Then run following command to create Wrapper classes in a location CCCC with package structure as DDDD.
java -jar tlbimp.jar -o "C:\CCCC" -p "DDDD" "C:\Users\MYACC\AppData\Local\HP\ALM-Client\10\OTAClient.dll"
Now copy the OTAClient.dll and WebClient.dll from C:\Users\MYACC\AppData\Local\HP\ALM-Client\10 and save it in Windows/System32 folder.
After following the step 2, you must have a com4j-x86.dll in the location where tlbimp.jar is present. Now copy that dll to Windows/System32 folder.
Now with Admin rights, register all 3 dll files using the commands 1 by 1 as follows.
regsvr32 com4j-x86.dll
regsvr32 OTAClient.dll
regsvr32 WebClient.dll
Now create a Java Project in eclipse. In the src folder copy the DDDD folder created during the step 2. Add com4j.jar in class build path. Then have the following code in a java file to test the HP QC connection. Run the java file to check the result.
ITDConnection itd=ClassFactory.createTDConnection();
itd.initConnectionEx("http://10.10.10.10:8080/qcbin");
System.out.println(itd.connected());
itd.connectProjectEx("DOMAIN_NAME", "PROJECT_NAME", "HPQC_USERID", "HPQC_CREDENTIAL");
System.out.println(itd.projectConnected());
Hope this helps. :)
I was finally able to solve this issue. I had install HP ALM QC Client. It would install in the following path- > Your Program files->HP->HP ALM Client.
After I installed this, I was able to connect to QC.
Hope this might be useful to someone else. Thanks!
I added all the 3 .dll files in c:\Windows\SysWOW64 and executed the same code.
// This is a fairly important section for x64 bit machines,
// as a note this took me forever to figure out. Basically,
// if the DLL is not registered in the SysWOW64 dir then we
// are unable to use this as it was created when 32-bit
// computers were still all the rage. This is a quick little
// hack that registers it if it is needed to be registered.
// If it's already registered, this does nothing.
try {
Runtime.getRuntime()
.exec("C:\\windows\\SysWOW64\\regsvr32 /s lib\\OTAClient.dll")
.waitFor();
Runtime.getRuntime()
.exec("C:\\windows\\SysWOW64\\regsvr32 /s lib\\com4j-amd64.dll")
.waitFor();
Runtime.getRuntime()
.exec("C:\\windows\\SysWOW64\\regsvr32 /s lib\\com4j-x86.dll")
.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Utilities
.showError(
new JFrame(),
"OTAClient.dll, com4j-amd64.dll or com4j-x86.dll could not "
+ "be registered, program may or may not work on a 64-bit machine "
+ "without these files. You can attempt to manually register them, "
+ "but this rarely works.");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run this before anything else in your code, it's what I used to force any machine to register them.

Call a command in terminal using Java (OSX)

I am trying to write Java code to run wget to retrieve an image from a server
I believe that I have wget properly installed. If I type:
wget http://insitu.fruitfly.org/insitu_image_storage/img_dir_38/insitu38795.jpe
I find the image in my user account folder.
The following Java code was working properly on Ubuntu, but I had to move the project over to OSX (Mountain Lion)
import java.io.*;
import java.io.IOException;
public class runWget
{
public static void main (String args[])
{
String whatToRun = "wget http://insitu.fruitfly.org/insitu_image_storage/img_dir_38/insitu38795.jpe";
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(whatToRun);
int exitVal = proc.waitFor();
System.out.println("Process exitValue:" + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
When I try to run it on OSX, I get the runtime error:
java.io.IOException: Cannot run program "wget": error=2, No such file
or directory
I would greatly appreciate if someone could tell me what I am doing wrong.
If wget is indeed installed on your OS X system, then try to specify the full path to it.
Try:
which wget
from the command line, then use that fully qualified path in your Java application.
String whatToRun = "/usr/local/bin/wget http://insitu.fruitfly.org/insitu_image_storage/img_dir_38/insitu38795.jpe";
Pretty obviously, wget is not installed by default in OS X.
Something more interesting is to write functionality like wget your own.
URL url = new URL("http://insitu.fruitfly.org/insitu_image_storage/img_dir_38/insitu38795.jpe");
InputStream in = url.openStream();
OutputStream os = new FileOutputStream(new File("picture.jpe"));
byte byffer[] = new byte[1024];
int nBytesRead;
while ((nBytesRead = in.read(buffer)) != -1)
{
os.write(buffer, 0, nBytesRead);
}
os.flush();
os.close();
in.close();
None of these answers explain what your actual problem is.
The reason Java is failing is that /usr/local/bin isn't on your PATH.
Obviously it is on the path of the bash shell you're running in Terminal. And probably of any new bash shell you start in Terminal (or via ssh, or whatever). That's probably because you've got a line like export PATH=$PATH:/usr/local/bin somewhere in ~/.profile, ~/.bash_profile, ~/.bashrc, or the /etc equivalents.
On linux, all your GUI stuff is a child of a login shell, so putting something in one of those files (as long as you pick the right one) means Java will end up inheriting that PATH no matter how it gets launched. But on Mac, all your GUI stuff is a child of launchd, and any shell you run is just a sibling of your GUI apps, not the parent. So, setting PATH in bash's startup isn't going to affect something launched from the Finder or an IDE or whatever.
Once you understand the problem, you can understand all the different solutions—you can set the default environment launchd gives to user processes, or do the same thing system-wide, or modify /etc/paths, etc.
It looks like wget is not installed on that OSX system. (It isn't on mine either, despite that being a few generations older.) Either install it or find another way to download a picture; Java does have HTTP support built-in natively after all (see the java.net.URL class).
if you get this error one more time , execute command like this :
which wget
Runtime.getRuntime().exec(new String[]{ "/bin/sh" , "-c" ,"/usr/local/bin/wget http://insitu.fruitfly.org/insitu_image_storage/img_dir_38/insitu38795.jpe" })

Open a path with Desktop.open() from java on ubuntu (linux)

From my application written in java I want to open a folder, using the operating system file explorer.
I use Desktop.open(new File(path))
This works fine on windows, but on ubuntu 11.10 (linux) it doesn't work.
Using the Desktop.open to open a file does work, both on ubuntu and windows.
Using a step in between:
File fPath=new File(fPath)
and testing it with fPath.exists() and fPath.isDirectory() both gives true.
using the Desktop.open(new File(path)) gives me this exception:
java.io.IOException: Failed to show URI:file:/and/here/the/path/I/use/
at sun.awt.X11.XDesktopPeer.launch(Unknown Source)
at sun.awt.X11.XDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
I was not able to test this on an apple computer yet, but I hoped the Desktop.open(new File(path)) was system independent.....
by the way, the complete code:
Desktop desktop = null;
// Before more Desktop API is used, first check
// whether the API is supported by this particular
// virtual machine (VM) on this particular host.
if (!Desktop.isDesktopSupported()) {
// show Error
return;
}
desktop = Desktop.getDesktop();
String path = "here the path ";
// by the way: I use System.getProperty("file.separator") as file seperator
try {
File fPath=new File(path);
if(!fPath.exists()){
// show Error
return;
}
if(!fPath.isDirectory()){
// show Error
return;
}
desktop.open(new File(path));
} catch (IOException e) {
log.severe(e.getMessage());
e.printStackTrace();
// show Error
return;
}
Some extra information:
OS: Linux (3.0.0-16-generic - amd64)
Java: 1.6.0_30-b12
Java home: /opt/java/64/jre1.6.0_30
I had the same problem. But in my case it was Ubuntu 18.04 and java 1.8.0_161-b12
In Windows 10, everything is working fine. But on Ubuntu
Desktop.getDesktop().open(new file)
the program stopped responding.
I decided to wrap the call in the executor:
private ExecutorService executorService;
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("YourPatternIndeficator")
.build();
executorService = Executors.newSingleThreadExecutor(factory);
if (Desktop.isDesktopSupported()) {
File myFile = new File(path);
executorService.execute(() -> {
try {
Desktop.getDesktop().open(myFile);
} catch (IOException e) {
e.printStackTrace();
}
});
}
I was running into what sounds like the same issue on Mint 13. From what I can tell, changes to mime handling for opening directories has broken the java Desktop api. I was able to work around the problem by editing
~/.local/share/applications/defaults.list
and adding this line
x-directory/normal=nautilus.desktop
I'm running Mint 13 Cinnamon with java version "1.7.0_05"
I can't confirm the error. I took your code and constructed a main method around it, and everything works as expected. I don't exactly know where the default applications are set (in my case PCMan was opened instead of usual Nautilus, but it should fulfil its purpose in the end).
Over at java.awt.Desktop.open doesn’t work with PDF files? I have found a link pointing to an issue in Suns (Oracles) bug tracker stating that the method for opening files using AWT isn't reliable even on Windows. Maybe you should think of alternative ways of opening such applications. Furthermore AWT is deprecating soon almost for sure.
If you are utilizing SWT in your application, you could use org.eclipse.swt.program.Program.
I was running into the same issue and decided to give Java 7 a whirl. I'm running java version "1.7.0_147-icedtea" on Ubuntu 11.10_x64 and am able to open file locations in Nautilus quite happily now.
I have the same issue on my Linux Mint (and not in Windows).
That link helped me :
Troubles with java.awt.Desktop browse() method.
This seems to work on my Linux Mint-KDE.
I changed the line
Desktop.getDesktop().desktop.open(new File("/home/user/mypath"));// this throws IOException: Failed to show URI (except in Windows)
with
Desktop.getDesktop().desktop.open(new File("///home/user/mypath"));// this launches Dolphin
or with
Desktop.getDesktop().desktop.open(new File(new URI("file:///home/user/mypath").getPath()));// this launches Dolphin
Dolphin was launched with my folder "mypath". But I found no way to open a file like a pdf or txt on my Linux while it works on Windows with the first code.
(Java 1.8.0_25, Netbeans 8.02, Linux Mint 12 KDE)
I have the issue with Kubuntu 18.04 and java 11. It was solved with
sudo apt install libgnome2-0 gvfs
see https://bugs.launchpad.net/ubuntu/+source/openjdk-8/+bug/1574879/comments/5 for details. java.awt.Desktop works with Gnome not with KDE.

Categories

Resources