Java Webstart "javaws -open" flag doesn't work with multiple arguments - java

I'm trying to make a call to Java Webstart that uses the "-open" run time option to send arguments to the webstart application. I have referenced the question: Passing command line arguments to javaws (Java WebStart) executable, but this syntax doesn't seem to work for multiple arguments. It seems to work find for a single argument though.
When i run "javaws URLtoMyJNLP" it runs the application fine, also when I send a single argument by "javaws -open arg URLtoMyJNLP" it also seems to work and the arg gets to the application. When I attempt to run "javaws -open arg arg arg URLtoMyJNLP" it says invalid arguments supplied. I enter the command into ProcessBuilder.command.
InvalidArgumentException[ Invalid arguments supplied: {hello, jnlp, launch.jnlp, 123 }]
For the above output I attempted to send "javaws -open abc 123 hello launch.jnlp"
Any ideas?
Code as requested. It's overly simplistic due to being a PoC.
private static void launchApp(String appName, String appPath, String... args)
{
logger.debug("Launching application: " + appName);
Properties props = System.getProperties();
ArrayList<String> fullCmdString = new ArrayList<String>();
logger.debug("http://" + System.getProperty("jnlp.serverip") + ":" + System.getProperty("jnlp.serverport") + "/FB2HMI/" + appPath);
if (args.length > 0)
{
fullCmdString.add("javaws");
fullCmdString.add("-open");
}
for (String arg : args)
{
fullCmdString.add(arg);
}
fullCmdString.add("http://" + System.getProperty("jnlp.serverip") + ":" + System.getProperty("jnlp.serverport") + "/FB2HMI/" + appPath);
logger.debug("Command = " + fullCmdString);
ProcessBuilder rmLauncher = new ProcessBuilder().command(fullCmdString.stream().toArray(String[]::new));
Process p;
try
{
p = rmLauncher.start();
processList.add(p);
logProcessOutput(p, logger, null, appName);
}
catch (Exception e)
{
logger.fatal("Failed to launch " + appName + ": " + e);
System.exit(1);
}
}

This may be an ugly answer but since there hasn't been any proper answers to this question I will show you my work around. Pass the arguments as environment variables into the JVM. This will require editing of the source application to look for environment variables as an alternative to arguments, but it is the only way around this webstart issue that I have found that even remotely works.
Map<String, String> saArgs = new HashMap<String, String>();
saArgs.put("jnlp.serverip", System.getProperty("jnlp.serverip"));
saArgs.put("jnlp.serverport", System.getProperty("jnlp.serverport"));
saArgs.put("port", "8887");
saArgs.put("surfaceip", "192.168.0.50");
ProcessBuilder rmLauncher = new ProcessBuilder().command(fullCmdString.stream().toArray(String[]::new));
Process p;
for (Map.Entry<String, String> entry : args.entrySet())
{
rmLauncher.environment().put(entry.getKey(), entry.getValue());
}
try
{
p = rmLauncher.start();
}
catch (Exception e)
{
logger.fatal("Failed to launch " + appName + ": " + e);
System.exit(1);
}
Inside the JAR application:
logger.debug("jnlp.serverip = " + env.get("jnlp.serverip"));
logger.debug("jnlp.serverport = " + env.get("jnlp.serverport"));
logger.debug("port = " + env.get("port"));
logger.debug("surfaceip = " + env.get("surfaceip"))

Related

jar compile Runtime.getRuntime.exec() full directory in jar

