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

The following examples show how to use org.eclipse.emf.common.util.EList#isEmpty() . 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: RouteResourceUtil.java    From tesb-studio-se with Apache License 2.0 6 votes vote down vote up
/**
 * Copy route resource
 *
 * @param model
 * @throws CoreException
 */
private static IFile copyResources(final IFolder folder, final ResourceDependencyModel model) {
    final ResourceItem item = model.getItem();
    EList<?> referenceResources = item.getReferenceResources();
    if (referenceResources.isEmpty()) {
        return null;
    }
    final IFile classpathFile = folder.getFile(new Path(model.getClassPathUrl()));
    final ReferenceFileItem refFile = (ReferenceFileItem) referenceResources.get(0);
    try (final InputStream inputStream = new ByteArrayInputStream(refFile.getContent().getInnerContent())) {
        if (classpathFile.exists()) {
            classpathFile.setContents(inputStream, 0, null);
        } else {
            if (!classpathFile.getParent().exists()) {
                prepareFolder((IFolder) classpathFile.getParent());
            }
            classpathFile.create(inputStream, true, null);
        }
    } catch (CoreException | IOException e) {
        ExceptionHandler.process(e);
    }

    return classpathFile;
}
 
Example 2
Source File: BibtexMergeWizardPage.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
private boolean validateTerms(EList<Term> toValidate, EList<Term> taxonomy) {
  	if(toValidate.isEmpty()) {
  		return true;
  	}
  	else if(taxonomy.isEmpty()) {
  		return false;
  	}
boolean result = true;
for(int i = 0; i < toValidate.size(); i++) {
	boolean match = false;
	for(int j = 0; j < taxonomy.size(); j++) {
		if(toValidate.get(i).getName().equals(taxonomy.get(j).getName())) {
			match = true;
			result = result && validateTerms(toValidate.get(i).getSubclasses(), taxonomy.get(j).getSubclasses());
			break;
		}
	}
	if(!match) {
		return false;
	}
}
return result;
  }
 
Example 3
Source File: EngineExpressionUtil.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private static String getLeftOperandVariableType(final org.bonitasoft.studio.model.expression.Expression leftOperand,
        final boolean external) {
    final EList<EObject> referencedElements = leftOperand.getReferencedElements();
    if (referencedElements != null && !referencedElements.isEmpty()) {
        final EObject referencedElement = referencedElements.get(0);
        if (referencedElement instanceof Data) {
            final Data data = (Data) referencedElement;
            if (data.isTransient()) {
                return ExpressionConstants.LEFT_OPERAND_TRANSIENT_DATA;
            } else if (data instanceof BusinessObjectData) {
                return ExpressionConstants.LEFT_OPERAND_BUSINESS_DATA;
            } else if (external || DatasourceConstants.PAGEFLOW_DATASOURCE.equals(data.getDatasourceId())) {
                return ExpressionConstants.LEFT_OPERAND_EXTERNAL_DATA;
            }
        }
    }
    return ExpressionConstants.LEFT_OPERAND_DATA;
}
 
Example 4
Source File: ScriptEngineImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private XExpression parseScriptIntoXTextEObject(String scriptAsString) throws ScriptParsingException {
    XtextResourceSet resourceSet = getResourceSet();
    Resource resource = resourceSet.createResource(computeUnusedUri(resourceSet)); // IS-A XtextResource
    try {
        resource.load(new StringInputStream(scriptAsString, StandardCharsets.UTF_8.name()),
                resourceSet.getLoadOptions());
    } catch (IOException e) {
        throw new ScriptParsingException(
                "Unexpected IOException; from close() of a String-based ByteArrayInputStream, no real I/O; how is that possible???",
                scriptAsString, e);
    }

    List<Diagnostic> errors = resource.getErrors();
    if (!errors.isEmpty()) {
        throw new ScriptParsingException("Failed to parse expression (due to managed SyntaxError/s)",
                scriptAsString).addDiagnosticErrors(errors);
    }

    EList<EObject> contents = resource.getContents();

    if (!contents.isEmpty()) {
        Iterable<Issue> validationErrors = getValidationErrors(contents.get(0));
        if (!validationErrors.iterator().hasNext()) {
            return (XExpression) contents.get(0);
        } else {
            throw new ScriptParsingException("Failed to parse expression (due to managed ValidationError/s)",
                    scriptAsString).addValidationIssues(validationErrors);
        }
    } else {
        return null;
    }
}
 
Example 5
Source File: DomainmodelLabelProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void append(StringBuilder builder, JvmTypeReference typeRef) {
	if (typeRef instanceof JvmParameterizedTypeReference) {
		JvmType type = ((JvmParameterizedTypeReference) typeRef).getType();
		append(builder, type);
		EList<JvmTypeReference> arguments = ((JvmParameterizedTypeReference) typeRef).getArguments();
		if (!arguments.isEmpty()) {
			builder.append("<");
			Iterator<JvmTypeReference> iterator = arguments.iterator();
			while (iterator.hasNext()) {
				JvmTypeReference jvmTypeReference = iterator.next();
				append(builder, jvmTypeReference);
				if (iterator.hasNext()) {
					builder.append(",");
				}
			}
			builder.append(">");
		}
	} else {
		if (typeRef instanceof JvmWildcardTypeReference) {
			builder.append("?");
			Iterator<JvmTypeConstraint> contraintsIterator = ((JvmWildcardTypeReference) typeRef).getConstraints().iterator();
			while (contraintsIterator.hasNext()) {
				JvmTypeConstraint constraint = contraintsIterator.next();
				if (constraint instanceof JvmUpperBound) {
					builder.append(" extends ");
				} else {
					builder.append(" super ");
				}
				append(builder, constraint.getTypeReference());
				if (contraintsIterator.hasNext()) {
					builder.append(" & ");
				}
			}
		} else {
			if (typeRef instanceof JvmGenericArrayTypeReference) {
				append(builder, ((JvmGenericArrayTypeReference) typeRef).getType());
			}
		}
	}
}
 
Example 6
Source File: RailroadSynchronizer.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IFigure createFigure(XtextResource state) {
	EList<EObject> contents = state.getContents();
	if (!contents.isEmpty()) {
		EObject rootObject = contents.get(0);
		return transformer.transform(rootObject);
	}
	return null;
}
 
Example 7
Source File: RefactoringHelper.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the effect definition of a transition contains at least one action.
 * 
 * @param transition
 * @return true if the condition is satisfied, false otherwise
 */
public boolean hasAtLeastOneAction(Transition transition) {
	Effect effect = transition.getEffect();
	if (effect instanceof ReactionEffect) {
		ReactionEffect reactionEffect = (ReactionEffect) effect;
		EList<Expression> actions = reactionEffect.getActions();
		return !actions.isEmpty();
	}
	return false;
}
 
Example 8
Source File: XtextComparisonExpressionLoader.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public Operation_Compare loadConditionExpression(final String comparisonExpression, final EObject context) throws ComparisonExpressionLoadException {
    final Resource resource = loadResource(comparisonExpression, context);
    final EList<EObject> contents = resource.getContents();
    if (contents.isEmpty()) {
        throw new ComparisonExpressionLoadException("Failed to load comparison expression " + comparisonExpression);
    }
    if (context != null && context.eResource() != null) {
        return resolveProxies(resource, context.eResource().getResourceSet());
    }
    return (Operation_Compare) contents.get(0);
}
 
Example 9
Source File: ExBundleClasspath.java    From tesb-studio-se with Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<BundleClasspath> to(NodeType t) {
    final Collection<BundleClasspath> bundleClasspaths = new HashSet<BundleClasspath>();
    for (Object e : t.getElementParameter()) {
        final ElementParameterType p = (ElementParameterType) e;
        if (name.equals(p.getName())) {
            final EList<?> elementValue = p.getElementValue();
            if (elementValue.isEmpty()) {
                String evtValue = p.getValue();
                if (evtValue != null) {
                    if (evtValue.startsWith("\"")) { //$NON-NLS-1$
                        evtValue = evtValue.substring(1);
                    }
                    if (evtValue.endsWith("\"")) { //$NON-NLS-1$
                        evtValue = evtValue.substring(0, evtValue.length() - 1);
                    }
                    if (!evtValue.isEmpty()) {
                        bundleClasspaths.add(createBundleClasspath(evtValue));
                    }
                }
            } else {
                for (Object pv : p.getElementValue()) {
                    ElementValueType evt = (ElementValueType) pv;
                    bundleClasspaths.add(createBundleClasspath(evt.getValue()));
                }
            }
            return bundleClasspaths;
        }
    }
    // no param - libs itself
    for (String lib : name.split(SEPARATOR)) {
        bundleClasspaths.add(createBundleClasspath(lib));
    }
    return bundleClasspaths;
}
 
