Java Code Examples for org.eclipse.emf.ecore.util.EcoreUtil#copy()

The following examples show how to use org.eclipse.emf.ecore.util.EcoreUtil#copy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExpressionHelper.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public static Expression createExpressionFromEObject(final EObject element) {
    if (element instanceof Data) {
        return createVariableExpression((Data) element);
    } else if (element instanceof Output) {
        return createConnectorOutputExpression((Output) element);
    } else if (element instanceof Parameter) {
        return createParameterExpression((Parameter) element);
    } else if (element instanceof org.bonitasoft.studio.model.expression.Expression) {
        return (Expression) EcoreUtil.copy(element);
    } else if (element instanceof Document) {
        return createDocumentExpressionWithDependency((Document) element);
    } else if (element instanceof ContractInput) {
        return createContractInputExpression((ContractInput) element);
    }
    throw new IllegalArgumentException("element argument is not supported: " + element);
}
 
Example 2
Source File: ConcreteSyntaxValidationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSimpleMultiplicities1() throws Exception {
	SimpleMultiplicities m = (SimpleMultiplicities) getModel2("#3 abc kw1 def kw2 fgh ijk kw3 lmn opq");
	validate(m).assertOK();
	m.setVal2(null);
	m.getVal3().remove(0);
	m.getVal4().clear();
	validate(m).assertOK();

	SimpleMultiplicities copy = EcoreUtil.copy(m);
	copy.setVal1(null);
	validate(copy).assertAll(err(p.getSimpleMultiplicities_Val1(), ERROR_VALUE_REQUIRED, 1, null, ""));

	copy = EcoreUtil.copy(m);
	copy.getVal3().clear();
	validate(copy).assertAll(err(p.getSimpleMultiplicities_Val3(), ERROR_LIST_TOO_FEW, 1, null, ""));
}
 
Example 3
Source File: RefactorDataOperation.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
protected void updateDataInListsOfData(final CompoundCommand cc) {
    final List<Data> data = ModelHelper.getAllItemsOfType(dataContainer, ProcessPackage.Literals.DATA);
    for (final DataRefactorPair pairToRefactor : pairsToRefactor) {
        for (final Data d : data) {
            if (!d.equals(pairToRefactor.getNewValue())
                    && d.getName().equals(pairToRefactor.getOldValue().getName())) {
                final Data copy = EcoreUtil.copy(pairToRefactor.getNewValue());
                final EObject container = d.eContainer();
                final EReference eContainmentFeature = d.eContainmentFeature();
                if (container != null && container.eGet(eContainmentFeature) instanceof Collection<?>) {
                    final List<?> dataList = (List<?>) container.eGet(eContainmentFeature);
                    final int index = dataList.indexOf(d);
                    cc.append(RemoveCommand.create(getEditingDomain(), container, eContainmentFeature, d));
                    cc.append(AddCommand.create(getEditingDomain(), container, eContainmentFeature, copy, index));
                } else if (container != null && container.eGet(eContainmentFeature) instanceof Data) {
                    cc.append(SetCommand.create(getEditingDomain(), container, eContainmentFeature, copy));
                }
            }
        }
    }
}
 
Example 4
Source File: FieldTypeEditingSupport.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private void updateToSimpleField(RelationField field, FieldType type) {
    EObject oldElement = EcoreUtil.copy(field);
    BusinessObject parent = (BusinessObject) field.eContainer();
    int index = parent.getFields().indexOf(field);
    parent.getFields().remove(field);
    SimpleField simpleField = new SimpleFieldBuilder()
            .withName(field.getName())
            .withCollection(field.isCollection())
            .withNullable(field.isNullable())
            .withLength(AttributeEditionControl.DEFAULT_LENGTH)
            .withType(type)
            .create();
    parent.getFields().add(index, simpleField);
    selectedFieldObservable.setValue(simpleField);
    DiffElement diffElement = new DiffElement(Event.UPDATE_ATTRIBUTE_TYPE, oldElement,
            simpleField);
    diffElement.addProperty(AttributeEditionControl.PARENT_QUALIFIED_NAME, parent.getQualifiedName());
    formPage.refactorAccessControl(diffElement);
}
 
Example 5
Source File: TaxonomyCheckboxListView.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
private void addTerm(Document document, Term element, boolean removeSubclasses) {
	final Term copy = EcoreUtil.copy(element);
	if (removeSubclasses) {
		copy.getSubclasses().clear();
	}
	if (element.eContainer() instanceof Term) {
		final Term elementContainer = (Term) element.eContainer();
		Term parent = SearchUtils.findTermInDocument(document, elementContainer);
		if (parent == null) {
			addTerm(document, elementContainer, true);
			parent = SearchUtils.findTermInDocument(document, elementContainer);
		}
		parent.getSubclasses().add(copy);
	} else { // Model
		document.getTaxonomy().getDimensions().add(copy);
	}
}
 
