Java tutorial
/** * $HeadURL$ */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bs.ws1.dm.itg; import bs.exceptions.ServiceException; import bs.util.Helper; import bs.ws1.dm.itg.csv.PurchaseOrder; import bs.xml.ws1.Delvry03IdocStrategy; import gen.ws1.idoc.delvry03.E1EDL20; import gen.ws1.idoc.delvry03.E1EDL24; import gen.ws1.idoc.delvry03.E1EDL41; import gen.ws1.idoc.delvry03.EDIDC40; import gen.ws1.idoc.delvry03.IDOC; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import org.milyn.Smooks; import org.milyn.SmooksException; import org.milyn.container.ExecutionContext; import org.milyn.csv.CSVRecordParserConfigurator; import org.milyn.flatfile.Binding; import org.milyn.flatfile.BindingType; import org.milyn.io.StreamUtils; import org.milyn.payload.JavaResult; import org.milyn.payload.StringSource; import org.xml.sax.SAXException; /** * TODO * * @author mb <mb@waggawagga.com> * @copyright (c) 2007-2014, . AG * @created Oct 8, 2014 11:48:38 AM * * @$Revision$ * * @$LastChangedBy$ * @$LastChangedDate$ * @$Id$ */ public class App { private static final Logger LOG = Logger.getLogger(App.class.getName()); /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { LOG.info("### Simon Support App ..."); readIdoc(); readCsv(); } private static void readCsv() { try { LOG.info("############################################# read CSV"); String path2csv = "src/main/resources/csv/"; String poFile = path2csv + "20141009_purchaseOrder_w-cn.csv"; List<PurchaseOrder> poList = readCsvIntoObject(new PurchaseOrder(), "poList", poFile); for (PurchaseOrder po : poList) { LOG.info("MATNR=" + po.getMaterialNumber() + ", PONR=" + po.getPurchaseOrderNumber()); } } catch (IOException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } private static void readIdoc() throws FileNotFoundException { LOG.info("############################################# read iDOC"); String path2xml = "src/main/resources/xml/"; String path2output = "src/main/resources/output/"; Delvry03IdocStrategy delvry03IdocStrategy = new Delvry03IdocStrategy(); FileInputStream fileInputStream = new FileInputStream(path2xml + "DESADV_49502236.xml"); //FileInputStream fileInputStream = new FileInputStream(path2xml + "DESADV_ch4.xml"); String output = ""; String separator = "|"; try { IDOC idoc = delvry03IdocStrategy.getIdoc(fileInputStream, Helper.IsToValidateXsd.TRUE); EDIDC40 edidc40 = idoc.getEDIDC40(); LOG.info("docType=" + edidc40.getIDOCTYP()); output = output.concat(edidc40.getIDOCTYP() + separator); LOG.info("docNum=" + edidc40.getDOCNUM()); output = output.concat(edidc40.getDOCNUM()); output = output.concat("\n"); output = output.concat("MATNR" + separator); output = output.concat("POSNR" + separator); output = output.concat("BSTNR" + separator); output = output.concat("BSTDT" + separator); output = output.concat("POSEX" + separator); output = output.concat("\n"); output = output.concat(edidc40.getDOCNUM() + separator); List<E1EDL20> e1edl20s = idoc.getE1EDL20(); for (E1EDL20 e1edl20 : e1edl20s) { List<E1EDL24> e1edl24s = e1edl20.getE1EDL24(); for (E1EDL24 e1edl24 : e1edl24s) { List<E1EDL41> e1edl41s = e1edl24.getE1EDL41(); LOG.info("MATNR=" + e1edl24.getMATNR()); output = output.concat(e1edl24.getMATNR() + separator); LOG.info("POSNR=" + e1edl24.getPOSNR()); output = output.concat(e1edl24.getPOSNR() + separator); for (E1EDL41 e1edl41 : e1edl41s) { LOG.info("BSTNR=" + e1edl41.getBSTNR()); output = output.concat(e1edl41.getBSTNR() + separator); LOG.info("BSTDT=" + e1edl41.getBSTDT()); output = output.concat(e1edl41.getBSTDT() + separator); LOG.info("POSEX=" + e1edl41.getPOSEX()); output = output.concat(e1edl41.getPOSEX()); } output = output.concat("\n"); } } writeToFile(output, path2output + "delvry03_report.csv"); } catch (ServiceException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } private static void writeToFile(String output, String filename) { Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename + ".csv"), "utf-8")); writer.write(output); } catch (IOException ex) { // report } finally { try { writer.close(); } catch (Exception ex) { } } } private static List<PurchaseOrder> readCsvIntoObject(PurchaseOrder dataObject, String beanID, String file) throws IOException, SAXException { return runSmooksTransformPurchaseOrder(dataObject, beanID, readFileIntoString(file)); } private static void validatePurchaseOrderStock(String file, String beanID) throws SmooksException, IOException, SAXException { try { PurchaseOrder data2validate = new PurchaseOrder(); if (csvStructureValid(file, PurchaseOrder.class.getSimpleName(), data2validate.getNofFields())) { List<PurchaseOrder> records = runSmooksTransformPurchaseOrder(data2validate, beanID, readFileIntoString(file)); if (records.size() > 0) { int totalRecords = records.size(), invalidRecords = 0; for (PurchaseOrder record : records) { if (record.isValid()) { // LOG.log(Level.INFO, record.getClass().getSimpleName() + " valid: " + record.toCsvString()); } else { LOG.log(Level.INFO, record.getClass().getSimpleName() + " INVALID: " + record.toCsvString()); invalidRecords++; } } LOG.log(Level.INFO, data2validate.getClass().getSimpleName() + ": " + String.valueOf(totalRecords - invalidRecords) + " of " + String.valueOf(totalRecords) + " records valid [" + percentage(totalRecords, invalidRecords) + "]"); } } } catch (FileNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } private static List<PurchaseOrder> runSmooksTransformPurchaseOrder(PurchaseOrder dataClass, String beanId, String messageIn) throws IOException, SAXException, SmooksException { Smooks smooks = new Smooks(); try { CSVRecordParserConfigurator csvrpc = new CSVRecordParserConfigurator(dataClass.getCsvFields()); csvrpc.setSeparatorChar(dataClass.getSeparatorChar()); Binding binding = new Binding(beanId, dataClass.getClass(), BindingType.LIST); smooks.setReaderConfig(csvrpc.setBinding(binding)); // Configure the execution context to generate a report... ExecutionContext executionContext = smooks.createExecutionContext(); //executionContext.setEventListener(new HtmlReportGenerator("target/report/report.html")); JavaResult javaResult = new JavaResult(); smooks.filterSource(executionContext, new StringSource(messageIn), javaResult); return (List<PurchaseOrder>) javaResult.getBean(beanId); } finally { smooks.close(); } } private static String readFileIntoString(String file) { try { return StreamUtils.readStreamAsString(new FileInputStream(file)); } catch (IOException e) { LOG.log(Level.SEVERE, e.getMessage()); return "<no-message/>"; } } public static List<String> readFileIntoStringList(String filename) throws FileNotFoundException { List<String> lines = new ArrayList<String>(); Scanner fileScanner = null; fileScanner = new Scanner(new File(filename)); while (fileScanner.hasNextLine()) { lines.add(fileScanner.nextLine()); } return lines; } private static String percentage(int total, int invalid) { int valid = total - invalid; int percentage = valid * 100 / total; return String.valueOf(percentage).concat(" %"); } private static boolean csvStructureValid(String csvFile, String dataClass, int nofFieldsReference) throws FileNotFoundException { boolean structureValid = false; List<String> lines = readFileIntoStringList(csvFile); int lineCounter = 1, nofFields = 1, invalidRecords = 0; for (String line : lines) { nofFields = StringUtils.countMatches(line, "|") + 1; if (nofFieldsReference != nofFields) { // error case .... LOG.log(Level.SEVERE, dataClass + ": Line " + String.valueOf(lineCounter) + " - " + nofFields + " fields -> expected=" + nofFieldsReference); //LOG.log(Level.SEVERE, line); invalidRecords++; } lineCounter++; nofFields = 1; } LOG.log(Level.INFO, "\n\n########################## csv structure test###################################"); if (invalidRecords < 1) { structureValid = true; LOG.log(Level.INFO, dataClass + ": CSV structure valid:\t\t".concat(String.valueOf(lines.size())).concat(" records")); } else { LOG.log(Level.INFO, dataClass + ": Total records:\t\t\t".concat(String.valueOf(lines.size())).concat(" lines")); LOG.log(Level.INFO, dataClass + ": Total invalid records:\t\t".concat(String.valueOf(invalidRecords)).concat(" lines")); LOG.log(Level.INFO, dataClass + ": Total valid records:\t\t" .concat(String.valueOf(lines.size() - invalidRecords)).concat(" lines")); } return structureValid; } }