Advertisement
Guest User

Untitled

a guest
Jan 25th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.46 KB | None | 0 0
  1. package com.java;
  2.  
  3. import java.io.File;
  4. import java.io.FileFilter;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.FileReader;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.sql.Connection;
  12. import java.sql.DriverManager;
  13. import java.sql.PreparedStatement;
  14. import java.sql.ResultSet;
  15. import java.sql.SQLException;
  16. import java.text.DateFormat;
  17. import java.text.SimpleDateFormat;
  18. import java.util.ArrayList;
  19. import java.util.Date;
  20. import java.util.List;
  21. import java.util.Properties;
  22.  
  23. import javax.mail.Message;
  24. import javax.mail.MessagingException;
  25. import javax.mail.PasswordAuthentication;
  26. import javax.mail.Session;
  27. import javax.mail.Transport;
  28. import javax.mail.internet.InternetAddress;
  29. import javax.mail.internet.MimeMessage;
  30. import javax.xml.parsers.SAXParser;
  31. import javax.xml.parsers.SAXParserFactory;
  32.  
  33. import org.apache.log4j.Logger;
  34. import org.apache.log4j.PropertyConfigurator;
  35. import org.xml.sax.Attributes;
  36. import org.xml.sax.SAXException;
  37. import org.xml.sax.helpers.DefaultHandler;
  38. import org.apache.commons.io.filefilter.WildcardFileFilter;
  39.  
  40. /**
  41. * Class responsible for fetching data from xml file and updating the database
  42. * column.
  43. *
  44. * @author Manojeet Padhy
  45. *
  46. */
  47. public class GDYNEmployeeImportPurchase extends DefaultHandler {
  48.  
  49. /**
  50. * The logger to which log messages will be sent.
  51. */
  52. private static final Logger logger = Logger
  53. .getLogger(GDYNEmployeeImportPurchase.class);
  54.  
  55. static Session session = null;
  56.  
  57. static String msgContent = null;
  58.  
  59. static String dbURL = null;
  60. static String dbDRIVER = null;
  61. static String dbUSER = null;
  62. static String dbPASS = null;
  63.  
  64. static String startMask = null;
  65. static String extension = null;
  66.  
  67. static String maskName = null;
  68.  
  69. static String user = null;
  70. static String pass = null;
  71. static String msgTo = null;
  72. static String msgFrom = null;
  73. static String msgCc = null;
  74. static String userName = null;
  75. static String subject = null;
  76. static String description = null;
  77. static String advertisement = null;
  78.  
  79. static InputStream inStream = null;
  80. static OutputStream outStream = null;
  81.  
  82. static String inDir = null;
  83. static String outDir = null;
  84. static String errDir = null;
  85. static String fileName = null;
  86. static String fileProcessName = null;
  87.  
  88. static String currentDateTime = null;
  89. static String currentMailDateTime = null;
  90.  
  91. static Boolean key = Boolean.FALSE;
  92. static Boolean dbConnectionsSet = Boolean.FALSE;
  93.  
  94. static int noSaveList;
  95.  
  96. static String insertQuery = null;
  97. static String updateQuery = null;
  98.  
  99. static String tempMsg = null;
  100. static String dispMsg = null;
  101. static String dupEmpId = null;
  102.  
  103. static String mailHost = null;
  104. static String mailPort = null;
  105.  
  106. static PreparedStatement preparedStatementOne = null;
  107. static PreparedStatement preparedStatement = null;
  108. static Connection connection = null;
  109. public Employee emp;
  110. private String temp;
  111. public static ArrayList<Employee> empList = new ArrayList<Employee>();
  112. public static List<String> selectedFiles = new ArrayList<String>();
  113.  
  114. public static List<String> ids = new ArrayList<String>();
  115.  
  116. /**
  117. * The main method sets things up for parsing
  118. *
  119. * @throws Exception
  120. */
  121. public static void main(String[] args) throws Exception {
  122. try{
  123. initialization();
  124.  
  125. // Create a "parser factory" for creating SAX parsers
  126. SAXParserFactory spfac = SAXParserFactory.newInstance();
  127.  
  128. // Now use the parser factory to create a SAXParser object
  129. SAXParser sp = spfac.newSAXParser();
  130.  
  131. // Create an instance of this class; it defines all the handler methods
  132. GDYNEmployeeImportPurchase handler = new GDYNEmployeeImportPurchase();
  133.  
  134. // Finally, tell the parser to parse the input and notify the handler
  135. // When the database connection is successful.
  136.  
  137. File filesFolder = new File(inDir);
  138. FileFilter fileFilter = new WildcardFileFilter(maskName);
  139. File[] files = filesFolder.listFiles(fileFilter);
  140.  
  141. logger.info("Total number of files to be processed with specified masking : "
  142. + files.length);
  143.  
  144. for (File f : files) {
  145. logger.info("Incoming folder contains file with name "
  146. + f.getName());
  147. }
  148.  
  149. if (dbConnectionsSet) {
  150.  
  151. if (files != null && files.length != 0) {
  152. for (File file : files) {
  153. try {
  154. String fileToProcess = file.getName();
  155. sp.parse(inDir + fileToProcess, handler);
  156. handler.saveList(fileToProcess);
  157. processFile(fileToProcess);
  158. } catch (IOException e) {
  159. logger.warn(e.getMessage());
  160. logger.info("Please check for file or location.");
  161. msgContent = ("Location doesn`t contains file.\n\nPlease check for path.\n\n")
  162. .concat(e.getMessage());
  163. mailing();
  164. }
  165. }
  166. } else {
  167. logger.info("Please check for file or location.");
  168. msgContent = ("Location doesn`t contains file.\n\nPlease check for path.\n\n");
  169.  
  170. mailing();
  171. }
  172. } else {
  173. logger.info("Connection not established");
  174.  
  175. }
  176. }catch(Exception e){
  177. logger.error("Error in main method "+e.getMessage());
  178. }finally{
  179. if(connection!=null){
  180. logger.info("Before closing connection");
  181. connection.close();
  182. }
  183. }
  184. }
  185.  
  186. /**
  187. * The initialization method sets parameter from properties file and then
  188. * loads the driver and then prepares connection object. Sets data flag as
  189. * success if successfully executed.
  190. */
  191. private static void initialization() {
  192. //PropertyConfigurator.configure("log4j.properties");
  193. PropertyConfigurator.configure("D:\\LoyalityDocuments\\GDTickets\\POS-327\\log4j.properties");
  194. DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  195.  
  196. // get current date time with Date()
  197. Date mailDateTime = new Date();
  198.  
  199. currentMailDateTime = dateFormat.format(mailDateTime);
  200. File file = new File("D:\\LoyalityDocuments\\GDTickets\\POS-327\\nameLoc.properties");
  201. try (FileReader read = new FileReader(file)) {
  202. Properties prop = new Properties();
  203. prop.load(read);
  204.  
  205. inDir = prop.getProperty("incoming");
  206. outDir = prop.getProperty("outgoing");
  207. errDir = prop.getProperty("error");
  208.  
  209. startMask = prop.getProperty("start");
  210. extension = prop.getProperty("ext");
  211.  
  212. maskName = startMask.concat("*").concat(".").concat(extension);
  213.  
  214. dbURL = prop.getProperty("url");
  215. dbDRIVER = prop.getProperty("driver");
  216. dbUSER = prop.getProperty("user");
  217. dbPASS = prop.getProperty("pswd");
  218.  
  219. user = prop.getProperty("userKey");
  220. pass = prop.getProperty("userPass");
  221. msgTo = prop.getProperty("messageTo");
  222. msgFrom = prop.getProperty("messageFrom");
  223. msgCc = prop.getProperty("messageCc");
  224. subject = prop.getProperty("sub");
  225. description = prop.getProperty("desc");
  226. advertisement = prop.getProperty("advt");
  227.  
  228. mailHost = prop.getProperty("mHost");
  229. mailPort = prop.getProperty("mPort");
  230.  
  231. prop.put("mail.smtp.auth", "true");
  232. prop.put("mail.smtp.starttls.enable", "true");
  233. prop.put("mail.smtp.host", mailHost);
  234. prop.put("mail.smtp.port", mailPort);
  235.  
  236. session = Session.getInstance(prop, new javax.mail.Authenticator() {
  237. protected PasswordAuthentication getPasswordAuthentication() {
  238. return new PasswordAuthentication(user, pass);
  239. }
  240. });
  241.  
  242. Class.forName(dbDRIVER);
  243. logger.info("Driver Loaded");
  244. connection = DriverManager.getConnection(dbURL, dbUSER, dbPASS);
  245. logger.info("Database Connection Successfull");
  246.  
  247. //String checkQuery = "select * from ct_eep_empl_master where EMPL_ID = ?";
  248. // String insertQuery =
  249. // "insert into ct_eep_empl_master values(?,?,?,?,?,?,?,?,?,?,?)";
  250. insertQuery = "insert into ct_eep_empl_master values(?,?,?,?,?,?,?,?,?,?,?)";
  251. updateQuery = "update ct_eep_empl_master set EMPL_ID = ?, SOURCE = ?,EMPL_ID_SRC =?,EMPL_DISC_GROUP_CODE=?,EMPL_NUMBER=?,FIRSTNAME=?,LASTNAME=?,"
  252. + "EMPL_STATUS_CODE=?,POSITION_CODE=?,EMAIL=?,HOMESTORENUMBER=? where EMPL_ID = ? ";
  253.  
  254. preparedStatementOne = connection.prepareStatement(insertQuery);
  255.  
  256. //preparedStatement = connection.prepareStatement(checkQuery);
  257.  
  258. dbConnectionsSet = Boolean.TRUE;
  259. } catch (IOException e) {
  260. logger.error("IOException in initialization method "+e.getMessage());
  261. logger.error("Please check for file or location.");
  262. } catch (ClassNotFoundException e) {
  263. logger.error("Driver Loading is failed.");
  264. logger.error("ClassNotFoundException in initialization method "+e.getMessage());
  265. msgContent = "Driver Loading is failed. \n\n"
  266. .concat(e.getMessage());
  267. mailing();
  268. } catch (SQLException e) {
  269. logger.error("Database Connection Failed");
  270. logger.error("SQLException in initialization method "+e.getMessage());
  271. logger.error("Please check for connection details.");
  272. msgContent = "Database Connection Failed.\n\nPlease check for connection details.\n\n"
  273. .concat(e.getMessage());
  274. mailing();
  275. }
  276.  
  277. }
  278.  
  279. /**
  280. * This mailing method mails the error message through e-mail
  281. */
  282. private static void mailing() {
  283. logger.info("mailing method called");
  284. try {
  285. Message message = new MimeMessage(session);
  286. message.setFrom(new InternetAddress(msgFrom));
  287. message.setRecipients(Message.RecipientType.TO,
  288. InternetAddress.parse(msgTo));
  289. message.setRecipients(Message.RecipientType.CC,
  290. InternetAddress.parse(msgCc));
  291. message.setSubject(subject);
  292. message.setText("Date: " + currentMailDateTime + "\n\n"
  293. + "Subject:" + subject + " - Description:" + description
  294. + "\n\n" + msgContent + "\n\n\n\n" + advertisement);
  295.  
  296. Transport.send(message);
  297.  
  298. } catch (MessagingException me) {
  299. logger.error("Please Check your mailing credentials.");
  300. logger.error("MessagingException in mailing method "+me.getMessage());
  301. }
  302.  
  303. }
  304.  
  305. /*
  306. * When the parser encounters plain text (not XML elements), it calls(this
  307. * method, which accumulates them in a string buffer
  308. */
  309. public void characters(char[] buffer, int start, int length) {
  310. temp = new String(buffer, start, length);
  311. }
  312.  
  313. /*
  314. * Every time the parser encounters the beginning of a new element, it calls
  315. * this method, which resets the string buffer
  316. */
  317. public void startElement(String uri, String localName, String qName,
  318. Attributes attributes) throws SAXException {
  319. temp = "";
  320. if (qName.equalsIgnoreCase("Record")) {
  321. emp = new Employee();
  322. }
  323. }
  324.  
  325. /*
  326. * When the parser encounters the end of an element, it calls this method
  327. */
  328. public void endElement(String uri, String localName, String qName)
  329. throws SAXException {
  330. if (qName.equalsIgnoreCase("Record")) {
  331. // add it to the list
  332. empList.add(emp);
  333. } else if (qName.equalsIgnoreCase("EmployeeNumber")) {
  334. emp.setEmployeeNumber(temp);
  335. } else if (qName.equalsIgnoreCase("EmployeeFirstName")) {
  336. emp.setEmployeeFirstName(temp);
  337. } else if (qName.equalsIgnoreCase("EmployeeLastName")) {
  338. emp.setEmployeeLastName(temp);
  339. } else if (qName.equalsIgnoreCase("BirthDate")) {
  340. emp.setBirthDate(temp);
  341. } else if (qName.equalsIgnoreCase("Email")) {
  342. emp.setEmail(temp);
  343. } else if (qName.equalsIgnoreCase("Cellphone")) {
  344. emp.setCellphone(temp);
  345. } else if (qName.equalsIgnoreCase("EmpStatusName")) {
  346. emp.setEmpStatusName(temp);
  347. } else if (qName.equalsIgnoreCase("EmpStatusXRef")) {
  348. emp.setEmpStatusXRef(temp);
  349. } else if (qName.equalsIgnoreCase("SupervisorName")) {
  350. emp.setSupervisorName(temp);
  351. } else if (qName.equalsIgnoreCase("JobName")) {
  352. emp.setJobName(temp);
  353. } else if (qName.equalsIgnoreCase("HomeStoreNumber")) {
  354. emp.setHomeStoreNumber(temp);
  355. } else if (qName.equalsIgnoreCase("EmployeeDiscountGroup")) {
  356. emp.setEmployeeDiscountGroup(temp);
  357. } else if (qName.equalsIgnoreCase("xRef")) {
  358. emp.setxRef(temp);
  359. }
  360. }
  361.  
  362. /**
  363. * The checkIfEmployeeExists method checks whether any duplicate entries are
  364. * there in the ct_eep_empl_master table.
  365. */
  366. private static Boolean checkIfEmployeeExists(String employeeId)throws SQLException
  367. {
  368. boolean empExists = Boolean.FALSE;
  369. ResultSet resultSet = null;
  370. try {
  371. String checkQuery = "select EMPL_ID from ct_eep_empl_master where EMPL_ID = ?";
  372. preparedStatement = connection.prepareStatement(checkQuery);
  373. preparedStatement.setString(1, employeeId);
  374. resultSet = preparedStatement.executeQuery();
  375. while (resultSet.next()) {
  376. /*
  377. * logger.warn(
  378. * "Employee is already present in the database with ID : " +
  379. * employeeId);
  380. */
  381. noSaveList++;
  382. ids.add(employeeId);
  383. return Boolean.TRUE;
  384. }
  385.  
  386. } catch (SQLException e) {
  387. logger.error("SQLException in checkIfEmployeeExists " + e.getMessage());
  388. }catch (Exception e) {
  389. logger.error("Exception in checkIfEmployeeExists " + e.getMessage());
  390. }
  391. finally {
  392. logger.info("inside finally block of checkIfEmployeeExists method ");
  393. if(resultSet!=null){
  394. resultSet.close();
  395. }
  396. if(preparedStatement!=null){
  397. preparedStatement.close();
  398. }
  399. }
  400. return empExists;
  401. }
  402.  
  403. /**
  404. * The saveList method saves the values from xml file to the
  405. * ct_eep_empl_master table.
  406. *
  407. */
  408. private Boolean saveList(String fileName) throws Exception {
  409.  
  410. int savedList = 0;
  411. int updateList = 0;
  412. int totalList = 0;
  413.  
  414. noSaveList = 0;
  415.  
  416.  
  417. logger.info("Processing file with name " + fileName);
  418. logger.info("------------------------------------------");
  419. for (Employee employee : empList) {
  420. Boolean isEmployeeExist = checkIfEmployeeExists(employee
  421. .getxRef());
  422. try {
  423. /*
  424. * String insertQuery =
  425. * "insert into ct_eep_empl_master values(?,?,?,?,?,?,?,?,?,?,?)"
  426. * ; String updateQuery =
  427. * "update ct_eep_empl_master set EMPL_ID = ?, SOURCEIE = ?,EMPL_ID_SRC =?,EMPL_DISC_GROUP_CODE=?,EMPL_NUMBER=?,FIRSTNAME=?,LASTNAME=?,"
  428. * +
  429. * "EMPL_STATUS_CODE=?,POSITION_CODE=?,EMAIL=?,HOMESTORENUMBER=? where EMPL_ID = ? "
  430. * ;
  431. */
  432. if (!isEmployeeExist) {
  433.  
  434. preparedStatementOne = connection
  435. .prepareStatement(insertQuery);
  436.  
  437. preparedStatementOne.setString(1, employee.getxRef()
  438. .toString());
  439. preparedStatementOne.setString(2, "E");
  440. preparedStatementOne.setString(3,
  441. "E:".concat(employee.getxRef().toString()));
  442. preparedStatementOne.setString(4, employee
  443. .getEmployeeDiscountGroup().toString());
  444. preparedStatementOne.setString(5, employee
  445. .getEmployeeNumber().toString());
  446. preparedStatementOne.setString(6, employee
  447. .getEmployeeFirstName().toString());
  448. preparedStatementOne.setString(7, employee
  449. .getEmployeeLastName().toString());
  450. preparedStatementOne.setString(8, employee
  451. .getEmpStatusXRef().toString());
  452. preparedStatementOne.setString(9, employee.getJobName()
  453. .toString());
  454. preparedStatementOne.setString(10, employee.getEmail()
  455. .toString());
  456. preparedStatementOne.setString(11, employee
  457. .getHomeStoreNumber().toString());
  458.  
  459. preparedStatementOne.executeUpdate();
  460.  
  461. savedList++;
  462. logger.info("Employee added with ID :"
  463. + employee.getxRef().toString());
  464.  
  465. } else {
  466. preparedStatementOne = connection
  467. .prepareStatement(updateQuery);
  468.  
  469. preparedStatementOne.setString(1, employee.getxRef()
  470. .toString());
  471.  
  472. preparedStatementOne.setString(2, "E");
  473. preparedStatementOne.setString(3,
  474. "E:".concat(employee.getxRef().toString()));
  475. preparedStatementOne.setString(4, employee
  476. .getEmployeeDiscountGroup().toString());
  477. preparedStatementOne.setString(5, employee
  478. .getEmployeeNumber().toString());
  479. preparedStatementOne.setString(6, employee
  480. .getEmployeeFirstName().toString());
  481. preparedStatementOne.setString(7, employee
  482. .getEmployeeLastName().toString());
  483. preparedStatementOne.setString(8, employee
  484. .getEmpStatusXRef().toString());
  485. preparedStatementOne.setString(9, employee.getJobName()
  486. .toString());
  487. preparedStatementOne.setString(10, employee.getEmail()
  488. .toString());
  489. preparedStatementOne.setString(11, employee
  490. .getHomeStoreNumber().toString());
  491.  
  492. preparedStatementOne.setString(12, employee.getxRef()
  493. .toString());
  494.  
  495. preparedStatementOne.executeUpdate();
  496.  
  497. updateList++;
  498. logger.info("Employee updated with ID :"
  499. + employee.getxRef().toString());
  500. }
  501. /*
  502. * logger.info("Employee added with ID :" +
  503. * employee.getxRef().toString());
  504. */
  505. // }
  506.  
  507. } catch (SQLException e) {
  508. logger.error("SQLException in savelist mathod "
  509. + e.getMessage());
  510. msgContent = e.getMessage();
  511. mailing();
  512. } catch (Exception e) {
  513. logger.error("Exception in savelist mathod " + e.getMessage());
  514. msgContent = e.getMessage();
  515. mailing();
  516. } finally {
  517. if (preparedStatementOne != null) {
  518. logger.info("Before closing preparedStatementOne");
  519. preparedStatementOne.close();
  520. }
  521. }
  522. totalList = savedList + updateList;
  523. logger.info("Total number of Employee added :" + savedList);
  524. logger.info("Total number of Employee updated :" + updateList);
  525.  
  526. if (empList.size() == totalList) {
  527. key = Boolean.TRUE;
  528.  
  529. } else {
  530. key = Boolean.FALSE;
  531. msgContent = "All the employee data are not added.";
  532. mailing();
  533. }
  534.  
  535. if (updateList > 0) {
  536. msgContent = "Following "
  537. + updateList
  538. + " Employee ID is/are already present in the database . \n\n"
  539. .concat(ids.toString()).concat(
  540. "\n\n And hence updated to the database.\n\nDetails for file : "
  541. + fileName);
  542.  
  543. mailing();
  544. }
  545.  
  546. }
  547. empList = new ArrayList<Employee>();
  548. ids = new ArrayList<String>();
  549. return key;
  550.  
  551. }
  552.  
  553. /**
  554. * The processFile method moves the xml file from incoming folder to Archive
  555. * folder if processed successfully.
  556. *
  557. */
  558. private static void processFile(String fileName) {
  559. DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
  560. // get current date time with Date()
  561. Date date = new Date();
  562.  
  563. currentDateTime = dateFormat.format(date);
  564.  
  565. try {
  566. File afile = new File(inDir + fileName);
  567.  
  568. if (key) {
  569. File bfile = new File(outDir.concat(currentDateTime.toString())
  570. + fileName);
  571.  
  572. inStream = new FileInputStream(afile);
  573. outStream = new FileOutputStream(bfile);
  574. logger.info("File processed successfully and moved to "
  575. + outDir + " with file name "
  576. + currentDateTime.toString() + fileName);
  577.  
  578. } else {
  579. File bfile = new File(errDir.concat(currentDateTime.toString())
  580. + fileName);
  581.  
  582. inStream = new FileInputStream(afile);
  583. outStream = new FileOutputStream(bfile);
  584. logger.info("File processing is unsuccessfull and moved to "
  585. + errDir + " with file name "
  586. + currentDateTime.toString() + fileName);
  587. }
  588.  
  589. byte[] buffer = new byte[1024];
  590.  
  591. int length;
  592.  
  593. // copy the file content in bytes
  594. while ((length = inStream.read(buffer)) > 0) {
  595. outStream.write(buffer, 0, length);
  596. }
  597.  
  598. inStream.close();
  599. outStream.close();
  600.  
  601. // delete the original file
  602. afile.delete();
  603. } catch (Exception e) {
  604. logger.error("Exception in processFile mathod "+e.getMessage());
  605. }
  606. }
  607. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement