I am running a PHP code using java.lang.Process, I want to return a value as a result from the PHP code so I can get it from Process, how can I do that ?
This is the code I am using:
public void callPhpListener(String handler, String logFile, String messageId) throws Exception {
try {
LOGGER.info("Calling PHP executore with message id:" + messageId);
// LOGGER.info("Handler:" + handler + ", logFile:" + logFile + ", message id:" + messageId);
Process exec = Runtime.getRuntime().exec(
new String[] {"/bin/bash", "-c",
"php " + handler + " " + messageId +
" >> " + logFile + " 2>&1"});
exec.waitFor();
int exitValue = exec.exitValue();
LOGGER.info("exit value is " + exitValue);
if(exitValue != 0) {
throw new Exception("Processed with error");
}
LOGGER.info("Done processing message with id:" + messageId);
} catch (Exception e) {
LOGGER.error(e.getMessage());
throw new Exception();
}
}
I am processing a .csvfile. I would like to print only my first and last lines. I have accomplished this using normal Java code but, I did not find any Inputformatwhich will read the lines and find first and last line. My Java code is as as below.
public class CSVToJSON {
public static void main(String[] args) throws ParseException, ClassNotFoundException, FileNotFoundException {
File file = new File("/../Desktop/ABCD.txt");
try {
BufferedReader csvFile = new BufferedReader(new FileReader("/../Desktop/.csv"));
BufferedWriter jsonFile = new BufferedWriter(new FileWriter(file));
InputStream inputStream = new ByteArrayInputStream(jsonNew.getBytes(StandardCharsets.UTF_8));
jsonFile.write(jsonNew);
jsonFile.newLine();
String next, fileContent = csvFile.readLine();
for (boolean first = true, last = (fileContent == null); !last; first = false, fileContent = next)
{
last = ((next = csvFile.readLine()) == null);
if (first)
{
String[] tab = fileContent.split(",");
String line = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "],";
InputStream inputStreamNew = new ByteArrayInputStream(line.getBytes(StandardCharsets.UTF_8));
jsonFile.write(line);
jsonFile.newLine();
}else if (last) {
String[] tab = fileContent.split(",");
String lineLast = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "]" + "\n" + "];
InputStream inputStreamNewLine = new ByteArrayInputStream(lineLast.getBytes(StandardCharsets.UTF_8));
jsonFile.write(lineLast);
jsonFile.newLine();
}else {
String[] tab = fileContent.split(",");
String line = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "],";
inputStream inputStreamNormalLine = new ByteArrayInputStream(line.getBytes(StandardCharsets.UTF_8));
jsonFile.write(line);
jsonFile.newLine();
}
}
csvFile.close();
jsonFile.close();
} catch (FileNotFoundException e) {
Logger.getLogger(CSVToJSON.class.getName()).log(Level.SEVERE, null, e);
} catch (IOException e) {
Logger.getLogger(CSVToJSON.class.getName()).log(Level.SEVERE, null, e);
}
I am going to take database backup by using java code.This code is excuting fine but I am getting int processComplete = runtimeProcess.waitFor(); This method calling is returning the integer as 1. So finally I am getting the message as could not create backup as sop.
public static void main(String[] args) {
String path = "D:/databasebackup/databasbac.sql";
String username = "root";
String password = "";
String dbname = "rac";
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 });
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();
}
}
I was facing similar problem in database backup from MYSQL through JDBC. So I ran the below code.
String path = C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump
String command= "cmd.exe /c "
+ "\"\""+path+"\" "
+ " --user="+UserInputs.getDbUserName()
+ " --password="+UserInputs.getDbPassword()
+ " --host="+UserInputs.getDbConnectionIP()
+ " --protocol=tcp "
+ " --port="+UserInputs.getDbConnectionPort()
+ " --default-character-set=utf8 "
+ " --single-transaction=TRUE "
+ " --routines "
+ " --events "
+ "\""+UserInputs.getDbName()
+"\" "
+ ">"
+ " \""
+ "D:\\MY DATA\\DB_Backup.sql"
+ "\""
+ " \"";
Runtime runtime = Runtime.getRuntime(command);
In case password is blank remove the --password line.
This will create your database backup.
In case you are running this on LINUX replace
cmd.exe /c
by
/bin/sh -c
Thanks!
Try out my code for backup the database using java. It works well for me.
try {
String filename = null;
FileChooser.setVisible(true);
int result = FileChooser.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
filename = FileChooser.getSelectedFile().toString().concat(".sql");
File file = new File(filename);
if (file.exists()) {
Object option[] = {"Sim", "Nao"};
int opcao = JOptionPane.showOptionDialog(null, "aaa", "bbbb", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, option, option[0]);
if (opcao == JOptionPane.YES_OPTION) {
Runtime backup = Runtime.getRuntime();
backup.exec("C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABSE NAME");
JOptionPane.showMessageDialog(null, "Backup succesfully");
} else {
FileChooserActionPerformed(evt);
}
} else {
Runtime backup = Runtime.getRuntime();
backup.exec("C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABASE NAME");
JOptionPane.showMessageDialog(null, "Backup succesfully");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "Error.!", 2);
}
And this is the DbOperation class That i have written.
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DbOperation {
String url = "jdbc:mysql://localhost:3306/give your database name";
String username = "your username";
String password = "your password";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public Connection backupDB(){
try{
con=DriverManager.getConnection(url, username, password);
}catch(SQLException e){
System.out.println(e.getMessage());
}
return con;
}
}
Try this:
int processComplete = runtimeProcess.exitValue();
runtime info
Hope this helps
I am trying to use wkhtml2pdf in JBoss with Java to create PDF files. I was successful, but it only creates a PDF file from my login-page, rather than from the jsp file.
I read that it is possible to add parameters like username or password, and this is what I did:
String command = applicationLocation + "wkhtmltopdf.exe " + "--post j_username=" + username +" --post j_password=" + password + " " + reqURL + "?" + reqQuery + " c:/PDF/" + folderName + "/" + id + "/" + folderName + ".pdf";
But that doesn't create a PDF file, not even an error output. This is how my class looks like:
public class GeneratePDF {
String logUserId = "0";
public String path = "c:/PDF";
String applicationLocation = "C:\\Program Files\\wkhtmltopdf\\";
/**
* This method creates a command which calls wkhtmltopdf from Google in order to create a PDF file.
*
* #param reqURL
* #param reqQuery
* #param folderName
* #param id
*/
public void genrateCmd(String reqURL, String username, String password, String reqQuery, String folderName, String id) {
try {
// make sure c:/eGP exists
File destFoldereGP = new File("c:/eGP");
if (destFoldereGP.exists() == false) {
destFoldereGP.mkdirs();
System.out.println("successfully created c:/eGP");
}
// make sure c:/PDF exists
File destFolderPDF = new File("c:/PDF/");
if (destFolderPDF.exists() == false) {
destFolderPDF.mkdirs();
System.out.println("successfully created c:/PDF");
}
// make sure c:/PDF/foldername exists
File destFolder = new File("c:/PDF/" + folderName);
if (destFolder.exists() == false) {
destFolder.mkdirs();
System.out.println("successfully created c:/PDF/foldername");
}
// make sure c:/PDF/foldername/id exists
File destFolder2 = new File("c:/PDF/" + folderName + "/" + id);
if (destFolder2.exists() == false) {
destFolder2.mkdirs();
System.out.println("successfully created c:/PDF/foldername/id");
}
//For Image change 'wkhtmltopdf.exe' to 'wkhtmltoimage.exe' and '.pdf' to '.jpeg'
String command = applicationLocation + "wkhtmltopdf.exe " + "--post j_username=" + username +" --post j_password=" + password + " " + reqURL + "?" + reqQuery + " c:/PDF/" + folderName + "/" + id + "/" + folderName + ".pdf";
System.out.println("Command to create PDF: " + command);
Runtime.getRuntime().exec(command);
System.out.println("Successfully created a new PDF file.");
} catch (IOException e1) {
System.out.println("Exception: " + e1);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Any idea how to create PDFs with wkhtml2pdf and form based authentication in JBoss?
Thanks a lot.
I have a java web application that I removed a function from the code and yet the database entries that this function writes are still being written to the database.
Inside the IssueWarrant function there is a call to insertWarrantFee that has been commented out.
private void issueWarrant(String CasePrefix, String CaseNumber, String HearingType, String Suspend)
{
int i = 0, intDivision = 0, pos = 0;
String SummSeq = getSummSeq(CasePrefix, CaseNumber);
String Charges = getCharges(CasePrefix, CaseNumber, HearingType);
boolean isVacated = false, isHearingFound = false;
NextBWNumber warrNbr = new NextBWNumber();
String WarrantNumber = warrNbr.getNextBWNumber();
String warrStatus = warrNbr.getNextBWNStatus();
String HearingDesc = "", Division = "";
isVacated = getVacatedStatus(CasePrefix, CaseNumber, HearingType);
isHearingFound = getHearingStatus (CasePrefix, CaseNumber, HearingType);
HearingDesc = getFormatToday() + " " + getHearingDesc(HearingType);
if (HearingDesc.length() > 30)
{
HearingDesc = HearingDesc.substring(0,30);
}
Division = getHearingJudge(CasePrefix,CaseNumber,HearingType);
intDivision = Integer.parseInt(Division);
if (intDivision < 10)
{ Division = "0" + Division; }
Statement localstmt = null;
String localqueryString;
localqueryString = "INSERT INTO " + library7 + "CMPBWPND" +
" (CASPRE, CASNUM, DEFSEQ, CHGSEQ, SUMSEQ, STSCOD, STSDAT," +
" STATUT, CHGABV, BWNBR, JUDCOD, PRVFLG, CT2FLG, DIVISN, BNDAMT," +
" BTYPE, CMNT, CUSER, TUSER, LUPDAT, SCRDAT, STATSDAT, SUMCRDAT, LUPDATE )" +
" VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + Charges.substring(i, i + 1) +
", " + SummSeq + ", 9, " + getShortDate() + ", 'RCP 12-A TA', 'WARRANT', '" +
WarrantNumber + "', " + intDivision + ", 'N', 1, '" + Division + "', " +
BondAmt + ", '" + BondType + "', '" + HearingDesc + "', 'TAAD', 'TAAD', " +
getShortDate() + ", " + getShortDate() + ", " + getLongDate() + ", " + getLongDate() +
", " + getLongDate() + ")";
try
{
if (!isVacated && isHearingFound)
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
StatusMsg = "Client No Show-WI";
}
if (isVacated)
{
StatusMsg = "Client Vacated Case";
}
if (!isHearingFound)
{
StatusMsg = "Client Hearing Missing";
}
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in IssueWarrant");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
**//insertWarrantFee(CasePrefix, CaseNumber, SummSeq, WarrantNumber);**
updateHearingRecord(CasePrefix, CaseNumber, HearingType, Charges.substring(i, i + 1), Suspend);
for ( i = 1; i < Charges.length(); i++ )
{
insertBWPTFRecord(CasePrefix, CaseNumber, SummSeq, Charges.substring(i, i + 1));
}
if (!success)
{
StatusMsg = "Client Iss. Warrant Failure";
}
}
Here is the code that the insertWarrantFee called before it was commented out:
private void insertWarrantFee(String CasePrefix, String CaseNumber, String SummSeq, String WarrantNumber)
{
Statement localstmt = null;
String localqueryString;
ResultSet localrSet = null;
String feeAmt = null;
localqueryString = "SELECT AUTO$$ FROM " + library3 + "CMPDKTTP WHERE DKTTYP = 'W'";
try
{
localstmt = conn.createStatement();
localrSet = localstmt.executeQuery(localqueryString);
while (localrSet.next())
{
feeAmt = localrSet.getString("AUTO$$");
}
localstmt.close();
localrSet.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in Insert Warrant Fee SQL1");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
localqueryString = "INSERT INTO " + library7 + "CMPBWTRN"
+ " (CASPRE, CASNUM, DEFSEQ, SUMSEQ, BWNBR, FEEAMT, DKTTYP, TUSER, LUPDAT)"
+ " VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + SummSeq + ", '" + WarrantNumber
+ "', " + feeAmt + ", 'W', 'TAAD', " + getShortDate() + ")";
try
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Insert Warrant Fee SQL2");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
}
So even though the line that called insertWarrantFee is commented out a record is still being inserted into CMPBWTRN.
Any ideas how this could happen? The developer is indicating it could be a tomcat connection cache issue? Any other suggestion beside magical code?
Thanks!
Leslie
A couple of things to try:
Make sure you've redeployed the application and have restarted Tomcat. Check the timestamp of the deployed class in question.
Clean Tomcat's tmp and work directories
Open the deployed Java class using a decompiler to see whether the removed code is still in there.
Add a logging (or System.out.println) statement to the method that's commented out, and to the method calling it. See whether one or both are printed after redeploying the changes.