Example 10
Source File: OrderElementControl.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public void refreshInput() {
	ISelection selection = viewer.getSelection();
	EList<EObject> listInput = getListInput();
	viewer.setInput(listInput);
	if (listInput.isEmpty()) {
		viewer.getTable().clearAll();
		TableItem item = new TableItem(viewer.getTable(), SWT.NONE);
		item.setData(EcoreFactory.eINSTANCE.createEObject());
		item.setText(placeholder);
	} else {
		viewer.setSelection(selection);
	}
	viewer.setSelection(selection);
}
 
Example 11
Source File: DataSetParameterAdapter.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the matched parameter definition by given name and position.
 * 
 * @param params
 *            the ODA data set parameters
 * @param paramName
 *            the parameter name
 * @param position
 *            the position of the parameter
 * @return the matched parameter definition
 */

static ParameterDefinition findParameterDefinition(
		DataSetParameters params, Integer position )
{
	if ( params == null )
		return null;
	if ( position == null )
		return null;

	EList odaParams = params.getParameterDefinitions( );
	if ( odaParams == null || odaParams.isEmpty( ) )
		return null;

	for ( int i = 0; i < odaParams.size( ); i++ )
	{
		ParameterDefinition odaParamDefn = (ParameterDefinition) odaParams
				.get( i );

		DataElementAttributes dataAttrs = odaParamDefn.getAttributes( );
		if ( dataAttrs == null )
			continue;

		if ( position.intValue( ) == dataAttrs.getPosition( ) )
			return odaParamDefn;

	}

	return null;
}
 
Example 12
Source File: ResultSetsAdapter.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the matched column definition with the specified name and
 * position.
 * 
 * @param columns
 *            the ODA defined result set column definitions
 * @param paramName
 *            the result set column name
 * @param position
 *            the position
 * @return the matched oda result set column
 */

private static ColumnDefinition findColumnDefinition(
		ResultSetColumns columns, String columnName, Integer position )
{
	if ( columns == null || columnName == null )
		return null;

	EList odaColumns = columns.getResultColumnDefinitions( );
	if ( odaColumns == null || odaColumns.isEmpty( ) )
		return null;

	for ( int i = 0; i < odaColumns.size( ); i++ )
	{
		ColumnDefinition columnDefn = (ColumnDefinition) odaColumns.get( i );

		DataElementAttributes dataAttrs = columnDefn.getAttributes( );
		if ( dataAttrs == null )
			continue;

		if ( columnName.equals( dataAttrs.getName( ) )
				&& ( position == null || position.intValue( ) == dataAttrs
						.getPosition( ) ) )
			return columnDefn;
	}

	return null;
}
 
