how to execute command in java having whitespaces in pathname - java

I want to take backup of database. I am using mysql databse and wamp server.For that i have written the following code.
Process runtimeProcess =Runtime.getRuntime().exec("C:\\wamp\\bin\\mysql\\mysql5.5.20\\bin\\mysqldump.exe -u root -pkarma dailyreport -r "+assign+"\\dailyreport.sql");
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0)
{
JOptionPane.showMessageDialog(null, "Backup has been taken successfully", "BackUp", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Could not take backup", "BackUp", JOptionPane.INFORMATION_MESSAGE);
}
In above code String assign denotes the the path where i want to save the backup of database. But problem is that i am taking the location to save backup at runtime.and if I select path where folder name contains space it could not take backup because System does not getting the path as it contains space.Please help me how should i change the runtime.getruntime.exec() command.

Pass the commands in as separate elements in a String array
String[] cmds = new String[] {
"C:\\wamp\\bin\\mysql\\mysql5.5.20\\bin\\mysqldump.exe",
"-u",
"root",
"-pkarma",
"dailyreport",
"-r",
assign+"\\dailyreport.sql"};
Process runtimeProcess = Runtime.getRuntime().exec(cmds);
Each element in the array becomes a separate parameter for the command.
Better still, use ProcessBuilder

Enclose the path in double quotes. That would help the shell see the entire argument as a single one instead of multiple arguments due to presence of space.
Process runtimeProcess =
Runtime.getRuntime().exec("C:\\wamp\\bin\\mysql\\mysql5.5.20\\bin\\mysqldump.exe "
+ "-u root -pkarma dailyreport -r \""
+ assign + "\\dailyreport.sql\" ");

Try to put the assign String between quotes:
Process runtimeProcess = Runtime.getRuntime().exec("C:\\wamp\\bin\\mysql"
+ "\\mysql5.5.20\\bin\\mysqldump.exe -u root -pkarma dailyreport "
+ "-r \""+assign+"\"\\dailyreport.sql");

Related

Java ProcessBuilder not executing git checkout command

I want to execute 4 commands using ProcessBuilder however 2nd command is not working properly.
My code:
public static void main(String[] args) {
String path_prj = "C:\\Users\\asali\\Desktop\\CallRepoCode";
String origBranch = "frontend";
ArrayList<String> paths = new ArrayList<>();
paths.add("server\\src\\main\\java\\org\\classes\\CallManager.java");
paths.add("server\\src\\main\\java\\org\\classes\\CallUtils.java");
paths.add("server\\src\\main\\java\\org\\classes\\Main.java");
String command_1 = "cd " + path_prj;
String command_2 = " & git checkout " + origBranch;
String command_3 = " & mkdir updated_cia_files ";
String command_4 = " ";
for (String path: paths) {
command_4 = command_4 + "& copy " + path + " updated_cia_files ";
}
String[] command = {"cmd.exe", "/C", command_1, command_2, command_3, command_4 };
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.start();
}
Basically, I want to go to the C:\\Users\\asali\\Desktop\\CallRepoCode and checkout to the frontend branch. There is a GitHub repo, so it should work. After checkout, I want to create a folder and copy 3 files to that folder.
I successfully create the folder and copy the files; however local repo does not checkout to the frontend branch.
EDIT
My command works when I run it manually on cmd.
When I remove the command_3 and command_4 on the code, it executes the git checkout command.
Maybe i can suggest you an other solution, You could use jgit and java directly to do these tasks from java directly
For example (not tested)
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.setMustExist( true );
repositoryBuilder.setGitDir( ... );
Repository repository = repositoryBuilder.build();
Ref ref = repository.checkout().
setCreateBranch(true).
setName("branchName").
setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).
setStartPoint("origin/" + branchName).
call();

Issue in Taking Mysql database backup from java

OK i know there are lots of questions and articles related to it,and after following them and playing with them still i can't able to succed.Here is my code
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.CodeSource;
import javax.swing.JOptionPane;
public class BackupData
{
public static void main(String[] args) {
try
{
/*NOTE: Getting path to the Jar file being executed*/
/*NOTE: YourImplementingClass-> replace with the class executing the code*/
CodeSource codeSource = BackupData.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
System.out.println("jarDir"+ jarDir);
/*NOTE: Creating Database Constraints*/
String dbName = "xyz";
String dbUser = "root";
String dbPass = "root";
/*NOTE: Creating Path Constraints for folder saving*/
/*NOTE: Here the backup folder is created for saving inside it*/
String folderPath = jarDir + "\\backup";
/*NOTE: Creating Folder if it does not exist*/
File f1 = new File(folderPath);
System.out.println("f1" + f1);
f1.mkdir();
/*NOTE: Creating Path Constraints for backup saving*/
/*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
String savePath = "\"" + jarDir + "\\backup\\" + "1.sql\"";
System.out.println("savepath" + savePath);
/*NOTE: Used to create a cmd command*/
String executeCmd = "C:\\Program Files\\MySQL\\MySQL Workbench 6.3 CE\\mysqldump -u " + dbUser + " -p " + dbPass + " --database " + dbName + " -r " + savePath;
/*NOTE: Executing the command here*/
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0)
{
System.out.println("Backup Complete");
}
else
{
System.out.println("Backup Failure");
System.out.println(processComplete);
}
}
catch (URISyntaxException | IOException | InterruptedException ex)
{
JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
}
}
}
And the output this code is giving - Backup Failure,2(Process Complete Value)
I just can't understand what am i doing wrong?am i missing something?
I just can't able to figure out that what the problem is,any help will be appreciated,Thanks.
Why do you do all this? There is a command line utility called mysqldump for this purpose.
The mysqldump client utility performs logical backups, producing a set
of SQL statements that can be executed to reproduce the original
database object definitions and table data. It dumps one or more MySQL
databases for backup or transfer to another SQL server. The mysqldump
command can also generate output in CSV, other delimited text, or XML
format. Also you can find the following links useful from mysql
manual.
https://dev.mysql.com/doc/refman/5.7/en/backup-methods.html
https://dev.mysql.com/doc/refman/5.7/en/copying-databases.html

Importing .sql file into MySQL using Java code

I'm trying to programmatically import a .sql file into MySQL. The .sql file was generated by mysqldump. I'm trying to do this dynamically in a Java program. But, it keeps failing on the "<" character within Java (I think). If I grab the String in the debugger of the command it's about to run (the "combined" variable below), and paste it into the command line, it works fine. Likewise, when I was trying to get the mysqldump working inside this program, it failed on the ">" character, and I had to replace it with the "--result-file=" argument to get it to work.
String command = mySqlPath + "mysql.exe";
String user = "-u " + settings.dbUser;
String password = "-p" + settings.dbPassword;
String db = settings.dbDatabase;
String inputFile = filePath + mySqlDumpFile;
String combined = command + " " + user + " " + password + " " + db + " < " + inputFile;
ExternalCommandExecuter ece = new ExternalCommandExecuter(combined);
int code = ece.execute();
This results in this String for example
C:\software\mysql5\bin\mysql.exe -u root -p<password>
db_name < C:\software\tomcat7\webapps\ROOT\WEB-INF\documents\dump-1461789460425.sql
Which will result in a exitCode of 1. Pasting it into the command line, and it'll work.
So I couldn't get it to work in Java by importing the file with a "<", instead I had to write an external .sh/.bat file which I call from my Java code.

SQL do not accept AbsolutePath Java

