Java Code Examples for org.eclipse.emf.common.util.EList#remove()

The following examples show how to use org.eclipse.emf.common.util.EList#remove() . 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: N4JSResourceSetCleanerUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes all non-N4 resources from the given resource set without sending any notification about the removal. This
 * specific resource set cleaning is required to avoid the accidental removal of the resources holding the built-in
 * types. For more details reference: IDEBUG-491.
 *
 * @param resourceSet
 *            the resource set to clean. Optional, can be {@code null}. If {@code null} this method has no effect.
 */
/* default */static void clearResourceSet(final ResourceSet resourceSet) {
	boolean wasDeliver = resourceSet.eDeliver();
	try {
		resourceSet.eSetDeliver(false);
		// iterate backwards to avoid costly shuffling in the underlying list
		EList<Resource> resources = resourceSet.getResources();
		// int originalSize = resources.size();
		for (int i = resources.size() - 1; i >= 0; i--) {
			final Resource resource = resources.get(i);
			final URI uri = resource.getURI();
			if (!isN4Scheme(uri)) {
				resources.remove(i);
			} else {
				LOGGER.info("Intentionally skipping the removal of N4 resource: " + uri);
			}
		}
	} finally {
		resourceSet.eSetDeliver(wasDeliver);
	}
}
 
Example 2
Source File: FormatterFacade.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Format the given code.
 *
 * @param sarlCode the code to format.
 * @param resourceSet the resource set that sohuld contains the code. This resource set may be
 *     used for resolving types by the underlying code.
 * @return the code to format.
 */
@Pure
public String format(String sarlCode, ResourceSet resourceSet) {
	try {
		final URI createURI = URI.createURI("synthetic://to-be-formatted." + this.fileExtension); //$NON-NLS-1$
		final Resource res = this.resourceFactory.createResource(createURI);
		if (res instanceof XtextResource) {
			final XtextResource resource = (XtextResource) res;
			final EList<Resource> resources = resourceSet.getResources();
			resources.add(resource);
			try (StringInputStream stringInputStream = new StringInputStream(sarlCode)) {
				resource.load(stringInputStream, Collections.emptyMap());
				return formatResource(resource);
			} finally {
				resources.remove(resource);
			}
		}
		return sarlCode;
	} catch (Exception exception) {
		throw Exceptions.sneakyThrow(exception);
	}
}
 
Example 3
Source File: DataDefinitionSelector.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected void removeSeriesDefinition( )
	{
		boolean isNotificaionIgnored = ChartAdapter.isNotificationIgnored( );
		ChartAdapter.ignoreNotifications( true );
		int firstIndex = getFirstIndexOfSameAxis( );
		EList<OrthogonalSampleData> list = getChart( ).getSampleData( )
				.getOrthogonalSampleData( );
		for ( int i = 0; i < list.size( ); i++ )
		{
			// Check each entry if it is associated with the series
			// definition to be removed
			if ( list.get( i ).getSeriesDefinitionIndex( ) == ( firstIndex + cmbSeriesSelect.getSelectionIndex( ) ) )
			{
				list.remove( i );
				break;
			}
		}
		// Reset index. If index is wrong, sample data can't display.
		ChartUIUtil.reorderOrthogonalSampleDataIndex( getChart( ) );
//		updateSeriesPalette( cmbSeriesSelect.getSelectionIndex( ) );
		ChartAdapter.ignoreNotifications( isNotificaionIgnored );

		seriesDefns.remove( cmbSeriesSelect.getSelectionIndex( ) );
	}
 
Example 4
Source File: ProxyCompositeNode.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private static ProxyCompositeNode uninstallProxyNode(final EObject eObject) {
  EList<Adapter> adapters = eObject.eAdapters();
  int size = adapters.size();
  for (int i = 0; i < size; ++i) {
    Adapter adapter = adapters.get(i);
    if (adapter.isAdapterForType(ProxyCompositeNode.class)) {
      if (adapter instanceof ProxyCompositeNode) {
        return (ProxyCompositeNode) adapters.remove(i);
      }
      break;
    }
  }
  return null;
}
 
Example 5
Source File: QuickFix.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
private void deleteFromFile(String[] path, String markerLocation) {
	EList<Term> terms = ModelRegistryPlugin.getModelRegistry().getActiveTaxonomy().get().getDimensions();
	List<Document> documents = SearchUtils.getDocumentList();
	for (Document d : documents) {
		if (d.getKey().equals(markerLocation)) {
			terms = d.getTaxonomy().getDimensions();
			
			int[] pathIndex = new int[path.length];

			for (int pathPosition=1; pathPosition<path.length; pathPosition++) {
				int index = 0;
				for (Term t : terms) {
					if (t.getName().equals(path[pathPosition])) {
						pathIndex[pathPosition-1] = index;
						if (pathPosition == (path.length-1)) { //check if pointer is at last path-element
							terms.remove(index);
							pathPosition = path.length; //break parent loop
						}
						terms = t.getSubclasses();
							
						break;
					}
					index++;
				}
				
			}
			BibtexFileWriter.updateBibtexFile(d.eResource());	
			
			BibtexFactory bib = BibtexFactoryImpl.init();
			bib.createBibtexFile();
		
			break;
		}
	}
	
}
 
Example 6
Source File: QuickFix.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
private void moveTermInFile(String[] path, String[] path2, String markerLocation) {
	EList<Term> terms = ModelRegistryPlugin.getModelRegistry().getActiveTaxonomy().get().getDimensions();
	List<Document> documents = SearchUtils.getDocumentList();
	for (Document d : documents) {
		if (d.getKey().equals(markerLocation)) {
			terms = d.getTaxonomy().getDimensions();
			
			int[] pathIndex = new int[path.length];

			for (int pathPosition=1; pathPosition<path.length; pathPosition++) {

				int index = 0;
				for (Term t : terms) {
					if (t.getName().equals(path[pathPosition])) {
						pathIndex[pathPosition-1] = index;
						if (pathPosition == (path.length-1)) { //check if pointer is at last path-element
							Term moveTerm = terms.get(index);
							addTerm(d, path2, moveTerm);
							
							terms.remove(index);
							pathPosition = path.length; //break parent loop
						}
						terms = t.getSubclasses();
						break;
					}
					index++;
				}
			}		

			BibtexFileWriter.updateBibtexFile(d.eResource());	
			//printTaxonomy(d.getTaxonomy().getDimensions(), "|");
			
			BibtexFactory bib = BibtexFactoryImpl.init();
			bib.createBibtexFile();
		
			break;
		}
	}
	
}
 
Example 7
Source File: CallOperationExporter.java    From txtUML with Eclipse Public License 1.0 4 votes vote down vote up
public String createCallOperationActionCode(CallOperationAction node) {
	StringBuilder source = new StringBuilder("");
	tempVariableExporter.exportAllOutputPinsToMap(node.getOutputs());
	OutputPin returnPin = searchReturnPin(node.getResults(), node.getOperation().outputParameters());
	if (returnPin != null)
		returnOutputsToCallActions.put(node, returnPin);

	if (CppExporterUtils.isConstructor(node.getOperation())) {

		/*
		 * In case of signal factory's constructor the first parameter is
		 * the signal type which is the target.
		 */
		InputPin target = node.getTarget() == null ? node.getArguments().get(0) : node.getTarget();
		EList<InputPin> arguments = node.getArguments();
		arguments.remove(target);
		return ActivityTemplates.blockStatement(createConstructorCallAction(target, arguments));
	}

	if (node.getOperation().getName().equals(ActivityTemplates.GetSignalFunctionName)) {
		return ActivityTemplates.getRealSignal(returnPin.getType().getName(),
				tempVariableExporter.getRealVariableName(returnPin));
	}
	String val = "";
	String returnTypeName = "";
	if (node.getOperation().getType() != null)
		returnTypeName = node.getOperation().getType().getName();

	if (isStdLibOperation(node)) {

		EList<OutputPin> outParamaterPins = node.getResults();
		outParamaterPins.remove(returnPin);
		source.append(declareAllOutTempParameters(outParamaterPins));
		List<String> parameterVariables = new ArrayList<String>(getParametersNames(node.getArguments()));
		addOutParametrsToList(parameterVariables, outParamaterPins);

		val = ActivityTemplates.stdLibCall(node.getOperation().getName(), parameterVariables);

		if (OperatorTemplates.isTimerSchedule(node.getOperation().getName())) {
			if (exportUser.isPresent()) {
				exportUser.get().addCppOnlyDependency(FileNames.TimerInterfaceHeader);
				exportUser.get().addCppOnlyDependency(FileNames.TimerHeader);
			}

		}

		if (node.getOperation().getType() != null) {
			if (node.getOutgoings().size() > 0) {
				returnTypeName = ((InputPin) node.getOutgoings().get(0).getTarget()).getType().getName();
			} else if (returnPin != null && returnPin.getOutgoings().size() > 0) {
				returnTypeName = ((InputPin) returnPin.getOutgoings().get(0).getTarget()).getType().getName();

			}

		}

	} else {

		Operation op = node.getOperation();

		Element opOwner = op.getOwner();
		if (opOwner instanceof NamedElement) {
			NamedElement namedOwner = (NamedElement) opOwner;
			if (exportUser.isPresent()) {
				exportUser.get().addCppOnlyDependency(namedOwner.getName());
			}
		}

		val = ActivityTemplates.operationCall(activityExportResolver.getTargetFromInputPin(node.getTarget(), false),
				ActivityTemplates.accesOperatoForType(activityExportResolver.getTypeFromInputPin(node.getTarget())),
				op.getName(), getParametersNames(node.getArguments()));
		
		
		if(op.getUpper() == 1 && returnPin != null) {
			val = ActivityTemplates.operationCall(val, PointerAndMemoryNames.SimpleAccess, 
					CollectionNames.SelectAnyFunctionName, Collections.emptyList());
		}


	}

	if (returnPin != null) {
		source.append(addValueToTemporalVariable(returnTypeName,
				tempVariableExporter.getRealVariableName(returnPin), val));
	} else {
		source.append(ActivityTemplates.blockStatement(val));
	}

	return source.toString();

}
 
