Example usage for org.jdom2 Element removeChild

List of usage examples for org.jdom2 Element removeChild

Introduction

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

Prototype

public boolean removeChild(final String cname) 

Source Link

Document

This removes the first child element (one level deep) with the given local name and belonging to no namespace.

Usage

From source file:org.artifactory.update.security.v2.SimpleUserConverter.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked" })
public void convert(Document doc) {
    Element usersTag = doc.getRootElement().getChild("users");
    List<Element> users = usersTag.getChildren();
    for (Element user : users) {
        if (user.getName().contains("SimpleUser")) {
            user.setName("user");
            user.removeChild("authorities");
        } else {/*  ww  w  .  ja v  a  2  s  .c  om*/
            log.warn("A tag " + user + " under users is not SimpleUSer!!");
        }
    }
}

From source file:org.artifactory.update.security.v4.AnnotatePermissionXmlConverter.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked" })
public void convert(Document doc) {
    Element aclsTag = doc.getRootElement().getChild("acls");
    List<Element> acls = aclsTag.getChildren();
    for (Element acl : acls) {
        Element acesTag = acl.getChild(ACES);
        List<Element> aces = acesTag.getChildren(ACE);
        Element newAces = new Element(ACES);
        Element aceTemplate = new Element(ACE);
        Element groupEl = new Element(GROUP);
        aceTemplate.addContent(new Element(PRINCIPAL)).addContent(groupEl).addContent(new Element(MASK));
        for (Element ace : aces) {
            Element child = ace.getChild("principal");
            Element newAce = (Element) aceTemplate.clone();
            newAce.getChild(PRINCIPAL).setText(ace.getChildText(PRINCIPAL));
            newAce.getChild(GROUP).setText(ace.getChildText(GROUP));

            Element maskEl = ace.getChild(MASK);
            int mask = Integer.parseInt(maskEl.getText());
            if (!child.getText().equals(UserInfo.ANONYMOUS)) {
                if ((mask & (ArtifactoryPermission.MANAGE.getMask()
                        | ArtifactoryPermission.DEPLOY.getMask())) > 0) {
                    mask |= ArtifactoryPermission.ANNOTATE.getMask();
                }//from   ww  w  .j  ava 2s .c o  m
            }
            newAce.getChild(MASK).setText("" + mask);
            newAces.addContent(newAce);
        }
        acl.removeChild(ACES);
        acl.addContent(newAces);
    }
}

From source file:org.mycore.frontend.editor.MCREditorServlet.java

License:Open Source License

