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

The following examples show how to use org.eclipse.emf.ecore.util.EcoreUtil#create() . 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: ShortFragmentProviderTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@BugTest(value = "DSL-601")
public void testLongFragment() {
  int reps = 100;
  EObject root = EcoreUtil.create(testClass);
  EObject parent = root;
  for (int i = 0; i < reps; i++) {
    EObject child = EcoreUtil.create(testClass);
    parent.eSet(testReference, child);
    parent = child;
  }

  ResourceImpl resource = new ResourceImpl();
  resource.getContents().add(root);

  String fragment = fragmentProvider.getFragment(parent, fragmentFallback);
  Assert.assertEquals("/0*" + (reps + 1), fragment);

  Assert.assertEquals(parent, fragmentProvider.getEObject(resource, fragment, fragmentFallback));
}
 
Example 2
Source File: EMFTreeComposite.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The constructor, takes a Ecore model tree EClass metadata object.
 * 
 * @param eClass
 */
public EMFTreeComposite(EClass eClass) {
	super();
	// Set the data
	if (eClass != null) {
		ecoreNodeMetaData = eClass;
		ecoreNode = EcoreUtil.create(ecoreNodeMetaData);
		setName(ecoreNodeMetaData.getName());
		setDescription(toString());

		// Create the active DataComponent
		createActiveDataNode();
	}

	return;
}
 
Example 3
Source File: RawTypeHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public JvmTypeReference doVisitCompoundTypeReference(JvmCompoundTypeReference reference, Resource resource) {
	JvmCompoundTypeReference result = null;
	List<JvmTypeReference> components = reference.getReferences();
	int recent = -1;
	for (int i = 0; i < components.size(); i++) {
		JvmTypeReference component = components.get(i);
		JvmTypeReference rawType = visit(component, resource);
		if (rawType != null && component != rawType) {
			if (result == null) {
				result = (JvmCompoundTypeReference) EcoreUtil.create(reference.eClass());
			}
			for (int j = recent + 1; j < i; j++) {
				result.getReferences().add(components.get(j));
			}
			result.getReferences().add(rawType);
			recent = i;
		}
	}
	if (result != null)
		return result;
	return reference;
}
 
Example 4
Source File: EMFTreeComposite.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This operation performs a deep copy of the attributes of another
 * EMFTreeComposite into the current EMFTreeComposite. It copies ALL of the
 * children of the EMFTreeComposite, data and child nodes alike.
 * 
 * @param otherTreeComposite
 */
public void copy(EMFTreeComposite otherTreeComposite) {

	// If null, return
	if (otherTreeComposite == null) {
		return;
	}

	if (otherTreeComposite.ecoreNodeMetaData != null) {
		ecoreNodeMetaData = otherTreeComposite.ecoreNodeMetaData;
		ecoreNode = EcoreUtil.create(ecoreNodeMetaData);
	}
	super.copy(otherTreeComposite, true);

	return;
}
 
Example 5
Source File: M2DocParser.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parse a bookmark construct. Bookmark are of the form
 * <code>{m:bookmark 'bookmark name'} runs {m:endbookmark}</code>
 * 
 * @return the created object
 * @throws DocumentParserException
 *             if something wrong happens during parsing.
 */
private Bookmark parseBookmark() throws DocumentParserException {
    // first read the tag that opens the bookmark
    final Bookmark bookmark = (Bookmark) EcoreUtil.create(TemplatePackage.Literals.BOOKMARK);

    String tagText = readTag(bookmark, bookmark.getRuns()).trim();
    // remove the prefix
    tagText = tagText.substring(TokenType.BOOKMARK.getValue().length()).trim();
    final AstResult result = queryParser.build(tagText);
    bookmark.setName(result);
    if (!result.getErrors().isEmpty()) {
        final XWPFRun lastRun = bookmark.getRuns().get(bookmark.getRuns().size() - 1);
        bookmark.getValidationMessages().addAll(getValidationMessage(result.getDiagnostic(), tagText, lastRun));
    }
    // read up the tags until the "m:endbookmark" tag is encountered.
    final Block body = parseBlock(null, TokenType.ENDBOOKMARK);
    bookmark.setBody(body);
    if (getNextTokenType() != TokenType.EOF) {
        readTag(bookmark, bookmark.getClosingRuns());
    }

    return bookmark;
}
 
