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