Example 8
Source File: ChartUIUtil.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Adds an orthogonal axis. Ensures only one event is fired.
 * 
 * @param chartModel
 *            chart model
 */
public static void addAxis( final ChartWithAxes chartModel )
{
	// Prevent notifications rendering preview
	ChartAdapter.beginIgnoreNotifications( );
	// --------------------------Begin

	// Create a clone of the existing Y Axis
	Axis xAxis = chartModel.getAxes( ).get( 0 );
	Axis yAxis = xAxis.getAssociatedAxes( ).get( 0 );
	Axis overlayAxis = yAxis.copyInstance( );
	// Now update overlay axis to set the properties that are
	// different from
	// the original
	overlayAxis.setPrimaryAxis( false );
	overlayAxis.setOrigin( AxisOriginImpl.create( IntersectionType.MAX_LITERAL,
			null ) );
	overlayAxis.setLabelPosition( Position.RIGHT_LITERAL );
	overlayAxis.setTitlePosition( Position.RIGHT_LITERAL );
	overlayAxis.eAdapters( ).addAll( yAxis.eAdapters( ) );

	// Retain the first series of the axis. Remove others
	if ( overlayAxis.getSeriesDefinitions( ).size( ) > 1 )
	{
		EList<SeriesDefinition> list = overlayAxis.getSeriesDefinitions( );
		for ( int i = list.size( ) - 1; i > 0; i-- )
		{
			list.remove( i );
		}
	}

	// Update overlay series definition(retain the group query,
	// clean the data query)
	SeriesDefinition sdOverlay = overlayAxis.getSeriesDefinitions( )
			.get( 0 );
	EList<Query> dds = sdOverlay.getDesignTimeSeries( ).getDataDefinition( );
	for ( int i = 0; i < dds.size( ); i++ )
	{
		dds.get( i ).setDefinition( "" ); //$NON-NLS-1$
	}
	
	// Update the sample values for the new overlay series
	SampleData sd = chartModel.getSampleData( );
	// Create a new OrthogonalSampleData instance from the existing
	// one
	int currentSize = sd.getOrthogonalSampleData( ).size( );
	OrthogonalSampleData sdOrthogonal = chartModel.getSampleData( )
			.getOrthogonalSampleData( )
			.get( 0 )
			.copyInstance( );
	sdOrthogonal.setDataSetRepresentation( ChartUtil.getNewSampleData( overlayAxis.getType( ),
			currentSize ) );
	sdOrthogonal.setSeriesDefinitionIndex( currentSize );
	sdOrthogonal.eAdapters( ).addAll( sd.eAdapters( ) );
	sd.getOrthogonalSampleData( ).add( sdOrthogonal );
	chartModel.getAxes( ).get( 0 ).getAssociatedAxes( ).add( overlayAxis );
	// ------------------End
	ChartAdapter.endIgnoreNotifications( );

	setSeriesName( chartModel );
}
 