Example 6
Source File: M2DocParser.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parse a comment block construct. Comment block are of the form
 * <code>{m:commentblock some comment} runs {m:endcommentblock}</code>
 * 
 * @return the created object
 * @throws DocumentParserException
 *             if something wrong happens during parsing.
 */
private Comment parseCommentBlock() throws DocumentParserException {
    final Comment comment = (Comment) EcoreUtil.create(TemplatePackage.Literals.COMMENT);
    final String commentText = readTag(comment, comment.getRuns()).trim()
            .substring(TokenType.COMMENTBLOCK.getValue().length());

    comment.setText(commentText.trim());

    final XWPFRun lastRun = comment.getRuns().get(comment.getRuns().size() - 1);
    // read up the tags until the "m:endcommentblock" tag is encountered.
    final Block body = parseBlock(null, TokenType.ENDCOMMENTBLOCK);
    // we discard the body, only keep messages from the block.
    for (TemplateValidationMessage message : body.getValidationMessages()) {
        comment.getValidationMessages()
                .add(new TemplateValidationMessage(message.getLevel(), message.getMessage(), lastRun));
    }
    if (getNextTokenType() != TokenType.EOF) {
        readTag(comment, comment.getClosingRuns());
    }

    return comment;
}
 
Example 7
Source File: AbstractBodyParser.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses a {@link ContentControl}.
 * 
 * @param control
 *            the {@link XWPFSDT}
 * @return the parsed {@link ContentControl}
 */
protected ContentControl parseContentControl(XWPFSDT control) {
    if (control == null) {
        throw new IllegalArgumentException("parseContentControl can't be called on a null argument.");
    }
    ContentControl contentControl = (ContentControl) EcoreUtil.create(TemplatePackage.Literals.CONTENT_CONTROL);
    contentControl.setBlock(getCTSdtBlock(document, control));

    return contentControl;
}
 
Example 8
Source File: M2DocParser.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses while matching an AQL expression.
 * 
 * @param expression
 *            the expression to parse
 * @return the corresponding {@link AstResult}
 */
private AstResult parseWhileAqlExpression(String expression) {
    final IQueryBuilderEngine.AstResult result;

    if (expression != null && expression.length() > 0) {
        AstBuilderListener astBuilder = AQL56Compatibility.createAstBuilderListener(queryEnvironment);
        CharStream input = new UnbufferedCharStream(new StringReader(expression), expression.length());
        QueryLexer lexer = new QueryLexer(input);
        lexer.setTokenFactory(new CommonTokenFactory(true));
        lexer.removeErrorListeners();
        lexer.addErrorListener(astBuilder.getErrorListener());
        TokenStream tokens = new UnbufferedTokenStream<CommonToken>(lexer);
        QueryParser parser = new QueryParser(tokens);
        parser.addParseListener(astBuilder);
        parser.removeErrorListeners();
        parser.addErrorListener(astBuilder.getErrorListener());
        // parser.setTrace(true);
        parser.expression();
        result = astBuilder.getAstResult();
    } else {
        ErrorExpression errorExpression = (ErrorExpression) EcoreUtil
                .create(AstPackage.eINSTANCE.getErrorExpression());
        List<org.eclipse.acceleo.query.ast.Error> errors = new ArrayList<>(1);
        errors.add(errorExpression);
        final Map<Object, Integer> positions = new HashMap<>();
        if (expression != null) {
            positions.put(errorExpression, Integer.valueOf(0));
        }
        final BasicDiagnostic diagnostic = new BasicDiagnostic();
        diagnostic.add(new BasicDiagnostic(Diagnostic.ERROR, AstBuilderListener.PLUGIN_ID, 0,
                "null or empty string.", new Object[] {errorExpression }));
        result = new AstResult(errorExpression, positions, positions, errors, diagnostic);
    }

    return result;
}
 
