001/*
002 * Copyright c 2018 Rusi Popov, MDA Tools.net All rights reserved.
003 *
004 * This program and the accompanying materials are made available under the terms of the
005 * Eclipse Public License v2.0 which accompanies this distribution, and is available at
006 * http://www.eclipse.org/legal/epl-v20.html
007 */
008package net.mdatools.modelant.core.operation.element;
009
010import java.util.Collection;
011
012import javax.jmi.reflect.RefFeatured;
013
014/**
015 * Associate or change the attribute value of a model element and return that updated model element.
016 * @author Rusi Popov (popovr@mdatools.net)
017 */
018public class Add extends NavigateObjectPath<RefFeatured> {
019
020  private final Object value;
021
022
023  /**
024   * @see NavigateObjectPath
025   */
026  public Add(String path, Object value) {
027    super( path );
028    this.value = value;
029  }
030
031
032  /**
033   * @see NavigateObjectPath
034   */
035  public Add(String[] path, Object value) {
036    super( path );
037    this.value = value;
038  }
039
040  /**
041   * Nothing to do
042   * @see net.mdatools.modelant.core.operation.element.NavigateObjectPath#processEmptyPath(javax.jmi.reflect.RefFeatured)
043   */
044  protected RefFeatured processEmptyPath(RefFeatured start) {
045    return start;
046  }
047
048
049  /**
050   * Clear an association *-to-one
051   * @see net.mdatools.modelant.core.operation.element.NavigateObjectPath#processLast(javax.jmi.reflect.RefFeatured, javax.jmi.reflect.RefFeatured, java.lang.String, javax.jmi.reflect.RefFeatured)
052   */
053  protected RefFeatured processLast(RefFeatured start,
054                                    RefFeatured current,
055                                    String itemName,
056                                    RefFeatured associated) {
057    current.refSetValue( itemName, value );
058
059    return current;
060  }
061
062
063  /**
064   * @see net.mdatools.modelant.core.operation.element.NavigateObjectPath#processLast(javax.jmi.reflect.RefFeatured, javax.jmi.reflect.RefFeatured, java.lang.String, java.lang.Object)
065   */
066  protected RefFeatured processLast(RefFeatured start, RefFeatured current, String itemName, Object actualValue) {
067    if ( actualValue instanceof Collection ) { // association to many
068      if ( value instanceof Collection) { // associate to many
069        ((Collection) actualValue).addAll( (Collection) value );
070
071      } else { // associate to one
072        ((Collection) actualValue).add( value );
073      }
074    } else { // set an attribute
075      throw new IllegalArgumentException("Expected "+actualValue+" is a collection attribute value to add "+value+" to");
076    }
077    return current;
078  }
079}