Back-up in JAVA takes too much time to execute - java

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.

Related

How to create Backup of a mysql database in java

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..

Request parameters coming from jsps are changed when two different users access the code same time

public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.

MYSQL Backup using java GUI

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

MySQL export with Java doesn't work

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.

Java FTP file get issue

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

Categories

Resources