Force target printer in Java - java

Is there a way to force the target printer in java, using HashPrintRequestAttributeSet ?
I don't want the user to be able to change the printer in the printdialog
Thanks

Had to figure this out the hard way, but for the future generations, here's some of my
code:
PrintService[] printServices;
PrintService printService;
PageFormat pageFormat;
String printerName = "Your printer name in Devices and Printers";
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName(printerName, null));
printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet);
pageFormat = new PageFormat(); // If you want to adjust heigh and width etc. of your paper.
pageFormat = printerjob.defaultPage();
PrinterJob printerjob = PrinterJob.getPrinterJob();
printerjob.setPrintable(new Server(), pageFormat); // Server was my class's name, you use yours.
try {
printService = printServices[0];
printerjob.setPrintService(printService); // Try setting the printer you want
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: No printer named '" + printerName + "', using default printer.");
pageFormat = printerjob.defaultPage(); // Set the default printer instead.
} catch (PrinterException exception) {
System.err.println("Printing error: " + exception);
}
try {
printerjob.print(); // Actual print command
} catch (PrinterException exception) {
System.err.println("Printing error: " + exception);
}

My code to solve this :
String printerNameDesired = "My Printer";
PrintService[] service = PrinterJob.lookupPrintServices(); // list of printers
DocPrintJob docPrintJob = null;
int count = service.length;
for (int i = 0; i < count; i++) {
if (service[i].getName().equalsIgnoreCase(printerNameDesired)) {
docPrintJob = service[i].createPrintJob();
i = count;
}
}
PrinterJob pjob = PrinterJob.getPrinterJob();
pjob.setPrintService(docPrintJob.getPrintService());
pjob.setJobName("job");
pjob.print();

I just solved this problem by running cmd command in Java
static void changeWindowsDefaultPrinter(String printerName) {
String cmdLine = String.format("RUNDLL32 PRINTUI.DLL,PrintUIEntry /y /n \"%s\"", printerName);
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", cmdLine );
builder.redirectErrorStream(true);
Process p = null;
try { p = builder.start(); }
catch (IOException e) { e.printStackTrace(); }
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = new String();
while (true) {
try {
line = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (line == null) { break; }
System.out.println( "result " + line);
}
}
And It's Wroked for Me :D

Related

Java Thermal Printer printing QRCode with Text

I am new to Java printing and wanted to to print a QRCode with a small number under it on a Thermal Printer (Brother QL-810W).
With my code I can print my QRCode, but I cannot figure out how to print a number or text, also I can't use ESC/P Commands for formatting.I tried using ByteArrays and escpos-coffe library but it won't work.
Code:
try {
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
aset.add(MediaSizeName.INVOICE);
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService printService: services) {
if (printService.getName().equals("Brother QL-810W")) {
DocPrintJob pj = printService.createPrintJob();
FileInputStream fis = new FileInputStream("C:/Local/QRCode1.png");
Doc doc = new SimpleDoc(fis, flavor, null);
pj.print(doc, aset);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
Heres the code I tried to work with the escpos-coffe libary:
try {
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService printService: services) {
if (printService.getName().equals("Brother QL-810W")) {
PrinterOutputStream printerOutputStream = new PrinterOutputStream(printService);
EscPos escpos = new EscPos(printerOutputStream);
escpos.writeLF("1235");
escpos.feed(5);
escpos.cut(EscPos.CutMode.FULL);
escpos.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
Thanks for helping me!

Printing plain text files to PDF printer using javax.print results in an empty file

I need to create a pdf file from plain text files. I supposed that the simplest method would be read these files and print them to a PDF printer.
My problem is that if I print to a pdf printer, the result will be an empty pdf file. If I print to Microsoft XPS Document Writer, the file is created in plain text format, not in oxps format.
I would be satisfied with a two or three step solution. (Eg. converting to xps first then to pdf using ghostscript, or something similar).
I have tried a couple of pdf printers such as: CutePDF, Microsoft PDF writer, Bullzip PDF. The result is the same for each one.
The environment is Java 1.7/1.8 Win10
private void print() {
try {
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
if (ps.length == 0) {
throw new IllegalStateException("No Printer found");
}
System.out.println("Available printers: " + Arrays.asList(ps));
PrintService myService = null;
for (PrintService printService : ps) {
if (printService.getName().equals("Microsoft XPS Document Writer")) { //
myService = printService;
break;
}
}
if (myService == null) {
throw new IllegalStateException("Printer not found");
}
myService.getSupportedDocFlavors();
DocPrintJob job = myService.createPrintJob();
FileInputStream fis1 = new FileInputStream("o:\\k\\t1.txt");
Doc pdfDoc = new SimpleDoc(fis1, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
HashPrintRequestAttributeSet pr = new HashPrintRequestAttributeSet();
pr.add(OrientationRequested.PORTRAIT);
pr.add(new Copies(1));
pr.add(MediaSizeName.ISO_A4);
PrintJobWatcher pjw = new PrintJobWatcher(job);
job.print(pdfDoc, pr);
pjw.waitForDone();
fis1.close();
} catch (PrintException ex) {
Logger.getLogger(Docparser.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(Docparser.class.getName()).log(Level.SEVERE, null, ex);
}
}
class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
If you can install LibreOffice, it is possible to use the Java UNO API to do this.
There is a similar example here which will load and save a file: Java Convert Word to PDF with UNO. This could be used to convert your text file to PDF.
Alternatively, you could take the text file and send it directly to the printer using the same API.
The following JARs give access to the UNO API. Ensure these are in your class path:
[Libre Office Dir]/URE/java/juh.jar
[Libre Office Dir]/URE/java/jurt.jar
[Libre Office Dir]/URE/java/ridl.jar
[Libre Office Dir]/program/classes/unoil.jar
[Libre Office Dir]/program
The following code will then take your sourceFile and print to the printer named "Local Printer 1".
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.view.XPrintable;
public class DirectPrintTest
{
public static void main(String args[])
{
// set to the correct name of your printers
String printer = "Local Printer 1";// "Microsoft Print to PDF";
File sourceFile = new File("c:/projects/WelcomeTemplate.doc");
if (!sourceFile.canRead()) {
throw new RuntimeException("Can't read:" + sourceFile.getPath());
}
com.sun.star.uno.XComponentContext xContext = null;
try {
// get the remote office component context
xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF = xContext
.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
com.sun.star.frame.XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime
.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
StringBuffer sUrl = new StringBuffer("file:///");
sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
List<PropertyValue> loadPropsList = new ArrayList<PropertyValue>();
PropertyValue pv = new PropertyValue();
pv.Name = "Hidden";
pv.Value = Boolean.TRUE;
loadPropsList.add(pv);
PropertyValue[] loadProps = new PropertyValue[loadPropsList.size()];
loadPropsList.toArray(loadProps);
// Load a Writer document, which will be automatically displayed
com.sun.star.lang.XComponent xComp = xCompLoader
.loadComponentFromURL(sUrl.toString(), "_blank", 0,
loadProps);
// Querying for the interface XPrintable on the loaded document
com.sun.star.view.XPrintable xPrintable = (XPrintable) UnoRuntime
.queryInterface(com.sun.star.view.XPrintable.class, xComp);
// Setting the property "Name" for the favoured printer (name of
// IP address)
com.sun.star.beans.PropertyValue propertyValue[] = new com.sun.star.beans.PropertyValue[2];
propertyValue[0] = new com.sun.star.beans.PropertyValue();
propertyValue[0].Name = "Name";
propertyValue[0].Value = printer;
// Setting the name of the printer
xPrintable.setPrinter(propertyValue);
propertyValue[0] = new com.sun.star.beans.PropertyValue();
propertyValue[0].Name = "Wait";
propertyValue[0].Value = Boolean.TRUE;
// Printing the loaded document
System.out.println("sending print");
xPrintable.print(propertyValue);
System.out.println("closing doc");
((com.sun.star.util.XCloseable) UnoRuntime.queryInterface(
com.sun.star.util.XCloseable.class, xPrintable))
.close(true);
System.out.println("closed");
System.exit(0);
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
Thank you for all. After two days struggling with various type of printers (I gave a chance to CUPS PDF printer too but I could not make it to print in landscape mode) I ended up using the Apache PDFbox.
It's only a POC solution but works and fits to my needs. I hope it will be useful for somebody.
( cleanTextContent() method removes some ESC control characters from the line to be printed. )
public void txt2pdf() {
float POINTS_PER_INCH = 72;
float POINTS_PER_MM = 1 / (10 * 2.54f) * POINTS_PER_INCH;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:m.ss");
PDDocument doc = null;
try {
doc = new PDDocument();
PDPage page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
doc.addPage(page);
PDPageContentStream content = new PDPageContentStream(doc, page);
//PDFont pdfFont = PDType1Font.HELVETICA;
PDFont pdfFont = PDTrueTypeFont.loadTTF(doc, new File("c:\\Windows\\Fonts\\lucon.ttf"));
float fontSize = 10;
float leading = 1.1f * fontSize;
PDRectangle mediabox = page.getMediaBox();
float margin = 20;
float startX = mediabox.getLowerLeftX() + margin;
float startY = mediabox.getUpperRightY() - margin;
content.setFont(pdfFont, fontSize);
content.beginText();
content.setLeading(leading);
content.newLineAtOffset(startX, startY);
BufferedReader fis1 = new BufferedReader(new InputStreamReader(new FileInputStream("o:\\k\\t1.txt"), "cp852"));
String inString;
//content.setRenderingMode(RenderingMode.FILL_STROKE);
float currentY = startY + 60;
float hitOsszesenOffset = 0;
int pageNumber = 1;
while ((inString = fis1.readLine()) != null) {
currentY -= leading;
if (currentY <= margin) {
content.newLineAtOffset(0, (mediabox.getLowerLeftX()-35));
content.showText("Date Generated: " + dateFormat.format(new Date()));
content.newLineAtOffset((mediabox.getUpperRightX() / 2), (mediabox.getLowerLeftX()));
content.showText(String.valueOf(pageNumber++)+" lap");
content.endText();
float yCordinate = currentY+30;
float sX = mediabox.getLowerLeftY()+ 35;
float endX = mediabox.getUpperRightX() - 35;
content.moveTo(sX, yCordinate);
content.lineTo(endX, yCordinate);
content.stroke();
content.close();
PDPage new_Page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
doc.addPage(new_Page);
content = new PDPageContentStream(doc, new_Page);
content.beginText();
content.setFont(pdfFont, fontSize);
content.newLineAtOffset(startX, startY);
currentY = startY;
}
String ss = new String(inString.getBytes(), "UTF8");
ss = cleanTextContent(ss);
if (!ss.isEmpty()) {
if (ss.contains("JAN") || ss.contains("SUMMARY")) {
content.setRenderingMode(RenderingMode.FILL_STROKE);
}
content.newLineAtOffset(0, -leading);
content.showText(ss);
}
content.setRenderingMode(RenderingMode.FILL);
}
content.newLineAtOffset((mediabox.getUpperRightX() / 2), (mediabox.getLowerLeftY()));
content.showText(String.valueOf(pageNumber++));
content.endText();
fis1.close();
content.close();
doc.save("o:\\k\\t1.pdf");
} catch (IOException ex) {
Logger.getLogger(Document_Creation.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (doc != null) {
try {
doc.close();
} catch (IOException ex) {
Logger.getLogger(Document_Creation.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

File rendering for PDF file print

I tried below code for print the PDF file for
public static void main(String args[])
{
FileInputStream psStream = null;
try {
psStream = new FileInputStream("E://ssc exam.pdf");
} catch (FileNotFoundException ffne) {
ffne.printStackTrace();
}
if (psStream == null) {
return;
}
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset);
// this step is necessary because I have several printers configured
PrintService myPrinter = null;
for (int i = 0; i < services.length; i++){
String svcName = services[i].toString();
System.out.println("service found: "+svcName);
if (svcName.contains("sfg")){
myPrinter = services[i];
System.out.println("my printer found: "+svcName);
break;
}
}
if (myPrinter != null) {
DocPrintJob job = myPrinter.createPrintJob();
try {
job.print(myDoc, aset);
} catch (Exception pe) {
pe.printStackTrace();}
} else {
System.out.println("no printer services found");
}
}
}
but i got "PDF file not printed.128 MB of memory is required to enable direct PDF printing" error,So I decide to use PDF rendering for print the PDF.can anyone to help how to use PDFfile rendering concept in detail.

what is the best way to print invoice in java

in my desktop application (POS System). I used IText api for generating invoices and printing, but my printer thermal invoice printer don't support .pdf file. only supporting text file and .docx file. i use simple text file printer print whole invoice in long vertical single word line and don't auto cut page. I used .docx file which works good, i got print as i designed. but my program first open document in ms word then give me print. my code is:
try
{
FileOutputStream output = new FileOutputStream(FILE);
XWPFDocument doc = new XWPFDocument();
CTBody body = doc.getDocument().getBody();
if(!body.isSetSectPr()){
body.addNewSectPr();
}
CTSectPr section = body.getSectPr();
if(!section.isSetPgSz()){
section.addNewPgSz();
}
CTPageSz pageSize = section.getPgSz();
pageSize.setOrient(STPageOrientation.PORTRAIT);
int value = 4000+(gui.model.getRowCount()*1000);
pageSize.setW(BigInteger.valueOf(4050));
pageSize.setH(BigInteger.valueOf(value));
CTPageMar pageMar = section.addNewPgMar();
pageMar.setLeft(BigInteger.valueOf(400L));
pageMar.setTop(BigInteger.valueOf(0L));
pageMar.setRight(BigInteger.valueOf(0L));
pageMar.setBottom(BigInteger.valueOf(0L));
XWPFParagraph para = doc.createParagraph();
para.setAlignment(ParagraphAlignment.LEFT);
XWPFRun run = para.createRun();
para.setWordWrap(true);
run.setBold(true);
run.setFontSize(10);
run.setText(" "+address.shopName);
run.addBreak();
run.setText(" "+address.phoneNo);
run.addBreak();
run.setText(" "+address.description);
run.addBreak();
para = doc.createParagraph();
para.setAlignment(ParagraphAlignment.LEFT);
run = para.createRun();
para.setWordWrap(true);
run.setFontSize(10);
run.setText("Invoice No."+invoiceno);
run.addBreak();
run.setText("Type: "+table);
run.addBreak();
run.setText("Customer Name: "+name+" "+tempObj);
run.addBreak();
run.setText("--------------------------------------------------------");
run.addBreak();
run.setText("Product Qty Price Total");
run.addBreak();
run.setText("--------------------------------------------------------");
run.addBreak();
String temp = null;
for(int i = 0 ; i < gui.table.getRowCount(); i++){
temp = gui.table.getValueAt(i, 1).toString();
String quanstr = gui.table.getValueAt(i, 2)+"";
String unitPricestr = gui.table.getValueAt(i, 3)+"";
String totalstr =gui.table.getValueAt(i, 4)+"";
run.setText(temp);run.addBreak();
run.setText(" "+quanstr+" "+unitPricestr+" "+totalstr);
run.addBreak();
}
double subTotal = tableTotalCounter();
run.setText("--------------------------------------------------------");run.addBreak();
run.setText("Discount: "+dis+"%");run.addBreak();
run.setText("Sub total: "+(subTotal - (subTotal*dis/100)));run.addBreak();
run.setText("Cash: "+cash);run.addBreak();
run.setText("Balance: "+(cash-(subTotal - (subTotal*dis/100))));
run.addBreak();
doc.write(output);
output.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("Exception");
e1.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Exception");
}
if(confirmation("Print invoice?","Confirmation")==0){
Desktop desktop = Desktop.getDesktop();
try {
desktop.print(new File(FILE));
} catch (IOException e) {
e.printStackTrace();
}
}
please tell me how to print without getting that file open. and there is any other way to print invoice.
Format your invoice in a string and pass to the code I have pasted below. Before executing this code print a test page (windows) (Linux) to make sure your printer is configured correctly.
public class GenerateInvoice {
public static void printInvoice(String invoice) {
try {
PrintService mPrinter = null;
Boolean bFoundPrinter = false;
PrintService[] printServices = PrinterJob.lookupPrintServices();
for (PrintService printService : printServices) {
String sPrinterName = printService.getName();
if (sPrinterName.equals("Black Cobra")) {
mPrinter = printService;
bFoundPrinter = true;
}
}
String testData = invoice+"\f";
InputStream is = new ByteArrayInputStream(testData.getBytes());
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE ;
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
System.out.println(service);
DocPrintJob job = service.createPrintJob();
Doc doc= new SimpleDoc(is, flavor, null);
PrintJobWatcher pjDone = new PrintJobWatcher(job);
job.print(doc, null);
pjDone.waitForDone();
is.close();
} catch (PrintException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
static class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
// Add a listener to the print job
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
}

How to restore a MySQL database backup using Java

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();
}
}
}

Categories

Resources