Example 9
Source File: LazyLinker.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected EObject createProxy(EObject obj, INode node, EReference eRef) {
	final Resource resource = obj.eResource();
	if (resource == null)
		throw new IllegalStateException("object must be contained in a resource");
	final URI uri = resource.getURI();
	final URI encodedLink = uri.appendFragment(encoder.encode(obj, eRef, node));
	EClass referenceType = getProxyType(obj, eRef);
	final EObject proxy = EcoreUtil.create(referenceType);
	((InternalEObject) proxy).eSetProxyURI(encodedLink);
	return proxy;
}
 
Example 10
Source File: AbstractBodyParser.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses a {@link StaticFragment}.
 * 
 * @return the object created
 * @throws DocumentParserException
 *             if something wrong happens during parsing
 */
protected StaticFragment parseStaticFragment() throws DocumentParserException {
    StaticFragment result = (StaticFragment) EcoreUtil.create(TemplatePackage.Literals.STATIC_FRAGMENT);
    while (getNextTokenType() == TokenType.STATIC) {
        result.getRuns().add(runIterator.next().getRun());
    }
    return result;
}
 
Example 11
Source File: WorldGenerator.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private Endpoint createExporter ( final EClass exporterClass, final Node node, final EquinoxApplication application, final int port )
{
    final Exporter exporter = (Exporter)EcoreUtil.create ( exporterClass );

    final Endpoint ep = Endpoints.registerEndpoint ( node, port, Endpoints.reference ( exporter ), String.format ( "Exporter Endpoint: %s - %s", exporter.getTypeTag (), exporter.getName () ) );
    node.getEndpoints ().add ( ep );

    exporter.setName ( application.getName () + "/exporter" );
    exporter.getEndpoints ().add ( ep );
    application.getExporter ().add ( exporter );
    return ep;
}
 
Example 12
Source File: OperationBuilder.java    From textuml with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Operation createProduct() {
    if (getParentProduct() != null) {
        if (getParentProduct() instanceof org.eclipse.uml2.uml.Class)
            return ((Class) getParentProduct()).createOwnedOperation(null, null, null);
        if (getParentProduct() instanceof DataType)
            return ((DataType) getParentProduct()).createOwnedOperation(null, null, null);
        if (getParentProduct() instanceof Interface)
            return ((Interface) getParentProduct()).createOwnedOperation(null, null, null);
    }
    return (Operation) EcoreUtil.create(getEClass());
}
 
Example 13
Source File: ParameterBuilder.java    From textuml with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected Parameter createProduct() {
    if (getParentProduct() != null)
        return ((Operation) getParentProduct()).createOwnedParameter(null, null);
    return (Parameter) EcoreUtil.create(getEClass());
}
 
Example 14
Source File: N4JSLinker.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the proxy with a custom encoded URI format (starting with "|"). The object used to produce the encoded
 * URI are collected as tuple inside {@link N4JSResource}. Then the node text is checked if it is convertible to a
 * valid value. If there is a {@link BadEscapementException} is thrown then there is either a warning or an error
 * produced via the diagnosticProducer.
 *
 *
 * @param resource
 *            the N4JSResource
 * @param obj
 *            the EObject containing the cross reference
 * @param node
 *            the node representing the EObject
 * @param eRef
 *            the cross reference in the domain model
 * @param xref
 *            the cross reference in the node model
 * @param diagnosticProducer
 *            to produce errors or warnings
 * @return the created proxy
 */
