001/*
002 * ModeShape (http://www.modeshape.org)
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 */
016package org.modeshape.schematic.internal.delta;
017
018import java.util.ArrayList;
019import java.util.Collections;
020import java.util.List;
021import org.modeshape.schematic.annotation.Immutable;
022import org.modeshape.schematic.document.Path;
023import org.modeshape.schematic.internal.HashCode;
024import org.modeshape.schematic.internal.document.MutableArray;
025import org.modeshape.schematic.internal.document.MutableDocument;
026
027/**
028 * An atomic remove operation for SchematicValueDelta.
029 * 
030 * @author (various)
031 */
032@Immutable
033public class ClearOperation extends ArrayOperation {
034
035    private transient List<?> removedValues;
036
037    public ClearOperation( Path path ) {
038        super(path, HashCode.compute(path));
039    }
040
041    @Override
042    public ClearOperation clone() {
043        return this; // immutable
044    }
045
046    @Override
047    public void replay( MutableDocument delegate ) {
048        MutableArray array = mutableParent(delegate);
049        if (!array.isEmpty()) {
050            removedValues = new ArrayList<>(array);
051            array.clear();
052        } else {
053            removedValues = Collections.emptyList();
054        }
055    }
056
057    @Override
058    public void rollback( MutableDocument delegate ) {
059        if (removedValues != null) {
060            MutableArray array = mutableParent(delegate);
061            array.clear();
062            array.addAll(removedValues);
063            removedValues = null;
064        }
065    }
066
067    @Override
068    public String toString() {
069        return "Clear at '" + parentPath + "' the existing values";
070    }
071
072    @Override
073    public int hashCode() {
074        return super.hashCode();
075    }
076
077    @Override
078    public boolean equals( Object obj ) {
079        if (obj instanceof ClearOperation) {
080            ClearOperation that = (ClearOperation)obj;
081            return equalsIfNotNull(getParentPath(), that.getParentPath());
082        }
083        return false;
084    }
085}