I was able to create a backup of my current mysql database as .SQL file using the mysqldump.exe with the help of the following java code.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
Now I want to restore this same .SQL Backup file to mysql database using java code similar to above on the event of a button clicked.
Thanks a lot :)
So now I tried this ;
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr < C:\\SCM Files\\SQL Backup\\RR.sql");
Still it didn't work :/
public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", " source "+source};
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup restored successfully");
return true;
}
} else {
System.out.println("Could not restore the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
source example : "E:\\My Backup\\Test\\file.sql"
Runtime.getRuntime().exec("mysql -u username -ppassword database_name FILE.sql")
This statement will regenerate database from the file
You have to use java swings where you can design forms. Here is some code which can do that.
import javax.swing.JFrame;
public final class RestoreMySQLDatabase extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
RestoreMySQLDatabase restoreMySQL = new RestoreMySQLDatabase();
restoreMySQL.setTitle("Restore mysql database");
javax.swing.JButton butRestore = new javax.swing.JButton("Restore");
butRestore.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
try{
Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Successfully restored");
}catch(java.lang.Exception e){
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Not able to restore");
}
}
});
}
}
I tried this code and works as perfect!
String[] restoreCmd = new String[]{"mysql ", "--user=" + DB.DB_USERNAME, "--password=" + DB.DB_PASSWORD, "-e", "source " + pathToFile};
try {
Process runtimeProcess = Runtime.getRuntime().exec(restoreCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Done");
} else {
System.out.println("Failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
You should try DbUnit for backup and restore of database.Here is the demo code for that:
try {
Class.forName(DBDRIVER);
Connection jdbcConnection = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new MySqlDataTypeFactory());
//////// Database backup
ITableFilter filter = new DatabaseSequenceFilter(connection);
IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
ExcludeTableFilter excludeFilter = new ExcludeTableFilter();
excludeFilter.excludeTable("DATABASECHANGELOG*");
IDataSet excludedataset = new FilteredDataSet(excludeFilter, dataset);
FlatXmlDataSet.write(excludedataset, new FileOutputStream(backupfilename));
System.out.println("\n Complete backup successful.");
//////// Database backup
//////// Database restore
IDataSetProducer producer = new FlatXmlProducer(new InputSource(restoreFileName));
IDataSet dataSet = new StreamingDataSet(producer);
TransactionOperation operation = new TransactionOperation(DatabaseOperation.INSERT);
operation.execute(connection, dataSet);
//////// Database restore
} catch (DatabaseUnitException e) {
e.printStackTrace();
flag = false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Use the same dump to import like this.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr database_name < "C:\\SCM Files\\SQL Backup\\RR.sql");
For restore use the executeCmd in the form m.Torkashvand provided (array of strings). A working example on how to use these commands from JSP code can be found here
public static void mysqlExport(String host, String port, String user, String password, String dbname, String table, String folder, String query) {
System.out.println("------ Exporting "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " --where=\"" + query + "\" > " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(Arrays.asList("mysqldump", "--host="+host, "--port="+port, "--user="+user, "--password="+password, dbname, table, "--where="+query), folder + table + ".sql");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void mysqlImport(String host, String port, String user, String password, String dbname, String table, String folder) {
System.out.println("------ Importing "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysql --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " < " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(new String[]{"mysql", "--host="+host, "--port="+port, "--user=" + user, "--password=" + password, dbname, "-e", "source " + folder + table + ".sql"});
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static int executeCommand(String[] commands) throws IOException
{
System.out.println(commands.toString());
Process process = Runtime.getRuntime().exec(commands);
return dumpProcess(process);
}
public static int executeCommand(List<String> commands, String folder) throws IOException
{
ProcessBuilder builder = new ProcessBuilder(commands);
System.out.println(builder.command());
builder.redirectOutput(new File(folder));
Process process = builder.start();
return dumpProcess(process);
}
public static int dumpProcess(Process process) throws IOException
{
int returnValue = -1;
try {
String s = null;
process.waitFor();
returnValue = process.exitValue();
if (returnValue == 0) {
System.out.println("Command successful !!");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} else {
System.out.println("Command failed. Exist Status code = "+returnValue);
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
This is working code
public class Recover {
final static String filepath = "/home/shubhampanchal/Downloads/backup/configuration_files.sql";
public static void main(String[] args) throws Exception {
try {
String[] restoreCmd = new String[]{"mysql", "-uroot", "-p1", "Student", "-e", "source " + filepath};
Runtime rt =Runtime.getRuntime();
rt.exec(restoreCmd);
System.out.println("Restored successfully!");
} catch(Exception e) {
e.printStackTrace();
}
}
}
Related
I want to run a PowerShell command for create user using Java on a remote windows machine, I am writing this code in eclipse.
And below is the output, tried every reference and forms to resolve this issue can someone help me with this.
The command works on PowerShell command line, but it is not working in Java.
public class PowerShellSession {
private static String subModule = "PowerShellSession";
String targetIpAddress;
String username;
String password;
public static Object connectPShellLock = new Object();
public PowerShellSession() {}
public void exec(String cmd, String credentials) {
//String ex = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";
String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";
String[] args = new String[] { "powershell", ex};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
String command = "Exit-PSSession";
String[] args = new String[] { "powershell", command};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCredentials(String domain, String userName,
String password) throws IOException {
String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
+ "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
+ "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
//creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";
String[] args = new String[] { "powershell", creds};
execRemote(args);
return creds;
}
private void execRemote(String[] arguments) throws IOException {
ProcessBuilder builder = new ProcessBuilder(arguments);
builder.redirectErrorStream(true);
Process process = builder.start();
doProcessIO(process);
}
// Do the IO for a passed process
private void doProcessIO(Process p) throws IOException {
p.getOutputStream().close();
String line;
System.out.println("Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
p.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
public static void main(String[] args) throws IOException {
String ip_add = "192.168.193.101";
String user = "gs-259412";
String pass = "Windows412";
PowerShellSession psSession = new PowerShellSession();
String credentials = psSession.getCredentials(ip_add, user, pass);
psSession.targetIpAddress = ip_add;//;
String cmdd = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";//"Get-Culture";
if(!credentials.equals("")) {
psSession.exec(cmdd, credentials);
System.out.println("Finished PowerShell remote session.");
}
psSession.close();
}
}
Output of this program :
Output:
Error:
Done
Output:
A positional parameter cannot be found that accepts argument 'of'.
+ CategoryInfo : InvalidArgument: (:) [New-LocalUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewLocalUserCommand
+ PSComputerName : 192.168.193.131
Error:
Done
Finished PowerShell remote session.
I tried this link also enter link description here
Below method return me below path
Output - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
private String getPath() {
String mysqlpath = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(dbUrl, user, password);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ##datadir");
while (res.next()) {
mysqlpath = res.getString(1);
}
mysqlpath = mysqlpath.replace("\\Data", "\\bin").replace("\\", "\\\\");
System.out.println("Mysql path is :" + mysqlpath);
} catch (Exception ee) {
System.out.println(ee);
}
return mysqlpath;
}
Now i run below command to export mysql dump.
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(batchCommand);
batchCommand - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\mysqldump" -h localhost --port 3306 -u root --password=root123 --add-drop-database -B accountingbook -r "E:\softwares\Tomcat_accountingBook\webapps\accountingbookaccountingbook-localhost-(02-08-2017).sql"
Exception - java.io.IOException: Cannot run program ""C:\ProgramData\MySQL\MySQL": CreateProcess error=2, The system cannot find the file specified
I also tried below, but same issue:-
1.) Process p = runtime.exec(batchCommand.split(" "));
2.) Adding double quotes like "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
Problem is it breaks as soon as it encounters space.
From the Exception, it looks like JVM is not able to find MYSQL executable file at the location given.
This can be due to "\" file separator. Try using "\\" to separate your paths. Then your path would be : "C:\\ProgramData\\MySQL\\MySQL.
I'v written one class this might help you click here
public class RuntimeExample {
private final String commandCode = "cmd /c";
private final Scanner scanner = new Scanner(System.in);
private Process process;
private BufferedReader reader;
private String input = "";
private final String defaultCode = "help";
public RuntimeExample() {
UserInput();
}
private void UserInput() {
System.out.println("Enter command (ex: ipconfig)");
input = scanner.nextLine();
if (input.isEmpty()) {
System.out.println("You didn't give any command please take a look at these available Commands." + "\n");
sendCommand(defaultCode);
} else {
sendCommand(input);
}
}
private void sendCommand(String command) {
try {
process = Runtime.getRuntime().exec(commandCode + " " + command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
showResult(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void showResult(String result) {
System.out.println(result + "\n");
}
public static void main(String[] args) {
new RuntimeExample();
}
}
I am using Ubuntu. I want to use java application to dump the MySQL database. Below are my code:
String userName = "root";
String userPassword = "root";
String oldDatabaseName = "testing";
String executeCommand = "";
executeCommand = "mysqldump -u "+userName+" -p"+userPassword+" --no-data "
+OldDatabaseName+" > testingbackup.sql";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
System.out.println("Backup successful.");
}else{
System.out.println("Backup failed.");
}
But, when I run the above program, I always get the "Backup failed" message.
Am I writing the wrong code? And what library/file I need to include in my java application? Any help please.
This is working fine in my windows machine.
package org.some.test;
import java.io.File;
public class dateformat {
private static final String dbUserName = "root";
private static final String dbPassword = "manager";
private static final String dbName = "opencms";
public static void main(String[] args){
try {
File path =new File("D:\\dump1.sql");
String[] executeCmd = new String[]{"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql", "--user=" + dbUserName, "--password=" + dbPassword,""+ dbName,"-e", "source "+path};
Process p = Runtime.getRuntime().exec(executeCmd);
int processComplete = p.waitFor();
if (processComplete == 0)
{
System.out.println("Restore created successfully");
//return true;
}
else
{
System.out.println("Could not restore");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
It seems to me you omitted a space between -p and quote:
-p "+userPassword+
^-- insert space here
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
read/write to Windows Registry using Java
I want to read the registry value of the path HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Uninstall\{2FC099BD-AC9B-33EB-809C-D332E1B27C40}.
Can you please help me with the code?
This shows how to read the registry, but could be extended to write operations: How to read the Windows Registry
import java.io.*;
public class RegQuery {
private static final String REGQUERY_UTIL = "reg query ";
private static final String REGSTR_TOKEN = "REG_SZ";
private static final String REGDWORD_TOKEN = "REG_DWORD";
private static final String PERSONAL_FOLDER_CMD = REGQUERY_UTIL +
"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\"
+ "Explorer\\Shell Folders\" /v Personal";
private static final String CPU_SPEED_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ~MHz";
private static final String CPU_NAME_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ProcessorNameString";
public static String getCurrentUserPersonalFolderPath() {
try {
Process process = Runtime.getRuntime().exec(PERSONAL_FOLDER_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGSTR_TOKEN);
if (p == -1)
return null;
return result.substring(p + REGSTR_TOKEN.length()).trim();
}
catch (Exception e) {
return null;
}
}
public static String getCPUSpeed() {
try {
Process process = Runtime.getRuntime().exec(CPU_SPEED_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGDWORD_TOKEN);
if (p == -1)
return null;
// CPU speed in Mhz (minus 1) in HEX notation, convert it to DEC
String temp = result.substring(p + REGDWORD_TOKEN.length()).trim();
return Integer.toString
((Integer.parseInt(temp.substring("0x".length()), 16) + 1));
}
catch (Exception e) {
return null;
}
}
public static String getCPUName() {
try {
Process process = Runtime.getRuntime().exec(CPU_NAME_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGSTR_TOKEN);
if (p == -1)
return null;
return result.substring(p + REGSTR_TOKEN.length()).trim();
}
catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
public void run() {
try {
int c;
while ((c = is.read()) != -1)
sw.write(c);
}
catch (IOException e) { ; }
}
String getResult() {
return sw.toString();
}
}
public static void main(String s[]) {
System.out.println("Personal directory : "
+ getCurrentUserPersonalFolderPath());
System.out.println("CPU Name : " + getCPUName());
System.out.println("CPU Speed : " + getCPUSpeed() + " Mhz");
}
}
There's a tutorial that shows you without using Runtime.exec() function and uses specifically java.util.prefs.WindowsPreferences.
I am new to cryptography. I have to develop project based on cryptography..In part of my project I have to insert a key to the registry and afterwards I have to retrieve the same key for decryption.. I done until getting the path of the registry ..
Here I am showing my code:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public final class Project {
public static final String readRegistry(String location, String key) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg query " +
'"' + location + "\" /v " + key);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
if (!output.contains("\t")) {
return null;
}
// Parse out the value
String[] parsed = output.split("\t");
return parsed[parsed.length - 1];
} catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw = new StringWriter();
public StreamReader(InputStream is) {
this.is = is;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1) {
System.out.println("Reading" + c);
sw.write(c);
}
} catch (IOException e) {
System.out.println("Exception in run() " + e);
}
}
public String getResult() {
System.out.println("Content " + sw.toString());
return sw.toString();
}
}
public static boolean addValue(String key, String valName, String val) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg add \"" + key + "\" /v \"" + valName + "\" /d \"\\\"" + val + "\\\"\" /f");
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
System.out.println("Processing........ggggggggggggggggggggg." + output);
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
return output.contains("The operation completed successfully");
} catch (Exception e) {
System.out.println("Exception in addValue() " + e);
}
return false;
}
public static void main(String[] args) {
// Sample usage
JAXRDeleteConcept hc = new JAXRDeleteConcept();
System.out.println("Before Insertion");
if (JAXRDeleteConcept.addValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU", "REG_SZ", "Muthus")) {
System.out.println("Inserted Successfully");
}
String value = JAXRDeleteConcept.readRegistry("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU" , "Project_Key");
System.out.println(value);
}
}
But i dont know how to insert a key in a registry and read the particular key which i inserted..Please help me..
Thanks in advance..
It would be a lot easier to use the JRegistry library to edit the registry, rather than execute commands.