Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.comarch.upgrader.controller;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.PrintWriter;
- import java.io.StringWriter;
- import java.security.MessageDigest;
- import java.security.Principal;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Locale;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletResponse;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.transform.OutputKeys;
- import javax.xml.transform.Transformer;
- import javax.xml.transform.TransformerFactory;
- import javax.xml.transform.dom.DOMSource;
- import javax.xml.transform.stream.StreamResult;
- import org.apache.commons.io.FileUtils;
- import org.rauschig.jarchivelib.ArchiveFormat;
- import org.rauschig.jarchivelib.Archiver;
- import org.rauschig.jarchivelib.ArchiverFactory;
- import org.rauschig.jarchivelib.CompressionType;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.ApplicationContext;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.context.WebApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- import org.springframework.web.multipart.MultipartFile;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.NodeList;
- import com.comarch.upgrader.model.BaseSystem;
- import com.comarch.upgrader.model.Directory;
- import com.comarch.upgrader.model.FileModel;
- import com.comarch.upgrader.model.History;
- import com.comarch.upgrader.model.SystemXML;
- import com.comarch.upgrader.model.Versions;
- import com.comarch.upgrader.service.FileService;
- import com.comarch.upgrader.service.IHistoryService;
- import com.comarch.upgrader.service.IUserService;
- import com.comarch.upgrader.service.IVersionsService;
- import com.comarch.upgrader.service.ZipDirectory;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.Session;
- /**
- * Handles requests for the application home page.
- */
- @Controller
- public class ManagerController {
- private String sPath = "";
- private String actPath = "";
- private String issues = "";
- private String sysName = "";
- private String release = "";
- private String additionalParameter = "";
- private String tarGzPath = "";
- @Autowired
- private IVersionsService versionsService;
- @Autowired
- private IHistoryService historyService;
- @Autowired
- private IUserService userService;
- private static final Logger logger = LoggerFactory.getLogger(ManagerController.class);
- /**
- * Simply selects the home view to render by returning its name.
- */
- @RequestMapping(value = "/filemanager", method = RequestMethod.GET)
- 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 {
- if(path.contains("/home/stazysta/workspace") == false){
- throw new Exception("Wrong path exception");
- }
- else {
- this.sPath = path;
- this.actPath = path;
- this.issues = issues;
- this.sysName = system;
- this.release = release;
- }
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- History newHistory = new History();
- newHistory.setPackageName(this.release + "_" + sysName + "_" + additionalParameter + "_" + String.format("%03d", historyService.getLastNumberOfVersionByReleaseAndSystemName(this.release, sysName) + 1));
- changeXML(newHistory.getPackageName(), getUrlFromSystem(sysName), issues);
- txtCreate(newHistory.getPackageName(), getUrlFromSystem(sysName), release, "SUM", "TODO", false, getSystemSections(sysName), getMailContent(sysName));
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(sPath), listFile));
- model.addAttribute("path", sPath);
- return "main";
- }
- @RequestMapping(value = "/black", method = RequestMethod.POST)
- public String addCustomer2(@RequestParam String path, Model model) {
- if(checkPath(path, model)){
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
- model.addAttribute("path", path);
- }
- return "main";
- }
- @RequestMapping(value = "/next", method = RequestMethod.POST)
- public String next(@RequestParam String path, Model model) {
- if(checkPath(path, model)){
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
- model.addAttribute("path", path);
- }
- return "main";
- }
- @RequestMapping(value = "/back", method = RequestMethod.POST)
- public String back(@RequestParam String path, Model model) throws IOException {
- if(checkPath(new FileService().backPath(path), model)){
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- String archiveName="";
- if (path.lastIndexOf("\\") != -1) {
- archiveName=path.substring(path.lastIndexOf("\\")+1);
- }
- if (path.lastIndexOf("/") != -1) {
- archiveName=path.substring(path.lastIndexOf("/")+1);
- }
- if(path.equals(tarGzPath)){
- File sourceDir = new File(path);
- File targetDir = new File(fileService.backPath(path)+"/tempFolder1");
- FileUtils.copyDirectory(sourceDir, targetDir);
- fileService.removeDirectory(fileService.createFileObject(path));
- sourceDir = new File(fileService.backPath(path)+"/tempFolder1");
- targetDir = new File(path + "/" + archiveName);
- FileUtils.copyDirectory(sourceDir, targetDir);
- fileService.removeDirectory(fileService.createFileObject(fileService.backPath(path)+"/tempFolder1"));
- System.out.println(path);
- System.out.println(path + "/" + archiveName);
- path = fileService.backPath(path);
- File destination = new File(path);
- File source = new File(tarGzPath);
- Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
- archiver.create(archiveName, destination, source);
- fileService.removeDirectory(fileService.createFileObject(tarGzPath));
- }else{
- path = fileService.backPath(path);
- }
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
- model.addAttribute("path", path);
- }
- return "main";
- }
- @RequestMapping(value = "/delete", method = RequestMethod.POST)
- public String delete(@RequestParam String path, Model model) {
- if(checkPath(path, model)){
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- fileService.removeDirectory(fileService.createFileObject(path));
- path = fileService.backPath(path);
- model.addAttribute("path", path);
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
- }
- return "main";
- }
- @RequestMapping(value = "/download", method = RequestMethod.POST)
- public void getFile(String path, HttpServletResponse response) {
- if(checkPath(path, null)){
- try {
- // get your file as InputStream
- System.out.println(path);
- InputStream is = new FileInputStream(new File(path));
- // copy it to response's OutputStream
- File tempFile = new File(path);
- String fileName = tempFile.getName();
- response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName);
- org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
- response.flushBuffer();
- }
- catch (IOException ex) {
- // log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
- throw new RuntimeException("IOError writing file to output stream");
- }
- }
- }
- @RequestMapping(value = "/upload", method = RequestMethod.POST)
- public/* @ResponseBody */String handleFileUpload(@RequestParam("file") MultipartFile file, String path,
- String name, Model model) {
- if(checkPath(path, model)){
- System.out.println(path + "/" + name);
- if (!file.isEmpty()) {
- try {
- byte[] bytes = file.getBytes();
- BufferedOutputStream stream = new BufferedOutputStream(
- new FileOutputStream(new File(path + "/" + name)));
- stream.write(bytes);
- stream.close();
- }
- catch (Exception e) {
- return "You failed to upload " + name + " => " + e.getMessage();
- }
- }
- else {
- return "You failed to upload " + name + " because the file was empty.";
- }
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
- model.addAttribute("path", path);
- }
- return "main";
- }
- @RequestMapping(value = "/edit", method = RequestMethod.POST)
- public String edit(@RequestParam String path, String name1, Model model) {
- if(checkPath(new FileService().backPath(path), model)){
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- fileService.renameDirectory(fileService.createFileObject(path), fileService.backPath(path) + "/" + name1);
- path = fileService.backPath(path);
- model.addAttribute("path", path);
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
- }
- return "main";
- }
- @RequestMapping(value = "/package/send", method = RequestMethod.POST)
- public String packageSend(Model model) throws IOException {
- /*//////////////////////////////*/
- // Zapisywanie do archiwum i wersjonowanie
- additionalParameter = "DodatkowyParametr"; //TODO wyciagac z xmla, lub jenkinsa
- List<Versions> versionsList = versionsService.findAllVersions();
- Versions newVersions = new Versions();
- newVersions.setRelease(release);
- newVersions.setSystem(sysName);
- for(Versions versions : versionsList) {
- if(versions.getSystem().equals(newVersions.getSystem()) && versions.getRelease().equals(newVersions.getRelease())) {
- newVersions = versions;
- }
- }
- if(!versionsList.contains(newVersions)) {
- versionsService.save(newVersions);
- }
- History newHistory = new History();
- newHistory.setVersionNumber(historyService.getLastNumberOfVersionByReleaseAndSystemName(release, sysName) + 1);
- newHistory.setDate(new Date().toString());
- newHistory.setPackageName(release + "_" + sysName + "_" + additionalParameter + "_" + String.format("%03d", newHistory.getVersionNumber()));
- newHistory.setVersions(newVersions);
- Principal principal = SecurityContextHolder.getContext().getAuthentication();
- newHistory.setUser(userService.findUserByUsername(principal.getName()));
- historyService.save(newHistory);
- /*//////////////////////////////*/
- FileService fileService = new FileService();
- File directoryToZip = new File(sPath);
- List<File> fileList = new ArrayList<File>();
- ZipDirectory.getAllFiles(directoryToZip, fileList);
- ZipDirectory.writeZipFile(directoryToZip, fileList);
- File asdasd = new File("");//?
- String nameOfZip = asdasd.getAbsoluteFile() + "/"+directoryToZip.getName() + ".zip";//?
- asdasd.delete();//?
- String newFile = "/home/stazysta/packages/" + newHistory.getPackageName() + ".zip";
- fileService.renameDirectory(fileService.createFileObject(nameOfZip), newFile);
- send(newFile);
- fileService.removeDirectory(fileService.createFileObject(sPath));
- return "completed";
- }
- @RequestMapping(value = "/unTargz", method = RequestMethod.POST)
- public String unTargz(@RequestParam String path, Model model) throws IOException {
- if(checkPath(new FileService().backPath(path), model)){
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- File archive = new File(path);
- File destination = new File("C:/Temp");
- Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
- archiver.extract(archive, destination);
- fileService.removeDirectory(fileService.createFileObject(path));
- path=path.substring(0, path.length()-7);
- tarGzPath=path;
- //path = fileService.backPath(path);
- model.addAttribute("path", path);
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(path), listFile));
- }
- return "main";
- }
- public void send (String fileName) {
- String SFTPHOST = "10.132.233.98";
- int SFTPPORT = 22;
- String SFTPUSER = "stazysta";
- String SFTPPASS = "stazysta";
- String SFTPWORKINGDIR = "/home/stazysta/client-resources";
- Session session = null;
- Channel channel = null;
- ChannelSftp channelSftp = null;
- try {
- JSch jsch = new JSch();
- session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
- session.setPassword(SFTPPASS);
- java.util.Properties config = new java.util.Properties();
- config.put("StrictHostKeyChecking", "no");
- session.setConfig(config);
- session.connect();
- channel = session.openChannel("sftp");
- channel.connect();
- channelSftp = (ChannelSftp) channel;
- channelSftp.cd(SFTPWORKINGDIR);
- File f = new File(fileName);
- channelSftp.put(new FileInputStream(f), f.getName());
- } catch (Exception ex) {
- System.out.println(ex.getMessage());
- }
- finally{
- channelSftp.exit();
- channel.disconnect();
- session.disconnect();
- }
- }
- public String calculateSum(String fileName){
- StringBuffer sb = new StringBuffer("");
- try{
- MessageDigest md = MessageDigest.getInstance("SHA1");
- FileInputStream fis = new FileInputStream(fileName);
- byte[] dataBytes = new byte[1024];
- int nread = 0;
- while ((nread = fis.read(dataBytes)) != -1) {
- md.update(dataBytes, 0, nread);
- };
- byte[] mdbytes = md.digest();
- //convert the byte to hex format
- for (int i = 0; i < mdbytes.length; i++) {
- sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
- }
- fis.close();
- }catch(Exception e){
- System.out.println(e.getMessage());
- }
- return sb.toString();
- }
- public void changeXML(String pName, String url, String jiraTasks) {
- try {
- File fXmlFile = new File("/home/stazysta/settings.xml");
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc = dBuilder.parse(fXmlFile);
- doc.getDocumentElement().normalize();
- String tasks = jiraTasks.split(" : ")[1];
- NodeList nListBean = doc.getElementsByTagName("bean");
- for (int temp = 0; temp < nListBean.getLength(); temp++) {
- Element eElement = (Element)nListBean.item(temp);
- if(eElement.getAttribute("id").equals("upgradeParameters")){
- NodeList jiraOrMqcIssues = eElement.getElementsByTagName("property");
- for(int i=0; i<jiraOrMqcIssues.getLength(); i++){
- Element el = (Element)jiraOrMqcIssues.item(i);
- if(el.getAttribute("name").equals("jiraOrMqcIssues")){
- Element e = (Element)jiraOrMqcIssues.item(i);
- e.getElementsByTagName("value").item(0).setTextContent(tasks);
- }
- }
- }
- }
- NodeList nListUtil = doc.getElementsByTagName("util:map");
- for (int temp = 0; temp < nListUtil.getLength(); temp++) {
- Element el = (Element)nListUtil.item(temp);
- if(el.getAttribute("id").equals("commonModulesParameters")){
- NodeList nListEntry = el.getElementsByTagName("entry");
- for (int i = 0; i < nListEntry.getLength(); i++) {
- Element e = (Element)nListEntry.item(i);
- if(e.getAttribute("key").equals("packageName")){
- e.setAttribute("value", pName);
- }
- else if(e.getAttribute("key").equals("url")){
- e.setAttribute("value", url + pName + ".zip");
- }
- }
- }
- }
- Transformer transformer = TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- StreamResult result = new StreamResult(new StringWriter());
- DOMSource source = new DOMSource(doc);
- transformer.transform(source, result);
- String xmlString = result.getWriter().toString();
- PrintWriter out = new PrintWriter(sPath + "/settings.xml");
- out.print(xmlString);
- System.out.println(xmlString);
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public String txtCreate(String pName, String url, String release, String md5, String time, Boolean efficiency, List<String> sections, String comment) {
- try {
- List<String> localSections = sections;
- localSections.add("");
- PrintWriter out;
- for(String str : localSections){
- if(str.equals("")){
- out = new PrintWriter(sPath + str + "/info.txt");
- } else {
- out = new PrintWriter(sPath + "/" + str + "/info.txt");
- }
- out.println("2.1: " + release);
- out.println("2.2:");
- out.println("Neptun: " + url + pName + ".zip");
- out.println("suma md5: " + md5);
- out.println("2.3: lista naprawianych bledow:");
- String issueSystem = issues.split(" : ")[0];
- out.println(issueSystem + ":");
- String[] tasks = issues.split(" : ")[1].split(" ");
- for(String s : tasks){
- out.println(s);
- }
- out.println("2.4: " + time);
- out.print("Wplyw na wydajnosc: ");
- if(efficiency) out.print("TAK");
- else out.print("NIE");
- out.println();
- out.print("2.6: Sekcje zawarte w paczce: ");
- for(int i=0; i<sections.size(); i++){
- if(i<sections.size()-1){
- out.print(sections.get(i) + " ");
- }
- else out.print(sections.get(i));
- }
- out.println();
- out.println("Uwagi: " + comment);
- out.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "txt";
- }
- @Autowired
- ApplicationContext context;
- public SystemXML initialize(){
- return (SystemXML) context.getBean("SystemXML");
- }
- public String getUrlFromSystem(String sysName){
- String url = "";
- SystemXML systemXML = initialize();
- for (BaseSystem baseSystem : systemXML.getSystemList()) {
- if(baseSystem.getSystemName().equals(sysName)){
- url = baseSystem.getRemoteURL();
- }
- }
- return url;
- }
- public String getMailContent(String sysName){
- String mailContent = "";
- SystemXML systemXML = initialize();
- for (BaseSystem baseSystem : systemXML.getSystemList()) {
- if(baseSystem.getSystemName().equals(sysName)){
- mailContent = baseSystem.getMailContent();
- }
- }
- return mailContent;
- }
- public List<String> getSystemSections(String sysName){
- List<String> sections = new ArrayList<String>();
- SystemXML systemXML = initialize();
- for (BaseSystem baseSystem : systemXML.getSystemList()) {
- if(baseSystem.getSystemName().equals(sysName)){
- for(Directory dir : baseSystem.getDirectories()){
- sections.add(dir.getName());
- }
- }
- }
- return sections;
- }
- public Boolean checkPath(String path, Model model){
- if(path.contains(sPath)){
- actPath = path;
- logger.info("true = " + actPath);
- return true;
- }
- else if (model != null){
- FileService fileService = new FileService();
- List<FileModel> listFile = new ArrayList<FileModel>();
- logger.info(path + "= false = " + actPath);
- model.addAttribute("serverTime", fileService.listDirectory(fileService.createFileObject(actPath), listFile));
- model.addAttribute("path", actPath);
- return false;
- }
- else return false;
- }
- public void setVersionsService(IVersionsService versionsService) {
- this.versionsService = versionsService;
- }
- public void setHistoryService(IHistoryService historyService) {
- this.historyService = historyService;
- }
- public void setUserService(IUserService userService) {
- this.userService = userService;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement