I have seen there are many articles on this issue and I tried all of them but I am still fail to create a backup using java.
Here is my code:
public class CreateBackup {
public static void main(String[] args) {
try {
File file = new File("mysqlBackup");
if (!file.isDirectory()) {
file.mkdir();
}
String fileName = "backup_" + new Date().getTime() + ".sql";
String path = file.getAbsolutePath() + "/" + fileName;
String cmd = "/usr/bin/mysqldump -uroot -proot userDb > " + path; //-The root after u is the mysql database user name, and the 123456 followed by - p is the user password. Note that there is no space; dbName fills in the database name that needs to be backed up, and the greater than sign is followed by the generated file path
System.out.println("path " +cmd);
Process runtimeProcess = Runtime.getRuntime().exec(cmd );
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");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I tried to run in ubuntu also tried with windows but mentioning mysqldump full path "C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump". Why my code is always returning backup failure? Help me, please. Thanks in advance.
I fixed this code by adding more lines. while executing.
File f = new File(file, new Timestamp(System.currentTimeMillis()).getTime() + ".sql");
String path = f.getPath();
String username = "root";
String password = "root";
String dbname = "userDb";
String executeCmd = "/usr/bin/mysqldump -u" + username + " -p" + password
+ " --add-drop-database -B " + dbname + " -r " + path;
Process runtimeProcess;
try {
// System.out.println(executeCmd);//this out put works in mysql shell
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
System.out.println(executeCmd);
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete" + processComplete);
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
Hope it will help others..
Related
I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.
I have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.
To achieve this:
I have to create Dir'y like
"/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put
data in it.
I've tried this so far:
private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
String fileName = filePath.substring(fileNameStartIndex);
String staticPath = "/var/local/recordingsbackup/";
String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";
try {
InputStream get = SourceChannel.get(filePath);
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
channelTarget.mkdir(completeBackupPath); // error on this line
channelTarget.put(get, completeBackupPath + fileName);
}
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
e.printStackTrace();
}
}
If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.
Please help me in this...how can I create these Nested Directories???
Finally, I've done it.
This is how I got succeed :
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
String[] complPath = completeBackupPath.split("/");
channelTarget.cd("/");
for (String dir : complPath) {
if (folder.length() > 0) {
try {
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.cd(folder);
} catch (SftpException e2) {
channelTarget.mkdir(folder);
channelTarget.cd(folder);
}
}
}
channelTarget.cd("/");
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.put(get, completeBackupPath + fileName);
}
I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
ch.mkdir(fullPath + folders[i]);
}
fullPath = fullPath + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I used this implementation to create nested folders.
I tried not to use Exception. Keep in mind that filesystem is linux based.
The OP already found a solution but I wanted to append to it.
Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.
Correction of the previous script:
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
// Add separator path
ch.mkdir(fullPath + "/" + folders[i]);
}
// Add separator path
fullPath = fullPath + "/" + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
Another solution is execute shell command:
String remotePath = "fake/folders/recursive/on/sftp/server";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// NOTE: the provided paths are expected to require no escaping
channel.setCommand("mkdir -p " + remotePath);
channel.connect();
while (!channel.isClosed()) {
// dir creation is usually fast, so only wait for a short time
Thread.sleep(SHORT_WAIT_MSEC);
}
channel.disconnect();
if (channel.getExitStatus() != 0) {
throw new IOException("Creating directory failed: " + remotePath);
}
So, I want to create a backup file for my mysql database.
However when i tried to run the code it takes too much time and still no response.
This is my code:
public void backup() {
String fileName = "";
URL url;
JFileChooser backupFile = new JFileChooser();
backupFile.setCurrentDirectory(new java.io.File("."));
backupFile.setDialogTitle("Select the Path of Backup");
backupFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
backupFile.setAcceptAllFileFilterUsed(false);
backupFile.setApproveButtonText("Backup Database");
backupFile.setSize(700, 400);
backupFile.setLocation(100, 100);
if (backupFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
url = backupFile.getSelectedFile().toURL();
fileName = url.toString().replaceAll("file:/", "").trim();
System.out.println(fileName);
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
System.out.println("No Selection");
}
try {
String dbName = AppVars.dbName;
String dbUser = AppVars.dbUserName;
String dbPass = AppVars.dbPassword;
if (!fileName.equals("") && fileName != null) {
String savePath = fileName + "ssmis.sql";
String executeCmd = AppVars.xamppUrl + "mysqldump -u " + dbUser + " -p " + dbPass + " --database " + dbName + " -r " + savePath;
System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("Here");
if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "Backup Successful", "Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Backup Failed", "Failed", JOptionPane.INFORMATION_MESSAGE);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error at Backup " + ex);
}
}
What am i doing wrong?
I am not sure if it is possible to take backup of all the tables individually in mysql, but if it is possible create a multi-threaded application which will take backup from all the tables and they will create backup file individually for each table which probably you can merge from your code. Use count down latch in each thread. Once the processing of threads are done you can merge the files.
If you're running this code in an event listener it will freeze the GUI until the backup completes. You need to run it in a separate thread.
I am trying to backup my database and this is the code I've written but for some reason it is not backing up?? i am using local host (MAMP) and the operating system I am using is MAC OSX.
public boolean databaseBackup(String dbName, String dbUserName, String dbPassword, String path) {
String qu = "/Applications/MAMP/Library/bin/mysqldump -u" + dbUserName + " -p" + dbPassword + " --database" + dbName + " -r " + path;
System.out.println(qu);
Process runtimeProcess;
Properties pr = new Properties();
pr.setProperty("user", "username");
pr.setProperty("password", "password");
Connection con = null;
PreparedStatement stmt = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:8889/Database", pr);
runtimeProcess = Runtime.getRuntime().exec(qu);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("5");
System.out.println("Backed up");
return true;
} else {
System.out.println("Not Backed up");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
}
in my jframe form I wrote this:
code.databaseBackup("Database","root", "root", "/Users/dipeshramesh/Dropbox/TeamProject/TeamProject2.sql");
so when a person press backup button it calls code.databaseBackup method and dose its jobs.
if I run this it shows a message "Not Backed up" dose any know this?
use String qu = "/Applications/MAMP/Library/bin/mysqldump -u" + dbUserName + " -p" + dbPassword + " --database" + dbName + " > " + path;
command - /Applications/MAMP/Library/bin/mysqldump -u yourUser -p --opt yourdb > yourdump.sql
This is the code I created for exporting the database. The problem is, the file is not exported, and the code shows no error message.
public boolean exportDatabase(String fromServer,
String FileName,
String FilePath,
int ExportOpions) {
try {
String dbName ="NMSAzzist";
String dbUser = "root";
String dbPass ="root";
String dumbPath = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\";
String executeCmd = dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+ "";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 1) { // if values equal 1 process failed
JOptionPane.showMessageDialog(null, "Backup Failed");//display message
} else if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "\n Backup created Successfully..");
// display message
}
return true;
} catch (final Exception ex) {
NmsLogger.writeErrorLog("Database Connection Failed ", ex.toString());
NmsLogger.writeDebugLog(ex);
return false;
}
How can I export the database to a path specified in the variable FilePath in the name FileName? How can I solve the issue?
And BTW, can i use the following to import the same??
String[] executeCmd = new String[]{"mysql", databaseName, "-u" + userName, "-p" + password, "-e" + FileName };
You first try your executeCmd can run successfullly in db.
In your executeCmd is syntax error. Your code left file name in execution command in
String executeCmd = "/" + dumbPath + "mysqldump -u " + dbUser
+ " -p" + dbPass + " " + dbName + " -r " + FilePath + "\\"
+ FileName;
Check the manual
This works for me.
public class exportDataBase {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
exportDatabase("", "Sma_test.sql", "C:", 0);
}
public static boolean exportDatabase(String fromServer, String FileName,
String FilePath, int ExportOpions) {
try {
String dbName = "dmsdev";
String dbUser = "root";
String dbPass = "root";
String dumbPath = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\";
String executeCmd = "/" + dumbPath + "mysqldump -u " + dbUser
+ " -p" + dbPass + " " + dbName + " -r " + FilePath + "\\"
+ FileName;
System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete: " + processComplete);
if (processComplete == 1) {// if values equal 1 process failed
System.out.println("Backup failed");
}
else if (processComplete == 0) {
System.out.println("Backup Success");
}
return true;
} catch (final Exception ex) {
System.out.println("Connection failed");
return false;
}
}
}
Didn't you forget the Filename?
String executeCmd =dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+"\\"+Filename"";
Make it as :
// you did not give file name.
String executeCmd = "cmd " + dumbPath+"mysqldump -u "+dbUser+ "-p"+dbPass+" "+dbName+ "-r "+FilePath+ "\\" + filename;
// I tried running I am getting error code 13.
I think you should make :
if(processComplete != 0) {
//error with error code
} else {
//success
}
instead of
if (processComplete == 1) {// if values equal 1 process failed
System.out.println("Backup failed");
}
else if (processComplete == 0) {
System.out.println("Backup Success");
}
because error-code returned may be other than 0 and 1.
Suggestion : Use Apache Commons exec API, this is more sophisticated than Runtime.exec.
I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen?
below is the code to import files.
private void importEDIFiles(String host, String user, String password, String path, String road) {
try {
String edi824Path = path + "/" + EDI_824_FOLDER;
FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path);
FTPClient client = ftpBroker.makeFTPConeection();
String os = client.getSystemName();
client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
File edi824File = null;
File edi824Filebak = null;
ArrayList<FTPFile> files;
try {
FTPFile[] ftpfiles = client.listFiles();
logger.info("\t" + ftpfiles.length + " files are in ftp location ");
if (ftpfiles.length > 0) {
files = removeZeroFiles(ftpfiles);
for(int x=0;x<files.size();x++){
logger.info("name ---"+files.get(x).getName());
logger.info("size ----"+files.get(x).getSize());
}
String ftpFile = null;
logger.info("\t" + files.size() + " downloading from " + road + " rail road.");
for (int i = 0; i < files.size(); i++) {
ftpFile = files.get(i).getName();
logger.info("\t" + ftpFile + " is downloading....");
// logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty());
String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile;
String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile;
edi824File = new File(source);
edi824Filebak = new File(target);
FileOutputStream fosout = new FileOutputStream(source);
boolean isRetrieved = client.retrieveFile(ftpFile, fosout);
logger.debug("isRetrieved : " + isRetrieved);
FileUtils.copyFile(edi824File,edi824Filebak);
fosout.flush();
fosout.close();
boolean isDelete = client.deleteFile(ftpFile);
logger.debug("isDelete : " + isDelete);
}
} else {
logger.info("No files to Pull in the FTP Location for " + user);
//throw new RuntimeException("No files to Pull in FTP Location.");
}
} catch (Exception e) {
logger.error(e,e);
e.printStackTrace();
} finally {
client.logout();
client.disconnect();
}
} catch (Exception ex) {
logger.error(ex, ex);
ex.printStackTrace();
}
}
you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time