Java Code Examples for org.jdom2.Element#getContentSize()

The following examples show how to use org.jdom2.Element#getContentSize() . 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: SoapTableAPI.java    From sndml3 with MIT License 6 votes vote down vote up
/**
 * It calls the SOAP getRecords method and allows specification of a list of
 * parameters and extended query parameters.
 * @see <a href="http://wiki.servicenow.com/index.php?title=Direct_Web_Service_API_Functions#getRecords">http://wiki.servicenow.com/index.php?title=Direct_Web_Service_API_Functions#getRecords</a>
 */

public RecordList getRecords(Parameters docParams, boolean displayValue) throws IOException {
	Log.setMethodContext(table, "getRecords");
	Parameters uriParams = new Parameters();
	uriParams.add("displayvalue", displayValue ? "all" : "false");
	Element responseElement = 
		client.executeRequest("getRecords", docParams, uriParams, "getRecordsResponse");
	int size = responseElement.getContentSize();
	RecordList list = new RecordList(getTable(), size);
	Iterator<Element> iter = responseElement.getChildren().iterator();
	while (iter.hasNext()) {
		Element next = iter.next();
		XmlRecord rec = new XmlRecord(this.table, next);
		list.add(rec);
	}
	return list;		
}
 
Example 2
Source File: WorkletService.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * updates the input datalist with the changed data in the output datalist
 *
 * @param in  - the JDOM Element containing the input params
 * @param out - the JDOM Element containing the output params
 * @return a JDOM Element with the data updated
 */
public Element updateDataList(Element in, Element out) {

    // get a copy of the 'in' list   	
    Element result = in.clone();

    // for each child in 'out' list, get its value and copy to 'in' list
    for (Element e : out.getChildren()) {

        // if there's a matching 'in' data item, update its value
        Element resData = result.getChild(e.getName());
        if (resData != null) {
            if (resData.getContentSize() > 0) resData.setContent(e.cloneContent());
            else resData.setText(e.getText());
        } else {
            // if the item is not in the 'in' list, add it.
            result.getChildren().add(e.clone());
        }
    }

    return result;
}
 
Example 3
Source File: ResourceManager.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * updates the input datalist with the changed data in the output datalist
 *
 * @param in  - the JDOM Element containing the input params
 * @param out - the JDOM Element containing the output params
 * @return a JDOM Element with the data updated
 */
private Element updateOutputDataList(Element in, Element out) {

    // get a copy of the 'in' list
    Element result = in.clone();

    // for each child in 'out' list, get its value and copy to 'in' list
    for (Element e : out.getChildren()) {

        // if there's a matching 'in' data item, update its value
        Element resData = result.getChild(e.getName());
        if (resData != null) {
            if (resData.getContentSize() > 0) resData.setContent(e.cloneContent());
            else resData.setText(e.getText());
        } else {
            result.addContent(e.clone());
        }
    }

    return result;
}
 
Example 4
Source File: MapFilePreprocessor.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private void processChildren(Path file, Element parent) throws InvalidXMLException {
    for(int i = 0; i < parent.getContentSize(); i++) {
        Content content = parent.getContent(i);
        if(!(content instanceof Element)) continue;

        Element child = (Element) content;
        List<Content> replacement = null;

        switch(child.getName()) {
            case "include":
                replacement = processIncludeElement(file, child);
                break;

            case "if":
                replacement = processConditional(child, false);
                break;

            case "unless":
                replacement = processConditional(child, true);
                break;
        }

        if(replacement != null) {
            parent.removeContent(i);
            parent.addContent(i, replacement);
            i--; // Process replacement content
        } else {
            processChildren(file, child);
        }
    }
}
 
Example 5
Source File: SoapTableAPI.java    From sndml3 with MIT License 5 votes vote down vote up
public Record getRecord(Key key) throws IOException {
	Log.setMethodContext(table, "get");
	Parameters params = new Parameters("sys_id", key.toString());
	Element responseElement = client.executeRequest("get", params, null, "getResponse");
	if (responseElement.getContentSize() == 0) return null;
	Record rec = new XmlRecord(getTable(), responseElement);
	return rec;		
}
 
Example 6
Source File: YTask.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Element performDataExtraction(String expression, YParameter inputParam)
        throws YDataStateException, YQueryException {

    Element result = evaluateTreeQuery(expression, _net.getInternalDataDocument());

    // if the param id of empty complex type flag type, don't return the query result
    // as input data if the flag is not currently set
    if (inputParam.isEmptyTyped()) {
        if (!isPopulatedEmptyTypeFlag(expression)) return null;
    }

    // else if we have an empty element and the element is not mandatory, don't pass
    // the element out to the task as input data.
    else if ((!inputParam.isRequired()) && (result.getChildren().size() == 0) &&
            (result.getContentSize() == 0)) {
        return null;
    }

    /**
     * AJH: Allow option to inhibit schema validation for outbound data.
     *      Ideally need to support this at task level.
     */
    if (_net.getSpecification().getSchemaVersion().isSchemaValidating()
            && (!skipOutboundSchemaChecks())) {
        performSchemaValidationOverExtractionResult(expression, inputParam, result);
    }
    return result;
}
 