private void processSubmit(MCRServletJob job, MCRRequestParameters parms)
        throws ServletException, IOException, TransformerException, SAXException {
    LOGGER.debug("Editor: process submit");

    String sessionID = parms.getParameter("_session");
    MCREditorSession editorSession = MCREditorSessionCache.instance().getEditorSession(sessionID);
    if (editorSession == null) {
        LOGGER.error("No editor for session <" + sessionID + ">");
        throw new ServletException("invalid session");
    }//w  w w  .  j  a  va 2  s  . c o  m

    Element editor = editorSession.getXML();
    String button = null;

    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (name.startsWith("_p-") || name.startsWith("_m-") || name.startsWith("_u-") || name.startsWith("_d-")
                || name.startsWith("_s-")) {
            button = name;

            break;
        }
    }

    if (button == null) {
        LOGGER.info("Editor session " + sessionID + " submitting form data");

        // We do not remove the editor session from cache, because
        // the user may use the back button and re-submit if an error
        // occured. In nearly all editor states this is safe, but sometimes
        // may result in ugly behaviour in conjunction with repeaters.
        //
        // sessions.remove(sessionID); // no good idea
        processTargetSubmission(job, parms, editor);
    } else if (button.startsWith("_s-")) {
        StringTokenizer sst = new StringTokenizer(button.substring(3), "-");
        String id = sst.nextToken();
        String var = sst.nextToken();
        LOGGER.debug("Editor start subselect " + id + " at position " + var);

        Element subselect = MCREditorDefReader.findElementByID(id, editor);
        StringBuilder sb = new StringBuilder(MCRFrontendUtil.getBaseURL());

        String webpage = URLEncoder.encode(parms.getParameter("_webpage"), "UTF-8");
        if ("editor".equals(subselect.getAttributeValue("type"))) {
            sb.append(subselect.getAttributeValue("href"));
            sb.append("?subselect.session=").append(sessionID);
            sb.append("&subselect.varpath=").append(var);
            sb.append("&subselect.webpage=").append(webpage);

            String wp = MCRFrontendUtil.getBaseURL() + parms.getParameter("_webpage");
            if (!wp.contains("XSL.editor.session.id")) {
                wp += "XSL.editor.session.id=" + sessionID;
            }
            String cancelURL = URLEncoder.encode(wp, "UTF-8");
            sb.append("&cancelURL=").append(cancelURL);
        } else if ("webpage".equals(subselect.getAttributeValue("type"))) {
            sb.append(subselect.getAttributeValue("href"));
            if (subselect.getAttributeValue("href").indexOf("?") > 0) {
                sb.append("&XSL.subselect.session.SESSION=").append(sessionID);
            } else {
                sb.append("?XSL.subselect.session.SESSION=").append(sessionID);
            }
            sb.append("&XSL.subselect.varpath.SESSION=").append(var);
            sb.append("&XSL.subselect.webpage.SESSION=").append(webpage);
        } else if ("servlet".equals(subselect.getAttributeValue("type"))) {
            sb.append(subselect.getAttributeValue("href"));
            sb.append("?subselect.session=").append(sessionID);
            sb.append("&subselect.varpath=").append(var);
            sb.append("&subselect.webpage=").append(webpage);
        }

        String url = sb.toString();

        editor.removeChild("input");
        editor.removeChild("repeats");

        MCREditorSubmission sub = new MCREditorSubmission(parms, editor, false);
        editor.addContent(sub.buildInputElements());
        editor.addContent(sub.buildRepeatElements());

        LOGGER.debug("Editor goto subselect at " + url);
        job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(url));
    } else {
        int pos = button.lastIndexOf("-");

        String action = button.substring(1, 2);
        String path = button.substring(3, pos);
        int nr = Integer.parseInt(button.substring(pos + 1, button.length() - 2));

        LOGGER.debug("Editor action " + action + " " + nr + " " + path);

        editor.removeChild("input");
        editor.removeChild("repeats");
        editor.removeChild("failed");

        MCREditorSubmission sub = new MCREditorSubmission(parms, editor, false);

        if ("p".equals(action)) {
            sub.doPlus(path, nr);
        } else if ("m".equals(action)) {
            sub.doMinus(path, nr);
        } else if ("u".equals(action)) {
            sub.doUp(path, nr);
        } else if ("d".equals(action)) {
            sub.doUp(path, nr + 1);
        }

        editor.addContent(sub.buildInputElements());
        editor.addContent(sub.buildRepeatElements());

        // Redirect to webpage to reload editor form
        StringBuilder sb = new StringBuilder(MCRFrontendUtil.getBaseURL());
        String wp = parms.getParameter("_webpage");
        sb.append(wp);
        if (!wp.contains("XSL.editor.session.id=")) {
            sb.append("XSL.editor.session.id=");
            sb.append(sessionID);
        }

        path = path.replace('/', '_').replace('@', '_').replace('[', '_').replace(']', '_');
        sb.append("#rep").append(path);

        LOGGER.debug("Editor redirect to " + sb.toString());
        job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(sb.toString()));
    }
}

From source file:org.mycore.frontend.editor.MCREditorServlet.java

License:Open Source License

