Java Runtime Class - Unable to cd in cmd Prompt - java

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");
}
}

Related

Is there a way to save data from csv to mongodb?

I have a CSV file, and I'm trying to import the CSV file in the MongoDB database. Unfortunately, the experience is not working as I wish it would. The content of the CSV file is not relevant, since when I use MongoDB Compass to import it manually, there is no issue and it's appearing as I want. Thus, I'm trying to save it from local folder to the MongoDB using Java and Spring Boot if possible, but I can't find any good advice or explaination about how to do so.
I'm using Spring Boot 2.6.3 and Java11.
Thanks a lot.
public class MongoImportUtil {
public static void main(String[] args) {
String Host = "localhost";
String Port = "27017";
String DB = "userDemo";
String CollectionName = "users";
String FileName = "D:/Test.csv";
// Without Credential
String command = "C:\\Program Files\\MongoDB\\Server\\5.0\\bin\\mongoimport.exe --host " + Host + " --port " + Port + " --db " + DB + " --collection " + CollectionName + " --headerline --type=csv --file "+ FileName;
// With Credential
/* String command = "C:\\Program Files\\MongoDB\\Server\\5.0\\bin\\mongoimport.exe --host " + Host + " --port " + Port + " --db " + DB + " --collection " + CollectionName + "--authenticationDatabase admin --username " + user + " --password " + password + " --headerline --type=csv --file "+ FileName; */
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println("Imported csv into Database");
} catch (Exception e) {
System.out.println("Error executing " + command + e.toString());
}
}
}

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

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"))

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();
}
}

mysqldump file creates an empty sql file

i apply comment 1 and 2 alternatively.But i didn't get myqldump file using java.mysqldump working in cmd. i think in cmd it ask password after typing mysqldump comment. please help me fast.thanks in advance.
String dumpCommand = "C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump" + " -u " + user + " -p" + " " + database + " > " + path;
**//command 1**
Runtime rt = Runtime.getRuntime();
File test = new File(path);
PrintStream ps;
try {
// Process child = rt.exec("Cmd /c \"C:/Program Files/MySQL/MySQL Server 5.0/bin/mysqldump\" -u root -p saxco > "+path);//command 2
Process child = rt.exec(dumpCommand);
ps = new PrintStream(test);
InputStream in = child.getInputStream();
int ch;
while ((ch = in.read()) != -1) {
ps.write(ch);
System.out.write(ch);
}
As documented here you can specify the password in the command like this [...] -pPASSWORD [...]. Note that there must not be a space between the -p option flag and the actual password.
Keep in mind that specifying the password this way is a security risk!
If you don't use a password just don't use the -p option too.
String dumpCommand = "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqldump" + " -u " + user + database + " > " + path;
or this if you have one (without the gaps)
String dumpCommand = "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqldump" + " -u " + user + " -p" + password + " " + database + " > " + path;
try this-
String cmd="mysqldump -u "+USER+" -p"+PASSWORD+" "+database+" --routines -r"+PATH;
Runtime runtime = Runtime.getRuntime();
Process exec;
exec = runtime.exec(cmd);
int processComplete = exec.waitFor();
if(processComplete == 0){
System.out.println("Backup taken successfully in "+PATH+" on "+new Date());
} else {
System.out.println("Could not take mysql backup :ERROR:");
}

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