Example 6
Source File: InstanceExtensionDescription.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected InstanceExtensionDescription(
		QualifiedName qualifiedName, 
		JvmFeature feature,
		XExpression receiver,
		LightweightTypeReference receiverType,
		Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> typeParameterMapping,
		int receiverConformanceFlags,
		XExpression firstArgument,
		LightweightTypeReference firstArgumentType,
		Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> firstArgumentTypeParameterMapping,
		int firstArgumentConformanceFlags,
		int bucketId,
		boolean visible,
		boolean validStaticState) {
	super(qualifiedName, feature, EcoreUtil.copy(receiver), receiverType, typeParameterMapping, receiverConformanceFlags, bucketId, visible);
	this.firstArgument = firstArgument;
	this.firstArgumentType = firstArgumentType;
	this.firstArgumentTypeParameterMapping = firstArgumentTypeParameterMapping;
	this.firstArgumentConformanceFlags = firstArgumentConformanceFlags;
	this.validStaticState = validStaticState;
}
 
Example 7
Source File: SelectionCopier.java    From graph-editor with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Copies the current selection and stores it in memory.
 */
public void copy() {

    if (selectionTracker.getSelectedNodes().isEmpty()) {
        return;
    }

    copiedNodes.clear();
    copiedConnections.clear();

    final Map<GNode, GNode> copyStorage = new HashMap<>();

    // Don't iterate directly over selectionTracker.getSelectedNodes() because that will not preserve ordering.
    for (final GNode node : model.getNodes()) {
        if (selectionTracker.getSelectedNodes().contains(node)) {

            final GNode copiedNode = EcoreUtil.copy(node);
            copiedNodes.add(copiedNode);
            copyStorage.put(node, copiedNode);
        }
    }

    copiedConnections.addAll(GModelUtils.copyConnections(copyStorage));
    saveParentPositionInScene();
}
 
Example 8
Source File: ManageOrganizationWizard.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public ManageOrganizationWizard() {
    this(null);
    organizations = new ArrayList<>();
    organizationsWorkingCopy = new ArrayList<>();
    for (final IRepositoryFileStore file : store.getChildren()) {
        try {
            organizations.add((Organization) file.getContent());
        } catch (final ReadFileStoreException e) {
            BonitaStudioLog.error("Failed read organization content", e);
        }
    }
    final String activeOrganizationName = activeOrganizationProvider.getActiveOrganization();
    for (final Organization orga : organizations) {
        final Organization copy = EcoreUtil.copy(orga);
        if (activeOrganizationName.equals(orga.getName())) {
            addActiveOrganizationAdapter(copy);
        }
        organizationsWorkingCopy.add(copy);

    }
}
 
Example 9
Source File: LambdaXsemanticsSystem.java    From xsemantics with Eclipse Public License 1.0 6 votes vote down vote up
protected Result<Type> applyRuleParameterType(final RuleEnvironment G, final RuleApplicationTrace _trace_, final Parameter param) throws RuleFailedException {
  Type type = null; // output parameter
  /* { param.type !== null type = EcoreUtil.copy(param.type) } or type = lambdaUtils.createFreshTypeVariable */
  {
    RuleFailedException previousFailure = null;
    try {
      Type _type = param.getType();
      boolean _tripleNotEquals = (_type != null);
      /* param.type !== null */
      if (!_tripleNotEquals) {
        sneakyThrowRuleFailedException("param.type !== null");
      }
      type = EcoreUtil.<Type>copy(param.getType());
    } catch (Exception e) {
      previousFailure = extractRuleFailedException(e);
      type = this.lambdaUtils.createFreshTypeVariable();
    }
  }
  return new Result<Type>(type);
}
 
Example 10
Source File: ConcreteSyntaxValidationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testList3() throws Exception {
	List3 copy, m = (List3) getModel2("#19 id1, id2, id2");
	validate(m).assertOK();

	copy = EcoreUtil.copy(m);
	copy.getVal1().clear();
	copy.getVal1().add("xxx");
	validate(copy).assertOK();

	copy = EcoreUtil.copy(m);
	copy.getVal1().clear();
	validate(copy).assertAll(err(p.getList3_Val1(), ERROR_LIST_TOO_FEW, 1, null, "(val1+|val2)"),
			err(p.getList3_Val2(), ERROR_VALUE_REQUIRED, 1, null, "(val1+|val2)"));

	copy = EcoreUtil.copy(m);
	copy.getVal1().clear();
	copy.setVal2("lala");
	validate(copy).assertOK();
}
 