private void processTargetSubmission(MCRServletJob job, MCRRequestParameters parms, Element editor)
        throws ServletException, IOException, TransformerException, SAXException {
    LOGGER.debug("Editor: processTargetSubmission ");

    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();

    editor.removeChild("failed");

    MCREditorSubmission sub = new MCREditorSubmission(parms, editor, true);

    if (sub.errors()) // validation failed, go back to editor form in
                      // webpage
    {//from w  w  w  . j a v a  2 s  .c  o  m
        editor.removeChild("input");
        editor.removeChild("repeats");
        editor.addContent(sub.buildInputElements());
        editor.addContent(sub.buildRepeatElements());
        editor.addContent(sub.buildFailedConditions());

        String sessionID = parms.getParameter("_session");

        // Redirect to webpage to reload editor form
        StringBuilder sb = new StringBuilder(MCRFrontendUtil.getBaseURL());
        String wp = parms.getParameter("_webpage");
        sb.append(wp);
        if (!wp.contains("XSL.editor.session.id=")) {
            sb.append("XSL.editor.session.id=");
            sb.append(sessionID);
        }
        LOGGER.debug("Editor redirect to " + sb.toString());
        res.sendRedirect(res.encodeRedirectURL(sb.toString()));

        return;
    }

    Document xml = sub.getXML();

    postProcess(editor, sub);

    String targetType = parms.getParameter("_target-type");
    LOGGER.debug("Editor: targettype=" + targetType);

    if (targetType.equals("servlet")) {
        sendToServlet(req, res, sub);
    } else if (targetType.equals("url")) {
        sendToURL(req, res);
    } else if (targetType.equals("webapp")) {
        sendToWebAppFile(req, res, sub, editor);
    } else if (targetType.equals("debug")) {
        sendToDebug(res, xml, sub);
    } else if (targetType.equals("display")) {
        getLayoutService().doLayout(req, res, new MCRJDOMContent(sub.getXML()));
    } else if (targetType.equals("subselect")) {
        List variables = sub.getVariables();
        String root = sub.getXML().getRootElement().getName();
        sendToSubSelect(res, parms, variables, root);
    } else {
        LOGGER.debug("Unknown targettype");
    }

    LOGGER.debug("Editor: processTargetSubmission DONE");
}

From source file:org.mycore.frontend.editor.MCREditorServlet.java

License:Open Source License

private void sendToSubSelect(HttpServletResponse res, MCRRequestParameters parms, List variables, String root)
        throws IOException {
    String webpage = parms.getParameter("subselect.webpage");
    String sessionID = parms.getParameter("subselect.session");

    Element editor = MCREditorSessionCache.instance().getEditorSession(sessionID).getXML();
    MCREditorSubmission subnew = new MCREditorSubmission(editor, variables, root, parms);

    editor.removeChild("input");
    editor.removeChild("repeats");
    editor.removeChild("failed");
    editor.addContent(subnew.buildInputElements());
    editor.addContent(subnew.buildRepeatElements());

    // Redirect to webpage to reload editor form
    StringBuilder sb = new StringBuilder(MCRFrontendUtil.getBaseURL());
    sb.append(webpage);/*from   ww w  .  j a  va2s.  c  o  m*/
    if (!webpage.contains("XSL.editor.session.id=")) {
        sb.append("XSL.editor.session.id=");
        sb.append(sessionID);
    }

    LOGGER.debug("Editor redirect to " + sb.toString());
    res.sendRedirect(res.encodeRedirectURL(sb.toString()));
}

From source file:org.yawlfoundation.yawl.elements.data.YParameter.java

License:Open Source License

public String toSummaryXML() {
    String result = "";
    Element eParam = JDOMUtil.stringToElement(toXML());
    if (eParam != null) {
        eParam.removeChild("initialValue");
        Element typeElement = eParam.getChild("type");
        Element orderingElem = new Element("ordering");
        orderingElem.setText("" + _ordering);
        int insPos = (null == typeElement) ? 0 : 1;
        eParam.addContent(insPos, orderingElem);
        result = JDOMUtil.elementToString(eParam);
    }/*  www  .j  ava2s. c  o m*/
    return result;
}

