/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl; import java.util.List; import java.util.Map; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode; import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder; import com.google.common.collect.Maps; abstract class AbstractImmutableDataContainerNodeBuilder> implements DataContainerNodeBuilder { private Map> value; private I nodeIdentifier; /* * Tracks whether the builder is dirty, e.g. whether the value map has been used * to construct a child. If it has, we detect this condition before any further * modification and create a new value map with same contents. This way we do not * force a map copy if the builder is not reused. */ private boolean dirty; protected AbstractImmutableDataContainerNodeBuilder() { this.value = Maps.newHashMap(); } protected final I getNodeIdentifier() { return nodeIdentifier; } protected final DataContainerChild getChild(final PathArgument child) { return value.get(child); } protected final Map> buildValue() { dirty = true; return value; } private void checkDirty() { if (dirty) { value = Maps.newHashMap(value); dirty = false; } } @Override public DataContainerNodeBuilder withValue(final List> value) { // TODO Replace or putAll ? for (final DataContainerChild dataContainerChild : value) { withChild(dataContainerChild); } return this; } @Override public DataContainerNodeBuilder withChild(final DataContainerChild child) { checkDirty(); this.value.put(child.getIdentifier(), child); return this; } @Override public DataContainerNodeBuilder withNodeIdentifier(final I nodeIdentifier) { this.nodeIdentifier = nodeIdentifier; return this; } @Override public DataContainerNodeBuilder addChild( final DataContainerChild child) { return withChild(child); } }