001/* 002 * (C) Copyright 2006-2007 Nuxeo SA (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 * 019 * $Id$ 020 */ 021 022package org.nuxeo.runtime.deployment.preprocessor.install.commands; 023 024import java.io.File; 025import java.io.IOException; 026import java.nio.file.Files; 027 028import org.apache.commons.io.FileUtils; 029import org.nuxeo.common.utils.Path; 030import org.nuxeo.runtime.deployment.preprocessor.install.Command; 031import org.nuxeo.runtime.deployment.preprocessor.install.CommandContext; 032 033/** 034 * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> 035 */ 036public class MkfileCommand implements Command { 037 038 protected final Path path; 039 040 protected final byte[] content; 041 042 /** 043 * Constructor for mkfile command. 044 * 045 * @param path the path relative to the root container 046 * @param content the file content as an array of bytes 047 */ 048 public MkfileCommand(Path path, byte[] content) { 049 this.path = path; 050 this.content = content; 051 } 052 053 @Override 054 public void exec(CommandContext ctx) throws IOException { 055 File baseDir = ctx.getBaseDir(); 056 File file = new File(baseDir, ctx.expandVars(path.toString())); 057 058 File parent = file.getParentFile(); 059 if (!parent.isDirectory()) { 060 // make sure the parent exists 061 parent.mkdirs(); 062 } 063 064 if (content != null && content.length > 0) { 065 FileUtils.writeByteArrayToFile(file, content); 066 } else { 067 Files.createFile(file.toPath()); 068 } 069 } 070 071 @Override 072 public String toString() { 073 return "mkfile " + path.toString(); 074 } 075 076 @Override 077 public String toString(CommandContext ctx) { 078 return "mkfile " + ctx.expandVars(path.toString()); 079 } 080 081}