com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java Source code

Java tutorial

Introduction

Here is the source code for com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java

Source

/*
 * 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 com.anritsu.mcreleaseportal.tcintegration;

import com.anritsu.mcreleaseportal.dbController.DBController;
import com.anritsu.mcreleaseportal.docgeneration.ReleaseMailGeneration;
import com.anritsu.mcreleaseportal.shared.MCPackage;
import com.anritsu.mcreleaseportal.shared.MCPackageAvailabilities;
import com.anritsu.mcreleaseportal.shared.MCPackageMail;
import com.anritsu.mcreleaseportal.utils.Configuration;
import com.anritsu.mcreleaseportal.utils.ProcessChangesXML;
import com.anritsu.mcreleaseportal.xml.Release;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author ro100051
 */
public class ProcessTCRequest {

    private String buildName = "";
    private String buildNumber = "";
    private String artifactsLocation = "";
    private String artifactsLocationInventory = "";
    private Artifacts artifacts;
    private Result result = new Result();
    private ProcessChangesXML pXML;
    private MCPackage mcPackage;
    private ArrayList<MCPackage> additionalMCPackages = new ArrayList<>();
    private Release release;

    public ProcessTCRequest(String buildName, String buildNumber) {
        this.buildName = buildName;
        this.buildNumber = buildNumber;
        this.artifactsLocation = Configuration.getInstance().getTeamcityArtifactsLink() + buildName + "/"
                + ((buildNumber.equals("")) ? "latest.lastSuccessful/" : buildNumber + ":id/");
        this.artifactsLocationInventory = artifactsLocation + "teamcity-ivy.xml";
        validateArtifactsPresence();
    }

    public Release getRelease() {
        return release;
    }

    public void setRelease(Release release) {
        this.release = release;
    }

    public String getArtifactsLocationInventory() {
        return artifactsLocationInventory;
    }

    public String getArtifactsLocation() {
        return artifactsLocation;
    }

    public void setArtifactsLocation(String artifactsLocation) {
        this.artifactsLocation = artifactsLocation;
    }

    public Artifacts getArtifacts() {
        return artifacts;
    }

    public MCPackage getMcPackage() {
        return mcPackage;
    }

    public void setMcPackage(MCPackage mcPackage) {
        this.mcPackage = mcPackage;
    }

    public ArrayList<MCPackage> getAdditionalMCPackages() {
        return additionalMCPackages;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public Result validateModiLinks() {
        String releaseNote = mcPackage.getReleaseNote();
        String str = mcPackage.getStr();
        ArrayList<String> mcPackagesLocations = mcPackage.getLocations();
        if (URLExists(releaseNote)) {
            result.setResultCode("1");
            result.setResultMessage(result.getResultMessage().concat("MODI RN file is already present: "
                    + releaseNote + "; Please make sure the package was not already released!\n"));
        }
        if (URLExists(str)) {
            result.setResultCode("1");
            result.setResultMessage(result.getResultMessage().concat("MODI STR file is already present: " + str
                    + ";Please make sure the package was not already released!\n"));
        }
        for (String s : mcPackagesLocations) {
            if (URLExists(s)) {
                result.setResultCode("1");
                result.setResultMessage(result.getResultMessage().concat("MODI PACKAGE file is already present: "
                        + s + ";Please make sure the package was not already released!\n"));
            }
        }
        return result;
    }

    public boolean URLExists(String url) {
        try {
            HttpURLConnection.setFollowRedirects(true);
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            con.setRequestMethod("HEAD");
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        } catch (Exception ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, url + "\n" + ex);
            return false;
        }

    }

    public Result validateChangesXML(String changesXMLFileName) {
        result = new Result();
        try {
            File dir = new File(Configuration.getInstance().getSavePath());
            if (!dir.isDirectory()) {
                new File(Configuration.getInstance().getSavePath()).mkdirs();
            }
            String fileName = buildName + "_" + buildNumber + "_" + System.currentTimeMillis();
            File file = new File(dir, fileName);
            file.createNewFile();

            FileUtils.copyURLToFile(new URL(artifactsLocation + changesXMLFileName), file);

            pXML = new ProcessChangesXML(file.getAbsolutePath());
            // Check if xml is succesfully validated. If validateXmlXsd() returns an non empty string result code is 1
            result.setResultMessage(pXML.validateXmlXsd());
            if (!result.getResultMessage().replace("Success", "").equalsIgnoreCase("")) {
                result.setResultCode("1");
            }
            file.delete();

        } catch (IOException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
            result.setResultCode("1");
            result.setResultMessage(ex.getMessage());
        }
        return result;
    }