Example 11
Source File: MoveItemsAndCopyDataCommand.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void mapProcessDataWithCallActivity(final Pool targetProcess, final CallActivity subprocessStep,
        final Data sourceData) {
    final Data targetData = EcoreUtil.copy(sourceData);
    targetProcess.getData().add(targetData);
    final InputMapping inputMapping = ProcessFactory.eINSTANCE.createInputMapping();
    inputMapping.setProcessSource(ExpressionHelper.createVariableExpression(sourceData));
    inputMapping.setSubprocessTarget(sourceData.getName());
    subprocessStep.getInputMappings().add(inputMapping);
    final OutputMapping outputMapping = ProcessFactory.eINSTANCE.createOutputMapping();
    outputMapping.setProcessTarget(sourceData);
    outputMapping.setSubprocessSource(sourceData.getName());
}
 
Example 12
Source File: DefaultFeatures.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void customize ( final Item item )
{
    final LevelMonitor levelMonitor = EcoreUtil.copy ( this.template );
    levelMonitor.setName ( this.name );
    levelMonitor.setPreset ( this.value );
    registerFeature ( item, levelMonitor );
}
 
Example 13
Source File: ConcreteSyntaxValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testList5() throws Exception {
	List5 copy, m = (List5) getModel2("#21 id11, id12, id13 kw3 id2");
	validate(m).assertOK();

	copy = EcoreUtil.copy(m);
	copy.getVal1().clear();
	copy.getVal1().add("xxx");
	validate(copy).assertOK();

	copy = EcoreUtil.copy(m);
	copy.getVal1().clear();
	copy.setVal2(null);
	copy.setVal3("foo");
	validate(copy).assertOK();

	copy = EcoreUtil.copy(m);
	copy.getVal1().clear();
	validate(copy).assertAll(err(p.getList5_Val1(), ERROR_LIST_TOO_FEW, 1, null, "((val1+ val2)|val3)"));

	copy = EcoreUtil.copy(m);
	copy.setVal2(null);
	validate(copy).assertAll(err(p.getList5_Val2(), ERROR_VALUE_REQUIRED, 1, null, "((val1+ val2)|val3)"));

	copy = EcoreUtil.copy(m);
	copy.setVal3("foo");
	validate(copy).assertAll(err(p.getList5_Val1(), ERROR_LIST_TOO_MANY, null, 0, "((val1+ val2)|val3)"),
			err(p.getList5_Val2(), ERROR_VALUE_PROHIBITED, null, 0, "((val1+ val2)|val3)"),
			err(p.getList5_Val3(), ERROR_VALUE_PROHIBITED, null, 0, "((val1+ val2)|val3)"));
}
 
Example 14
Source File: RolesWizardPage.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void handleRoleDescriptionChange(final ValueChangeEvent event) {
    final Role role = (Role) roleSingleSelectionObservable.getValue();
    final Role oldRole = EcoreUtil.copy(role);
    final Object oldValue = event.diff.getOldValue();
    if (oldValue != null) {
        oldRole.setName(oldValue.toString());

        if (getViewer() != null && !getViewer().getControl().isDisposed()) {
            getViewer().refresh(role);
        }
    }
}
 
Example 15
Source File: ExpressionHelper.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private static EObject createSearchIndexDependency(final EObject dependency) {
    final SearchIndex searchIndexDependency = (SearchIndex) ProcessFactory.eINSTANCE.create(dependency.eClass());
    final Expression name = ((SearchIndex) dependency).getName();
    if (name != null) {
        final Expression nameExpression = EcoreUtil.copy(name);
        nameExpression.getReferencedElements().clear();
        searchIndexDependency.setName(nameExpression);
    }
    return searchIndexDependency;
}
 
Example 16
Source File: DecisionTableWizard.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void setTable(DecisionTable table) {
	if (table != null) {
		this.oldTable = table ;
		this.table = EcoreUtil.copy(table);
	} else {
		this.table = DecisionFactory.eINSTANCE.createDecisionTable();
	}
}
 
Example 17
Source File: IteratorRefactorOperationFactory.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
private Data dataWithNewName(final Data data, final String newValue) {
    final Data copy = EcoreUtil.copy(data);
    copy.setName(newValue);
    return copy;
}
 
