Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

In this page you can find the example usage for org.dom4j Element getTextTrim.

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.alfresco.web.config.ViewsElementReader.java

License:Open Source License

/**
 * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element)
 */// ww  w  .ja  va 2s .co  m
@SuppressWarnings("unchecked")
public ConfigElement parse(Element element) {
    ViewsConfigElement configElement = null;

    if (element != null) {
        String name = element.getName();
        if (name.equals(ViewsConfigElement.CONFIG_ELEMENT_ID) == false) {
            throw new ConfigException(
                    "ViewsElementReader can only parse " + ViewsConfigElement.CONFIG_ELEMENT_ID
                            + " elements, the element passed was '" + name + "'");
        }

        configElement = new ViewsConfigElement();

        // get the configured views
        Iterator<Element> renderers = element.elementIterator(ELEMENT_VIEWIMPL);
        while (renderers.hasNext()) {
            Element renderer = renderers.next();
            configElement.addView(renderer.getTextTrim());
        }

        // get all the view related default settings
        Element viewDefaults = element.element(ELEMENT_VIEWDEFAULTS);
        if (viewDefaults != null) {
            Iterator<Element> pages = viewDefaults.elementIterator();
            while (pages.hasNext()) {
                Element page = pages.next();
                String pageName = page.getName();

                // get the default view mode for the page
                Element defaultView = page.element(ELEMENT_VIEW);
                if (defaultView != null) {
                    String viewName = defaultView.getTextTrim();
                    configElement.addDefaultView(pageName, viewName);
                }

                // get the initial sort column
                Element sortColumn = page.element(ELEMENT_SORTCOLUMN);
                if (sortColumn != null) {
                    String column = sortColumn.getTextTrim();
                    configElement.addDefaultSortColumn(pageName, column);
                }

                // get the sort direction option
                Element sortDir = page.element(ELEMENT_SORTDIRECTION);
                if (sortDir != null) {
                    configElement.addSortDirection(pageName, sortDir.getTextTrim());
                }

                // process the page-size element
                processPageSizeElement(page.element(ELEMENT_PAGESIZE), pageName, configElement);
            }
        }
    }

    return configElement;
}

From source file:org.alfresco.web.config.ViewsElementReader.java

License:Open Source License

/**
 * Processes a page-size element/*  w  w  w. ja  va2  s  . c  om*/
 * 
 * @param pageSizeElement The element to process
 * @param page The page the page-size element belongs to
 * @param configElement The config element being populated
 */
@SuppressWarnings("unchecked")
private void processPageSizeElement(Element pageSizeElement, String page, ViewsConfigElement configElement) {
    if (pageSizeElement != null) {
        Iterator<Element> views = pageSizeElement.elementIterator();
        while (views.hasNext()) {
            Element view = views.next();
            String viewName = view.getName();
            String pageSize = view.getTextTrim();
            try {
                configElement.addDefaultPageSize(page, viewName, Integer.parseInt(pageSize));
            } catch (NumberFormatException nfe) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Failed to set page size for view '" + viewName + "' in page '" + page
                            + "' as '" + pageSize + "' is an invalid number!");
                }
            }
        }
    }
}

From source file:org.apache.archiva.xml.ElementTextListClosure.java

License:Apache License

@Override
public void execute(Object input) {
    if (input instanceof Element) {
        Element elem = (Element) input;
        list.add(elem.getTextTrim());
    }//from  w w  w.  ja  va  2  s  .c om
}

From source file:org.apache.archiva.xml.XMLReader.java

License:Apache License

public String getElementText(Node context, String xpathExpr) throws XMLException {
    XPath xpath = createXPath(xpathExpr);
    Object evaluated = xpath.selectSingleNode(context);

    if (evaluated == null) {
        return null;
    }/*from w ww . j  a va2 s.  c  o m*/

    if (evaluated instanceof Element) {
        Element evalElem = (Element) evaluated;
        return evalElem.getTextTrim();
    } else {
        // Unknown evaluated type.
        throw new XMLException(".getElementText( Node, Expr: " + xpathExpr
                + " ) resulted in non-Element type -> (" + evaluated.getClass().getName() + ") " + evaluated);
    }
}

From source file:org.apache.archiva.xml.XMLReader.java

License:Apache License

public String getElementText(String xpathExpr) throws XMLException {
    XPath xpath = createXPath(xpathExpr);
    Object evaluated = xpath.selectSingleNode(document);

    if (evaluated == null) {
        return null;
    }//from   ww w  . j  av  a 2s.  c  o  m

    if (evaluated instanceof Element) {
        Element evalElem = (Element) evaluated;
        return evalElem.getTextTrim();
    } else {
        // Unknown evaluated type.
        throw new XMLException(".getElementText( Expr: " + xpathExpr + " ) resulted in non-Element type -> ("
                + evaluated.getClass().getName() + ") " + evaluated);
    }
}

From source file:org.apache.archiva.xml.XMLReader.java

License:Apache License

