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 javax.jmi.reflect.RefClass;
011import javax.jmi.reflect.RefObject;
012import javax.jmi.reflect.RefPackage;
013
014import net.mdatools.modelant.core.api.Operation;
015import net.mdatools.modelant.core.util.Navigator;
016
017/**
018 * Instantiate a the model class, which is the class of a specific model element,
019 * in the the wrapped extent.
020 * @author Rusi Popov (popovr@mdatools.net)
021 */
022public class ConstructSameInExtent implements Operation<RefObject> {
023
024  /**
025   * Extent where the model is loaded
026   */
027  private final RefPackage extent;
028
029  /**
030   * @param extent not null extent where to construct in
031   */
032  public ConstructSameInExtent(RefPackage extent) {
033    if (extent == null) {
034      throw new IllegalArgumentException("Expected a non-null model extent");
035    }
036    this.extent = extent;
037  }
038
039  /**
040   * @param source Navigate from this element, down the path
041   */
042  public RefObject execute(RefObject source) throws IllegalArgumentException {
043    RefObject result;
044    RefClass refClass;
045    String metaclass;
046
047    // fond the source object
048    if ( source == null ) {
049      throw new IllegalArgumentException("Expected a non-null model element");
050    }
051
052    metaclass = Navigator.getMetaClassName( source );
053    refClass = Navigator.getMetaClass( extent, metaclass ); // non-null
054
055    result = refClass.refCreateInstance( null );
056    return result;
057  }
058}