de.egore911.versioning.deployer.performer.PerformCopy.java Source code

Java tutorial

Introduction

Here is the source code for de.egore911.versioning.deployer.performer.PerformCopy.java

Source

/*
 * Copyright 2013  Christoph Brill <egore911@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.egore911.versioning.deployer.performer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import de.egore911.versioning.deployer.util.XmlHolder;
import de.egore911.versioning.util.UrlUtil;

/**
 * Performs an actual copy operation as told by the versioning web application.
 * 
 * @author Christoph Brill &lt;egore911@gmail.com&gt;
 */
public class PerformCopy {

    private static final Logger LOG = LoggerFactory.getLogger(PerformCopy.class);

    private final XPathExpression copyXpath;
    private final XPathExpression urlXpath;
    private final XPathExpression targetXpath;
    private final XPathExpression filenameXpath;

    public PerformCopy(XPath xPath) throws XPathExpressionException {
        copyXpath = xPath.compile("copy");
        urlXpath = xPath.compile("url/text()");
        targetXpath = xPath.compile("target/text()");
        filenameXpath = xPath.compile("filename/text()");
    }

    public void perform(Node serverDeploymentsDeploymentNode) throws XPathExpressionException {
        NodeList copyOperations = (NodeList) copyXpath.evaluate(serverDeploymentsDeploymentNode,
                XPathConstants.NODESET);
        for (int j = 0; j < copyOperations.getLength(); j++) {
            Node copyOperation = copyOperations.item(j);
            String uri = (String) urlXpath.evaluate(copyOperation, XPathConstants.STRING);
            String target = (String) targetXpath.evaluate(copyOperation, XPathConstants.STRING);
            String targetFilename = (String) filenameXpath.evaluate(copyOperation, XPathConstants.STRING);
            if (!copy(uri, target, targetFilename)) {
                LOG.error("Failed copy operation");
            }
        }
    }

    private boolean copy(String uri, String target, String targetFilename) {
        URL url;
        try {
            url = new URL(uri);
        } catch (MalformedURLException e) {
            LOG.error("Invalid URI: {}", e.getMessage(), e);
            return false;
        }
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int response = connection.getResponseCode();

            int lastSlash = uri.lastIndexOf('/');
            if (lastSlash < 0) {
                LOG.error("Invalid URI: {}", uri);
                return false;
            }

            int lastDot = uri.lastIndexOf('.');
            if (lastDot < 0) {
                LOG.error("Invalid URI: {}", uri);
                return false;
            }

            String filename;
            if (StringUtils.isEmpty(targetFilename)) {
                filename = uri.substring(lastSlash + 1);
            } else {
                filename = targetFilename;
            }

            XmlHolder xmlHolder = XmlHolder.getInstance();
            XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()");

            if (response == HttpURLConnection.HTTP_OK) {
                String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename);

                File downloadFile = new File(downloadFilename);
                FileUtils.forceMkdir(downloadFile.getParentFile());
                try (InputStream in = connection.getInputStream();
                        FileOutputStream out = new FileOutputStream(downloadFilename)) {
                    IOUtils.copy(in, out);
                }
                LOG.debug("Downloaded {} to {}", url, downloadFilename);

                if (StringUtils.isEmpty(targetFilename)) {
                    // Check if finalName if exists in pom.xml
                    String destFile = null;
                    try (ZipFile zipFile = new ZipFile(downloadFilename)) {
                        Enumeration<? extends ZipEntry> entries = zipFile.entries();
                        while (entries.hasMoreElements()) {
                            ZipEntry entry = entries.nextElement();
                            if (entry.getName().endsWith("/pom.xml")) {

                                String finalNameInPom;
                                try (InputStream inputStream = zipFile.getInputStream(entry)) {
                                    try {
                                        MavenXpp3Reader mavenreader = new MavenXpp3Reader();
                                        Model model = mavenreader.read(inputStream);
                                        finalNameInPom = model.getBuild().getFinalName();
                                    } catch (Exception e) {
                                        Document doc = xmlHolder.documentBuilder.parse(inputStream);
                                        finalNameInPom = (String) finalNameXpath.evaluate(doc,
                                                XPathConstants.STRING);
                                    }
                                }

                                if (StringUtils.isNotEmpty(finalNameInPom)) {
                                    destFile = UrlUtil.concatenateUrlWithSlashes(target,
                                            finalNameInPom + "." + uri.substring(lastDot + 1));
                                }
                                break;
                            }
                        }
                    }

                    // Move file to finalName if existed in pom.xml
                    if (destFile != null) {
                        try {
                            File dest = new File(destFile);
                            if (dest.exists()) {
                                FileUtils.forceDelete(dest);
                            }
                            FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile());
                            LOG.debug("Moved file from {} to {}", downloadFilename, destFile);
                        } catch (IOException e) {
                            LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e);
                        }
                    }
                }

                return true;
            } else {
                LOG.error("Could not download file: {}", uri);
                return false;
            }
        } catch (SAXException | IOException | XPathExpressionException e) {
            LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e);
            return false;
        }
    }
}