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