Example 18
Source File: ConcreteSyntaxValidationTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testGroupMultiplicities1() throws Exception {
	GroupMultiplicities m = (GroupMultiplicities) getModel2("#4 abc kw1 def def kw2 fgh ijk kw3 lmn opq");
	validate(m).assertOK();

	GroupMultiplicities copy = EcoreUtil.copy(m);
	copy.setVal2(null);
	copy.setVal3(null);
	copy.getVal6().clear();
	copy.getVal7().clear();
	validate(copy).assertOK();

	copy = EcoreUtil.copy(m);
	copy.setVal2(null);
	validate(copy).assertAll(err(p.getGroupMultiplicities_Val2(), ERROR_VALUE_REQUIRED, 1, null, "(val2 val3)?"),
			err(p.getGroupMultiplicities_Val3(), ERROR_VALUE_PROHIBITED, null, 0, "(val2 val3)?"));

	copy = EcoreUtil.copy(m);
	copy.getVal5().clear();
	validate(copy).assertAll(err(p.getGroupMultiplicities_Val5(), ERROR_LIST_TOO_FEW, 1, null, "(val4 val5)+"));

	copy = EcoreUtil.copy(m);
	copy.getVal4().clear();
	copy.getVal5().clear();
	validate(copy).assertAll(err(p.getGroupMultiplicities_Val4(), ERROR_LIST_TOO_FEW, 1, null, "(val4 val5)+"),
			err(p.getGroupMultiplicities_Val5(), ERROR_LIST_TOO_FEW, 1, null, "(val4 val5)+"));

	copy = EcoreUtil.copy(m);
	copy.getVal5().add("sdlasjdk");
	validate(copy).assertAll(err(p.getGroupMultiplicities_Val4(), ERROR_LIST_TOO_FEW, 2, null, "(val4 val5)+"),
			err(p.getGroupMultiplicities_Val5(), ERROR_LIST_TOO_MANY, null, 1, "(val4 val5)+"));

	copy = EcoreUtil.copy(m);
	copy.getVal6().clear();
	validate(copy).assertAll(err(p.getGroupMultiplicities_Val6(), ERROR_LIST_TOO_FEW, 1, 1, "(val6 val7)*"),
			err(p.getGroupMultiplicities_Val7(), ERROR_LIST_TOO_MANY, 0, 0, "(val6 val7)*"));

	copy = EcoreUtil.copy(m);
	copy.getVal7().add("test");
	validate(copy).assertAll(err(p.getGroupMultiplicities_Val6(), ERROR_LIST_TOO_FEW, 2, null, "(val6 val7)*"),
			err(p.getGroupMultiplicities_Val7(), ERROR_LIST_TOO_MANY, 1, 1, "(val6 val7)*"));

}
 