Example 9
Source File: CopyEObjectFeaturesCommand.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param targetElement
 * @param sourceElement
 * 
 */
public static void copyFeatures(EObject sourceElement, EObject targetElement) {
    List<EStructuralFeature> targetFeatures = targetElement.eClass().getEAllStructuralFeatures();
    for (EStructuralFeature feature : sourceElement.eClass().getEAllStructuralFeatures()) {
        if (targetFeatures.contains(feature)) {
            if (feature instanceof EReference) {
                EReference reference = (EReference)feature;
                Object value = sourceElement.eGet(reference);
                if (value instanceof EList<?>) {
                    EList<EObject> sourceList = (EList<EObject>)value;
                    EList<EObject> destList = (EList<EObject>)targetElement.eGet(feature);
                    while (!sourceList.isEmpty()) {
                        EObject referencedItem = sourceList.get(0);
                        sourceList.remove(referencedItem);
                        if (reference.getEOpposite() != null) {
                            referencedItem.eSet(reference.getEOpposite(), targetElement);
                        } else {
                            destList.add(referencedItem);
                        }
                    }
                } else {
                    targetElement.eSet(feature, sourceElement.eGet(feature));
                }
            } else if (feature instanceof EAttribute) {
                targetElement.eSet(feature, sourceElement.eGet(feature));
            }
        }else{//unset other features
            if(feature.isMany()){
                sourceElement.eSet(feature, Collections.emptyList());
            }else{
                sourceElement.eSet(feature, feature.getDefaultValue());
            }
        }
    }


    EObject container = sourceElement.eContainer();
    if (container != null) {
        Object parentFeatureValue = container.eGet(sourceElement.eContainingFeature());
        if (parentFeatureValue instanceof EList<?>) {
            //			int index = ((EList) parentFeatureValue).indexOf(sourceElement);
            ((EList<?>) parentFeatureValue).remove(sourceElement);
            // Add the new element at the same place than the older one
            // ((EList) parentFeatureValue).set(((EList)
            // parentFeatureValue).indexOf(sourceElement), targetElement);
            ((EList) parentFeatureValue).add(/* index, */targetElement);
        } else {
            container.eSet(sourceElement.eContainingFeature(), targetElement);
        }
    }
}
 
Example 10
Source File: EditingDomainResourcesDisposer.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
/**
 * called to dispose the resource set when closing the editor in parameter.
 * The resource set will be unloaded only if it's not in use
 * @param resourceSet
 * @param editorInput
 */
public static void disposeEditorInput(final ResourceSet resourceSet, final IEditorInput editorInput) {
    final EList<Resource> allResources = resourceSet.getResources();
    final List<Resource> resourcesToDispose = new ArrayList<Resource>(allResources);
    IEditorReference[] editorReferences;
    if(PlatformUI.isWorkbenchRunning()){
        final IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        if(activePage != null){
            editorReferences = activePage.getEditorReferences();
        } else {
            return;
        }
    }else{
        return;
    }
    for (final IEditorReference editorRef : editorReferences) {
        try {
            final IEditorInput currentEditorInput = editorRef.getEditorInput();
            if (currentEditorInput != editorInput) {
                final IEditorPart openEditor = editorRef.getEditor(false);
                if (openEditor instanceof DiagramEditor) {
                    final DiagramEditor openDiagramEditor = (DiagramEditor) openEditor;
                    final ResourceSet diagramResourceSet = openDiagramEditor.getEditingDomain().getResourceSet();
                    if (diagramResourceSet == resourceSet) {
                        final Resource diagramResource = EditorUtil.getDiagramResource(diagramResourceSet, currentEditorInput);
                        if(diagramResource != null){
                            resourcesToDispose.remove(diagramResource);
                            final Collection<?> imports = EMFCoreUtil.getImports(diagramResource);
                            resourcesToDispose.removeAll(imports);
                        }
                    }
                }
            }
        } catch (final Exception e) {
            BonitaStudioLog.error(e);
        }
    }
    for (final Resource resource : resourcesToDispose) {
        try {
            resource.unload();
            allResources.remove(resource);
        } catch (final Exception t) {
            BonitaStudioLog.error(t);
        }
    }
}