public List<String> getElementListText(String xpathExpr) throws XMLException {
    List<Element> elemList = getElementList(xpathExpr);
    if (elemList == null) {
        return null;
    }/* w w  w  .  ja  va2s  .  co m*/

    List<String> ret = new ArrayList<>();
    for (Iterator<Element> iter = elemList.iterator(); iter.hasNext();) {
        Element listelem = iter.next();
        ret.add(listelem.getTextTrim());
    }
    return ret;
}

From source file:org.axonframework.eventstore.legacy.LegacyAxonEventUpcaster.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override/*from ww w . j  a  v a  2s  .  c  o m*/
public Document upcast(Document event) {
    Element rootNode = event.getRootElement();
    if (rootNode.attribute("eventRevision") == null) {
        rootNode.addAttribute("eventRevision", "0");
        Element metaData = rootNode.addElement("metaData").addElement("values");
        Iterator<Element> children = rootNode.elementIterator();
        while (children.hasNext()) {
            Element childNode = children.next();
            String childName = childNode.getName();
            if ("eventIdentifier".equals(childName)) {
                addMetaDataEntry(metaData, "_identifier", childNode.getTextTrim(), "uuid");
                rootNode.remove(childNode);
            } else if ("timestamp".equals(childName)) {
                addMetaDataEntry(metaData, "_timestamp", childNode.getTextTrim(), "localDateTime");
                rootNode.remove(childNode);
            }
        }
    }
    return event;
}

From source file:org.axonframework.migration.eventstore.LegacyAxonEventUpcaster.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override//  w ww .  j  a  v a2s.  co m
public IntermediateRepresentation upcast(IntermediateRepresentation event) {
    Element rootNode = ((Document) event.getContents()).getRootElement();
    if (rootNode.attribute("eventRevision") == null) {
        rootNode.addAttribute("eventRevision", "0");
        Element metaData = rootNode.addElement("metaData").addElement("values");
        Iterator<Element> children = rootNode.elementIterator();
        while (children.hasNext()) {
            Element childNode = children.next();
            String childName = childNode.getName();
            if ("eventIdentifier".equals(childName)) {
                addMetaDataEntry(metaData, "_identifier", childNode.getTextTrim(), "uuid");
                rootNode.remove(childNode);
            } else if ("timestamp".equals(childName)) {
                addMetaDataEntry(metaData, "_timestamp", childNode.getTextTrim(), "localDateTime");
                rootNode.remove(childNode);
            }
        }
    }
    Document document = new DefaultDocument();
    Element newRoot = document.addElement("domain-event");
    Element payload = newRoot.addElement("payload");
    String objectType = rootNode.getName().replaceAll("\\_\\-", "\\$");
    payload.addAttribute("class", objectType);
    Set<String> forbiddenPayloadElements = new HashSet<String>(
            Arrays.asList("metaData", "aggregateIdentifier", "sequenceNumber", "timestamp"));
    for (Object node : rootNode.elements()) {
        Element element = (Element) node;
        if (!forbiddenPayloadElements.contains(element.getName())) {
            payload.add(element.createCopy());
        } else {
            newRoot.add(element.createCopy());
        }
    }
    newRoot.addElement("timestamp").addText(extractMetaDataValue(newRoot, "_timestamp"));
    newRoot.addElement("eventIdentifier").addText(extractMetaDataValue(newRoot, "_identifier"));
    String eventRevision = rootNode.attribute("eventRevision").getValue();
    payload.addAttribute("eventRevision", eventRevision);
    return new Dom4jRepresentation(document, DomainEventMessage.class.getName(),
            Integer.parseInt(eventRevision));
}

From source file:org.b5chat.crossfire.core.net.sasl.SASLAuthentication.java

License:Open Source License

/**
 * Handles the SASL authentication packet. The entity may be sending an initial
 * authentication request or a response to a challenge made by the server. The returned
 * value indicates whether the authentication has finished either successfully or not or
 * if the entity is expected to send a response to a challenge.
 *
 * @param session the session that is authenticating with the server.
 * @param doc the stanza sent by the authenticating entity.
 * @return value that indicates whether the authentication has finished either successfully
 *         or not or if the entity is expected to send a response to a challenge.
 * @throws UnsupportedEncodingException If UTF-8 charset is not supported.
 *//*from  www .ja v  a  2 s .  c  o m*/
public static Status handle(LocalSession session, Element doc) throws UnsupportedEncodingException {
    Status status;
    String mechanism;
    if (doc.getNamespace().asXML().equals(SASL_NAMESPACE)) {
        ElementType type = ElementType.valueof(doc.getName());
        switch (type) {
        case AUTH:
            mechanism = doc.attributeValue("mechanism");
            // Store the requested SASL mechanism by the client
            session.setSessionData("SaslMechanism", mechanism);
            //Log.debug("SASLAuthentication.doHandshake() AUTH entered: "+mechanism);
            if (mechanism.equalsIgnoreCase("ANONYMOUS") && mechanisms.contains("ANONYMOUS")) {
                status = doAnonymousAuthentication(session);
            } else if (mechanisms.contains(mechanism)) {
                // The selected SASL mechanism requires the server to send a challenge
                // to the client
                try {
                    Map<String, String> props = new TreeMap<String, String>();
                    props.put(Sasl.QOP, "auth");
                    if (mechanism.equals("GSSAPI")) {
                        props.put(Sasl.SERVER_AUTH, "TRUE");
                    }
                    SaslServer ss = Sasl.createSaslServer(mechanism, "xmpp",
                            Globals.getProperty("xmpp.fqdn", session.getServerName()), props,
                            new XMPPCallbackHandler());
                    // evaluateResponse doesn't like null parameter
                    byte[] token = new byte[0];
                    if (doc.getText().length() > 0) {
                        // If auth request includes a value then validate it
                        token = StringUtils.decodeBase64(doc.getText().trim());
                        if (token == null) {
                            token = new byte[0];
                        }
                    }
                    if (mechanism.equals("DIGEST-MD5")) {
                        // RFC2831 (DIGEST-MD5) says the client MAY provide an initial response on subsequent
                        // authentication. Java SASL does not (currently) support this and thows an exception
                        // if we try.  This violates the RFC, so we just strip any initial token.
                        token = new byte[0];
                    }
                    byte[] challenge = ss.evaluateResponse(token);
                    if (ss.isComplete()) {
                        authenticationSuccessful(session, ss.getAuthorizationID(), challenge);
                        status = Status.authenticated;
                    } else {
                        // Send the challenge
                        sendChallenge(session, challenge);
                        status = Status.needResponse;
                    }
                    session.setSessionData("SaslServer", ss);
                } catch (SaslException e) {
                    Log.info("User Login Failed. " + e.getMessage());
                    authenticationFailed(session);
                    status = Status.failed;
                }
            } else {
                Log.warn("Client wants to do a MECH we don't support: '" + mechanism + "'");
                authenticationFailed(session);
                status = Status.failed;
            }
            break;
        case RESPONSE:
            // Store the requested SASL mechanism by the client
            mechanism = (String) session.getSessionData("SaslMechanism");
            if (mechanism.equalsIgnoreCase("b5chat-SHAREDSECRET")) {
                status = doSharedSecretAuthentication(session, doc);
            } else if (mechanisms.contains(mechanism)) {
                SaslServer ss = (SaslServer) session.getSessionData("SaslServer");
                if (ss != null) {
                    boolean ssComplete = ss.isComplete();
                    String response = doc.getTextTrim();
                    try {
                        if (ssComplete) {
                            authenticationSuccessful(session, ss.getAuthorizationID(), null);
                            status = Status.authenticated;
                        } else {
                            byte[] data = StringUtils.decodeBase64(response);
                            if (data == null) {
                                data = new byte[0];
                            }
                            byte[] challenge = ss.evaluateResponse(data);
                            if (ss.isComplete()) {
                                authenticationSuccessful(session, ss.getAuthorizationID(), challenge);
                                status = Status.authenticated;
                            } else {
                                // Send the challenge
                                sendChallenge(session, challenge);
                                status = Status.needResponse;
                            }
                        }
                    } catch (SaslException e) {
                        Log.debug("SASLAuthentication: SaslException", e);
                        authenticationFailed(session);
                        status = Status.failed;
                    }
                } else {
                    Log.error("SaslServer is null, should be valid object instead.");
                    authenticationFailed(session);
                    status = Status.failed;
                }
            } else {
                Log.warn("Client responded to a MECH we don't support: '" + mechanism + "'");
                authenticationFailed(session);
                status = Status.failed;
            }
            break;
        default:
            authenticationFailed(session);
            status = Status.failed;
            // Ignore
            break;
        }
    } else {
        Log.debug("SASLAuthentication: Unknown namespace sent in auth element: " + doc.asXML());
        authenticationFailed(session);
        status = Status.failed;
    }
    // Check if SASL authentication has finished so we can clean up temp information
    if (status == Status.failed || status == Status.authenticated) {
        // Remove the SaslServer from the ISession
        session.removeSessionData("SaslServer");
        // Remove the requested SASL mechanism by the client
        session.removeSessionData("SaslMechanism");
    }
    return status;
}

From source file:org.b5chat.crossfire.core.net.sasl.SASLAuthentication.java

License:Open Source License

private static Status doSharedSecretAuthentication(LocalSession session, Element doc)
        throws UnsupportedEncodingException {
    String secretDigest;/* w  w  w. java 2 s. co m*/
    String response = doc.getTextTrim();
    if (response == null || response.length() == 0) {
        // No info was provided so send a challenge to get it
        sendChallenge(session, new byte[0]);
        return Status.needResponse;
    }

    // Parse data and obtain username & password
    String data = new String(StringUtils.decodeBase64(response), CHARSET);
    StringTokenizer tokens = new StringTokenizer(data, "\0");
    tokens.nextToken();
    secretDigest = tokens.nextToken();
    if (authenticateSharedSecret(secretDigest)) {
        authenticationSuccessful(session, null, null);
        return Status.authenticated;
    }
    // Otherwise, authentication failed.
    authenticationFailed(session);
    return Status.failed;
}