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.util.ArrayList;
031
032import org.apache.commons.io.IOUtils;
033import org.apache.commons.lang3.StringUtils;
034import org.nuxeo.common.utils.FileNamePattern;
035import org.nuxeo.common.utils.FileUtils;
036import org.nuxeo.common.utils.Path;
037import org.nuxeo.runtime.deployment.preprocessor.install.Command;
038import org.nuxeo.runtime.deployment.preprocessor.install.CommandContext;
039
040import com.fasterxml.jackson.databind.ObjectMapper;
041import com.fasterxml.jackson.databind.node.ObjectNode;
042
043/**
044 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
045 */
046public class AppendCommand implements Command {
047
048    protected final Path src;
049
050    protected final Path dst;
051
052    protected final boolean addNewLine;
053
054    protected final FileNamePattern pattern;
055
056    public AppendCommand(Path src, Path dst, boolean addNewLine, FileNamePattern pattern) {
057        this.src = src;
058        this.dst = dst;
059        this.addNewLine = addNewLine;
060        this.pattern = pattern;
061    }
062
063    public AppendCommand(Path src, Path dst) {
064        this(src, dst, true, null);
065    }
066
067    @Override
068    public void exec(CommandContext ctx) throws IOException {
069        File baseDir = ctx.getBaseDir();
070        File srcFile = new File(baseDir, ctx.expandVars(src.toString()));
071        File dstFile = new File(baseDir, ctx.expandVars(dst.toString()));
072
073        if (pattern == null && !srcFile.exists()) {
074            throw new FileNotFoundException("Could not find the file " + srcFile.getAbsolutePath()
075                    + " to append to ' when deploying bundle '" + ctx.get("bundle") + "'.");
076        }
077
078        if (!dstFile.isFile()) {
079            try {
080                File parent = dstFile.getParentFile();
081                if (!parent.isDirectory()) {
082                    parent.mkdirs();
083                }
084                dstFile.createNewFile();
085            } catch (IOException e) {
086                throw new IOException(
087                        "Could not create '" + dstFile + "' when deploying bundle '" + ctx.get("bundle") + "'.", e);
088            }
089        }
090        if (pattern == null) {
091            append(srcFile, dstFile, addNewLine);
092        } else {
093            ArrayList<File> files = new ArrayList<File>();
094            FileUtils.collectFiles(srcFile, pattern, files);
095            for (File file : files) {
096                append(file, dstFile, false);
097            }
098        }
099    }
100
101    @Override
102    public String toString() {
103        return "append " + src.toString() + " > " + dst.toString();
104    }
105
106    @Override
107    public String toString(CommandContext ctx) {
108        return "append " + ctx.expandVars(src.toString()) + " > " + ctx.expandVars(dst.toString());
109    }
110
111    private void append(File srcFile, File dstFile, boolean appendNewLine) throws IOException {
112        String srcExt = FileUtils.getFileExtension(srcFile.getName());
113        String dstExt = FileUtils.getFileExtension(dstFile.getName());
114        boolean isDstEmpty = dstFile.length() == 0; // file empty or doesn't exists
115        if (!isDstEmpty && StringUtils.equalsIgnoreCase(srcExt, dstExt) && "json".equalsIgnoreCase(srcExt)) {
116            // merge the json
117            ObjectMapper m = new ObjectMapper();
118            ObjectNode destNode = m.readValue(dstFile, ObjectNode.class);
119            ObjectNode srcNode = m.readValue(srcFile, ObjectNode.class);
120            destNode.setAll(srcNode);
121            m.writeValue(dstFile, destNode);
122        } else {
123            try (InputStream in = new FileInputStream(srcFile);
124                    OutputStream out = new BufferedOutputStream(new FileOutputStream(dstFile, true))) {
125                if (appendNewLine) {
126                    out.write(System.getProperty("line.separator").getBytes());
127                }
128                IOUtils.copy(in, out);
129            }
130        }
131    }
132}