Example 13
Source File: NamesAreUniqueValidationHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Return the type that describes the set of instances that should have unique names. The default information will
 * return the topmost type or the first super type that is contained in the set of cluster types
 * ({@link NamesAreUniqueValidationHelper#getClusterTypes()}). Only the first super type will be taken into account
 * when walking the hierarchy.
 * 
 * Return <code>null</code> if objects of the given type are not subject to validation.
 */
protected EClass getAssociatedClusterType(EClass eClass) {
	if (clusterTypes.contains(eClass))
		return eClass;
	EList<EClass> superTypes = eClass.getESuperTypes();
	if (superTypes.isEmpty())
		return eClass;
	return getAssociatedClusterType(superTypes.get(0));
}
 
Example 14
Source File: CFGraphProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Searches the script node in the given input. */
private Script findScript(Object input) {
	if (input instanceof ResourceSet) {
		ResourceSet rs = (ResourceSet) input;
		if (!rs.getResources().isEmpty()) {
			Resource res = rs.getResources().get(0);
			EList<EObject> contents = res.getContents();
			if (!contents.isEmpty()) {
				Script script = EcoreUtil2.getContainerOfType(contents.get(0), Script.class);
				return script;
			}
		}
	}
	return null;
}
 
Example 15
Source File: SARLEarlyExitValidator.java    From sarl with Apache License 2.0 5 votes vote down vote up
private boolean markAsDeadCode(XExpression expression) {
	if (expression instanceof XBlockExpression) {
		final XBlockExpression block = (XBlockExpression) expression;
		final EList<XExpression> expressions = block.getExpressions();
		if (!expressions.isEmpty()) {
			markAsDeadCode(expressions.get(0));
			return true;
		}
	}
	if (expression != null) {
		error(Messages.SARLEarlyExitValidator_0, expression, null, IssueCodes.UNREACHABLE_CODE); //$NON-NLS-1$
		return true;
	}
	return false;
}
 
Example 16
Source File: PrettyPrinterSwitch.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void processTypeParams(EList<TypeVariable> typeParams) {
	if (typeParams.isEmpty())
		return;

	// In case of plain-JS output no types will be written
	throw new IllegalStateException("Type reference still left in code. typeParams=" + typeParams);
}
 
Example 17
Source File: BaseRenderer.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Renders the chart block.
 * 
 * @param ipr
 * @param b
 * 
 * @throws ChartException
 */
protected void renderChartBlock( IPrimitiveRenderer ipr, Block b,
		Object oSource ) throws ChartException
{
	final double dScale = getDeviceScale( );
	final RectangleRenderEvent rre = ( (EventObjectCache) ipr ).getEventObject( oSource,
			RectangleRenderEvent.class );
	rre.updateFrom( b, dScale );
	try
	{
		ipr.fillRectangle( rre );
	}
	catch ( Exception e )
	{
		logger.log( e );
	}
	ipr.drawRectangle( rre );

	if ( isInteractivityEnabled( ) )
	{
		Trigger tg;
		EList<Trigger> elTriggers = b.getTriggers( );
		Location[] loaHotspot = new Location[4];
		Bounds bo = goFactory.scaleBounds( b.getBounds( ), dScale );
		double dLeft = bo.getLeft( );
		double dTop = bo.getTop( );
		double dWidth = bo.getWidth( );
		double dHeight = bo.getHeight( );
		loaHotspot[0] = goFactory.createLocation( dLeft, dTop );
		loaHotspot[1] = goFactory.createLocation( dLeft + dWidth, dTop );
		loaHotspot[2] = goFactory.createLocation( dLeft + dWidth, dTop
				+ dHeight );
		loaHotspot[3] = goFactory.createLocation( dLeft, dTop + dHeight );

		if ( !elTriggers.isEmpty( ) )
		{
			final InteractionEvent iev = ( (EventObjectCache) ipr ).getEventObject( StructureSource.createChartBlock( b ),
					InteractionEvent.class );
			iev.setCursor( b.getCursor( ) );
			
			for ( int t = 0; t < elTriggers.size( ); t++ )
			{
				tg = goFactory.copyOf( elTriggers.get( t ) );
				processTrigger( tg, StructureSource.createChartBlock( b ) );
				iev.addTrigger( tg );
			}

			final PolygonRenderEvent pre = ( (EventObjectCache) ipr ).getEventObject( StructureSource.createChartBlock( b ),
					PolygonRenderEvent.class );
			pre.setPoints( loaHotspot );
			iev.setHotSpot( pre );
			ipr.enableInteraction( iev );
		}

	}
}
 
Example 18
Source File: SARLFormatter.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("checkstyle:cyclomaticcomplexity")
protected ISemanticRegion formatBody(XtendTypeDeclaration type, IFormattableDocument document) {
	final ISemanticRegionsFinder regionFor = this.textRegionExtensions.regionFor(type);

	final ISemanticRegion open = regionFor.keyword(this.keywords.getLeftCurlyBracketKeyword());
	final ISemanticRegion close = regionFor.keyword(this.keywords.getRightCurlyBracketKeyword());
	document.prepend(open, XbaseFormatterPreferenceKeys.bracesInNewLine);
	document.interior(open, close, INDENT);

	final EList<XtendMember> members = type.getMembers();
	if (!members.isEmpty()) {
		XtendMember previous = null;
		for (final XtendMember current : members) {
			document.format(current);
			if (previous == null) {
				document.prepend(current, XtendFormatterPreferenceKeys.blankLinesBeforeFirstMember);
			} else if (previous instanceof XtendField) {
				if (current instanceof XtendField) {
					document.append(previous, XtendFormatterPreferenceKeys.blankLinesBetweenFields);
				} else {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_MEMBER_CATEGORIES);
				}
			} else if (previous instanceof XtendExecutable) {
				if (current instanceof XtendExecutable) {
					document.append(previous, XtendFormatterPreferenceKeys.blankLinesBetweenMethods);
				} else {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_MEMBER_CATEGORIES);
				}
			} else if (previous instanceof XtendTypeDeclaration) {
				if (current instanceof XtendTypeDeclaration) {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_INNER_TYPES);
				} else {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_MEMBER_CATEGORIES);
				}
			} else if (previous instanceof XtendEnumLiteral) {
				if (current instanceof XtendEnumLiteral) {
					document.append(previous, XtendFormatterPreferenceKeys.blankLinesBetweenEnumLiterals);
				} else {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_MEMBER_CATEGORIES);
				}
			} else if (previous instanceof SarlCapacityUses) {
				if (current instanceof SarlCapacityUses) {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_CAPACITY_USES);
				} else {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_MEMBER_CATEGORIES);
				}
			} else if (previous instanceof SarlRequiredCapacity) {
				if (current instanceof SarlCapacityUses) {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_CAPACITY_REQUIREMENTS);
				} else {
					document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_MEMBER_CATEGORIES);
				}
			} else {
				document.append(previous, SARLFormatterPreferenceKeys.BLANK_LINES_BETWEEN_MEMBER_CATEGORIES);
			}
			previous = current;
		}
		if (previous != null) {
			document.append(previous, XtendFormatterPreferenceKeys.blankLinesAfterLastMember);
		}
		return null;
	}
	return document.append(open, NEW_LINE);
}
 