    public MCPackage extractMCPackage(String changesXMLFileName) throws Exception {
        MCPackage mcp;
        File dir = new File(Configuration.getInstance().getSavePath());
        if (!dir.isDirectory()) {
            new File(Configuration.getInstance().getSavePath()).mkdirs();
        }
        String fileName = buildName + "_" + buildNumber + "_" + System.currentTimeMillis();
        File file = new File(dir, fileName);
        file.createNewFile();

        FileUtils.copyURLToFile(new URL(artifactsLocation + changesXMLFileName), file);

        pXML = new ProcessChangesXML(file.getAbsolutePath());
        // Check if xml is succesfully validated. If validateXmlXsd() returns an non empty string result code is 1
        result.setResultMessage(pXML.validateXmlXsd());
        if (!result.getResultMessage().replace("Success", "").equalsIgnoreCase("")) {
            result.setResultCode("1");
        }
        mcp = pXML.getMcPackage();
        file.delete();
        return mcp;

    }

    public Release extractRelease(String changesXMLFileName) throws Exception {
        Release rel;
        File dir = new File(Configuration.getInstance().getSavePath());
        if (!dir.isDirectory()) {
            new File(Configuration.getInstance().getSavePath()).mkdirs();
        }
        String fileName = buildName + "_" + buildNumber + "_" + System.currentTimeMillis();
        File file = new File(dir, fileName);
        file.createNewFile();

        FileUtils.copyURLToFile(new URL(artifactsLocation + changesXMLFileName), file);

        pXML = new ProcessChangesXML(file.getAbsolutePath());
        // Check if xml is succesfully validated. If validateXmlXsd() returns an non empty string result code is 1
        result.setResultMessage(pXML.validateXmlXsd());
        if (!result.getResultMessage().replace("Success", "").equalsIgnoreCase("")) {
            result.setResultCode("1");
        }
        rel = pXML.getRelease();
        file.delete();
        return rel;
    }

    public Result saveChangesXML(String changesXMLFileName) {
        try {
            File tempFile = File.createTempFile(changesXMLFileName, "changes.xml");
            String changesXMLUrl = artifactsLocation + "/" + changesXMLFileName;
            System.out.println("Downloading " + changesXMLUrl);
            FileUtils.copyURLToFile(new URL(changesXMLUrl), tempFile);

            Path source = Paths.get((String) tempFile.getAbsolutePath());
            new File(new File("").getAbsolutePath() + "/" + Configuration.getInstance().getSavePath() + "/"
                    + mcPackage.getPackageName()).mkdirs();
            Path destination = Paths.get(new File("").getAbsolutePath() + "/"
                    + Configuration.getInstance().getSavePath() + "/" + mcPackage.getPackageName() + "/"
                    + changesXMLFileName + "_" + mcPackage.getStatus() + "_" + System.currentTimeMillis());

            Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
            System.out.println(source.toString() + " renamed to " + destination.toAbsolutePath().toString());
            result.setResultMessage(destination.toAbsolutePath().toString());

        } catch (IOException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
            result.setResultCode("1");
            result.setResultMessage(ex.getMessage());
        }
        return result;
    }

