This question already has answers here:
backup mysql database java code
(3 answers)
Closed 9 years ago.
I am trying to take mysql database backup by using following code but I am getting exception like below when I run the program. Plz can anyone plz help out to solve this problem.
Java Code:
String path = "D:/databasbac.sql";
String username = "root";
String password = "";
String dbname = "ranjith";
String executeCmd = "<Path to MySQL>/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(new String[] { "cmd.exe", "/c", executeCmd });
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
There are at least two issues:
Provide a full path to mysqldump.exe (e.g. C:\Program Files\MySQL\bin\mysqldump.exe)
-p parameter without a password value forces mysqldump to prompt for it. And you don't want it since you running it in a batch mode. Therefore either provide a password -p"your password" or better (and more secure) use an option file to avoid giving the password on the command line. Read more on this End-User Guidelines for Password Security
Related
The following commands works directly:
rsync -rtuc --delete-after --exclude '.git*' --filter 'protect .git/**/*' ~/some/source/ ~/some/destination/
But when run via java:
private Boolean syncFiles() {
// Success flag default to true
Boolean success = true;
// Attempt sync repo
try {
ProcessBuilder runtimeProcessBuilder = new ProcessBuilder().inheritIO().command(new String[]{
"rsync", "-rtuc","--delete-after", "--exclude", "'.git*'", "--filter", "'protect .git/**/*'", "~/some/source/", "~/some/destination/"
});
// Wait until process terminates
int output = runtimeProcessBuilder.start().waitFor();
// Determine if successful
if (output == 0) {
System.out.println("Backup of " + getSource() + " to " + getDestination()
+ " was successful");
} else {
System.out.println("Error: rsync returned error code: " + output);
success = false;
}
} catch (Exception ex) {
success = false;
System.out.println("Error:");
System.out.println(ex.getMessage());
Logger.getLogger(Rsync.class.getName()).log(Level.SEVERE, null, ex);
}
return success;
}
I get the error:
Unknown filter rule: `'protect .git/**/*'' Error: rsync returned error
code: 1 rsync error: syntax or usage error (code 1) at exclude.c(902)
[client=3.1.2]
The shell handles quoting before passing the parameters to the command.
The comes into play with this part of your command line:
'protect .git/**/*'
The shell interprets this as the single parameter:
protect .git/**/*
If the single quotes had not been there in the first place, the shell would have:
interpreted it as two parameters (because of the space)
expanded glob characters like "*"
The solution is to pass:
"protect .git/**/"
as one of your Java parameters, rather than "'protect .git/**/*'".
You may have similar problems with ~, which the shell will expand to your home directory.
The answer to the solution is as follows:
The ProcessBuilder object needs to be initialised as follows:
ProcessBuilder runtimeProcessBuilder = new ProcessBuilder().inheritIO().command(new String[]{
"rsync", "-rtuc","--delete-after", "--filter", "protect .git", "--exclude", "'.git*'", "~/some/source/", "~/some/destination/"
});
I am trying to run Appium Serve on my Windows 7 machine using a simple command:
D:\Appium\node.exe D:\Appium\node_modules\appium\bin\Appium.js -g C:\Users\vdopia\AppData\Local\Temp\applog_12232015_110310.txt --no-reset
in command prompt, it shows that Appium is started. When I browse the url http://127.0.0.1:4723, I get the message below in my command prompt and because of this I am not able initialize remotedriver also. Surprisingly, the same thing works well in MAC.
Logs:
> info: --> GET / {}
> info: [debug] Responding to client that we did not find a valid resource
> info: <-- GET / 404 0.712 ms - 47
> info: <-- GET /favicon.ico 200 0.535 ms - 1150
I am pasting code here to start appium server, first I am writing command in a sh or bat file then executing the bat file.
public static boolean startAppiumServer()
{
//Kill any Existing Appium Before Starting new session
logger.info("Stopping any running instance of appium. ");
try{SDKCommonUtils.killAppiumServer();}catch(Exception e){}
boolean flag = false;
File logFile = null;
String commandFile = null;
if(System.getProperty("os.name").matches("^Windows.*"))
{
//Getting temp dir
String tempDir = System.getProperty("java.io.tmpdir").toString();
logFile = new File(tempDir+"\\applog"+"_"+MobileTestClass_Methods.DateTimeStamp()+".txt");
commandFile = System.getenv("AUTOMATION_HOME").concat("\\tpt\\appium_commands.bat");
String appiumCmdLocation_Windows = MobileTestClass_Methods.propertyConfigFile.getProperty("appiumCmdLocationForWindows").toString();
String nodeExe = appiumCmdLocation_Windows.concat("\\node.exe");
String appiumJs = appiumCmdLocation_Windows.concat("\\node_modules\\appium\\bin\\Appium.js");
String strText = "start /B " + nodeExe + " " + appiumJs + " -g " + logFile.toString() + " --full-reset --command-timeout 60 ";
FileLib.WriteTextInFile(commandFile, strText);
}
else
{
logFile = new File("/tmp/applog"+"_"+MobileTestClass_Methods.DateTimeStamp()+".txt");
commandFile = System.getenv("AUTOMATION_HOME").concat("/tpt/appium_commands.sh");
String strText = "export PATH=$PATH:/usr/local/bin; /usr/local/bin/appium -g " + logFile.toString() + " --full-reset --command-timeout 60 " ;
FileLib.WriteTextInFile(commandFile, strText);
}
try
{
logger.info("Executing Command File: "+ commandFile +" to start appium service. ");
Runtime.getRuntime().exec(commandFile);
/** wait until appium server is started */
flag = waitForAppiumServer();
}
catch(Exception e)
{
flag = false;
logger.error("There were some issues while executing command to launch appium service. ",e);
}
return flag;
}
If you do not provide server address then it will be used as 0.0.0.0 from command prompt in windows as
info: Appium REST http interface listener started on 0.0.0.0:4723.
Please provide --address 127.0.0.1 --port 4723 parameter from command line and try to use same address and port while initializing driver object in your script.
Here is my code for mysql database restore code .when i tried this code app works without exception but application get hangs and database is not restored ..please help me
String databaseName = "sample"; //database name
String userName = "root"; // MySQL username
String password = ""; // MySQL password
int processComplete; // this variable for verify the process
String[] executeCmd = new String[]{"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
databaseName, "-u" + userName, "-p" + password, "-e", " source D:/data.sql"};
System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);// execute the command
processComplete = runtimeProcess.waitFor();
System.out.println(processComplete);
if (processComplete == 1) { // if return value equal to 1 then failed the process
JOptionPane.showMessageDialog(null, "Restore Failed");
} else if (processComplete == 0) {{// if return value equal to 0 then failed the process
JOptionPane.showMessageDialog(null, "Restore Completed");
}
I suspect that the last parameter is been mishandled
String[] executeCmd = new String[]{
"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
databaseName,
"-u" + userName,
"-p" + password,
"-e",
" source D:/data.sql" }
It should probably look more like...
String[] executeCmd = new String[]{
"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
databaseName,
"-u" + userName,
"-p" + password,
"-e",
"source",
"D:/data.sql" }
Each element in the array will be a separate argument passed to the command, this allows you the flexibility of passing arguments that have spaces in them without need to first escape them using quotes
You should consider using ProcessBuilder instead of trying to build the Process yourself, apart from allowing you to re-direct the error stream to the input stream, it also allows you to specify the starting context for the process.
You should also be reading the output of the process (via it's InputStream) which would possibly highlight issues and may also allow the process to exit (as some process won't exit until there stdout is read completely)
For example: How do I execute Windows commands in Java?
Is there a way to connect and disconnect VPN in Forticlient programmatically?
I see that with Cisco VPN Client, there are options such as using the APIs they provide or executing connectivity commands from my Java code. Views and opinions on these ways of connecting to VPN are also most welcome.
I am looking for such options or any other that is possible, with Forticlient software.
Any directions from here would be of great help.
My trial so far :
private static final String COMMAND = "C:/Program Files/Cisco/Cisco AnyConnect Secure Mobility Client/vpncli";
private ExpectJ exp = new ExpectJ(10);
public void connectToVPNViaCLI(String server, String uname, String pwd)
{
try {
String command = COMMAND + " connect " + server;
Spawn sp = exp.spawn(command);
sp.expect("Username: ");
sp.send(uname + "\n");
sp.expect("Password: ");
sp.send(pwd + "\n");
sp.expect("accept? [y/n]: ");
sp.send("y" + "\n");
} catch(Exception e) {
LOGGER.severe(e.getMessage());
}
}
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.
Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
upDomain(HSystemRDB.java:198)
at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)
Here is my code :
private static void flush() {
Class.forName("com.mysql.jdbc.Driver").newInstance();
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");
} catch (Exception e) {
System.out.println("Class Not Found Exception:");
System.out.println(e.getMessage());
}
try {
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String serverName = "localhost";
String mydatabase = "hpdata";
String url = "jdbc:mysql :// " + serverName + "/" + mydatabase;
String username = "root";
String password = "123456";
connection = DriverManager.getConnection(url, username, password);
} catch(Exception e) {
// appropriate action
}
Try loading the driver before using it by incorporating this line.
Class.forName("com.mysql.jdbc.Driver")
Make sure mysql-connector-java-<version-number>-bin.jar is in your classpath. If you don't have it, you can download it here.
You're assuming that you've set CLASSPATH properly. Please explain how you're doing that so we can tell you whether it's correct or not.
If you've set an environment variable named CLASSPATH, that's almost certainly wrong.
It makes a difference if your app is for the web or desktop. Please tell us which is true for you.
UPDATE:
The right way to set CLASSPATH for a desktop app is to use the -classpath option on the JVM when you run:
java -classpath .;<paths-to-your-JARs-separated-by-semi-colons>;<paths-to-the-root-of-package-trees> foo.YourCode
After setting CLASSPATH please copy mysql-connector-java-5.1.16-bin into these folders:
C:\Program Files\Java\jdk1.6.0_18\jre\lib\ext
and
C:\Program Files\Java\jre6\lib\ext