Example 19
Source File: TaxonomyCheckboxListView.java    From slr-toolkit with Eclipse Public License 1.0 4 votes vote down vote up
private void matchTaxonomy(String[] path, EList<Term> generalTerms, EList<Term> fileTerms, Document document) {
	String[] newPath = new String[]{};
	if (generalTerms.isEmpty() || fileTerms.isEmpty()) {
		return;
	}
	for(Term fileTerm : fileTerms) {
		boolean foundMatch = false;
		for(Term generalTerm : generalTerms) {
			if (fileTerm.getName().equals(generalTerm.getName())) {
				foundMatch = true;
				if (!fileTerm.getSubclasses().isEmpty()) {
					newPath = Arrays.copyOf(path, path.length+1);
					newPath[newPath.length-1] = generalTerm.getName();
					matchTaxonomy(newPath, generalTerm.getSubclasses(), fileTerm.getSubclasses(), document);
				}
			}
		}
		if (!foundMatch) {
			String txt = "Taxonomy match conflict: '"+fileTerm.getName()+"' in ";
			if (path.length >= 1) {
				txt += "'"+path[path.length-1]+"'";
			}
			else {
				txt += "root";
			}
			
			//search for move quickfix and set path2
			String path2String = getPossibleMovePath(
					fileTerm.getName(),
					ModelRegistryPlugin.getModelRegistry().getActiveTaxonomy().get().getDimensions(),
					""
			);
			
			
			String pathString = "";
			for (String entry : path) {
				pathString += "/"+entry;
			}
			pathString += "/"+fileTerm.getName();

			Utils.mark(document, txt, pathString, path2String, ID);
		}
	}
}
 
Example 20
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);
        }
    }
}