From source file:org.yawlfoundation.yawl.engine.interfce.Marshaller.java

License:Open Source License

public static String getMergedOutputData(Element inputData, Element outputData) {
    try {//from  ww w  .  ja  v a  2  s  .co  m
        Element merged = inputData.clone();
        JDOMUtil.stripAttributes(merged);
        JDOMUtil.stripAttributes(outputData);

        List<Element> children = outputData.getChildren();

        // iterate through the output vars and add them to the merged doc.
        for (int i = children.size() - 1; i >= 0; i--) {
            Element child = children.get(i);

            // the input data will be removed from the merged doc and
            // the output data will be added.
            merged.removeChild(child.getName());
            merged.addContent(child.detach());
        }
        return JDOMUtil.elementToString(merged);
    } catch (Exception e) {
        return "";
    }
}

From source file:org.yawlfoundation.yawl.engine.YEngine.java

License:Open Source License

private String mapOutputDataForSkippedWorkItem(YWorkItem workItem, String data) throws YStateException {

    // get input and output params for task
    YSpecificationID specID = workItem.getSpecificationID();
    String taskID = workItem.getTaskID();
    YTask task = getTaskDefinition(specID, taskID);

    Map<String, YParameter> inputs = task.getDecompositionPrototype().getInputParameters();
    Map<String, YParameter> outputs = task.getDecompositionPrototype().getOutputParameters();

    if (outputs.isEmpty()) { // no output data to map
        return StringUtil.wrap("", taskID);
    }//from w ww. jav a 2  s  .  c om

    // map data values to params
    Element itemData = JDOMUtil.stringToElement(data);
    Element outputData = itemData != null ? itemData.clone() : new Element(taskID);

    // remove the input-only params from output data
    for (String name : inputs.keySet())
        if (outputs.get(name) == null)
            outputData.removeChild(name);

    // for each output param:
    //   1. if matching output Element, do nothing
    //   2. else if matching input param, use its value
    //   3. else if default value specified, use its value
    //   4. else use default value for the param's data type
    List<YParameter> outParamList = new ArrayList<YParameter>(outputs.values());
    Collections.sort(outParamList); // get in right order
    for (YParameter outParam : outParamList) {
        String name = outParam.getName();
        if (outputData.getChild(name) != null)
            continue; // matching I/O element

        // the output param has no corresponding input param, so add an element
        String defaultValue = outParam.getDefaultValue();
        if (defaultValue == null) {
            String typeName = outParam.getDataTypeName();
            if (!XSDType.isBuiltInType(typeName)) {
                throw new YStateException(
                        String.format("Could not skip work item [%s]: Output-Only parameter [%s]"
                                + " requires a default value.", workItem.getIDString(), name));
            }
            defaultValue = JDOMUtil.getDefaultValueForType(typeName);
        }
        Element outData = new Element(name);
        outData.setText(defaultValue);
        outputData.addContent(outData);
    }

    return JDOMUtil.elementToStringDump(outputData);
}

From source file:org.yawlfoundation.yawl.scheduling.FormGenerator.java

License:Open Source License

/**
 * get ResourceUtilisationPlan updated with data from request
 *
 * @return/*from  w ww .jav a  2s .  c  om*/
 */