private EObject createProxy(N4JSResource resource, EObject obj, INode node, EReference eRef, CrossReference xref,
		IDiagnosticProducer diagnosticProducer) {
	final URI uri = resource.getURI();
	/*
	 * as otherwise with 0 the EObjectDescription created for Script would be fetched
	 */
	final int fragmentNumber = resource.addLazyProxyInformation(obj, eRef, node);
	final URI encodedLink = uri.appendFragment("|" + fragmentNumber);
	EClass referenceType = findInstantiableCompatible(eRef.getEReferenceType());
	final EObject proxy = EcoreUtil.create(referenceType);
	((InternalEObject) proxy).eSetProxyURI(encodedLink);
	AbstractElement terminal = xref.getTerminal();
	if (!(terminal instanceof RuleCall)) {
		throw new IllegalArgumentException(String.valueOf(xref));
	}
	AbstractRule rule = ((RuleCall) terminal).getRule();
	try {
		String tokenText = NodeModelUtils.getTokenText(node);
		Object value = valueConverterService.toValue(tokenText, rule.getName(), node);
		if (obj instanceof IdentifierRef && value instanceof String) {
			((IdentifierRef) obj).setIdAsText((String) value);
		} else if (obj instanceof ParameterizedTypeRef && value instanceof String) {
			((ParameterizedTypeRef) obj).setDeclaredTypeAsText((String) value);
		} else if (obj instanceof LabelRef && value instanceof String) {
			((LabelRef) obj).setLabelAsText((String) value);
		} else if (obj instanceof ParameterizedPropertyAccessExpression && value instanceof String) {
			((ParameterizedPropertyAccessExpression) obj).setPropertyAsText((String) value);
		} else if (obj instanceof ImportDeclaration && value instanceof String) {
			((ImportDeclaration) obj).setModuleSpecifierAsText((String) value);
		} else if (obj instanceof NamedImportSpecifier && value instanceof String) {
			((NamedImportSpecifier) obj).setImportedElementAsText((String) value);
		} else if ((obj instanceof JSXPropertyAttribute) && (value instanceof String)) {
			((JSXPropertyAttribute) obj).setPropertyAsText((String) value);
		} else {
			setOtherElementAsText(tokenText, obj, value);
		}
	} catch (BadEscapementException e) {
		diagnosticProducer.addDiagnostic(new DiagnosticMessage(e.getMessage(), e.getSeverity(), e.getIssueCode(),
				Strings.EMPTY_ARRAY));
	} catch (N4JSValueConverterException vce) {
		diagnosticProducer.addDiagnostic(new DiagnosticMessage(vce.getMessage(), vce.getSeverity(),
				vce.getIssueCode(), Strings.EMPTY_ARRAY));
	} catch (N4JSValueConverterWithValueException vcwve) {
		diagnosticProducer.addDiagnostic(new DiagnosticMessage(vcwve.getMessage(), vcwve.getSeverity(),
				vcwve.getIssueCode(), Strings.EMPTY_ARRAY));
	}
	return proxy;
}
 
Example 15
Source File: M2DocParser.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Parses a let construct.
 * 
 * @return the created object
 * @throws DocumentParserException
 *             if a problem occurs while parsing.
 */
private Let parseLet() throws DocumentParserException {
    Let let = (Let) EcoreUtil.create(TemplatePackage.Literals.LET);

    String letText = readTag(let, let.getRuns()).trim().substring(TokenType.LET.getValue().length());
    letText = letText.trim();

    int currentIndex = 0;
    if (currentIndex < letText.length() && Character.isJavaIdentifierStart(letText.charAt(currentIndex))) {
        currentIndex++;
        while (currentIndex < letText.length() && Character.isJavaIdentifierPart(letText.charAt(currentIndex))) {
            currentIndex++;
        }
        let.setName(letText.substring(0, currentIndex));
    } else {
        M2DocUtils.validationError(let, "Missing identifier");
    }

    while (currentIndex < letText.length() && Character.isWhitespace(letText.charAt(currentIndex))) {
        currentIndex++;
    }

    if (currentIndex < letText.length() && letText.charAt(currentIndex) == '=') {
        currentIndex++;
    } else {
        M2DocUtils.validationError(let, "Missing =");
    }

    while (currentIndex < letText.length() && Character.isWhitespace(letText.charAt(currentIndex))) {
        currentIndex++;
    }

    final String queryString = letText.substring(currentIndex);
    final AstResult result = queryParser.build(queryString);
    let.setValue(result);
    if (!result.getErrors().isEmpty()) {
        final XWPFRun lastRun = let.getRuns().get(let.getRuns().size() - 1);
        let.getValidationMessages().addAll(getValidationMessage(result.getDiagnostic(), queryString, lastRun));
    }

    final Block body = parseBlock(null, TokenType.ENDLET);
    let.setBody(body);
    if (getNextTokenType() != TokenType.EOF) {
        readTag(let, let.getClosingRuns());
    }

    return let;
}
 
