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 org.modeshape.schematic.document.Path; 019import org.modeshape.schematic.internal.HashCode; 020import org.modeshape.schematic.internal.document.MutableDocument; 021 022/** 023 * An atomic put-if-absent operation for SchematicValueDelta. 024 * 025 * @author (various) 026 */ 027public class PutIfAbsentOperation extends Operation { 028 protected final String fieldName; 029 protected final Object newValue; 030 private transient boolean absent = false; 031 032 public PutIfAbsentOperation( Path parentPath, 033 String fieldName, 034 Object newValue ) { 035 super(parentPath, HashCode.compute(parentPath, fieldName, newValue)); 036 this.fieldName = fieldName; 037 this.newValue = newValue; 038 } 039 040 @Override 041 public PutIfAbsentOperation clone() { 042 return new PutIfAbsentOperation(getParentPath(), fieldName, cloneValue(newValue)); 043 } 044 045 public Object getNewValue() { 046 return newValue; 047 } 048 049 public String getFieldName() { 050 return fieldName; 051 } 052 053 public boolean isApplied() { 054 return absent; 055 } 056 057 @Override 058 public void rollback( MutableDocument delegate ) { 059 MutableDocument parent = mutableParent(delegate); 060 assert parent != null; 061 if (absent) { 062 parent.remove(fieldName); 063 } 064 } 065 066 @Override 067 public void replay( MutableDocument delegate ) { 068 MutableDocument parent = mutableParent(delegate); 069 assert parent != null; 070 if (!parent.containsField(fieldName)) { 071 parent.put(fieldName, newValue); 072 absent = true; 073 } 074 } 075 076 @Override 077 public int hashCode() { 078 return super.hashCode(); 079 } 080 081 @Override 082 public boolean equals( Object obj ) { 083 if (obj instanceof PutIfAbsentOperation) { 084 PutIfAbsentOperation other = (PutIfAbsentOperation)obj; 085 return equalsIfNotNull(fieldName, other.fieldName) && absent == other.absent 086 && equalsIfNotNull(newValue, other.newValue) && getParentPath().equals(other.getParentPath()); 087 088 } 089 return false; 090 } 091 092 @Override 093 public String toString() { 094 return "Put-if-absent at '" + parentPath + "' the '" + fieldName + "' field value '" + newValue + "'"; 095 } 096}