Example 19
Source File: InteractivityCharts.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
protected static final Chart createRCChart( )
{
	ChartWithAxes cwaBar = ChartWithAxesImpl.create( );
	cwaBar.setDimension( ChartDimension.TWO_DIMENSIONAL_WITH_DEPTH_LITERAL );
	cwaBar.getBlock( ).setBackground( ColorDefinitionImpl.WHITE( ) );
	cwaBar.getInteractivity( )
			.setLegendBehavior( LegendBehaviorType.HIGHLIGHT_SERIE_LITERAL );
	Plot p = cwaBar.getPlot( );
	p.getClientArea( ).setBackground( ColorDefinitionImpl.create( 255,
			255,
			225 ) );
	cwaBar.getTitle( )
			.getLabel( )
			.getCaption( )
			.setValue( "Right Click \"Items\" to Highlight Seires" ); //$NON-NLS-1$
	cwaBar.setUnitSpacing( 20 );

	Legend lg = cwaBar.getLegend( );
	LineAttributes lia = lg.getOutline( );
	lg.getText( ).getFont( ).setSize( 16 );
	lia.setStyle( LineStyle.SOLID_LITERAL );
	lg.getInsets( ).set( 10, 5, 0, 0 );
	lg.getOutline( ).setVisible( false );
	lg.setAnchor( Anchor.NORTH_LITERAL );
	lg.setItemType( LegendItemType.CATEGORIES_LITERAL );

	// X-Axis
	Axis xAxisPrimary = cwaBar.getPrimaryBaseAxes( )[0];

	xAxisPrimary.setType( AxisType.TEXT_LITERAL );
	xAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.BELOW_LITERAL );
	xAxisPrimary.getOrigin( ).setType( IntersectionType.VALUE_LITERAL );
	xAxisPrimary.getTitle( ).setVisible( true );

	// Y-Axis
	Axis yAxisPrimary = cwaBar.getPrimaryOrthogonalAxis( xAxisPrimary );
	yAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.LEFT_LITERAL );
	yAxisPrimary.setType( AxisType.LINEAR_LITERAL );
	yAxisPrimary.getLabel( ).getCaption( ).getFont( ).setRotation( 90 );

	// Data Set
	TextDataSet categoryValues = TextDataSetImpl.create( new String[]{
			"Item 1", "Item 2", "Item 3"} ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	NumberDataSet orthoValues = NumberDataSetImpl.create( new double[]{
			25, 35, 15
	} );

	// X-Series
	Series seCategory = SeriesImpl.create( );
	seCategory.setDataSet( categoryValues );

	SeriesDefinition sdX = SeriesDefinitionImpl.create( );
	sdX.getSeriesPalette( ).shift( 0 );
	xAxisPrimary.getSeriesDefinitions( ).add( sdX );
	sdX.getSeries( ).add( seCategory );

	// Y-Series
	BarSeries bs = (BarSeries) BarSeriesImpl.create( );
	bs.setStacked( true );
	bs.setDataSet( orthoValues );
	bs.setRiser( RiserType.TUBE_LITERAL );
	bs.setSeriesIdentifier( "Highlight" ); //$NON-NLS-1$
	bs.getLabel( ).setVisible( true );
	bs.setLabelPosition( Position.INSIDE_LITERAL );
	bs.getTriggers( )
			.add( TriggerImpl.create( TriggerCondition.ONRIGHTCLICK_LITERAL,
					ActionImpl.create( ActionType.HIGHLIGHT_LITERAL,
							SeriesValueImpl.create( String.valueOf( bs.getSeriesIdentifier( ) ) ) ) ) );
	lg.getTriggers( )
			.add( TriggerImpl.create( TriggerCondition.ONRIGHTCLICK_LITERAL,
					ActionImpl.create( ActionType.HIGHLIGHT_LITERAL,
							SeriesValueImpl.create( String.valueOf( bs.getSeriesIdentifier( ) ) ) ) ) );

	SeriesDefinition sdY = SeriesDefinitionImpl.create( );
	yAxisPrimary.getSeriesDefinitions( ).add( sdY );
	sdY.getSeries( ).add( bs );

	Series bs2 =  EcoreUtil.copy( bs );
	bs2.setDataSet( NumberDataSetImpl.create( new double[]{
			35, 30, 10
	} ) );
	sdY.getSeries( ).add( bs2 );

	Series bs3 =  EcoreUtil.copy( bs );
	bs3.setDataSet( NumberDataSetImpl.create( new double[]{
			20, 10, 30
	} ) );
	sdY.getSeries( ).add( bs3 );

	return cwaBar;
}
 
Example 20
Source File: AbstractPortableURIsTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void doTestResource(String platformPath, String... packageNames) {
	Resource resource = resourceSet.getResource(URI.createPlatformPluginURI(platformPath, false), true);
	assertNotNull(resource);
	assertEquals(1, resource.getContents().size());
	EObject obj = resource.getContents().get(0);
	if (obj instanceof EPackage) {
		assertEquals(packageNames[0], ((EPackage) obj).getName());
	} else if (obj instanceof GenModel) {
		GenModel model = (GenModel) obj;
		List<GenPackage> packages = Lists.newArrayList(model.getGenPackages());
		assertEquals(packageNames.length, packages.size());
		ListExtensions.sortInplaceBy(packages, new Functions.Function1<GenPackage, String>() {
			@Override
			public String apply(GenPackage p) {
				return p.getEcorePackage().getName();
			}
		});
		List<String> packageNamesList = Arrays.asList(packageNames);
		Collections.sort(packageNamesList);
		for(int i = 0; i < packageNamesList.size(); i++) {
			assertEquals(packageNamesList.get(i), packages.get(i).getEcorePackage().getName());
		}
		IStatus status = model.validate();
		assertTrue(printLeafs(status), status.isOK());
		EObject orig = EcoreUtil.copy(obj);
		((GenModel) obj).reconcile();
		if (!EcoreUtil.equals(orig, obj)) {
			Predicate<EStructuralFeature> ignoreContainer = new Predicate<EStructuralFeature>() {
				@Override
				public boolean apply(EStructuralFeature f) {
					if (f instanceof EReference) {
						EReference casted = (EReference) f;
						return !casted.isContainment();
					}
					return false;
				}
			};
			String origAsString = EmfFormatter.objToStr(orig, ignoreContainer);
			String newAsString = EmfFormatter.objToStr(obj, ignoreContainer);
			throw new ComparisonFailure("Reconcile changed model", origAsString, newAsString);
		}
	} else {
		fail("Unexpected root element type: " + obj.eClass().getName());
	}
}