Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.08 KB | None | 0 0
  1. package com.comarch.upgrader.controller;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.PrintWriter;
  10. import java.io.StringWriter;
  11. import java.security.MessageDigest;
  12. import java.security.Principal;
  13. import java.util.ArrayList;
  14.  
  15. import java.util.Date;
  16. import java.util.List;
  17. import java.util.Locale;
  18.  
  19. import javax.servlet.http.HttpServlet;
  20. import javax.servlet.http.HttpServletResponse;
  21. import javax.xml.parsers.DocumentBuilder;
  22. import javax.xml.parsers.DocumentBuilderFactory;
  23. import javax.xml.transform.OutputKeys;
  24. import javax.xml.transform.Transformer;
  25. import javax.xml.transform.TransformerFactory;
  26. import javax.xml.transform.dom.DOMSource;
  27. import javax.xml.transform.stream.StreamResult;
  28.  
  29. import org.apache.commons.io.FileUtils;
  30. import org.rauschig.jarchivelib.ArchiveFormat;
  31. import org.rauschig.jarchivelib.Archiver;
  32. import org.rauschig.jarchivelib.ArchiverFactory;
  33. import org.rauschig.jarchivelib.CompressionType;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import org.springframework.beans.factory.annotation.Autowired;
  37. import org.springframework.context.ApplicationContext;
  38. import org.springframework.security.core.context.SecurityContextHolder;
  39. import org.springframework.stereotype.Controller;
  40. import org.springframework.ui.Model;
  41.  
  42. import org.springframework.web.bind.annotation.RequestMapping;
  43. import org.springframework.web.bind.annotation.RequestMethod;
  44. import org.springframework.web.bind.annotation.RequestParam;
  45. import org.springframework.web.context.WebApplicationContext;
  46. import org.springframework.web.context.support.WebApplicationContextUtils;
  47. import org.springframework.web.multipart.MultipartFile;
  48. import org.w3c.dom.Document;
  49. import org.w3c.dom.Element;
  50. import org.w3c.dom.NodeList;
  51.  
  52. import com.comarch.upgrader.model.BaseSystem;
  53. import com.comarch.upgrader.model.Directory;
  54. import com.comarch.upgrader.model.FileModel;
  55. import com.comarch.upgrader.model.History;
  56. import com.comarch.upgrader.model.SystemXML;
  57. import com.comarch.upgrader.model.Versions;
  58. import com.comarch.upgrader.service.FileService;
  59. import com.comarch.upgrader.service.IHistoryService;
  60. import com.comarch.upgrader.service.IUserService;
  61. import com.comarch.upgrader.service.IVersionsService;
  62. import com.comarch.upgrader.service.ZipDirectory;
  63. import com.jcraft.jsch.Channel;
  64. import com.jcraft.jsch.ChannelSftp;
  65. import com.jcraft.jsch.JSch;
  66. import com.jcraft.jsch.Session;
  67.  
  68. /**
  69. * Handles requests for the application home page.
  70. */
  71. @Controller
  72. public class ManagerController {
  73.  
  74. private String sPath = "";
  75. private String actPath = "";
  76. private String issues = "";
  77. private String sysName = "";
  78. private String release = "";
  79. private String additionalParameter = "";
  80. private String tarGzPath = "";
  81.  
  82. @Autowired
  83. private IVersionsService versionsService;
  84.  
  85. @Autowired
  86. private IHistoryService historyService;
  87.  
  88. @Autowired
  89. private IUserService userService;
  90.  
  91. private static final Logger logger = LoggerFactory.getLogger(ManagerController.class);
  92.  
  93. /**
  94. * Simply selects the home view to render by returning its name.
  95. */
  96. @RequestMapping(value = "/filemanager", method = RequestMethod.GET)
  97. public String home(@RequestParam("path")String path, @RequestParam("release")String release, @RequestParam("issues")String issues, @RequestParam("system")String system, Locale locale, Model model) throws IOException, Exception {
  98. if(path.contains("/home/stazysta/workspace") == false){
  99. throw new Exception("Wrong path exception");
  100. }
  101. else {
  102. this.sPath = path;
  103. this.actPath = path;
  104. this.issues = issues;
  105. this.sysName = system;
  106. this.release = release;
  107. }
  108. FileService fileService = new FileService();
  109. List<FileModel> listFile = new ArrayList<FileModel>();
  110.  
  111. History newHistory = new History();
  112. newHistory.setPackageName(this.release + "_" + sysName + "_" + additionalParameter + "_" + String.format("%03d", historyService.getLastNumberOfVersionByReleaseAndSystemName(this.release, sysName) + 1));
  113.  
  114. changeXML(newHistory.getPackageName(), getUrlFromSystem(sysName), issues);
  115. txtCreate(newHistory.getPackageName(), getUrlFromSystem(sysName), release, "SUM", "TODO", false, getSystemSections(sysName), getMailContent(sysName));
  116.  
  117. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(sPath), listFile));
  118. model.addAttribute("path", sPath);
  119. return "main";
  120. }
  121.  
  122. @RequestMapping(value = "/black", method = RequestMethod.POST)
  123. public String addCustomer2(@RequestParam String path, Model model) {
  124. if(checkPath(path, model)){
  125.  
  126. FileService fileService = new FileService();
  127. List<FileModel> listFile = new ArrayList<FileModel>();
  128.  
  129. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
  130. model.addAttribute("path", path);
  131. }
  132. return "main";
  133. }
  134.  
  135. @RequestMapping(value = "/next", method = RequestMethod.POST)
  136. public String next(@RequestParam String path, Model model) {
  137. if(checkPath(path, model)){
  138.  
  139. FileService fileService = new FileService();
  140. List<FileModel> listFile = new ArrayList<FileModel>();
  141.  
  142. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
  143. model.addAttribute("path", path);
  144. }
  145. return "main";
  146. }
  147.  
  148. @RequestMapping(value = "/back", method = RequestMethod.POST)
  149. public String back(@RequestParam String path, Model model) throws IOException {
  150. if(checkPath(new FileService().backPath(path), model)){
  151.  
  152. FileService fileService = new FileService();
  153. List<FileModel> listFile = new ArrayList<FileModel>();
  154.  
  155.  
  156. String archiveName="";
  157. if (path.lastIndexOf("\\") != -1) {
  158. archiveName=path.substring(path.lastIndexOf("\\")+1);
  159. }
  160.  
  161. if (path.lastIndexOf("/") != -1) {
  162. archiveName=path.substring(path.lastIndexOf("/")+1);
  163. }
  164.  
  165. if(path.equals(tarGzPath)){
  166.  
  167.  
  168. File sourceDir = new File(path);
  169.  
  170. File targetDir = new File(fileService.backPath(path)+"/tempFolder1");
  171.  
  172. FileUtils.copyDirectory(sourceDir, targetDir);
  173.  
  174. fileService.removeDirectory(fileService.createFileObject(path));
  175.  
  176. sourceDir = new File(fileService.backPath(path)+"/tempFolder1");
  177. targetDir = new File(path + "/" + archiveName);
  178. FileUtils.copyDirectory(sourceDir, targetDir);
  179.  
  180. fileService.removeDirectory(fileService.createFileObject(fileService.backPath(path)+"/tempFolder1"));
  181.  
  182. System.out.println(path);
  183. System.out.println(path + "/" + archiveName);
  184.  
  185. path = fileService.backPath(path);
  186.  
  187. File destination = new File(path);
  188. File source = new File(tarGzPath);
  189.  
  190. Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
  191. archiver.create(archiveName, destination, source);
  192.  
  193. fileService.removeDirectory(fileService.createFileObject(tarGzPath));
  194.  
  195. }else{
  196. path = fileService.backPath(path);
  197. }
  198.  
  199. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
  200. model.addAttribute("path", path);
  201. }
  202. return "main";
  203. }
  204.  
  205. @RequestMapping(value = "/delete", method = RequestMethod.POST)
  206. public String delete(@RequestParam String path, Model model) {
  207. if(checkPath(path, model)){
  208.  
  209. FileService fileService = new FileService();
  210. List<FileModel> listFile = new ArrayList<FileModel>();
  211.  
  212. fileService.removeDirectory(fileService.createFileObject(path));
  213.  
  214. path = fileService.backPath(path);
  215.  
  216. model.addAttribute("path", path);
  217. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
  218. }
  219. return "main";
  220. }
  221.  
  222. @RequestMapping(value = "/download", method = RequestMethod.POST)
  223. public void getFile(String path, HttpServletResponse response) {
  224. if(checkPath(path, null)){
  225. try {
  226. // get your file as InputStream
  227. System.out.println(path);
  228. InputStream is = new FileInputStream(new File(path));
  229. // copy it to response's OutputStream
  230. File tempFile = new File(path);
  231. String fileName = tempFile.getName();
  232.  
  233. response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName);
  234.  
  235. org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
  236.  
  237. response.flushBuffer();
  238. }
  239. catch (IOException ex) {
  240. // log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
  241. throw new RuntimeException("IOError writing file to output stream");
  242. }
  243. }
  244. }
  245.  
  246. @RequestMapping(value = "/upload", method = RequestMethod.POST)
  247. public/* @ResponseBody */String handleFileUpload(@RequestParam("file") MultipartFile file, String path,
  248. String name, Model model) {
  249. if(checkPath(path, model)){
  250. System.out.println(path + "/" + name);
  251. if (!file.isEmpty()) {
  252. try {
  253. byte[] bytes = file.getBytes();
  254. BufferedOutputStream stream = new BufferedOutputStream(
  255. new FileOutputStream(new File(path + "/" + name)));
  256. stream.write(bytes);
  257. stream.close();
  258.  
  259. }
  260. catch (Exception e) {
  261. return "You failed to upload " + name + " => " + e.getMessage();
  262. }
  263. }
  264. else {
  265. return "You failed to upload " + name + " because the file was empty.";
  266. }
  267.  
  268. FileService fileService = new FileService();
  269. List<FileModel> listFile = new ArrayList<FileModel>();
  270.  
  271. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
  272. model.addAttribute("path", path);
  273. }
  274. return "main";
  275. }
  276.  
  277. @RequestMapping(value = "/edit", method = RequestMethod.POST)
  278. public String edit(@RequestParam String path, String name1, Model model) {
  279. if(checkPath(new FileService().backPath(path), model)){
  280. FileService fileService = new FileService();
  281. List<FileModel> listFile = new ArrayList<FileModel>();
  282.  
  283. fileService.renameDirectory(fileService.createFileObject(path), fileService.backPath(path) + "/" + name1);
  284.  
  285. path = fileService.backPath(path);
  286.  
  287. model.addAttribute("path", path);
  288. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
  289. }
  290. return "main";
  291. }
  292.  
  293. @RequestMapping(value = "/package/send", method = RequestMethod.POST)
  294. public String packageSend(Model model) throws IOException {
  295.  
  296. /*//////////////////////////////*/
  297.  
  298. // Zapisywanie do archiwum i wersjonowanie
  299.  
  300. additionalParameter = "DodatkowyParametr"; //TODO wyciagac z xmla, lub jenkinsa
  301.  
  302. List<Versions> versionsList = versionsService.findAllVersions();
  303. Versions newVersions = new Versions();
  304. newVersions.setRelease(release);
  305. newVersions.setSystem(sysName);
  306. for(Versions versions : versionsList) {
  307. if(versions.getSystem().equals(newVersions.getSystem()) && versions.getRelease().equals(newVersions.getRelease())) {
  308. newVersions = versions;
  309. }
  310. }
  311. if(!versionsList.contains(newVersions)) {
  312. versionsService.save(newVersions);
  313. }
  314. History newHistory = new History();
  315. newHistory.setVersionNumber(historyService.getLastNumberOfVersionByReleaseAndSystemName(release, sysName) + 1);
  316. newHistory.setDate(new Date().toString());
  317. newHistory.setPackageName(release + "_" + sysName + "_" + additionalParameter + "_" + String.format("%03d", newHistory.getVersionNumber()));
  318. newHistory.setVersions(newVersions);
  319. Principal principal = SecurityContextHolder.getContext().getAuthentication();
  320. newHistory.setUser(userService.findUserByUsername(principal.getName()));
  321. historyService.save(newHistory);
  322.  
  323. /*//////////////////////////////*/
  324.  
  325. FileService fileService = new FileService();
  326.  
  327. File directoryToZip = new File(sPath);
  328.  
  329. List<File> fileList = new ArrayList<File>();
  330.  
  331. ZipDirectory.getAllFiles(directoryToZip, fileList);
  332. ZipDirectory.writeZipFile(directoryToZip, fileList);
  333.  
  334. File asdasd = new File("");//?
  335. String nameOfZip = asdasd.getAbsoluteFile() + "/"+directoryToZip.getName() + ".zip";//?
  336. asdasd.delete();//?
  337.  
  338. String newFile = "/home/stazysta/packages/" + newHistory.getPackageName() + ".zip";
  339. fileService.renameDirectory(fileService.createFileObject(nameOfZip), newFile);
  340. send(newFile);
  341. fileService.removeDirectory(fileService.createFileObject(sPath));
  342. return "completed";
  343. }
  344.  
  345. @RequestMapping(value = "/unTargz", method = RequestMethod.POST)
  346. public String unTargz(@RequestParam String path, Model model) throws IOException {
  347. if(checkPath(new FileService().backPath(path), model)){
  348. FileService fileService = new FileService();
  349. List<FileModel> listFile = new ArrayList<FileModel>();
  350.  
  351.  
  352. File archive = new File(path);
  353. File destination = new File("C:/Temp");
  354.  
  355. Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
  356. archiver.extract(archive, destination);
  357.  
  358. fileService.removeDirectory(fileService.createFileObject(path));
  359.  
  360. path=path.substring(0, path.length()-7);
  361. tarGzPath=path;
  362. //path = fileService.backPath(path);
  363.  
  364. model.addAttribute("path", path);
  365. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
  366. }
  367. return "main";
  368. }
  369.  
  370. public void send (String fileName) {
  371. String SFTPHOST = "10.132.233.98";
  372. int SFTPPORT = 22;
  373. String SFTPUSER = "stazysta";
  374. String SFTPPASS = "stazysta";
  375. String SFTPWORKINGDIR = "/home/stazysta/client-resources";
  376.  
  377. Session session = null;
  378. Channel channel = null;
  379. ChannelSftp channelSftp = null;
  380. try {
  381. JSch jsch = new JSch();
  382. session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
  383. session.setPassword(SFTPPASS);
  384. java.util.Properties config = new java.util.Properties();
  385. config.put("StrictHostKeyChecking", "no");
  386. session.setConfig(config);
  387. session.connect();
  388. channel = session.openChannel("sftp");
  389. channel.connect();
  390. channelSftp = (ChannelSftp) channel;
  391. channelSftp.cd(SFTPWORKINGDIR);
  392. File f = new File(fileName);
  393. channelSftp.put(new FileInputStream(f), f.getName());
  394. } catch (Exception ex) {
  395. System.out.println(ex.getMessage());
  396. }
  397. finally{
  398.  
  399. channelSftp.exit();
  400. channel.disconnect();
  401. session.disconnect();
  402. }
  403. }
  404.  
  405. public String calculateSum(String fileName){
  406.  
  407. StringBuffer sb = new StringBuffer("");
  408. try{
  409. MessageDigest md = MessageDigest.getInstance("SHA1");
  410. FileInputStream fis = new FileInputStream(fileName);
  411. byte[] dataBytes = new byte[1024];
  412.  
  413. int nread = 0;
  414.  
  415. while ((nread = fis.read(dataBytes)) != -1) {
  416. md.update(dataBytes, 0, nread);
  417. };
  418.  
  419. byte[] mdbytes = md.digest();
  420.  
  421. //convert the byte to hex format
  422. for (int i = 0; i < mdbytes.length; i++) {
  423. sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
  424. }
  425. fis.close();
  426. }catch(Exception e){
  427. System.out.println(e.getMessage());
  428. }
  429. return sb.toString();
  430. }
  431.  
  432. public void changeXML(String pName, String url, String jiraTasks) {
  433. try {
  434. File fXmlFile = new File("/home/stazysta/settings.xml");
  435. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  436. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  437. Document doc = dBuilder.parse(fXmlFile);
  438. doc.getDocumentElement().normalize();
  439.  
  440. String tasks = jiraTasks.split(" : ")[1];
  441.  
  442. NodeList nListBean = doc.getElementsByTagName("bean");
  443.  
  444. for (int temp = 0; temp < nListBean.getLength(); temp++) {
  445. Element eElement = (Element)nListBean.item(temp);
  446. if(eElement.getAttribute("id").equals("upgradeParameters")){
  447. NodeList jiraOrMqcIssues = eElement.getElementsByTagName("property");
  448. for(int i=0; i<jiraOrMqcIssues.getLength(); i++){
  449. Element el = (Element)jiraOrMqcIssues.item(i);
  450. if(el.getAttribute("name").equals("jiraOrMqcIssues")){
  451. Element e = (Element)jiraOrMqcIssues.item(i);
  452. e.getElementsByTagName("value").item(0).setTextContent(tasks);
  453. }
  454. }
  455. }
  456. }
  457.  
  458. NodeList nListUtil = doc.getElementsByTagName("util:map");
  459.  
  460. for (int temp = 0; temp < nListUtil.getLength(); temp++) {
  461. Element el = (Element)nListUtil.item(temp);
  462. if(el.getAttribute("id").equals("commonModulesParameters")){
  463. NodeList nListEntry = el.getElementsByTagName("entry");
  464. for (int i = 0; i < nListEntry.getLength(); i++) {
  465. Element e = (Element)nListEntry.item(i);
  466. if(e.getAttribute("key").equals("packageName")){
  467. e.setAttribute("value", pName);
  468. }
  469. else if(e.getAttribute("key").equals("url")){
  470. e.setAttribute("value", url + pName + ".zip");
  471. }
  472. }
  473. }
  474. }
  475.  
  476. Transformer transformer = TransformerFactory.newInstance().newTransformer();
  477. transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  478.  
  479. StreamResult result = new StreamResult(new StringWriter());
  480. DOMSource source = new DOMSource(doc);
  481. transformer.transform(source, result);
  482.  
  483. String xmlString = result.getWriter().toString();
  484. PrintWriter out = new PrintWriter(sPath + "/settings.xml");
  485. out.print(xmlString);
  486. System.out.println(xmlString);
  487. out.close();
  488.  
  489. } catch (Exception e) {
  490. e.printStackTrace();
  491. }
  492. }
  493. public String txtCreate(String pName, String url, String release, String md5, String time, Boolean efficiency, List<String> sections, String comment) {
  494. try {
  495. List<String> localSections = sections;
  496. localSections.add("");
  497. PrintWriter out;
  498. for(String str : localSections){
  499. if(str.equals("")){
  500. out = new PrintWriter(sPath + str + "/info.txt");
  501. } else {
  502. out = new PrintWriter(sPath + "/" + str + "/info.txt");
  503. }
  504. out.println("2.1: " + release);
  505. out.println("2.2:");
  506. out.println("Neptun: " + url + pName + ".zip");
  507. out.println("suma md5: " + md5);
  508. out.println("2.3: lista naprawianych bledow:");
  509. String issueSystem = issues.split(" : ")[0];
  510. out.println(issueSystem + ":");
  511. String[] tasks = issues.split(" : ")[1].split(" ");
  512. for(String s : tasks){
  513. out.println(s);
  514. }
  515. out.println("2.4: " + time);
  516. out.print("Wplyw na wydajnosc: ");
  517. if(efficiency) out.print("TAK");
  518. else out.print("NIE");
  519. out.println();
  520. out.print("2.6: Sekcje zawarte w paczce: ");
  521. for(int i=0; i<sections.size(); i++){
  522. if(i<sections.size()-1){
  523. out.print(sections.get(i) + " ");
  524. }
  525. else out.print(sections.get(i));
  526. }
  527. out.println();
  528. out.println("Uwagi: " + comment);
  529. out.close();
  530. }
  531.  
  532. } catch (Exception e) {
  533. e.printStackTrace();
  534. }
  535. return "txt";
  536. }
  537.  
  538. @Autowired
  539. ApplicationContext context;
  540.  
  541. public SystemXML initialize(){
  542. return (SystemXML) context.getBean("SystemXML");
  543. }
  544.  
  545. public String getUrlFromSystem(String sysName){
  546. String url = "";
  547. SystemXML systemXML = initialize();
  548. for (BaseSystem baseSystem : systemXML.getSystemList()) {
  549. if(baseSystem.getSystemName().equals(sysName)){
  550. url = baseSystem.getRemoteURL();
  551. }
  552. }
  553. return url;
  554. }
  555.  
  556. public String getMailContent(String sysName){
  557. String mailContent = "";
  558. SystemXML systemXML = initialize();
  559. for (BaseSystem baseSystem : systemXML.getSystemList()) {
  560. if(baseSystem.getSystemName().equals(sysName)){
  561. mailContent = baseSystem.getMailContent();
  562. }
  563. }
  564. return mailContent;
  565. }
  566.  
  567. public List<String> getSystemSections(String sysName){
  568. List<String> sections = new ArrayList<String>();
  569. SystemXML systemXML = initialize();
  570. for (BaseSystem baseSystem : systemXML.getSystemList()) {
  571. if(baseSystem.getSystemName().equals(sysName)){
  572. for(Directory dir : baseSystem.getDirectories()){
  573. sections.add(dir.getName());
  574. }
  575. }
  576. }
  577. return sections;
  578. }
  579.  
  580. public Boolean checkPath(String path, Model model){
  581. if(path.contains(sPath)){
  582. actPath = path;
  583. logger.info("true = " + actPath);
  584. return true;
  585. }
  586. else if (model != null){
  587. FileService fileService = new FileService();
  588. List<FileModel> listFile = new ArrayList<FileModel>();
  589. logger.info(path + "= false = " + actPath);
  590. model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(actPath), listFile));
  591. model.addAttribute("path", actPath);
  592. return false;
  593. }
  594. else return false;
  595. }
  596.  
  597. public void setVersionsService(IVersionsService versionsService) {
  598. this.versionsService = versionsService;
  599. }
  600.  
  601. public void setHistoryService(IHistoryService historyService) {
  602. this.historyService = historyService;
  603. }
  604.  
  605. public void setUserService(IUserService userService) {
  606. this.userService = userService;
  607. }
  608.  
  609.  
  610.  
  611. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement