Example usage for org.jdom2 Element clone

List of usage examples for org.jdom2 Element clone

Introduction

In this page you can find the example usage for org.jdom2 Element clone.

Prototype

@Override
public Element clone() 

Source Link

Document

This returns a deep clone of this element.

Usage

From source file:org.xflatdb.xflat.db.ElementTable.java

License:Apache License

@Override
public boolean replaceOne(XPathQuery query, Element origValue) {
    Element e = this.findOne(query);
    if (e == null) {
        return false;
    }/*from ww  w.j  a va  2s .  c om*/

    final String id = getId(e);
    setId(id, origValue);

    //always clone incoming data
    final Element newValue = origValue.clone();

    try {
        this.doWithEngine(new EngineActionEx<Object, KeyNotFoundException>() {
            @Override
            public Object act(Engine engine) throws KeyNotFoundException {
                engine.replaceRow(id, newValue);
                return null;
            }
        });
        return true;
    } catch (KeyNotFoundException ex) {
        //someone concurrently deleted this row, try again by identifying
        //a new row by the query.
        return replaceOne(query, origValue);
    }
}

From source file:org.xflatdb.xflat.db.ElementTable.java

License:Apache License

@Override
public boolean upsert(Element newValue) {

    //always clone incoming data
    final Element data = newValue.clone();

    final String id = getId(newValue);
    if (id == null) {
        while (true) {
            final String nId = generateNewId();
            setId(nId, newValue);/*w  w w  .  j a v  a2  s.co m*/

            try {
                this.doWithEngine(new EngineActionEx<Object, DuplicateKeyException>() {
                    @Override
                    public Object act(Engine engine) throws DuplicateKeyException {
                        engine.insertRow(nId, data);
                        return null;
                    }
                });
                //inserted, return true
                return true;
            } catch (DuplicateKeyException ex) {
                //somehow our "new" ID already existed - try again
            }
        }
    } else {
        return this.doWithEngine(new EngineAction<Boolean>() {
            @Override
            public Boolean act(Engine engine) {
                return engine.upsertRow(id, data);
            }
        });
    }
}

From source file:org.xflatdb.xflat.engine.CachedDocumentEngine.java

License:Apache License

@Override
protected boolean spinUp() {
    if (!this.state.compareAndSet(EngineState.Uninitialized, EngineState.SpinningUp)) {
        return false;
    }//from w  w w  .  java2  s.c o  m

    this.getTableLock();
    try {
        synchronized (syncRoot) {
            //concurrency level 4 - don't expect to need more than this.
            this.cache = new ConcurrentHashMap<>(16, 0.75f, 4);
            this.uncommittedRows = new ConcurrentHashMap<>(16, 0.75f, 4);

            if (file.exists()) {
                try {
                    Document doc = this.file.readFile();
                    List<Element> rowList = doc.getRootElement().getChildren("row", XFlatConstants.xFlatNs);

                    for (int i = rowList.size() - 1; i >= 0; i--) {
                        Element row = rowList.get(i);

                        if (row.getChildren().isEmpty()) {
                            continue;
                        }

                        String id = getId(row);

                        Row newRow = null;

                        for (Element data : row.getChildren()) {
                            //default it to zero so that we know it's committed but if we don't get an actual
                            //value for the commit then we have the lowest value.
                            long txId = 0;
                            long commitId = 0;

                            String a = data.getAttributeValue("tx", XFlatConstants.xFlatNs);
                            if (a != null && !"".equals(a)) {
                                try {
                                    txId = Long.parseLong(a, TRANSACTION_ID_RADIX);
                                } catch (NumberFormatException ex) {
                                    //just leave it as 0.
                                }
                            }
                            a = data.getAttributeValue("commit", XFlatConstants.xFlatNs);
                            if (a != null && !"".equals(a)) {
                                try {
                                    commitId = Long.parseLong(a, TRANSACTION_ID_RADIX);
                                } catch (NumberFormatException ex) {
                                    //just leave it as 0.
                                }
                            }

                            if ("delete".equals(data.getName())
                                    && XFlatConstants.xFlatNs.equals(data.getNamespace())) {
                                //it's a delete marker
                                data = null;
                            } else {
                                data = data.clone();
                            }

                            RowData rData = new RowData(txId, data, id);
                            rData.commitId = commitId;

                            if (newRow == null)
                                newRow = new Row(id, rData);
                            else
                                newRow.rowData.put(txId, rData);
                        }

                        if (newRow != null)
                            this.cache.put(id, newRow);
                    }
                } catch (JDOMException | IOException ex) {
                    throw new XFlatException("Error building document cache", ex);
                }
            }

            this.state.set(EngineState.SpunUp);
            if (operationsReady.get()) {
                this.state.set(EngineState.Running);
                synchronized (operationsReady) {
                    operationsReady.notifyAll();
                }
            }

            return true;
        }
    } finally {
        this.releaseTableLock();
    }
}

From source file:org.yawlfoundation.yawl.elements.YAtomicTask.java

License:Open Source License

/**
 * Builds the enablement data set for the task.
 * @return the enablement data set; that is, a set of data variables and
 * corresponding values that were populated after evaluating their mapping
 * expressions.//from  ww w.j a  va  2  s . c om
 * @throws YQueryException if there's a problem with a query evaluation.
 * @throws YDataStateException if there's a problem with the evaluated data.
 * @throws YStateException if there's a problem setting the task state.
 * @deprecated Since 2.0, enablement mappings have no function.
 */
public Element prepareEnablementData() throws YQueryException, YDataStateException {
    if (null == getDecompositionPrototype()) {
        return null;
    }
    Element enablementData = produceDataRootElement();
    YAWLServiceGateway serviceGateway = (YAWLServiceGateway) _decompositionPrototype;
    List<YParameter> enablementParams = new ArrayList<YParameter>(
            serviceGateway.getEnablementParameters().values());
    Collections.sort(enablementParams);
    for (YParameter parameter : enablementParams) {
        String paramName = parameter.getPreferredName();
        String expression = _dataMappingsForTaskEnablement.get(paramName);
        Element result = performDataExtraction(expression, parameter);
        enablementData.addContent(result.clone());
    }
    return enablementData;
}

From source file:org.yawlfoundation.yawl.elements.YDecomposition.java

License:Open Source License

/**
 * This method returns the list of data from a decomposition. According to
 * its declared output parameters.  Only useful for Beta 4 and above.
 * The data inside this decomposition is groomed so to speak so that the
 * output data is returned in sequence.  Furthermore no internal variables, \
 * or input only parameters are returned.
 * @return a JDom Document of the output data.
 *///  w ww . j a va 2  s  . c o  m
public Document getOutputData() {

    //create a new output document to return
    Document outputDoc = new Document();
    Element root = _data.getRootElement();
    outputDoc.setRootElement(new Element(root.getName()));

    //now prepare a list of output params to iterate over.
    List<YParameter> outputParamsList = new ArrayList<YParameter>(getOutputParameters().values());
    Collections.sort(outputParamsList);

    for (YParameter parameter : outputParamsList) {
        Element child = root.getChild(parameter.getPreferredName());
        outputDoc.getRootElement().addContent(child.clone());
    }
    return outputDoc;
}

From source file:org.yawlfoundation.yawl.elements.YDecomposition.java

License:Open Source License

protected void addData(YPersistenceManager pmgr, Element element) throws YPersistenceException {
    assignData(pmgr, element.clone());
}

From source file:org.yawlfoundation.yawl.elements.YNet.java

License:Open Source License

public void setIncomingData(YPersistenceManager pmgr, Element incomingData)
        throws YDataStateException, YPersistenceException {
    for (YParameter parameter : getInputParameters().values()) {
        Element actualParam = incomingData.getChild(parameter.getName());
        if (parameter.isMandatory() && actualParam == null) {
            throw new IllegalArgumentException("The input data for Net:" + getID()
                    + " is missing mandatory input data for a parameter (" + parameter.getName() + ").  "
                    + " Alternatively the data is there but the query in the super net produced data with"
                    + " the wrong name (Check your specification). "
                    + new XMLOutputter(Format.getPrettyFormat()).outputString(incomingData).trim());
        }/*w  ww .  j a v  a  2  s . c o m*/

        // remove any attributes - not required and cause validation errors if left
        if ((actualParam != null) && !actualParam.getAttributes().isEmpty()) {
            JDOMUtil.stripAttributes(actualParam);
        }
    }

    // validate against schema
    getSpecification().getDataValidator().validate(getInputParameters().values(), incomingData, getID());

    for (Element element : incomingData.getChildren()) {
        if (getInputParameters().containsKey(element.getName())) {
            addData(pmgr, element.clone());
        } else {
            throw new IllegalArgumentException(
                    "Element " + element + " is not a valid input parameter of " + this);
        }
    }
}

From source file:org.yawlfoundation.yawl.elements.YTask.java

License:Open Source License

public synchronized boolean t_complete(YPersistenceManager pmgr, YIdentifier childID,
        Document decompositionOutputData)
        throws YDataStateException, YStateException, YQueryException, YPersistenceException {
    if (t_isBusy()) {
        YSpecification spec = _net.getSpecification();
        YDataValidator validator = spec.getDataValidator();
        validateOutputs(validator, decompositionOutputData);

        for (String query : getQueriesForTaskCompletion()) {
            if (ExternalDBGatewayFactory.isExternalDBMappingExpression(query)) {
                AbstractExternalDBGateway gateway = ExternalDBGatewayFactory.getInstance(query);
                updateExternalFromTaskCompletion(gateway, query, decompositionOutputData);
                continue;
            }//from  w  w  w. ja  v  a2  s. c o  m

            String localVarThatQueryResultGetsAppliedTo = getMIOutputAssignmentVar(query);
            Element queryResultElement = evaluateTreeQuery(query, decompositionOutputData);

            //debugging method call
            generateCompletingReport1(query, decompositionOutputData, queryResultElement);

            if (queryResultElement == null) {
                throw new YDataQueryException(query, queryResultElement, null,
                        "The result of the output query (" + query + ") is null");
            }

            // handle empty complex type flag elements
            if (queryResultElement.getContentSize() == 0) {
                handleEmptyComplexTypeFlagOutput(decompositionOutputData, queryResultElement, query,
                        localVarThatQueryResultGetsAppliedTo);
            }

            if (query.equals(getPreJoiningMIQuery())) {
                _groupedMultiInstanceOutputData.getRootElement().addContent(queryResultElement.clone());
            } else {
                _localVariableNameToReplaceableOutputData.put(localVarThatQueryResultGetsAppliedTo,
                        queryResultElement);
            }

            //Now we check that the resulting transformation produced data according
            //to the net variable's type.
            if (spec.getSchemaVersion().isSchemaValidating() && (!query.equals(getPreJoiningMIQuery()))) {
                YVariable var = _net.getLocalOrInputVariable(localVarThatQueryResultGetsAppliedTo);
                try {
                    Element tempRoot = new Element(_decompositionPrototype.getID());
                    tempRoot.addContent(queryResultElement.clone());
                    /**
                     * MF: Skip schema checking if we have an empty XQuery result to allow us to effectively blank-out
                     * a net variable.
                     */
                    if ((queryResultElement.getChildren().size() != 0
                            || (queryResultElement.getContent().size() != 0))) {
                        validator.validate(var, tempRoot, getID());
                    }
                } catch (YDataValidationException e) {
                    YDataStateException f = new YDataStateException(query,
                            decompositionOutputData.getRootElement(), validator.getSchema(), queryResultElement,
                            e.getErrors(), getID(),
                            "BAD PROCESS DEFINITION. Data extraction failed schema validation at task completion.");
                    f.setStackTrace(e.getStackTrace());
                    throw f;
                }
                generateCompletingReport2(queryResultElement, localVarThatQueryResultGetsAppliedTo, query,
                        decompositionOutputData);
            }
        }
        _mi_executing.removeOne(pmgr, childID);
        _mi_complete.add(pmgr, childID);
        if (t_isExitEnabled()) {
            t_exit(pmgr);
            return true;
        }
        return false;
    } else {
        throw new RuntimeException("This task [" + (getName() != null ? getName() : getID())
                + "] is not active, and therefore cannot be completed.");
    }
}

From source file:org.yawlfoundation.yawl.elements.YTask.java

License:Open Source License

private void performDataAssignmentsAccordingToOutputExpressions(YPersistenceManager pmgr)
        throws YDataStateException, YQueryException, YPersistenceException {
    if (null == getDecompositionPrototype()) {
        return;//from www .  j a  v a2s  . c o  m
    }
    if (logger.isDebugEnabled())
        generateExitReport1();
    for (String localVariableName : _localVariableNameToReplaceableOutputData.keySet()) {
        Element queryResult = _localVariableNameToReplaceableOutputData.get(localVariableName);
        //todo check that queryResult is valid instance of variable type
        _net.addData(pmgr, queryResult);
    }
    if (this.isMultiInstance() && _multiInstAttr.getMIJoiningQuery() != null) {
        Element result;

        result = evaluateTreeQuery(_multiInstAttr.getMIJoiningQuery(), _groupedMultiInstanceOutputData);
        if (_net.getSpecification().getSchemaVersion().isSchemaValidating()) {
            //if betaversion > beta3 then validate the results of the aggregation query
            String uniqueInstanceOutputQuery = _multiInstAttr.getMIFormalOutputQuery();
            String localVarThatQueryResultGetsAppliedTo = _dataMappingsForTaskCompletion
                    .get(uniqueInstanceOutputQuery);
            YVariable var = _net.getLocalOrInputVariable(localVarThatQueryResultGetsAppliedTo);
            Element tempRoot = new Element(_decompositionPrototype.getID());
            tempRoot.addContent(result.clone());
            try {
                _net.getSpecification().getDataValidator().validate(var, tempRoot, getID());
            } catch (YDataValidationException e) {

                YDataStateException f = new YDataStateException(_multiInstAttr.getMIJoiningQuery(),
                        _groupedMultiInstanceOutputData.getRootElement(),
                        _net.getSpecification().getDataValidator().getSchema(), result, e.getErrors(), getID(),
                        "BAD PROCESS DEFINITION. "
                                + "Data extraction failed schema validation at task completion.");
                f.setStackTrace(e.getStackTrace());
                throw f;
            }
        }
        if (logger.isDebugEnabled())
            generateExitReports2(_multiInstAttr.getMIJoiningQuery(), _groupedMultiInstanceOutputData, result);
        _net.addData(pmgr, result);
        if (logger.isDebugEnabled())
            generateExitReports3();
    }
}

From source file:org.yawlfoundation.yawl.elements.YTask.java

License:Open Source License

public Element getStartingDataSnapshot() throws YDataStateException, YStateException, YQueryException {

    logger.debug("--> getStartingDataSnapshot");
    if (null == getDecompositionPrototype())
        return null;

    Element dataForChildCase = produceDataRootElement();
    List<YParameter> inputParams = new ArrayList<YParameter>(
            _decompositionPrototype.getInputParameters().values());
    Collections.sort(inputParams);
    for (YParameter parameter : inputParams) {
        String inputParamName = parameter.getPreferredName();
        String expression = _dataMappingsForTaskStarting.get(inputParamName);
        if (this.isMultiInstance() && inputParamName.equals(_multiInstAttr.getMIFormalInputParam())) {
            if (_multiInstanceSpecificParamsIterator == null)
                continue;

            Element specificMIData = (Element) _multiInstanceSpecificParamsIterator.next();

            if (specificMIData != null) {
                if (YEngine.getInstance().generateUIMetaData()) {

                    // Add in attributes for input parameter
                    specificMIData.setAttributes(parameter.getAttributes().toJDOM());
                }/*from www .  ja  va 2s  .  c o m*/
                dataForChildCase.addContent(specificMIData.detach());
            }
        } else {
            Element result = ExternalDBGatewayFactory.isExternalDBMappingExpression(expression)
                    ? performExternalDataExtraction(expression, parameter)
                    : performDataExtraction(expression, parameter);

            if (result != null) {
                if (YEngine.getInstance().generateUIMetaData()) {
                    result.setAttributes(parameter.getAttributes().toJDOM());
                }
                dataForChildCase.addContent(result.clone());
            }
        }
    }

    if (YEngine.getInstance().generateUIMetaData()) {
        /**
         * AJH: Add in task level attributes for specifcation to XMLdoclet pass-thru.
         * Note that we skip processing of the YAWL standard task attributes as we only
         * pass-thru the additional (user interface hints) attributes.
         */
        for (String attrName : getDecompositionPrototype().getAttributes().keySet()) {
            String attrValue = getDecompositionPrototype().getAttributes().get(attrName);
            if (!STANDARD_TASK_ATTRIBUTES.contains("/" + attrName + "/")) {
                dataForChildCase.setAttribute(attrName, attrValue);
            }
        }
    }
    logger.debug("<-- getStartingDataSnapshot");
    return dataForChildCase;
}