Example 7
Source File: YWorkItem.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private YLogDataItemList assembleLogDataItemList(Element data, boolean input) {
    YLogDataItemList result = new YLogDataItemList();
    if (data != null) {
        Map<String, YParameter> params =
                _engine.getParameters(_specID, getTaskID(), input) ;
        String descriptor = (input ? "Input" : "Output") + "VarAssignment";
        for (Element child : data.getChildren()) {
            String name = child.getName();
            String value = child.getValue();
            YParameter param = params.get(name);
            if (param != null) {
                String dataType = param.getDataTypeNameUnprefixed();

                // if a complex type, store the structure with the value
                if (child.getContentSize() > 1) {
                    value = JDOMUtil.elementToString(child);
                }
                result.add(new YLogDataItem(descriptor, name, value, dataType));

                // add any configurable logging predicates for this parameter
                YLogDataItem dataItem = getDataLogPredicate(param, input);
                if (dataItem != null) result.add(dataItem);
            }    
        }
    }
    return result;        
}
 
Example 8
Source File: DynFormFieldAssembler.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private int getInitialInstanceCount(String min, Element data, String dataName) {
    int dataCount = 1;
    int minOccurs = Math.max(SubPanelController.convertOccurs(min), 1) ;
    if ((data != null) && (data.getContentSize() > 1)) {
        dataCount = data.getChildren(dataName).size();
    }
    return Math.max(minOccurs, dataCount) ;
}
 
Example 9
Source File: MCRBreakpoint.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
public static MCRChangeData setBreakpoint(Element context, String label) {
    return new MCRChangeData("breakpoint", label, context.getContentSize(), context);
}
 
Example 10
Source File: MCRDerivateLinkServlet.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void doGetPost(MCRServletJob job) throws Exception {
    @SuppressWarnings("unchecked")
    Map<String, String[]> pMap = job.getRequest().getParameterMap();
    String webpage = pMap.get("subselect.webpage")[0];
    String mcrId = getSubParameterValueOfBrowserAddressParameter(webpage, "mcrid");
    String parentId = getSubParameterValueOfBrowserAddressParameter(webpage, "parentID");

    // create a new root element
    Element rootElement = new Element("derivateLinks-parentList");

    MCRObjectID objId = MCRObjectID.getInstance(mcrId);
    if (MCRMetadataManager.exists(objId)) {
        /* mcr object exists in datastore -> add all parent with their
         * derivates to the jdom tree */
        addParentsToElement(rootElement, objId);
    } else if (parentId != null && MCRMetadataManager.exists(MCRObjectID.getInstance(parentId))) {
        /* mcr object doesnt exists in datastore -> use the parent id
         * to create the content */
        Element firstParent = getMyCoReObjectElement(MCRObjectID.getInstance(parentId));
        if (firstParent != null) {
            rootElement.addContent(firstParent);
        }
        addParentsToElement(rootElement, MCRObjectID.getInstance(parentId));
    }

    // check if root element has content -> if not, show an error page
    if (rootElement.getContentSize() == 0) {
        job.getResponse().sendRedirect(
            job.getResponse().encodeRedirectURL(MCRFrontendUtil.getBaseURL() + derivateLinkErrorPage));
        return;
    }

    // set some important attributes to the root element
    rootElement.setAttribute("session", pMap.get("subselect.session")[0]);
    rootElement.setAttribute("varpath", pMap.get("subselect.varpath")[0]);
    rootElement.setAttribute("webpage", webpage);

    // transform & display the generated xml document
    getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(rootElement));
}
 
Example 11
Source File: YTask.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
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 (ExternalDataGatewayFactory.isExternalDataMappingExpression(query)) {
                ExternalDataGateway gateway =
                        ExternalDataGatewayFactory.getInstance(query);
                updateExternalFromTaskCompletion(gateway, query, decompositionOutputData);
                continue;
            }

            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.");
    }
}
 
