Example usage for org.dom4j Element elementText

List of usage examples for org.dom4j Element elementText

Introduction

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

Prototype

String elementText(QName qname);

Source Link

Usage

From source file:nl.knaw.dans.dccd.repository.fedora.FedoraRepositoryService.java

License:Apache License

/** Creates the list with projects specified by the given xml string
 * The project only have the id and title set and no further data
 * Create empty list if nothing found/*from w ww  .j a  v a2s. c o m*/
 *
 * @param xmlResultString
 * @return
 * @throws DocumentException If the input string is incorrect parsing fails
 */
@SuppressWarnings("unchecked")
private Collection<Project> createProjectListFromXMLResultString(String xmlResultString)
        throws DocumentException {
    if (xmlResultString == null || xmlResultString.length() == 0)
        throw new IllegalArgumentException("string must be specified");

    // should be xml from fedora, parse it with dom4j
    // and fill the list with projects
    Collection<Project> dendroProjects = new ArrayList<Project>();
    Document domDoc;
    try {
        domDoc = DocumentHelper.parseText(xmlResultString);//response.toString());
        Element xmlResult = domDoc.getRootElement();
        Element xmlResultList = xmlResult.element("resultList");

        // logger.info("root: " + xmlResultList.asXML());

        // get all objectFields
        for (Iterator i = xmlResultList.elementIterator("objectFields"); i.hasNext();) {
            Element objectFields = (Element) i.next();
            // get id
            String id = objectFields.elementText("pid");
            // get titel
            String title = objectFields.elementText("title");
            logger.info("Found Id: " + id + " Title: " + title);
            Project dendroProject = new Project(id, title);
            dendroProjects.add(dendroProject);
        }
    } catch (DocumentException e) {
        throw e;
    }

    return dendroProjects;
}

From source file:nl.tue.gale.ae.grapple.CAMFormat.java

License:Open Source License

@SuppressWarnings("unchecked")
private List<Concept> getInternalConcepts(Element cam) {
    URI baseURI = URIs//from ww  w. ja  v a2 s.c  om
            .of("gale://gale.tue.nl/cam/" + replaceSpace(cam.element("header").elementText("title")) + "/");

    List<Element> models = cam.element("body").element("cam").element("camInternal").element("domainModel")
            .elements("model");
    for (Element model : models) {
        Element vdex = model.element("body").element("dm").element("vdex");
        for (Element termElement : (Collection<Element>) vdex.elements("term")) {
            Concept c = new Concept(
                    baseURI.resolve(replaceSpace(termElement.element("caption").elementText("langstring"))));
            conceptIdToName.put(baseURI.resolve(termElement.elementText("termIdentifier")), c.getUri());
            conceptMap.put(c.getUri(), c);
            c.setProperty("cam.model.guid", cam.element("header").elementText("modeluuid"));
            c.setProperty("cam.concept.guid", termElement.elementText("termIdentifier"));
            Attribute a;
            try {
                a = makeAttribute("resource", resourceCode(termElement), "", "java.lang.String", false);
                addResourceAttributes(a, termElement);
                c.addAttribute(a);
            } catch (Exception e) {
            }
            c.setProperty("title", termElement.element("caption").elementText("langstring"));
            if (termElement.elements("metadata").size() > 0)
                addConceptProperties(c, termElement.element("metadata"));
        }
        for (Element relElement : (Collection<Element>) vdex.elements("relationship")) {
            ConceptRelation cr = new ConceptRelation(relElement.elementText("relationshipType"));
            cr.changeInConcept(
                    conceptMap.get(conceptIdToName.get(baseURI.resolve(relElement.elementText("sourceTerm")))));
            cr.changeOutConcept(
                    conceptMap.get(conceptIdToName.get(baseURI.resolve(relElement.elementText("targetTerm")))));
        }
    }
    Element crts = cam.element("body").element("cam").element("camInternal").element("crtModel");
    for (Element crtElement : (Collection<Element>) crts.elements("model")) {
        CRT crt = CRT.parse(crtElement);
        crtMap.put(crt.getUid(), crt);
    }
    for (Element crtElement : (Collection<Element>) cam.element("body").element("cam").element("camInternal")
            .elements("crt"))
        interpretCRT(crtElement, baseURI);
    List<Concept> resultList = new LinkedList<Concept>();
    resultList.addAll(conceptMap.values());
    for (Concept c : resultList) {
        if (c.getAttribute("visited") == null) {
            Attribute a = makeAttribute("visited", "0", "", "java.lang.Integer", true);
            c.addAttribute(a);
        }
        if (c.getAttribute("suitability") == null) {
            Attribute a = makeAttribute("suitability", "true", "", "java.lang.Boolean", false);
            c.addAttribute(a);
        }
        for (Attribute a : c.getAttributes()) {
            String pubString = a.getProperty("public");
            if (pubString != null && !"false".equals(pubString))
                a.setProperty("persistent", "true");
        }
    }
    return resultList;
}

From source file:nl.tue.gale.ae.grapple.CAMFormat.java

License:Open Source License

private void addResourceAttributes(Attribute a, Element termElement) {
    @SuppressWarnings("unchecked")
    List<Element> rlist = (List<Element>) termElement.elements("mediaDescriptor");
    rlist = ImmutableList.copyOf(rlist);
    for (Element urlElement : rlist) {
        String label = getResourceProperty(termElement, urlElement, "label");
        if (label != null)
            a.setProperty(label, urlElement.elementText("mediaLocator"));
    }//from   w  w  w.j  a v a 2s  .  c om
}

From source file:nl.tue.gale.ae.grapple.CAMFormat.java

License:Open Source License

@SuppressWarnings("unchecked")
private String resourceCode(Element termElement) {
    List<Element> rlist = new ArrayList<Element>();
    rlist.addAll(termElement.elements("mediaDescriptor"));
    Collections.reverse(rlist);//from   ww w.j a  v a 2 s.  c om
    if (rlist.size() == 0)
        return "\"gale:/empty.xhtml\"";
    if (rlist.size() == 1)
        return "\"" + rlist.get(0).elementText("mediaLocator") + "\"";
    StringBuilder result = new StringBuilder();
    result.append("\"gale:/empty.xhtml\"");
    for (Element urlElement : rlist) {
        String expr = getResourceProperty(termElement, urlElement, "expr");
        if (expr == null)
            expr = "true";

        // build part of resource string
        result.insert(0, "\":");
        result.insert(0, urlElement.elementText("mediaLocator"));
        result.insert(0, "?\"");
        result.insert(0, expr);
        result.insert(0, "(");
        result.append(")");
    }
    return result.toString();
}

From source file:nl.tue.gale.ae.grapple.CAMFormat.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addConceptProperties(Concept c, Element element) {
    for (Element prop : (List<Element>) element.elements("concept")) {
        Element entry = prop.element("lom").element("general").element("catalogentry");
        String name = entry.elementText("catalog");
        String value = entry.element("entry").elementText("langstring");
        c.setProperty(name, value);//ww  w. j ava  2 s.  c  o  m
    }
}

From source file:nl.tue.gale.ae.grapple.CAMFormat.java

License:Open Source License

@SuppressWarnings("unchecked")
private void interpretCRT(Element crtElement, URI baseURI) {
    CRT crt = crtMap.get(crtElement.elementText("uuid"));
    if (crt == null)
        throw new IllegalArgumentException(
                "the CRT '" + crtElement.elementText("uuid") + "' is referenced but not included");
    Map<String, Set<URI>> socketData = new HashMap<String, Set<URI>>();
    for (Element crtSocketElement : (Collection<Element>) crtElement.elements("camSocket")) {
        CRTsocket socket = crt.getSocketById(crtSocketElement.elementText("socketid"));
        Set<URI> cList = new HashSet<URI>();
        socketData.put(socket.getUid(), cList);
        for (Element entityElement : (Collection<Element>) crtSocketElement.elements("entity")) {
            Concept c = conceptMap.get(conceptIdToName.get(baseURI.resolve(entityElement.elementText("dmId"))));
            if (c == null)
                throw new IllegalArgumentException("unable to find DM concept with ID '"
                        + entityElement.elementText("dmId") + "' mentioned in CRT '" + crt.getName() + "'");
            cList.add(c.getUri());/*from www. j  a  v  a 2 s  .  c om*/
        }
    }
    for (CRTvar var : crt.getVariables()) {
        Set<URI> cList = socketData.get(crt.getSocketByName(var.getSocketName()).getUid());
        if (cList == null)
            throw new IllegalArgumentException(
                    "the CRT '" + crt.getName() + "' has UM variables that refer to non-existing sockets");
        for (URI cname : cList) {
            Concept c = conceptMap.get(cname);
            if (c.getAttribute(var.getName()) == null) {
                Attribute attr = makeAttribute(var.getName(), var.getDefaultVar(), "", var.getJavaType(),
                        var.isPersistent());
                if (var.getRange() != null)
                    attr.setProperty("gumf.range", var.getRange());
                if (var.isPublicVar()) {
                    attr.setProperty("persistent", "true");
                    attr.setProperty("public", c.getUri().resolve("#" + attr.getName()).toString());
                    attr.setProperty("authorative", (var.isPersistent() ? "true" : "false"));
                }
                c.addAttribute(attr);
            } else {
                if (!var.getJavaType().equals(c.getAttribute(var.getName()).getType()))
                    throw new IllegalArgumentException("attribute type mismatch in CRT '" + crt.getName()
                            + "' (" + var.getName() + "): '" + var.getJavaType() + "' cannot be assigned to '"
                            + c.getAttribute(var.getName()).getType() + "'");
            }
        }
    }
    Pointer<String, URI> socketPointer = null;
    try {
        socketPointer = new Pointer<String, URI>(socketData);
    } catch (Exception e) {
        throw new IllegalArgumentException("empty socket in CRT '" + crt.getName() + "'", e);
    }
    String crtGUID = GaleUtil.newGUID();
    while (socketPointer.hasPointer()) {
        String code = crt.getCode();
        Map<String, URI> current = socketPointer.current();
        for (String socketId : current.keySet()) {
            CRTsocket s = crt.getSocketById(socketId);
            try {
                code = code.replace("%" + s.getName() + "%", current.get(socketId).toString());
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "the CRT '" + crt.getName() + "' has code that refers to socket '" + s.getName()
                                + "' that does not exist in the definition",
                        e);
            }
        }
        for (Element param : (List<Element>) crtElement.elements("parameter")) {
            String pname = param.attributeValue("name");
            String pvalue = param.getText();
            code = code.replace("%" + pname + "%", pvalue);
        }
        try {
            List<Concept> codeConcepts = GAMFormat.readGAM(code, baseURI, dm);
            for (Concept c : codeConcepts)
                interpretConceptAdditions(c, crtGUID);
        } catch (Exception e) {
            throw new IllegalArgumentException(
                    "the CRT '" + crt.getName() + "' has errors in its code: " + e.getMessage(), e);
        }
        socketPointer.next();
    }
}

From source file:nl.tue.gale.ae.impl.SAMLServlet.java

License:Open Source License

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sxml = new String(Base64.decode(req.getParameter("SAMLResponse")), "UTF-8");
    BufferedReader br = new BufferedReader(new StringReader(sxml));
    Document xml = GaleUtil.parseXML(br);
    String userid = null;/* ww w. java  2 s  .  co m*/
    String email = "unknown email";
    String name = "unknown user";
    String firstname = null;
    String lastname = null;
    for (Element assertion : (List<Element>) xml.getRootElement().elements("Assertion")) {
        for (Element attributeStatement : (List<Element>) assertion.elements("AttributeStatement")) {
            for (Element attribute : (List<Element>) attributeStatement.elements("Attribute")) {
                String attrname = attribute.attributeValue("Name");
                String attrvalue = attribute.elementText("AttributeValue");
                if ("urn:oid:2.5.4.4".equals(attrname))
                    lastname = attrvalue;
                if ("urn:oid:2.5.4.3".equals(attrname))
                    userid = attrvalue;
                if ("urn:oid:0.9.2342.19200300.100.1.3".equals(attrname))
                    email = attrvalue;
                if ("urn:oid:2.5.4.42".equals(attrname))
                    firstname = attrvalue;
            }
        }
    }
    if (firstname == null && lastname == null) {
        if (userid != null)
            name = userid;
    } else if (firstname == null)
        name = lastname;
    else if (lastname == null)
        name = firstname;
    else
        name = firstname + " " + lastname;

    GaleContext gc = getGaleContext(req, resp);
    UserEntityCache userEntityCache = gc.uec();
    UMCache umCache = gc.um();
    CacheSession<UserEntity> entitySession = userEntityCache.openSession();
    UserEntity entity = entitySession.get(UserEntity.getUriFromId(userid));
    if (entity == null) {
        CacheSession<EntityValue> umSession = umCache.openSession();
        entity = new UserEntity(userid);
        entity.setProperty("password", GaleUtil.adminpw);
        entitySession.put(entity.getUri(), entity);
        URI uri = URIs.of("gale://" + entity.getId() + "@gale.tue.nl/personal");
        umSession.put(uri.resolve("#name"), EntityValue.create(uri.resolve("#name"), name));
        umSession.put(uri.resolve("#email"), EntityValue.create(uri.resolve("#email"), email));
        umSession.commit();
    }
    entitySession.commit();

    if (userid != null) {
        req.getSession().setAttribute("nl.tue.gale.userId", userid);
        resp.sendRedirect(req.getParameter("RelayState"));
    } else {
        throw new IllegalArgumentException("unable to login: " + sxml);
    }
}

From source file:nl.tue.gale.ae.processor.xmlmodule.PluginModule.java

License:Open Source License

@SuppressWarnings("unchecked")
public Element traverse(Element element, Resource resource) throws ProcessorException {
    // first process the children (content of new anchor tag)
    processor.traverseChildren(element, resource);
    // create new anchor tag
    Element a = DocumentFactory.getInstance()
            .createElement(DocumentFactory.getInstance().createQName("a", "", "http://www.w3.org/1999/xhtml"));
    // backward compatibility
    List<Element> dlist = element.elements("linkdescription");
    Element parent = (dlist.size() == 0 ? element : dlist.get(0));
    // add children to new anchor tag
    a.appendContent(parent);/*  w  ww. j av  a 2  s  .  c  o m*/
    /*
     * List<Node> nodes = new ArrayList<Node>(); for (Node node :
     * (List<Node>) parent.content()) nodes.add(node); for (Node node :
     * nodes) a.(node);
     */
    // plugin name
    String name = element.attributeValue("name");
    if (name == null)
        name = element.elementText("name");
    // add parameters
    URI reqUri = URIs.of(GaleContext.req(resource).getRequestURL().toString());
    Map<String, String> params = new HashMap<String, String>();
    params.put("plugin", name);
    for (Element child : (List<Element>) element.elements("param"))
        params.put(child.attributeValue("name"), child.attributeValue("value"));
    reqUri = GaleUtil.setURIPart(reqUri, GaleUtil.URIPart.QUERY, GaleUtil.getQueryString(params));
    // finish the new anchor tag
    a.addAttribute("href", reqUri.toString());
    a.addAttribute("class", "good");
    // replace the original tag by the new anchor tag
    GaleUtil.replaceNode(element, a);
    return null;
}

From source file:org.b5chat.crossfire.xmpp.auth.IQAuthHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    JID from = packet.getFrom();//from  www  .j a  va  2  s. c o  m
    LocalClientSession session = (LocalClientSession) sessionManager.getSession(from);
    // If no session was found then answer an error (if possible)
    if (session == null) {
        Log.error("Error during authentication. ISession not found in "
                + sessionManager.getPreAuthenticatedKeys() + " for key " + from);
        // This error packet will probably won't make it through
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }
    IQ response;
    boolean resourceBound = false;
    if (Globals.getBooleanProperty("xmpp.auth.iqauth", true)) {
        try {
            Element iq = packet.getElement();
            Element query = iq.element("query");
            Element queryResponse = probeResponse.createCopy();
            if (IQ.Type.get == packet.getType()) {
                String username = query.elementText("username");
                if (username != null) {
                    queryResponse.element("username").setText(username);
                }
                response = IQ.createResultIQ(packet);
                response.setChildElement(queryResponse);
                // This is a workaround. Since we don't want to have an incorrect TO attribute
                // value we need to clean up the TO attribute and send directly the response.
                // The TO attribute will contain an incorrect value since we are setting a fake
                // JID until the user actually authenticates with the server.
                if (session.getStatus() != ISession.STATUS_AUTHENTICATED) {
                    response.setTo((JID) null);
                }
            }
            // Otherwise set query
            else {
                if (query.elements().isEmpty()) {
                    // Anonymous authentication
                    response = anonymousLogin(session, packet);
                    resourceBound = session.getStatus() == ISession.STATUS_AUTHENTICATED;
                } else {
                    String username = query.elementText("username");
                    // Login authentication
                    String password = query.elementText("password");
                    String digest = null;
                    if (query.element("digest") != null) {
                        digest = query.elementText("digest").toLowerCase();
                    }

                    // If we're already logged in, this is a password reset
                    if (session.getStatus() == ISession.STATUS_AUTHENTICATED) {
                        // Check that a new password has been specified
                        if (password == null || password.trim().length() == 0) {
                            response = IQ.createResultIQ(packet);
                            response.setError(PacketError.Condition.not_allowed);
                            response.setType(IQ.Type.error);
                        } else {
                            // Check if a user is trying to change his own password
                            if (session.getUsername().equalsIgnoreCase(username)) {
                                response = passwordReset(password, packet, username, session);
                            }
                            // Check if an admin is trying to set the password for another user
                            else if (XmppServer.getInstance().getAdmins()
                                    .contains(new JID(from.getNode(), from.getDomain(), null, true))) {
                                response = passwordReset(password, packet, username, session);
                            } else {
                                // User not authorized to change the password of another user
                                throw new UnauthorizedException();
                            }
                        }
                    } else {
                        // it is an auth attempt
                        response = login(username, query, packet, password, session, digest);
                        resourceBound = session.getStatus() == ISession.STATUS_AUTHENTICATED;
                    }
                }
            }
        } catch (UserNotFoundException e) {
            response = IQ.createResultIQ(packet);
            response.setChildElement(packet.getChildElement().createCopy());
            response.setError(PacketError.Condition.not_authorized);
        } catch (UnauthorizedException e) {
            response = IQ.createResultIQ(packet);
            response.setChildElement(packet.getChildElement().createCopy());
            response.setError(PacketError.Condition.not_authorized);
        } catch (ConnectionException e) {
            response = IQ.createResultIQ(packet);
            response.setChildElement(packet.getChildElement().createCopy());
            response.setError(PacketError.Condition.internal_server_error);
        } catch (InternalUnauthenticatedException e) {
            response = IQ.createResultIQ(packet);
            response.setChildElement(packet.getChildElement().createCopy());
            response.setError(PacketError.Condition.internal_server_error);
        }
    } else {
        response = IQ.createResultIQ(packet);
        response.setChildElement(packet.getChildElement().createCopy());
        response.setError(PacketError.Condition.not_authorized);
    }
    // Send the response directly since we want to be sure that we are sending it back
    // to the correct session. Any other session of the same user but with different
    // resource is incorrect.
    session.process(response);
    if (resourceBound) {
        // After the client has been informed, inform all listeners as well.
        SessionEventDispatcher.dispatchEvent(session, SessionEventDispatcher.EventType.resource_bound);
    }
    return null;
}

From source file:org.b5chat.crossfire.xmpp.auth.IQAuthHandler.java

License:Open Source License

private IQ login(String username, Element iq, IQ packet, String password, LocalClientSession session,
        String digest) throws UnauthorizedException, UserNotFoundException, ConnectionException,
        InternalUnauthenticatedException {
    // Verify the validity of the username
    if (username == null || username.trim().length() == 0) {
        throw new UnauthorizedException("Invalid username (empty or null).");
    }/*  w  ww  . ja va  2 s . c  om*/
    try {
        Stringprep.nodeprep(username);
    } catch (StringprepException e) {
        throw new UnauthorizedException("Invalid username: " + username, e);
    }

    // Verify that specified resource is not violating any string prep rule
    String resource = iq.elementText("resource");
    if (resource != null) {
        try {
            resource = JID.resourceprep(resource);
        } catch (StringprepException e) {
            throw new UnauthorizedException("Invalid resource: " + resource, e);
        }
    } else {
        // Answer a not_acceptable error since a resource was not supplied
        IQ response = IQ.createResultIQ(packet);
        response.setChildElement(packet.getChildElement().createCopy());
        response.setError(PacketError.Condition.not_acceptable);
        return response;
    }
    if (!Globals.getBooleanProperty("xmpp.auth.iqauth", true)) {
        throw new UnauthorizedException();
    }
    username = username.toLowerCase();
    // Verify that supplied username and password are correct (i.e. user authentication was successful)
    AuthToken token = null;
    if (password != null && AuthFactory.isPlainSupported()) {
        token = AuthFactory.authenticate(username, password);
    } else if (digest != null && AuthFactory.isDigestSupported()) {
        token = AuthFactory.authenticate(username, session.getStreamID().toString(), digest);
    }
    if (token == null) {
        throw new UnauthorizedException();
    }
    // Verify if there is a resource conflict between new resource and existing one.
    // Check if a session already exists with the requested full JID and verify if
    // we should kick it off or refuse the new connection
    IClientSession oldSession = routingTable.getClientRoute(new JID(username, serverName, resource, true));
    if (oldSession != null) {
        try {
            int conflictLimit = sessionManager.getConflictKickLimit();
            if (conflictLimit == SessionManager.NEVER_KICK) {
                IQ response = IQ.createResultIQ(packet);
                response.setChildElement(packet.getChildElement().createCopy());
                response.setError(PacketError.Condition.forbidden);
                return response;
            }

            int conflictCount = oldSession.incrementConflictCount();
            if (conflictCount > conflictLimit) {
                // Send a stream:error before closing the old connection
                StreamError error = new StreamError(StreamError.Condition.conflict);
                oldSession.deliverRawText(error.toXML());
                oldSession.close();
            } else {
                IQ response = IQ.createResultIQ(packet);
                response.setChildElement(packet.getChildElement().createCopy());
                response.setError(PacketError.Condition.forbidden);
                return response;
            }
        } catch (Exception e) {
            Log.error("Error during login", e);
        }
    }
    // Set that the new session has been authenticated successfully
    session.setAuthToken(token, resource);
    packet.setFrom(session.getAddress());
    return IQ.createResultIQ(packet);
}