I get a text file via:
JFileChooser dialog = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Текстовый файл", "txt");
dialog.removeChoosableFileFilter(dialog.getFileFilter());
dialog.addChoosableFileFilter(filter);
dialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
dialog.setDialogTitle("Выберите текстовый файл");
dialog.setDialogType(JFileChooser.OPEN_DIALOG);
dialog.setMultiSelectionEnabled(false);
int ret = dialog.showDialog(null, "Открыть");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = dialog.getSelectedFile();
pach = file.getAbsolutePath();
} else return;
System.out.println(pach);
Last command shows:
D:\data\streets.txt
Now I make a request:
try {
querySQL = "LOAD DATA LOCAL INFILE '" + pach + "' INTO TABLE " + DB_NAME + "." + TABLE_NAME + ";";
stSQL.execute(querySQL);
} catch (SQLException e) {
ErrorMsg(e, querySQL);
isError = true;
break;
}
And I do my ErrorMsg issues:
Unable to process the query:
LOAD DATA LOCAL INFILE 'D:\data\streets.txt' INTO TABLE base2.streets;
java.sql.SQLException: Unable to open file 'D:datastreets.txt'for 'LOAD DATA LOCAL INFILE' command.Due to underlying IOException:
Where it removes the skew, and why all this is happening? In fact, if such a request is inserted into Workbench, the query is executed without error. Please tell me the solution of this problem, it is very necessary. Thank you in advance.
P.S. The text is translated into English by Google Translate
You may want to escape the backslashes contained in your path. For you database a backslash ( \ ) can change the value in a way that the string cannot be saved in the database. This can be a problem with other special characters like ' also. Concatenating a string containing ' to you query, adds an additional ' which will break the query.
You can use StringEscapeUtils for doing this. https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

Convert image using image magick via java command says error

I need to convert all the tif, jpeg, gif to jpg format. For this am using
ProcessBuilder pb2 = new ProcessBuilder("convert.exe", "\"" +dest.toString()+ "\" ", "\" " + dest.getParent().toString().concat("/").concat(dest.getName().toString().substring(0, dest.getName().toString().lastIndexOf(".")).concat(".jpg"))+ "\" " );
System.out.println("convert " + "\"" + dest.toString() + "\" " + "\" " + dest.getParent().toString().concat("/").concat(dest.getName().toString().substring(0, dest.getName().toString().lastIndexOf(".")).concat(".jpg")) + "\" " );
pb2.redirectErrorStream(true);
try {
Process p2 = pb2.start();
System.out.println("jpg done for " + dest.getName());
new Thread(new InputConsumer(p2.getInputStream())).start();
try {
System.out.println("Exited with: " + p2.waitFor());
} catch (InterruptedException ex) {
Logger.getLogger(ImageFileCopy.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(ImageFileCopy.class.getName()).log(Level.SEVERE, null, ex);
}
It is saying error
"Invalid parameter - and
Exited with: 4"
I also tried giving "C:\Program Files\ImageMagick-6.8.6-Q16\convert.exe". If i use full path system not showing error but wating for long time.
Any idea plz suggest.
If you're using ProcessBuilder there's no need to "quote" your parameters, this is the point of using ProcessBuilder, it will guarantee that each separate parameter is passed as an argument to the command
ProcessBuilder pb2 = new ProcessBuilder(
"convert.exe",
dest.toString(),
dest.getParent().toString().concat("/").concat(dest.getName().toString().substring(0, dest.getName().toString().lastIndexOf(".")).concat(".jpg")));
I also agree with Rafael's suggestion, a wrapper API will make life a LOT easier ...
[face palm]...Windows has it's own convert program which is accessible via the PATH environment variable.
Even when I used pb.directory and set the directory to the install location of ImageMagick, it still picked up the Windows/MS program...
Try adding the full path to convert.exe
ProcessBuilder pb2 = new ProcessBuilder(
"C:\\Program Files\\ImageMagick-6.8.6-Q16\\convert.exconvert.exe",
dest.toString(),
dest.getParent().toString().concat("/").concat(dest.getName().toString().substring(0, dest.getName().toString().lastIndexOf(".")).concat(".jpg")));
And thanks to this answer for pointing it out...
I recommend to use im4java to call ImageMagick from your java code.
It is opensource, has API to call many ImageMagick functions and is easy to use.
invokation of an ImageMagick resize-function (for example) looks like that:
// create command
ConvertCmd cmd = new ConvertCmd();
// create the operation, add images and operators/options
IMOperation op = new IMOperation();
op.addImage("myimage.jpg");
op.resize(800,600);
op.addImage("myimage_small.jpg");
// execute the operation
cmd.run(op);
Check this simple developer's guide for more information.

Categories

Resources