Just for fun I'm making a little Java project file to keep on my dropbox to compile java for me without an ide easier than typing all those pesky command line arguments myself.
Right now I am just having one small problem...
First here's my code which does manage to compile class files into a jar with a manifest.
public static String listFilesString(String dirLocation){
String allPaths = ""; //pretty self explanatory returns full list of files in directory with spaces
File f = new File(dirLocation);
if(f.isDirectory()&&f.list().length>0){
for(File f2 : f.listFiles()){
if(f2.isDirectory()){
allPaths = allPaths + listFilesString(f2.toString());
} else {
allPaths = allPaths + f2.toString() + " ";
}
}
}
return allPaths;
}
public static boolean compileOutputToJar(String output, String jarLocation){
output = output.replace('\\', '/'); //replacements just for uniformity
String binF = WorkspaceVariables.workspaceDir+output;
String toCompile = listFilesString(binF).replace('\\', '/');
try {
Runtime.getRuntime().exec("jar cvfm " + jarLocation + " " + binF + "manifest.txt " + toCompile); // this line represents the problem
System.out.println("Compiled Workspace to Jar!");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
As is commented on the line containing Runtime.getRuntime().exec("jar cvfm " + jarLocation + " " + binF + "manifest.txt " + toCompile); this is where the problem occurs. Indeed the command properly executes but I do provide the full path to the class files to be compiled into the jar.
As an example I'll use the sample project this compiles. with a directory structure of:
/bin/manifest.txt < The manifest is compiled properly
/bin/Main.class < Calls k.Me to get the n variable which is printed
/bin/k/Me.class < Defines a string 'n' equal to "hi"
this however is compiled into the jar as:
META_INF/MANIFEST.MF
Users/MYUSERNAME/Desktop/Other/ide/javas/bin/Main.class
Users/MYUSERNAME/Desktop/Other/ide/javas/bin/manifest.txt < Nevermind this inclusion, just a problem I've not fixed.
Users/MYUSERNAME/Desktop/Other/ide/javas/bin/k/Me.class
The problem is clear, the file cannot run while it's like this and it is plainly compiled incorrectly. I could compile it correctly by changing to the directory they're found in before execution (not found a way to do this). Or possibly changing the location during command execution (I've tried using -cp, but to no avail).
The best option seems to be the use of -C as it can move the Main.class and manifest.txt to the proper place, however it doesn't include sub-directories to Me.class and the k folder no longer exist. and adding this to the beginning of each files name by adding "-C " + f2.getParent() + " ". in the listFilesString method prevents any of the class files from compiling into the jar at all.
Thanks for any help/ contributions!
One line was missing, a slight adjustment I've made corrected the error.
public static String listFilesString(String dirLocation){
String allPaths = ""; //pretty self explanatory returns full list of files in directory with spaces
File f = new File(dirLocation);
if(f.isDirectory()&&f.list().length>0){
for(File f2 : f.listFiles()){
if(f2.isDirectory()){
allPaths = allPaths + f2.toString() + " "; //THIS LINE WAS ADDED
allPaths = allPaths + listFilesString(f2.toString());
} else {
allPaths = allPaths + f2.toString() + " ";
}
}
}
return allPaths;
}
public static boolean compileOutputToJar(String output, String jarLocation){
output = output.replace('\\', '/'); //replacements just for uniformity
String binF = WorkspaceVariables.workspaceDir+output;
String toCompile = listFilesString(binF).replace('\\', '/');
try {
Runtime.getRuntime().exec("jar cvfm " + jarLocation + " " + binF + "manifest.txt " + toCompile); // this line represents the problem
System.out.println("Compiled Workspace to Jar!");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

mysqldump creates a blank file using java

Goodmorning everyone.
I have a problem with my java program: i would like to create a directory to store a .sql file, which will be generated through mysqldump.exe. I've been trying to follow guides on Stack Overflow or others, but i still can't resolve my problem: directory and .sql file are generated, but the file is totally blank. The best part is that pasting the same command (ctrl+C, ctrl+V) on the command line, it works well and generates an ordinary .sql file for a dump operation.
Please help me. I'm using NetBeans 8.0.2 as IDE, there's my code (there are some variables, like SelectedTable, that allows me to get the current user, password etc. Don't care about them: those parts works and the command is correctly generated):
private void jMenuExternalBackupActionPerformed(java.awt.event.ActionEvent evt) {
LocalDate today = LocalDate.now();
GregorianCalendar now = new GregorianCalendar();
String BackupFolderName = SelectedTable.getMaster().getName()+" "+SelectedTable.getName()+" "+today.getYear()+"_"+today.getMonth().getValue()+"_"+today.getDayOfMonth()+" "+now.get(now.HOUR_OF_DAY)+"_"+now.get(now.MINUTE)+"_"+now.get(now.SECOND);
new File("/HyperSQL/Backups/").mkdirs();
new File("/HyperSQL/Backups/"+BackupFolderName+"/").mkdirs();
String command;
if (SelectedTable.getMasterApplication().getPassword().isEmpty())
command = "mysqldump -u" + SelectedTable.getMasterApplication().getUserLogged() + " " + SelectedTable.getMaster().getName() + ""
+ " > \"C:\\HyperSQL\\Backups\\"+BackupFolderName+"\\backup.sql\"";
else
command = "mysqldump -u" + SelectedTable.getMasterApplication().getUserLogged() + " -p" + SelectedTable.getMasterApplication().getPassword() + " " + SelectedTable.getMaster().getName() + ""
+ " > \"C:\\HyperSQL\\Backups\\"+BackupFolderName+"\\backup.sql\"";
try
{
Process exec = Runtime.getRuntime().exec(new String[]{"cmd.exe","/c", command});
}
catch (Exception e)
{
e.printStackTrace();
}
}

How to run application with parameters from within java application on mac osx

I am writing a small java application to load ZDoom with custom wad files on mac osx and am having trouble executing the command.
I have generated a string within the application that will run ZDoom and load the custom wad, I have tested this by copy-pasting the string from the netbeans breakline debugger and running it directly in terminal.
When I run the code through my application ZDoom does load up but it does so without the custom wad so I believe it is executing without it's arguments.
I have tried two different techniques to run the command:
private void loadZdoom() {
// get selected wad
String wad = (String) wadListComboBox.getSelectedItem();
ProcessBuilder builder = new ProcessBuilder(defaultZdoomInstallPath + "/Contents/MacOS/zdoom", "-file", defaultZdoomWadsPath.replace(" ", "\\ ") + "/" + wad);
builder.redirectErrorStream(true);
try {
Process p = builder.start();
} catch (IOException ex) {
}
}
And
private void loadZdoom() {
// get selected wad
String wad = (String) wadListComboBox.getSelectedItem();
String runCommand = defaultZdoomInstallPath + "/Contents/MacOS/zdoom " + "-file " + defaultZdoomWadsPath.replace(" ", "\\ ") + "/" + wad;
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec(runCommand);
} catch (IOException e) {
}
}
What am I doing wrong here?
I figured out what the problem was, I was escaping the space in the path to the wad file as you need to do this in terminal but it seems this is unnecessary in JAVA. All is working as expected now :)

Java Runtime Class - Unable to cd in cmd Prompt

This program is to create a server certificate from java without opening a command prompt(at least manually) This code executes successfully, but i can't see my file "server.jks" neither in the "cd"ed directory nor in the default directory where cmd loads up(c:\Documents and Settings\administrator). I am more interested in generating in a specified directory. help me alter my code to do that.
public class SslKeytool
{
public void createServerCertificate(String dn, String alias, String validity, String keystoreName, String keypass, String storepass, String drive, String path)
{
try
{
Runtime runtime = Runtime.getRuntime();
String result;
result = "keytool -genkeypair ";
result = result + "-alias " + alias + " ";
result = result + "-keyalg RSA -dname " + dn + " -validity " + validity + " -keypass" + keypass + " -keystorename " + keystoreName
+ " -storepass" + storepass;
runtime.exec("cmd " + drive + ":");
runtime.exec("cmd cd " + path);
runtime.exec("cmd " + result);
}
catch (Exception e)
{
System.out.println("Whoa! Something went wrong! please make sure that you read the API ");
e.printStackTrace();
}
}
public static void main(String[] args)
{
SslKeytool obj = new SslKeytool();
obj.createServerCertificate("CN=LCMS,OU=Software Solutions,O=Live Connections,L=Chennai,S=TamilNadu,C=Ind", "servercert", "365", "abc.jks", "lcmsauth"
, "lcmsauth", "f", "/keytest");
}
}

Running .pkg on MAC OS from java code

Am trying to run a .mpkg application from my java code :
public void runNewPkg(){
try {
String command = "sudo installer -pkg Snip.mpkg -target /Applications";
Process p = Runtime.getRuntime().exec(command);
System.out.println(p.getErrorStream());
} catch (Exception ex) {
ex.printStackTrace();
}
}
And am getting the following error and my terminal window hangs..
java.lang.UNIXProcess$DeferredCloseInputStream#2747ee05
Password:
Sumit-Ghoshs-iMac-3:downloads sumitghosh3$ Password:
Password:
-bash: **********: command not found
Sumit-Ghoshs-iMac-3:downloads sumitghosh3$
I Think i need to provide the password also to run the pkg from the command line
Could you tell me how i can do that?
You can provide the password to sudo:
echo "p#sw0rd" | sudo -S cal -y 2011
The command above runs 'cal -y 2011' with root permissions.
I would actually try editing your /etc/sudoers file to not prompt for a password. If you use the NOPASSWD tag, you should be able to do that. An example entry would be:
sumitghosh3 ALL=(ALL) NOPASSWD: ALL
If you want an interactive solution for elevating privilege, I have used openscript to elevate privilege of a wrapped shell script. It goes something like this:
import java.io.File;
import java.text.MessageFormat;
/**
* OsxExecutor.java
*/
public class OsxExecutor {
private String error = null;
private String output = null;
/**
* Privileged script template format string.
* Format Arguments:
* <ul>
* <li> 0 = command
* <li> 1 = optional with clause
* </ul>
*/
private final static String APPLESCRIPT_TEMPLATE =
"osascript -e ''try''"
+ " -e ''do shell script \"{0}\" {1}''"
+ " -e ''return \"Success\"''"
+ " -e ''on error the error_message number the error_number'' "
+ " -e ''return \"Error: \" & error_message''"
+ " -e ''end try'';";
public void executeCommand(String command, boolean withPriviledge) {
String script = MessageFormat.format(APPLESCRIPT_TEMPLATE,
command,
withPriviledge
? "with administrator privileges"
: "");
File scriptFile = null;
try {
scriptFile = createTmpScript(script);
if (scriptFile == null) {
return;
}
// run script
Process p = Runtime.getRuntime().exec(scriptFile.getAbsolutePath());
StreamReader outputReader = new StreamReader(p.getInputStream());
outputReader.start();
StreamReader errorReader = new StreamReader(p.getErrorStream());
errorReader.start();
int result = p.waitFor();
this.output = outputReader.getString();
if (result != 0) {
this.error = "Unable to run script "
+ (withPriviledge ? "with administrator privileges" : "")
+ "\n" + script + "\n"
+ "Failed with exit code: " + result
+ "\nError output: " + errorReader.getString();
return;
}
} catch (Throwable e) {
this.error = "Unable to run script:\n" + script
+ "\nScript execution "
+ (withPriviledge ? " with administrator privileges" : "")
+ " failed: " + e.getMessage();
} finally {
if (scriptFile.exists()) {
scriptFile.delete();
}
}
}
}
If withPriviledge flag is true, a password dialog will be raised. Not shown is createTmpScript() which creates an executable file in /tmp, and StreamReader which extends Thread and is used to capture both stdout and stderr streams.

Categories

Resources