Example 16
Source File: BodyGeneratedParser.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Block parseBlock(List<Template> templates, TokenType... endTypes) throws DocumentParserException {
    final Block res = (Block) EcoreUtil.create(TemplatePackage.Literals.BLOCK);

    TokenType type = getNextTokenType();
    Set<TokenType> endTypeSet = new HashSet<>(Arrays.asList(endTypes));
    endBlock: while (!endTypeSet.contains(type)) {
        switch (type) {
            case USERCONTENT:
                res.getStatements().add(parseUserContent());
                break;
            case ENDUSERCONTENT:
                // report the error and ignore the problem so that parsing
                // continues in other parts of the document.
                XWPFRun run = runIterator.lookAhead(1).getRun();
                if (run == null) {
                    throw new IllegalStateException(
                            "Token of type " + type + " detected. Run shouldn't be null at this place.");
                }
                res.getValidationMessages().add(new TemplateValidationMessage(ValidationMessageLevel.ERROR,
                        message(ParsingErrorMessage.UNEXPECTEDTAG, type.getValue()), run));
                readTag(res, res.getRuns());
                break;
            case EOF:
                final XWPFParagraph lastParagraph = document.getParagraphs()
                        .get(document.getParagraphs().size() - 1);
                final XWPFRun lastRun = lastParagraph.getRuns().get(lastParagraph.getRuns().size() - 1);
                res.getValidationMessages()
                        .add(new TemplateValidationMessage(ValidationMessageLevel.ERROR,
                                message(ParsingErrorMessage.UNEXPECTEDTAGMISSING, type, Arrays.toString(endTypes)),
                                lastRun));
                break endBlock;
            case STATIC:
                res.getStatements().add(parseStaticFragment());
                break;
            case WTABLE:
                res.getStatements().add(parseTable((XWPFTable) runIterator.next().getBodyElement()));
                break;
            case CONTENTCONTROL:
                res.getStatements().add(parseContentControl((XWPFSDT) runIterator.next().getBodyElement()));
                break;
            default:
                throw new UnsupportedOperationException(
                        String.format("Developer error: TokenType %s is not supported", type));
        }
        type = getNextTokenType();
    }

    return res;
}
 
Example 17
Source File: M2DocParser.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Parses a conditional.
 * conditional are made of the following set of tags : {m:if "query"} ...
 * [{m:elseif "query"} ....]* ({m:else})? ... {m:endif}
 * 
 * @return the created object
 * @throws DocumentParserException
 *             if something wrong happens during parsing.
 */
private Conditional parseConditional() throws DocumentParserException {
    Conditional conditional = (Conditional) EcoreUtil.create(TemplatePackage.Literals.CONDITIONAL);
    String tag = readTag(conditional, conditional.getRuns()).trim();
    boolean headConditionnal = tag.startsWith(TokenType.IF.getValue());
    int tagLength = headConditionnal ? TokenType.IF.getValue().length() : TokenType.ELSEIF.getValue().length();
    String query = tag.substring(tagLength).trim();
    final AstResult result = queryParser.build(query);
    conditional.setCondition(result);
    if (!result.getErrors().isEmpty()) {
        final XWPFRun lastRun = conditional.getRuns().get(conditional.getRuns().size() - 1);
        conditional.getValidationMessages().addAll(getValidationMessage(result.getDiagnostic(), query, lastRun));
    }
    final Block thenCompound = parseBlock(null, TokenType.ELSEIF, TokenType.ELSE, TokenType.ENDIF);
    conditional.setThen(thenCompound);
    TokenType nextRunType = getNextTokenType();
    switch (nextRunType) {
        case ELSEIF:
            final Block elseIfCompound = (Block) EcoreUtil.create(TemplatePackage.Literals.BLOCK);
            elseIfCompound.getStatements().add(parseConditional());
            conditional.setElse(elseIfCompound);
            break;
        case ELSE:
            final Block block = (Block) EcoreUtil.create(TemplatePackage.Literals.BLOCK);
            readTag(block, block.getRuns());
            final Block elseCompound = parseBlock(null, TokenType.ENDIF);
            conditional.setElse(elseCompound);

            // read up the m:endif tag if it exists
            if (getNextTokenType() != TokenType.EOF) {
                readTag(conditional, conditional.getClosingRuns());
            }
            break;
        case ENDIF:
            readTag(conditional, conditional.getClosingRuns());
            break; // we just finish the current conditional.
        default:
            M2DocUtils.validationError(conditional, M2DocUtils.message(ParsingErrorMessage.CONDTAGEXPEXTED));
    }
    return conditional;
}
 
