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();
}
}
Related
I'm trying to create an installer for the java program it's supposed to download a zip file from a URL. to do this I'm using the Wget command to download the files in a specific directory. I made it so the code prints out the command it's executing so I can copy and paste it to test. When I test the command it works perfectly, but when I run the code to do it automatically it corrupts the zip file. it won't unzip, and if i transfer the file to my mac it says Unable to expand filename.zip it is an unsupported file I believe this is because the file is corrupted.
This is the command it runs
wget -O /home/pi/1.2.1.zip https://install.swiftpcb.tech/1.2.1.zip
unzip /home/pi/1.2.1.zip -d /home/pi
this is the output of running the unzip one manually
Archive: 1.2.1.zip
End-of-central-directory signature not found. Either this file is not
a zip file, or it constitutes one disk of a multi-part archive. In the
latter case, the central directory and zip file comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile directory in one of 1.2.1.zip or
1.2.1.zip.zip, and cannot find 1.2.1.zip.ZIP, period.
this is the class running the command in java (you only need to focus what in the if statement ran == 0
package Installer;
import java.io.IOException;
import java.sql.*;
public class Main {
public void start() throws IOException, InterruptedException {
// SQLite connection string
String url = new Info().getConfigDir();
// SQL statement for creating a new table
String sql = "CREATE TABLE IF NOT EXISTS appInfo (\n"
+ " \"ID\" INTEGER,\n"
+ " \"version\" TEXT,\n"
+ " \"ran\" INTEGER DEFAULT 0,\n"
+ " PRIMARY KEY(\"ID\" AUTOINCREMENT) \n"
+ ");";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
SQLite lite = new SQLite();
lite.createData();
int versionChangeStatus = lite.updateVersionInDB();
if(versionChangeStatus != 0) System.out.println("Something went wrong");
int ran = lite.getRanValue();
if(ran == 0){
String version = new Info().getVersion();
//for deploy
Process p = Runtime.getRuntime().exec("wget -O /home/pi/" + version + ".zip " + "https://install.swiftpcb.tech/" + version + ".zip" + " && unzip /home/pi/" + version + ".zip -d /home/pi");
System.out.println("wget -O /home/pi/" + version + ".zip " + "https://install.swiftpcb.tech/" + version + ".zip" + " | unzip /home/pi/" + version + ".zip -d /home/pi");
Thread.sleep(2 * 1000);
p = Runtime.getRuntime().exec("unzip /home/pi/1.2.1.zip -d /home/pi");
// Process p = Runtime.getRuntime().exec("wget https://install.swiftpcb.tech/" + version + ".zip" + " && unzip" + version + ".zip -d /home/pi ");
int updateStat = lite.updateRanValue("1");
if(updateStat != 0) System.out.println("Something went wrong");
}
}
}
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"))
I have a Java program created that runs VBSscripts after button clicks.
examplescript.vbs
How do I compile these vbs files and then call them to run in the program code? I've been troubleshooting for several days and can't find an answer. Once again I need to be able to run these scripts, at one point I had an input stream created to it but couldn't get it as a vbs file. Hopefully I'm overlooking something here
Edit:
This is what I currently have. With this code I receive the error "Windows Script Host. There is no script extension for file extension ".BufferedInputStream#4e34904""
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("hello.vbs");
try {
Runtime.getRuntime().exec("wscript " + is);
}
catch( IOException e ) {
System.out.println(e);
System.exit(0);
}
System.out.print(is);
You can run your VBScript as below.
Runtime.getRuntime().exec( "wscript path/to/examplescript.vbs" );
As already mentioned, VBScript is a script and doesn't need compiling. If you want to run code written in VBScript then you can do it this way:
This example uses VBScript to get the Motherboard Serial Number of a computer that is running Microsoft Windows:
try {
// Create a temporary script file named MBSerialxxxxxxxx.vbs
File file = File.createTempFile("MBSerial",".vbs");
// Delete the temporary file when virtual machines terminates
file.deleteOnExit();
try (FileWriter fw = new java.io.FileWriter(file)) {
String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
fw.write(vbs);
}
// Run the VBScript file....
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
// Read in any output to the command window.
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
// display the output...
System.out.println(line.trim());
}
input.close();
}
catch(IOException e){
e.printStackTrace();
}
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;
}
}
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 :)