001/*
002 * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *
017 * $Id$
018 */
019
020package org.nuxeo.runtime.deployment.preprocessor.install.commands;
021
022import java.io.File;
023import java.io.IOException;
024
025import org.nuxeo.common.utils.FileUtils;
026import org.nuxeo.common.utils.Path;
027import org.nuxeo.runtime.deployment.preprocessor.install.Command;
028import org.nuxeo.runtime.deployment.preprocessor.install.CommandContext;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033public class MkfileCommand implements Command {
034
035    protected final Path path;
036
037    protected final byte[] content;
038
039    /**
040     * Constructor for mkfile command.
041     *
042     * @param path the path relative to the root container
043     * @param content the file content as an array of bytes
044     */
045    public MkfileCommand(Path path, byte[] content) {
046        this.path = path;
047        this.content = content;
048    }
049
050    @Override
051    public void exec(CommandContext ctx) throws IOException {
052        File baseDir = ctx.getBaseDir();
053        File file = new File(baseDir, ctx.expandVars(path.toString()));
054
055        File parent = file.getParentFile();
056        if (!parent.isDirectory()) {
057            // make sure the parent exists
058            parent.mkdirs();
059        }
060
061        if (content != null && content.length > 0) {
062            FileUtils.writeFile(file, content);
063        } else {
064            file.createNewFile();
065        }
066    }
067
068    @Override
069    public String toString() {
070        return "mkfile " + path.toString();
071    }
072
073    @Override
074    public String toString(CommandContext ctx) {
075        return "mkfile " + ctx.expandVars(path.toString());
076    }
077
078}