Example 18
Source File: VariableBuilder.java    From textuml with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected Variable createProduct() {
    if (getParentProduct() != null)
        return ((StructuredActivityNode) getParentProduct()).createVariable(null, null);
    return (Variable) EcoreUtil.create(getEClass());
}
 
Example 19
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Parses a template document and returns the {@link DocumentTemplate} resulting from
 * this parsing.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param templateURI
 *            URI for the template, used when external links (images, includes) have to be resolved
 * @param queryEnvironment
 *            the {@link IQueryEnvironment}
 * @param classProvider
 *            the {@link IClassProvider} to use for service Loading
 * @param monitor
 *            used to track the progress will generating
 * @return the {@link DocumentTemplate} resulting from parsing the specified
 *         document
 * @throws DocumentParserException
 *             if a problem occurs while parsing the document.
 */
@SuppressWarnings("resource")
public static DocumentTemplate parse(URIConverter uriConverter, URI templateURI, IQueryEnvironment queryEnvironment,
        IClassProvider classProvider, Monitor monitor) throws DocumentParserException {
    final DocumentTemplate result = (DocumentTemplate) EcoreUtil.create(TemplatePackage.Literals.DOCUMENT_TEMPLATE);
    final ResourceImpl r = new ResourceImpl(templateURI);

    try {
        monitor.beginTask("Parsing " + templateURI, TOTAL_PARSE_MONITOR_WORK);
        monitor.subTask("Loading template");
        // resources are closed in DocumentTemplate.close()
        final InputStream is = uriConverter.createInputStream(templateURI);
        final OPCPackage oPackage = OPCPackage.open(is);
        final XWPFDocument document = new XWPFDocument(oPackage);

        nextSubTask(monitor, LOAD_TEMPLATE_MONITOR_WORK, "Parsing template custom properties");

        final List<TemplateValidationMessage> messages = parseTemplateCustomProperties(queryEnvironment,
                classProvider, document);
        r.getContents().add(result);

        nextSubTask(monitor, PARSE_TEMPLATE_CUSTOM_PROPERTIES_MONITOR_WORK, "Parsing template body");
        final int unitOfWork = PARSE_TEMPLATE_MONITOR_WORK
            / (1 + document.getFooterList().size() + document.getHeaderList().size());

        final M2DocParser parser = new M2DocParser(document, queryEnvironment);
        final Block documentBody = parser.parseBlock(result.getTemplates(), TokenType.EOF);
        for (TemplateValidationMessage validationMessage : messages) {
            documentBody.getValidationMessages().add(validationMessage);
        }
        result.setBody(documentBody);
        result.setInputStream(is);
        result.setOpcPackage(oPackage);
        result.setDocument(document);

        nextSubTask(monitor, unitOfWork, "Parsing template footers");

        for (XWPFFooter footer : document.getFooterList()) {
            final M2DocParser footerParser = new M2DocParser(footer, queryEnvironment);
            result.getFooters().add(footerParser.parseBlock(null, TokenType.EOF));

            monitor.worked(unitOfWork);
        }

        nextSubTask(monitor, 0, "Parsing template headers");

        for (XWPFHeader header : document.getHeaderList()) {
            final M2DocParser headerParser = new M2DocParser(header, queryEnvironment);
            result.getHeaders().add(headerParser.parseBlock(null, TokenType.EOF));

            monitor.worked(unitOfWork);
        }

    } catch (IOException e) {
        throw new DocumentParserException("Unable to open " + templateURI, e);
    } catch (InvalidFormatException e1) {
        throw new DocumentParserException("Invalid .docx format " + templateURI, e1);
    } finally {
        monitor.done();
    }

    return result;
}
 
Example 20
Source File: ClassifierBuilder.java    From textuml with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected Classifier createProduct() {
    if (getParentProduct() != null)
        return (Classifier) ((Package) getParentProduct()).createOwnedType(getName(), getEClass());
    return (Classifier) EcoreUtil.create(getEClass());
}