001/*
002 * (C) Copyright 2006-2017 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *     Kevin Leturc <kleturc@nuxeo.com>
019 */
020package org.nuxeo.runtime.deployment.preprocessor.install.commands;
021
022import java.io.BufferedOutputStream;
023import java.io.File;
024import java.io.FileInputStream;
025import java.io.FileNotFoundException;
026import java.io.FileOutputStream;
027import java.io.IOException;
028import java.io.InputStream;
029import java.io.OutputStream;
030import java.nio.file.Files;
031import java.util.ArrayList;
032
033import org.apache.commons.io.IOUtils;
034import org.apache.commons.lang3.StringUtils;
035import org.nuxeo.common.utils.FileNamePattern;
036import org.nuxeo.common.utils.FileUtils;
037import org.nuxeo.common.utils.Path;
038import org.nuxeo.runtime.deployment.preprocessor.install.Command;
039import org.nuxeo.runtime.deployment.preprocessor.install.CommandContext;
040
041import com.fasterxml.jackson.databind.ObjectMapper;
042import com.fasterxml.jackson.databind.node.ObjectNode;
043
044/**
045 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
046 */
047public class AppendCommand implements Command {
048
049    protected final Path src;
050
051    protected final Path dst;
052
053    protected final boolean addNewLine;
054
055    protected final FileNamePattern pattern;
056
057    public AppendCommand(Path src, Path dst, boolean addNewLine, FileNamePattern pattern) {
058        this.src = src;
059        this.dst = dst;
060        this.addNewLine = addNewLine;
061        this.pattern = pattern;
062    }
063
064    public AppendCommand(Path src, Path dst) {
065        this(src, dst, true, null);
066    }
067
068    @Override
069    public void exec(CommandContext ctx) throws IOException {
070        File baseDir = ctx.getBaseDir();
071        File srcFile = new File(baseDir, ctx.expandVars(src.toString()));
072        File dstFile = new File(baseDir, ctx.expandVars(dst.toString()));
073
074        if (pattern == null && !srcFile.exists()) {
075            throw new FileNotFoundException("Could not find the file " + srcFile.getAbsolutePath()
076                    + " to append to ' when deploying bundle '" + ctx.get("bundle") + "'.");
077        }
078
079        if (!dstFile.isFile()) {
080            try {
081                File parent = dstFile.getParentFile();
082                if (!parent.isDirectory()) {
083                    parent.mkdirs();
084                }
085                Files.createFile(dstFile.toPath());
086            } catch (IOException e) {
087                throw new IOException(
088                        "Could not create '" + dstFile + "' when deploying bundle '" + ctx.get("bundle") + "'.", e);
089            }
090        }
091        if (pattern == null) {
092            append(srcFile, dstFile, addNewLine);
093        } else {
094            ArrayList<File> files = new ArrayList<File>();
095            FileUtils.collectFiles(srcFile, pattern, files);
096            for (File file : files) {
097                append(file, dstFile, false);
098            }
099        }
100    }
101
102    @Override
103    public String toString() {
104        return "append " + src.toString() + " > " + dst.toString();
105    }
106
107    @Override
108    public String toString(CommandContext ctx) {
109        return "append " + ctx.expandVars(src.toString()) + " > " + ctx.expandVars(dst.toString());
110    }
111
112    private void append(File srcFile, File dstFile, boolean appendNewLine) throws IOException {
113        String srcExt = FileUtils.getFileExtension(srcFile.getName());
114        String dstExt = FileUtils.getFileExtension(dstFile.getName());
115        boolean isDstEmpty = dstFile.length() == 0; // file empty or doesn't exists
116        if (!isDstEmpty && StringUtils.equalsIgnoreCase(srcExt, dstExt) && "json".equalsIgnoreCase(srcExt)) {
117            // merge the json
118            ObjectMapper m = new ObjectMapper();
119            ObjectNode destNode = m.readValue(dstFile, ObjectNode.class);
120            ObjectNode srcNode = m.readValue(srcFile, ObjectNode.class);
121            destNode.setAll(srcNode);
122            m.writeValue(dstFile, destNode);
123        } else {
124            try (InputStream in = new FileInputStream(srcFile);
125                    OutputStream out = new BufferedOutputStream(new FileOutputStream(dstFile, true))) {
126                if (appendNewLine) {
127                    out.write(System.getProperty("line.separator").getBytes());
128                }
129                IOUtils.copy(in, out);
130            }
131        }
132    }
133}