    public boolean validateArtifactsLocationInventory() {
        Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null,
                "Checking: " + artifactsLocationInventory);
        return URLExists(artifactsLocationInventory);
    }

    public boolean validateArtifactsPresence() {
        artifacts = extractArtifacts();
        System.out.println("Changes: " + artifacts.getChangesXML());
        //System.out.println("Release mail: " + artifacts.getReleaseAnnouncement());
        System.out.println("Release note: " + artifacts.getReleaseNote());
        return artifacts.getChangesXML().contains(Configuration.getInstance().getChangesXMLExtension())
                && artifacts.getReleaseNote().contains(Configuration.getInstance().getReleaseNoteExtension())
                && artifacts.getPackages().size() > 0;
    }

    private Artifacts extractArtifacts() {
        Artifacts resultingArtifacts = new Artifacts();
        try {

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new URL(artifactsLocationInventory).openStream());

            NodeList descNodes = doc.getElementsByTagName("artifact");
            for (int i = 0; i < descNodes.getLength(); i++) {
                Element e = (Element) descNodes.item(i);
                String name = e.getAttribute("name");
                String type = e.getAttribute("type");
                String nameType = name + "." + type;
                System.out
                        .println("###Checking artifact: " + e.getAttribute("name") + "." + e.getAttribute("type"));
                if (nameType.contains(Configuration.getInstance().getChangesXMLExtension())) {
                    resultingArtifacts.setChangesXML(nameType);
                }

                if (nameType.contains(Configuration.getInstance().getChangesXMLAddtitionalExtension())) {
                    ArrayList<String> changesXMLAdditional = resultingArtifacts.getChangesXMLAdditional();
                    changesXMLAdditional.add(nameType);
                    resultingArtifacts.setChangesXMLAdditional(changesXMLAdditional);
                    System.out.println(
                            "###Additional artifacts: " + e.getAttribute("name") + "." + e.getAttribute("type"));
                }

                if (nameType.contains(Configuration.getInstance().getReleaseNoteExtension())) {
                    resultingArtifacts.setReleaseNote(nameType);
                }

                if (Configuration.getInstance().getAcceptedItemsExtensions().contains(type)
                        && !nameType.contains("/")) {
                    resultingArtifacts.getPackages().add(artifactsLocation + nameType);
                }
            }

        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        return resultingArtifacts;
    }

    public Result moveItemsToModi(MCPackage mcp) {
        try {

            // Build a Map<artifactFileName,ArtifactFileLocation> for available artifacts
            HashMap<String, String> artifactsMap = new HashMap<>();
            for (String artifactFileLocation : artifacts.getPackages()) {
                artifactsMap.put(getLastElementFromString(artifactFileLocation), artifactFileLocation);
            }

            for (String mcPackageFileLocation : mcp.getLocations()) {
                String fileName = getLastElementFromString(mcPackageFileLocation);
                System.out.println("Checking file " + fileName);
                String fileNameExtension = FilenameUtils.getExtension(fileName);

                if (!Configuration.getInstance().getAcceptedItemsExtensions().contains(fileNameExtension)) {
                    result.setResultCode("1");
                    result.setResultMessage("The file " + mcPackageFileLocation
                            + " is not a valid entry for <cms:item> list. Accepted files: "
                            + Configuration.getInstance().getAcceptedItemsExtensions());
                    return result;
                }
                if (artifactsMap.containsKey(fileName)) {
                    System.out.println("Transfering: " + mcPackageFileLocation);
                    copyFile(artifactsMap.get(fileName), mcPackageFileLocation);
                } else {
                    System.out.println("The file " + mcPackageFileLocation
                            + " is present in cms:item list but is missing from TC artifacts.");
                    result.setResultCode("1");
                    result.setResultMessage("The file " + mcPackageFileLocation
                            + " is present in cms:item list but is missing from TC artifacts.");
                    return result;
                }

            }

        } catch (Exception exp) {
            result.setResultCode("1");
            result.setResultMessage(exp.getMessage());
        }
        return result;
    }

    public Result moveReleaseNoteToModi(MCPackage mcp) {
        result = new Result();
        try {
            //copy rn to modi
            System.out.println("Copying: " + artifacts.getReleaseNote() + " to " + mcp.getReleaseNote());
            copyFile(artifacts.getReleaseNote(), mcp.getReleaseNote());
        } catch (JSchException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public Result moveStrToModi(MCPackage mcp) {
        Session session = null;
        ChannelSftp channel = null;
        String utmnnfsSourceStr = "";
        try {
            utmnnfsSourceStr = Configuration.getInstance().getUtmnnfsStrSource()
                    + getLastElementFromString(mcp.getStr());

            String modiFileName = getLastElementFromString(mcp.getStr());
            System.out.println("####STR####" + mcp.getStr());
            String modiDirectoryPath = mcp.getStr().replaceAll(modiFileName, "").replaceAll(
                    Configuration.getInstance().getModiHttpPrefix(),
                    Configuration.getInstance().getModiFileSystemPrefix());
            String utmnnfsDestinationStr = modiDirectoryPath + "/" + modiFileName;

            JSch jsch = new JSch();
            session = jsch.getSession(Configuration.getInstance().getModiUser(),
                    Configuration.getInstance().getModiHost(), 22);
            session.setPassword(Configuration.getInstance().getModiPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            System.out.println("Connected to " + session.getHost());

            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            // If it's and update and STR is not present we return the result.
            System.out.println("#############STATUS##########" + mcp.getStatus());
            if (mcp.getStatus().equalsIgnoreCase("update")) {
                System.out.println("This is an update. Checking if STR exists!" + utmnnfsSourceStr);
                try {
                    Vector<ChannelSftp.LsEntry> strList = channel.ls(utmnnfsSourceStr);
                    System.out.println("STR file is available.");
                } catch (SftpException ex) {
                    System.out.println("STR file not available. This is an update, moving forward...");
                    return result;
                }
            }

            ArrayList<MCPackageAvailabilities> availabilities = mcp.getAvailabilities();
            for (MCPackageAvailabilities mcpa : availabilities) {
                System.out.println("Moving " + utmnnfsSourceStr + " to " + utmnnfsDestinationStr);
                try {
                    channel.rename(utmnnfsSourceStr, utmnnfsDestinationStr);
                    return result;
                } catch (SftpException ex) {
                    if (Configuration.getInstance().getStrMandatoryFor().contains(mcpa.getAvailability())) {
                        result.setResultCode("1");
                        result.setResultMessage(utmnnfsSourceStr + " : " + ex.getMessage());
                        return result;
                    }
                }
            }

        } catch (JSchException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
            result.setResultMessage(utmnnfsSourceStr + " :" + ex.getMessage());
            result.setResultCode("1");
        } finally {
            try {
                channel.disconnect();
                session.disconnect();
            } catch (Exception ex) {
                Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return result;
    }

    public Result deleteArtifactsFromModi() {
        result = new Result();
        try {
            // Delete Release Note
            deleteFile(mcPackage.getReleaseNote());

            // Delete str Note
            deleteFile(mcPackage.getStr());

            // Delete package files
            for (String mcPackageFileLocation : mcPackage.getLocations()) {
                deleteFile(mcPackageFileLocation);
            }
        } catch (JSchException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SftpException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public Result updatePackageInfoToDB(MCPackage mcp) {
        DBController.getInstance().deleteMCPackage(mcp);
        if (DBController.getInstance().insertMCPackage(mcp)) {
            result.setResultMessage(mcp.getPackageName() + "-" + mcp.getPackageVersion() + " was added to DB:");
        } else {
            result.setResultCode("1");
            result.setResultMessage(
                    "Couldn't add " + mcp.getPackageName() + "-" + mcp.getPackageVersion() + " package info to DB");
        }
        return result;
    }

    public Result cancelPackageInDB(String mcPackageName, String mcPackageVersion) {
        if (DBController.getInstance().cancelMCPackage(mcPackageName, mcPackageVersion)) {
            result.setResultMessage(mcPackageName + "-" + mcPackageVersion + " was CANCELED in DB:");
        } else {
            result.setResultCode("1");
            result.setResultMessage("Couldn't cancel " + mcPackageName + "-" + mcPackageVersion + " in DB");
        }
        return result;
    }

    public Result sendGeneratedReleaseAnnouncement(MCPackage mcPack) {
        try {
            ArrayList<MCPackageMail> mcPackageMail = (new ReleaseMailGeneration(release, mcPack)).getReleaseMail();
            mcPack.setMcPackageMail(mcPackageMail);
            for (MCPackageMail mail : mcPackageMail) {
                result = sendMail(mail);
                if (result.getResultCode().equalsIgnoreCase("1")) {
                    return result;
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
            result.setResultCode("1");
            result.setResultMessage(ex.getMessage());
        }

        return result;
    }

    private Result sendMail(MCPackageMail mcPackageMail) {
        try {
            Map<String, String> statusAction = new HashMap<>();
            statusAction.put("NEW", "released");
            statusAction.put("CANCEL", "withdrawn");
            statusAction.put("UPDATE", "updated");

            String html = mcPackageMail.getMail();

            ArrayList<String> to = new ArrayList<>();
            to.add(mcPackageMail.getDestination());

            String from = mcPackageMail.getSource();
            String host = Configuration.getInstance().getSmtpHost();
            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.smtp.localhost", host);
            javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));

            for (String s : to) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
            }

            System.out.println("Destination: " + Arrays.asList(to).toString());

            message.setSubject(mcPackageMail.getSubject().replace("[", "").replace("]", ""));
            message.setContent(html, "text/html");
            Transport.send(message);
            System.out.println("Release mail for " + mcPackageMail.getPackageName() + "-"
                    + mcPackageMail.getPackageVersion() + " was succesfully sent!");

        } catch (Exception ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
            result.setResultCode("1");
            result.setResultMessage(ex.getMessage());
        }

        return result;
    }

    public String getLastElementFromString(String s) {
        String sArray[] = s.split("/");
        return sArray[sArray.length - 1];
    }

    public Result deletePackageFiles(String mcPackageName, String mcPackageVersion) {
        try {
            File changesXML = getChangesXML(mcPackageName, mcPackageVersion);
            if (changesXML == null) {
                result.setResultCode("1");
                result.setResultMessage(
                        "changes.xml for " + mcPackageName + "-" + mcPackageVersion + " was not found!");
                return result;
            }
            String changesXMLPath = changesXML.getAbsolutePath();
            System.out.println("ChangesXML path: " + changesXMLPath);
            pXML = new ProcessChangesXML(changesXML.getAbsolutePath());
            result.setResultMessage(pXML.validateXmlXsd());

            mcPackage = pXML.getMcPackage();
            release = pXML.getRelease();

            deleteFile(mcPackage.getReleaseNote());
            deleteFile(mcPackage.getStr());
            for (String s : mcPackage.getLocations()) {
                deleteFile(s);
            }
        } catch (JSchException | SftpException exp) {
            result.setResultCode("1");
            result.setResultMessage(exp.getMessage());
        }
        return result;
    }

    private File getChangesXML(String mcPackageName, String mcPackageVersion) {
        File changesXML = null;
        try {
            File directorychangesXMLDirectory = new File(new File("").getAbsolutePath() + "/"
                    + Configuration.getInstance().getSavePath() + "/" + mcPackageName + "/");
            System.out.println("Listing files in: " + directorychangesXMLDirectory.getAbsolutePath());
            File[] filesChangesXML = directorychangesXMLDirectory.listFiles();
            if (filesChangesXML.length > 0) {
                /**
                 * The newest file comes first *
                 */
                Arrays.sort(filesChangesXML, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
                changesXML = filesChangesXML[0];
            }

        } catch (Exception ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        return changesXML;
    }

    public void deleteFile(String modiFileLocation) throws JSchException, SftpException {
        String modiFileName = getLastElementFromString(modiFileLocation);
        String modiDirectoryPath = modiFileLocation.replaceAll(modiFileName, "").replaceAll(
                Configuration.getInstance().getModiHttpPrefix(),
                Configuration.getInstance().getModiFileSystemPrefix());

        JSch jsch = new JSch();
        Session session = null;
        session = jsch.getSession(Configuration.getInstance().getModiUser(),
                Configuration.getInstance().getModiHost(), 22);
        session.setPassword(Configuration.getInstance().getModiPassword());
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        System.out.println("Connected to " + session.getHost());
        ChannelSftp channel = null;
        channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        System.out.println("We are currently in: " + channel.pwd());

        channel.cd(modiDirectoryPath);
        System.out.println("################Deleting: " + modiFileLocation);
        channel.rm(modiFileName);
        System.out.println("################Deleted: " + modiFileLocation);
    }

    public void copyFile(String tcFileLocation /* Teamcity full url */,
            String modiFileLocation /* modi full path */) throws JSchException {
        try {
            String modiFileName = getLastElementFromString(modiFileLocation);
            String modiDirectoryPath = modiFileLocation.replaceAll(modiFileName, "").replaceAll(
                    Configuration.getInstance().getModiHttpPrefix(),
                    Configuration.getInstance().getModiFileSystemPrefix());
            String tcFileName = getLastElementFromString(tcFileLocation);
            File tempFile = File.createTempFile(tcFileName, "");
            System.out
                    .println("Downloading " + artifactsLocation + tcFileName + " to " + tempFile.getAbsolutePath());
            FileUtils.copyURLToFile(new URL(artifactsLocation + tcFileName), tempFile, 10000, 10000);

            JSch jsch = new JSch();
            Session session = null;
            session = jsch.getSession(Configuration.getInstance().getModiUser(),
                    Configuration.getInstance().getModiHost(), 22);
            session.setPassword(Configuration.getInstance().getModiPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            System.out.println("Connected to " + session.getHost());
            ChannelSftp channel = null;
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
            System.out.println("We are currently in: " + channel.pwd());

            try {
                channel.cd(modiDirectoryPath);
                System.out.println("Directory changed to: " + channel.pwd());
            } catch (Exception exp) {
                System.out.println("Creating Directory...");
                String[] complPath = modiDirectoryPath.split("/");
                channel.cd("/");
                for (String folder : complPath) {
                    if (folder.length() > 0) {
                        try {
                            System.out.println("Current Dir : " + channel.pwd());
                            channel.cd(folder);
                        } catch (SftpException e2) {
                            channel.mkdir(folder);
                            channel.cd(folder);
                        }
                    }
                }
                System.out.println("Current Dir : " + channel.pwd());
            }
            channel.put(new FileInputStream(tempFile), modiFileName);
            System.out.println(tcFileLocation + " transfered to " + modiFileName);
            channel.disconnect();
            session.disconnect();
            tempFile.delete();
        } catch (IOException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SftpException ex) {
            Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Result processAdditionalChangesXML() {
        // validate additional changes.xml
        for (String s : artifacts.getChangesXMLAdditional()) {
            result = new Result();
            result = validateChangesXML(s);
            if (result.getResultCode().equals("1")) {
                return result;
            }

        }
        // generate MCPackage for changes.xml
        ArrayList<MCPackage> additionalMCPackages = new ArrayList<>();
        for (String s : artifacts.getChangesXMLAdditional()) {
            MCPackage mcp;
            try {
                mcp = extractMCPackage(s);
                additionalMCPackages.add(mcp);
            } catch (Exception ex) {
                result.setResultCode("1");
                result.setResultMessage(ex.getMessage());
                return result;
            }
        }

        // upload MCPackage info into DB
        for (MCPackage m : additionalMCPackages) {
            result = updatePackageInfoToDB(m);
            if (result.getResultCode().equals("1")) {
                return result;
            }
        }

        // save changes.xml for later use
        for (String s : artifacts.getChangesXMLAdditional()) {
            result = saveChangesXML(s);
            if (result.getResultCode().equalsIgnoreCase("1")) {
                return result;
            }
        }
        return result;
    }

    public Result cancelAdditionalChangesXML() {
        ArrayList<MCPackage> additionalMCPackages = new ArrayList<>();
        for (String s : artifacts.getChangesXMLAdditional()) {
            MCPackage mcp;
            try {
                mcp = extractMCPackage(s);
                additionalMCPackages.add(mcp);
            } catch (Exception ex) {
                result.setResultCode("1");
                result.setResultMessage(ex.getMessage());
                return result;
            }
        }

        for (MCPackage m : additionalMCPackages) {
            String lastMcPackageVersionAvailableInDB = DBController.getInstance()
                    .getLastAvailableVersionForMCPackage(m.getPackageName(),
                            m.getAvailabilities().get(0).getMcVersion());
            System.out.println(
                    "########### Deleting: " + m.getPackageName() + "-" + lastMcPackageVersionAvailableInDB);
            if (lastMcPackageVersionAvailableInDB.equals("")) {
                result.setResultMessage("No previous version found for " + m.getPackageName());
                result.setResultCode("1");
                return result;
            }
            result = cancelPackageInDB(m.getPackageName(), lastMcPackageVersionAvailableInDB);
            if (result.getResultCode().equalsIgnoreCase("1"))
                return result;
        }

        return result;
    }

}