001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (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 *     bstefanescu
016 */
017package org.nuxeo.connect.update.task.standalone.commands;
018
019import java.io.File;
020import java.io.IOException;
021import java.util.Map;
022
023import org.nuxeo.common.utils.FileUtils;
024import org.nuxeo.common.utils.StringUtils;
025import org.nuxeo.connect.update.PackageException;
026
027/**
028 * Copy a file to the given target directory or file. If the target is a directory the file name is preserved. If the
029 * target file exists it will be replaced if overwrite is true otherwise the command validation fails.
030 * <p>
031 * If md5 is set then the copy command will be validated only if the target file has the same md5 as the one specified
032 * in the command.
033 * <p>
034 * The Copy command has as inverse either Delete either another Copy command. If the file was copied without overwriting
035 * then Delete is the inverse (with a md5 set to the one of the copied file). If the file was overwritten then the Copy
036 * command has an inverse another copy command with the md5 to the one of the copied file and the overwrite flag to
037 * true. The file to copy will be the backup of the overwritten file.
038 *
039 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
040 */
041public class ParameterizedCopy extends Copy {
042
043    @SuppressWarnings("hiding")
044    public static final String ID = "pcopy";
045
046    public ParameterizedCopy() {
047        super(ID);
048    }
049
050    public ParameterizedCopy(File file, File tofile, String md5, boolean overwrite) {
051        this();
052        this.file = file;
053        this.tofile = tofile;
054        this.md5 = md5;
055        this.overwrite = overwrite;
056    }
057
058    @Override
059    protected String getContentToCopy(File fileToCopy, Map<String, String> prefs) throws PackageException {
060        try {
061            String content = FileUtils.readFile(fileToCopy);
062            return StringUtils.expandVars(content, prefs);
063        } catch (IOException e) {
064            throw new PackageException("Failed to run parameterized copy for: " + fileToCopy.getName(), e);
065        }
066    }
067
068}