Example 12
Source File: Marshaller.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static WorkItemRecord unmarshalWorkItem(Element workItemElement) {
    if (workItemElement == null) return null;
    
    WorkItemRecord wir;
    String status = workItemElement.getChildText("status");
    String caseID = workItemElement.getChildText("caseid");
    String taskID = workItemElement.getChildText("taskid");
    String specURI = workItemElement.getChildText("specuri");
    if (caseID != null && taskID != null && specURI != null && status != null) {
        wir = new WorkItemRecord(caseID, taskID, specURI, status);

        wir.setExtendedAttributes(unmarshalWorkItemAttributes(workItemElement));
        wir.setUniqueID(workItemElement.getChildText("uniqueid"));
        wir.setTaskName(workItemElement.getChildText("taskname"));
        wir.setDocumentation(workItemElement.getChildText("documentation"));
        wir.setAllowsDynamicCreation(workItemElement.getChildText(
                                                          "allowsdynamiccreation"));
        wir.setRequiresManualResourcing(workItemElement.getChildText(
                                                       "requiresmanualresourcing"));
        wir.setCodelet(workItemElement.getChildText("codelet"));
        wir.setDeferredChoiceGroupID(workItemElement.getChildText(
                                                          "deferredChoiceGroupID"));
        wir.setSpecVersion(workItemElement.getChildText("specversion"));
        wir.setEnablementTimeMs(workItemElement.getChildText("enablementTimeMs"));
        wir.setFiringTimeMs(workItemElement.getChildText("firingTimeMs"));
        wir.setStartTimeMs(workItemElement.getChildText("startTimeMs"));
        wir.setCompletionTimeMs(workItemElement.getChildText("completionTimeMs"));
        wir.setTimerTrigger(workItemElement.getChildText("timertrigger"));
        wir.setTimerExpiry(workItemElement.getChildText("timerexpiry"));
        wir.setStartedBy(workItemElement.getChildText("startedBy"));
        wir.setTag(workItemElement.getChildText("tag"));
        wir.setCustomFormURL(workItemElement.getChildText("customform"));

        String specid = workItemElement.getChildText("specidentifier") ;
        if (specid != null) wir.setSpecIdentifier(specid);

        String resStatus = workItemElement.getChildText("resourceStatus");
        if (resStatus != null) wir.setResourceStatus(resStatus);
        
        Element data = workItemElement.getChild("data");
        if ((null != data) && (data.getContentSize() > 0))
               wir.setDataList((Element) data.getContent(0));

        Element updateddata = workItemElement.getChild("updateddata");
        if ((null != updateddata) && (updateddata.getContentSize() > 0))
               wir.setUpdatedData((Element) updateddata.getContent(0));

        Element logPredicate = workItemElement.getChild("logPredicate");
        if (logPredicate != null) {
            wir.setLogPredicateStarted(logPredicate.getChildText("start"));
            wir.setLogPredicateCompletion(logPredicate.getChildText("completion"));
        }
                    
        return wir;
    }
    throw new IllegalArgumentException("Input element could not be parsed.");
}
 
Example 13
Source File: DynFormFieldAssembler.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param eField
 * @param data
 * @param ns
 * @param level
 * @return a list of 'DynFormField'
 */
private List<DynFormField> createField(Element eField, Element data,
                                 Namespace ns, int level) throws DynFormException {
    DynFormField field;
    List<DynFormField> result = new ArrayList<DynFormField>() ;

    // get eField element's attributes
    String minOccurs = eField.getAttributeValue("minOccurs");
    String maxOccurs = eField.getAttributeValue("maxOccurs");
    String name = eField.getAttributeValue("name");
    Map<String, String> appInfo = getAppInfo(eField);                // uda, value
    String type = getElementDataType(eField, ns);

    if (level == 0) _currentParam = _params.get(name);

    if (type == null) {

        // check for a simpleType definition
        Element simple = eField.getChild("simpleType", ns);
        if (simple != null) {
            List<DynFormField> fieldList = addElementField(name, null, data,
                    minOccurs, maxOccurs, level, appInfo);
            for (DynFormField aField : fieldList) {
                applySimpleTypeFacets(simple, ns, aField);
            }
            result.addAll(fieldList);
        }
        else {
            // check for empty complex type (flag defn)
            Element complex = eField.getChild("complexType", ns);
            if ((complex != null) && complex.getContentSize() == 0) {
                field = addField(name, null, data, minOccurs, maxOccurs, level, appInfo);
                field.setEmptyComplexTypeFlag(true);
                if ((data != null) && (data.getChild(name) != null)) {
                    field.setValue("true");
                }
                result.add(field);
            }
            else {
                // new populated complex type - recurse in a new field list
                String groupID = getNextGroupID();
                List<Element> dataList = (data != null) ? data.getChildren(name) : null;
                if (! (dataList == null || dataList.isEmpty())) {
                    for (Element var : dataList) {
                        field = addGroupField(name, eField, ns, var,
                                minOccurs, maxOccurs, level, appInfo);
                        field.setGroupID(groupID);
                        result.add(field);
                    }
                }
                else {
                    field = addGroupField(name, eField, ns, null,
                            minOccurs, maxOccurs, level, appInfo);
                    field.setGroupID(groupID);
                    result.add(field);
                }
            }
        }
    }
    else  {
        // a plain element
        result.addAll(addElementField(name, type, data, minOccurs, maxOccurs, level, appInfo));
    }

    return result;
}