private void updateRUPFromRequest(Document doc) throws Exception {
    String xpath = XMLUtils.getXPATH_RUP();
    Element rupElement = XMLUtils.getElement(doc, xpath);

    // remove elements from rup for reinsert in next step
    for (Element activity : activities) {
        activity.removeChildren(Constants.XML_RESERVATION);
        activity.removeChildren(Constants.XML_UTILISATIONREL);
        activity.removeChildren(Constants.XML_MSGTRANSFER);
    }

    XMLUtils.removeAttributes(rupElement, XML_ERROR);
    XMLUtils.removeAttributes(rupElement, XML_WARNING);

    // build new parameter list with rup fields only
    Map<String, Object[]> params = new HashMap<String, Object[]>();
    for (String key : new ArrayList<String>(request.getParameterMap().keySet())) {
        if (!key.startsWith(XML_ACTIVITY + "_") || key.contains(XML_RESOURCE_TYPE)
                || key.endsWith("__sexyComboHidden")) {
            continue;
        }

        Object[] values = ((Object[]) request.getParameterMap().get(key));

        // for sexycombo plugin only: write value of key "bla__sexyCombo" to newKey "bla"
        if (key.endsWith("__sexyCombo")) {
            String newKey = key.substring(0, key.length() - "__sexyCombo".length());
            params.put(newKey, values);
        } else if (!params.containsKey(key)) {
            params.put(key, values);
        }
    }

    ArrayList<String> keys = new ArrayList<String>(params.keySet());
    final List<String> possibleActivities = Utils
            .parseCSV(_props.getSchedulingProperty("possibleActivitiesSorted"));
    Collections.sort(keys, new Comparator<String>() {
        public int compare(String a1, String a2) {
            if (a1.startsWith(XML_ACTIVITY)) {
                a1 = a1.substring(XML_ACTIVITY.length() + 1);
                a1 = a1.substring(0, a1.indexOf("_"));
            }
            if (a2.startsWith(XML_ACTIVITY)) {
                a2 = a2.substring(XML_ACTIVITY.length() + 1);
                a2 = a2.substring(0, a2.indexOf("_"));
            }
            return possibleActivities.indexOf(a1) - possibleActivities.indexOf(a2);
        }
    });

    // update RUP with input values
    for (String key : keys) {
        Object[] values = params.get(key);
        String value = (String) values[0];

        StringTokenizer st = new StringTokenizer(key, "_");
        st.nextToken(); // ignore 'Activity.'
        String activityName = st.nextToken();
        xpath = XMLUtils.getXPATH_Activities(activityName);
        Element activity = XMLUtils.getElement(doc, xpath);
        if (activity == null) {
            activity = getTemplate(XML_ACTIVITY);
            Element name = activity.getChild(XML_ACTIVITYNAME);
            name.setText(activityName);
            rupElement.addContent(activity);
        }

        Element var = null;
        String resOrUtilName = st.nextToken();
        if (resOrUtilName.equals(XML_RESERVATION) || resOrUtilName.equals(XML_UTILISATIONREL)
                || resOrUtilName.equals(XML_MSGTRANSFER)) {
            Integer resOrUtilIndex = Integer.valueOf(st.nextToken().substring(1)); // index, remove '#'
            xpath = XMLUtils.getXPATH_ActivityElement(activityName, resOrUtilName, resOrUtilIndex);

            Element resOrUtilElem = XMLUtils.getElement(doc, xpath);

            // insert empty 'dummy' resOrUtils, will be removed later
            while (resOrUtilElem == null) {
                resOrUtilElem = getTemplate(resOrUtilName);
                resOrUtilElem.addContent(new Element(XML_DUMMY));
                activity.addContent(resOrUtilElem);

                resOrUtilElem = XMLUtils.getElement(doc, xpath);
            }
            resOrUtilElem.removeChild(XML_DUMMY); // only if exists one

            String pathName = "";
            while (st.hasMoreTokens()) {
                String elementName = st.nextToken();
                pathName += elementName;
                xpath = XMLUtils.getXPATH_ResOrUtilElement(activityName, resOrUtilName, resOrUtilIndex,
                        pathName);
                var = XMLUtils.getElement(doc, xpath);
                if (var == null) {
                    var = new Element(elementName);
                    resOrUtilElem.addContent(var);
                }
                resOrUtilElem = var;
                pathName += "/";
            }

        } else {
            xpath = XMLUtils.getXPATH_ActivityElement(activityName, resOrUtilName, null);
            var = XMLUtils.getElement(doc, xpath);
            if (var == null) {
                var = new Element(resOrUtilName);
                activity.addContent(var);
            }
        }

        String cssClass = validateElement(var, new ArrayList<Element>());
        if (cssClass.equals(CSS_DATEINPUT)) {
            try {
                Date date = Utils.string2Date(value, isShortForm ? Utils.DATE_PATTERN : Utils.DATETIME_PATTERN);
                XMLUtils.setDateValue(var, date);
            } catch (ParseException e) {
                //_log.error("cannot parse into date" + value);
            }
        } else if (cssClass.equals(CSS_DURATIONINPUT)) {
            try {
                value = Utils.stringMinutes2stringXMLDuration(value);
            } catch (Exception e) {
                //_log.error("cannot parse into duration" + value);
            }
            XMLUtils.setStringValue(var, value);
        } else {
            XMLUtils.setStringValue(var, value);
        }

        validateElement(var, new ArrayList<Element>());
    }

    updateActivities(doc);
}

From source file:org.yawlfoundation.yawl.wsif.WSIFController.java

License:Open Source License

/**
 * Implements InterfaceBWebsideController.  It receives messages from the engine
 * notifying an enabled task and acts accordingly.  In this case it takes the message,
 * tries to check out the work item, and if successful it begins to start up a web service
 * invocation.//from   w  w w. j  a v a 2s  .co m
 * @param enabledWorkItem
 */
public void handleEnabledWorkItemEvent(WorkItemRecord enabledWorkItem) {
    try {
        if (!checkConnection(_sessionHandle)) {
            _sessionHandle = connect(engineLogonName, engineLogonPassword);
        }
        if (successful(_sessionHandle)) {
            List<WorkItemRecord> executingChildren = checkOutAllInstancesOfThisTask(enabledWorkItem,
                    _sessionHandle);
            for (WorkItemRecord itemRecord : executingChildren) {
                Element inputData = itemRecord.getDataList();
                String wsdlLocation = inputData.getChildText(WSDL_LOCATION_PARAMNAME);
                String portName = inputData.getChildText(WSDL_PORTNAME_PARAMNAME);
                String operationName = inputData.getChildText(WSDL_OPERATIONNAME_PARAMNAME);

                Element webServiceArgsData = inputData.clone();
                webServiceArgsData.removeChild(WSDL_LOCATION_PARAMNAME);
                webServiceArgsData.removeChild(WSDL_PORTNAME_PARAMNAME);
                webServiceArgsData.removeChild(WSDL_OPERATIONNAME_PARAMNAME);

                Map replyFromWebServiceBeingInvoked = WSIFInvoker.invokeMethod(wsdlLocation, portName,
                        operationName, webServiceArgsData, getAuthenticationConfig());

                _log.warn("\n\nReply from Web service being invoked is : {}", replyFromWebServiceBeingInvoked);

                Element caseDataBoundForEngine = prepareReplyRootElement(enabledWorkItem, _sessionHandle);
                Map<String, String> outputDataTypes = getOutputDataTypes(enabledWorkItem);

                for (Object o : replyFromWebServiceBeingInvoked.keySet()) {
                    String varName = (String) o;
                    Object replyMsg = replyFromWebServiceBeingInvoked.get(varName);
                    System.out.println("replyMsg class = " + replyMsg.getClass().getName());
                    String varVal = replyMsg.toString();
                    String varType = outputDataTypes.get(varName);
                    if ((varType != null) && (!varType.endsWith("string"))) {
                        varVal = validateValue(varType, varVal);
                    }
                    Element content = new Element(varName);
                    content.setText(varVal);
                    caseDataBoundForEngine.addContent(content);
                }

                _logger.debug("\nResult of item [" + itemRecord.getID() + "] checkin is : " + checkInWorkItem(
                        itemRecord.getID(), inputData, caseDataBoundForEngine, null, _sessionHandle));
            }
        }

    } catch (Throwable e) {
        _logger.error(e.getMessage(), e);
    }
}