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:org.jivesoftware.openfire.handler.IQAuthHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    JID from = packet.getFrom();/*  w  w w  . j a  v  a  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. Session 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 (JiveGlobals.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() != Session.STATUS_AUTHENTICATED) {
                    response.setTo((JID) null);
                }
            }
            // Otherwise set query
            else {
                if (query.elements().isEmpty()) {
                    // Anonymous authentication
                    response = anonymousLogin(session, packet);
                    resourceBound = session.getStatus() == Session.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() == Session.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() == Session.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.jivesoftware.openfire.handler.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).");
    }/*from   ww w . j a  va2  s  .c o m*/
    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 (!JiveGlobals.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
    ClientSession 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);
}

From source file:org.jivesoftware.openfire.handler.IQRegisterHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
    ClientSession session = sessionManager.getSession(packet.getFrom());
    IQ reply = null;/*  w w w . j  a  va2 s  .co  m*/
    // If no session was found then answer an error (if possible)
    if (session == null) {
        Log.error("Error during registration. Session not found in " + sessionManager.getPreAuthenticatedKeys()
                + " for key " + packet.getFrom());
        // This error packet will probably won't make it through
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }
    if (IQ.Type.get.equals(packet.getType())) {
        // If inband registration is not allowed, return an error.
        if (!registrationEnabled) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.forbidden);
        } else {
            reply = IQ.createResultIQ(packet);
            if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                try {
                    User user = userManager.getUser(session.getUsername());
                    Element currentRegistration = probeResult.createCopy();
                    currentRegistration.addElement("registered");
                    currentRegistration.element("username").setText(user.getUsername());
                    currentRegistration.element("password").setText("");
                    currentRegistration.element("email")
                            .setText(user.getEmail() == null ? "" : user.getEmail());
                    currentRegistration.element("name").setText(user.getName());

                    Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
                    Iterator fields = form.elementIterator("field");
                    Element field;
                    while (fields.hasNext()) {
                        field = (Element) fields.next();
                        if ("username".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getUsername());
                        } else if ("name".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getName());
                        } else if ("email".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getEmail() == null ? "" : user.getEmail());
                        }
                    }
                    reply.setChildElement(currentRegistration);
                } catch (UserNotFoundException e) {
                    reply.setChildElement(probeResult.createCopy());
                }
            } else {
                // This is a workaround. Since we don't want to have an incorrect TO attribute
                // value we need to clean up the TO attribute. The TO attribute will contain an
                // incorrect value since we are setting a fake JID until the user actually
                // authenticates with the server.
                reply.setTo((JID) null);
                reply.setChildElement(probeResult.createCopy());
            }
        }
    } else if (IQ.Type.set.equals(packet.getType())) {
        try {
            Element iqElement = packet.getChildElement();
            if (iqElement.element("remove") != null) {
                // If inband registration is not allowed, return an error.
                if (!registrationEnabled) {
                    reply = IQ.createResultIQ(packet);
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.forbidden);
                } else {
                    if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                        User user = userManager.getUser(session.getUsername());
                        // Delete the user
                        userManager.deleteUser(user);
                        // Delete the roster of the user
                        rosterManager.deleteRoster(session.getAddress());
                        // Delete the user from all the Groups
                        GroupManager.getInstance().deleteUser(user);

                        reply = IQ.createResultIQ(packet);
                        session.process(reply);
                        // Take a quick nap so that the client can process the result
                        Thread.sleep(10);
                        // Close the user's connection
                        final StreamError error = new StreamError(StreamError.Condition.not_authorized);
                        for (ClientSession sess : sessionManager.getSessions(user.getUsername())) {
                            sess.deliverRawText(error.toXML());
                            sess.close();
                        }
                        // The reply has been sent so clean up the variable
                        reply = null;
                    } else {
                        throw new UnauthorizedException();
                    }
                }
            } else {
                String username;
                String password = null;
                String email = null;
                String name = null;
                User newUser;
                DataForm registrationForm;
                FormField field;

                Element formElement = iqElement.element("x");
                // Check if a form was used to provide the registration info
                if (formElement != null) {
                    // Get the sent form
                    registrationForm = new DataForm(formElement);
                    // Get the username sent in the form
                    List<String> values = registrationForm.getField("username").getValues();
                    username = (!values.isEmpty() ? values.get(0) : " ");
                    // Get the password sent in the form
                    field = registrationForm.getField("password");
                    if (field != null) {
                        values = field.getValues();
                        password = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the email sent in the form
                    field = registrationForm.getField("email");
                    if (field != null) {
                        values = field.getValues();
                        email = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the name sent in the form
                    field = registrationForm.getField("name");
                    if (field != null) {
                        values = field.getValues();
                        name = (!values.isEmpty() ? values.get(0) : " ");
                    }
                } else {
                    // Get the registration info from the query elements
                    username = iqElement.elementText("username");
                    password = iqElement.elementText("password");
                    email = iqElement.elementText("email");
                    name = iqElement.elementText("name");
                }
                if (email != null && email.matches("\\s*")) {
                    email = null;
                }
                if (name != null && name.matches("\\s*")) {
                    name = null;
                }

                // So that we can set a more informative error message back, lets test this for
                // stringprep validity now.
                if (username != null) {
                    Stringprep.nodeprep(username);
                }

                if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                    // Flag that indicates if the user is *only* changing his password
                    boolean onlyPassword = false;
                    if (iqElement.elements().size() == 2 && iqElement.element("username") != null
                            && iqElement.element("password") != null) {
                        onlyPassword = true;
                    }
                    // If users are not allowed to change their password, return an error.
                    if (password != null && !canChangePassword) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    }
                    // If inband registration is not allowed, return an error.
                    else if (!onlyPassword && !registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    } else {
                        User user = userManager.getUser(session.getUsername());
                        if (user.getUsername().equalsIgnoreCase(username)) {
                            if (password != null && password.trim().length() > 0) {
                                user.setPassword(password);
                            }
                            if (!onlyPassword) {
                                user.setEmail(email);
                            }
                            newUser = user;
                        } else if (password != null && password.trim().length() > 0) {
                            // An admin can create new accounts when logged in.
                            newUser = userManager.createUser(username, password, null, email);
                        } else {
                            // Deny registration of users with no password
                            reply = IQ.createResultIQ(packet);
                            reply.setChildElement(packet.getChildElement().createCopy());
                            reply.setError(PacketError.Condition.not_acceptable);
                            return reply;
                        }
                    }
                } else {
                    // If inband registration is not allowed, return an error.
                    if (!registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    }
                    // Inform the entity of failed registration if some required
                    // information was not provided
                    else if (password == null || password.trim().length() == 0) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.not_acceptable);
                        return reply;
                    } else {
                        // Create the new account
                        newUser = userManager.createUser(username, password, name, email);
                    }
                }
                // Set and save the extra user info (e.g. full name, etc.)
                if (newUser != null && name != null && !name.equals(newUser.getName())) {
                    newUser.setName(name);
                }

                reply = IQ.createResultIQ(packet);
            }
        } catch (UserAlreadyExistsException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.conflict);
        } catch (UserNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.bad_request);
        } catch (StringprepException e) {
            // The specified username is not correct according to the stringprep specs
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.jid_malformed);
        } catch (IllegalArgumentException e) {
            // At least one of the fields passed in is not valid
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_acceptable);
            Log.warn(e.getMessage(), e);
        } catch (UnsupportedOperationException e) {
            // The User provider is read-only so this operation is not allowed
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_allowed);
        } catch (Exception e) {
            // Some unexpected error happened so return an internal_server_error
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            Log.error(e.getMessage(), e);
        }
    }
    if (reply != null) {
        // why is this done here instead of letting the iq handler do it?
        session.process(reply);
    }
    return null;
}

From source file:org.jivesoftware.openfire.net.SocketReadingMode.java

License:Open Source License

/**
 * Start using compression but first check if the connection can and should use compression.
 * The connection will be closed if the requested method is not supported, if the connection
 * is already using compression or if client requested to use compression but this feature
 * is disabled./*  w  ww.  ja  v  a  2  s .c o  m*/
 *
 * @param doc the element sent by the client requesting compression. Compression method is
 *        included.
 * @return true if it was possible to use compression.
 * @throws IOException if an error occurs while starting using compression.
 */
protected boolean compressClient(Element doc) throws IOException, XmlPullParserException {
    String error = null;
    if (socketReader.connection.getCompressionPolicy() == Connection.CompressionPolicy.disabled) {
        // Client requested compression but this feature is disabled
        error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
        // Log a warning so that admins can track this case from the server side
        Log.warn("Client requested compression while compression is disabled. Closing " + "connection : "
                + socketReader.connection);
    } else if (socketReader.connection.isCompressed()) {
        // Client requested compression but connection is already compressed
        error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
        // Log a warning so that admins can track this case from the server side
        Log.warn("Client requested compression and connection is already compressed. Closing " + "connection : "
                + socketReader.connection);
    } else {
        // Check that the requested method is supported
        String method = doc.elementText("method");
        if (!"zlib".equals(method)) {
            error = "<failure xmlns='http://jabber.org/protocol/compress'><unsupported-method/></failure>";
            // Log a warning so that admins can track this case from the server side
            Log.warn("Requested compression method is not supported: " + method + ". Closing connection : "
                    + socketReader.connection);
        }
    }

    if (error != null) {
        // Deliver stanza
        socketReader.connection.deliverRawText(error);
        return false;
    } else {
        // Start using compression for incoming traffic
        socketReader.connection.addCompression();

        // Indicate client that he can proceed and compress the socket
        socketReader.connection.deliverRawText("<compressed xmlns='http://jabber.org/protocol/compress'/>");

        // Start using compression for outgoing traffic
        socketReader.connection.startCompression();
        return true;
    }
}

From source file:org.jivesoftware.openfire.net.StanzaHandler.java

License:Open Source License

/**
 * Start using compression but first check if the connection can and should use compression.
 * The connection will be closed if the requested method is not supported, if the connection
 * is already using compression or if client requested to use compression but this feature
 * is disabled.//  w ww.j av  a 2s.c o  m
 *
 * @param doc the element sent by the client requesting compression. Compression method is
 *            included.
 * @return true if it was possible to use compression.
 */
private boolean compressClient(Element doc) {
    String error = null;
    if (connection.getCompressionPolicy() == Connection.CompressionPolicy.disabled) {
        // Client requested compression but this feature is disabled
        error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
        // Log a warning so that admins can track this case from the server side
        Log.warn("Client requested compression while compression is disabled. Closing " + "connection : "
                + connection);
    } else if (connection.isCompressed()) {
        // Client requested compression but connection is already compressed
        error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
        // Log a warning so that admins can track this case from the server side
        Log.warn("Client requested compression and connection is already compressed. Closing " + "connection : "
                + connection);
    } else {
        // Check that the requested method is supported
        String method = doc.elementText("method");
        if (!"zlib".equals(method)) {
            error = "<failure xmlns='http://jabber.org/protocol/compress'><unsupported-method/></failure>";
            // Log a warning so that admins can track this case from the server side
            Log.warn("Requested compression method is not supported: " + method + ". Closing connection : "
                    + connection);
        }
    }

    if (error != null) {
        // Deliver stanza
        connection.deliverRawText(error);
        return false;
    } else {
        // Start using compression for incoming traffic
        connection.addCompression();

        // Indicate client that he can proceed and compress the socket
        connection.deliverRawText("<compressed xmlns='http://jabber.org/protocol/compress'/>");

        // Start using compression for outgoing traffic
        connection.startCompression();
        return true;
    }
}

From source file:org.jivesoftware.phone.xmpp.PacketHandler.java

License:Open Source License

public void handleDial(IQ iq) {
    JID jid = iq.getFrom();//from   ww w . j av  a  2 s  .co  m

    Element phoneElement = iq.getChildElement();

    try {

        String extension = phoneElement.elementText("extension");
        if (extension != null) {
            phoneManager.originate(jid.getNode(), extension);
        }
        // try dialing by jid
        else {
            String targetJID = phoneElement.elementText("jid");
            if (targetJID == null) {
                throw new PhoneException("No extension or jid was specified");
            }

            phoneManager.originate(jid.getNode(), new JID(targetJID));
        }

        //send reply
        IQ reply = IQ.createResultIQ(iq);
        reply.setType(IQ.Type.result);

        PhoneAction phoneAction = new PhoneAction(PhoneAction.Type.DIAL);
        reply.setChildElement(phoneAction);

        send(reply);

    } catch (PhoneException e) {
        Log.debug(e);
        IQ reply = IQ.createResultIQ(iq);
        reply.setType(IQ.Type.error);
        PacketError error = new PacketError(PacketError.Condition.undefined_condition, PacketError.Type.cancel,
                e.getMessage());
        reply.setError(error);
        send(reply);
    }
}

From source file:org.jivesoftware.phone.xmpp.PacketHandler.java

License:Open Source License

public void handleForward(IQ iq) {

    Element phoneElement = iq.getChildElement();

    try {// w w  w  .  ja  v a 2 s  . co  m
        String callSessionID = phoneElement.attributeValue("id");

        if (callSessionID == null || "".equals(callSessionID)) {
            throw new PhoneException("a call 'id' is a required attribute for type FORWARD");
        }

        String extension = phoneElement.elementText("extension");
        if (extension != null && !"".equals(extension)) {
            phoneManager.forward(callSessionID, iq.getFrom().getNode(), extension);
        }
        // try dialing by jid
        else {
            String targetJID = phoneElement.elementText("jid");
            if (targetJID == null) {
                throw new PhoneException("No extension or jid was specified");
            }

            iq.getFrom().getNode();

            phoneManager.forward(callSessionID, iq.getFrom().getNode(), new JID(targetJID));
        }

        //send reply
        IQ reply = IQ.createResultIQ(iq);
        reply.setType(IQ.Type.result);

        PhoneAction phoneAction = new PhoneAction(PhoneAction.Type.FORWARD);
        reply.setChildElement(phoneAction);

        send(reply);

    } catch (PhoneException e) {
        Log.debug(e);
        IQ reply = IQ.createResultIQ(iq);
        reply.setType(IQ.Type.error);
        PacketError error = new PacketError(PacketError.Condition.undefined_condition, PacketError.Type.cancel,
                e.getMessage());
        reply.setError(error);
        send(reply);
    }

}

From source file:org.jivesoftware.smack.util.PacketParserUtils.java

License:Open Source License

/**
 * Parses stream error packets./*  www . ja  v  a  2  s .c  o m*/
 * 
 * @param doc
 *            the XML parser.
 * @return an stream error packet.
 * @throws Exception
 *             if an exception occurs while parsing the packet.
 */
public static StreamError parseStreamError(Element el) throws IOException, XmlPullParserException {
    String code = null;
    Element condEl = (Element) el.elements().iterator().next();
    if (condEl.getNamespace().getURI().equals(StreamError.NAMESPACE)) {
        code = condEl.getName();
    }
    String text = condEl.elementText("text");
    return new StreamError(code, text);
}

From source file:org.makumba.commons.tags.MakumbaTLDGenerator.java

License:Open Source License

/**
 * Generates a TLD based on its makumba skeleton
 * //from   w w w.j  a v  a2  s. com
 * @param sourcePath
 *            path to the documented source XML file to parse
 * @param jspTldPath
 *            path to the output TLD file
 * @param documentationPath
 *            path to the makumba documentation pages (JSPwiki)
 */
public void generateTLD(final String sourcePath, final String jspTldPath, final String jspTldPathHibernate,
        final String documentationPath) {

    HashMap<String, Element> processedTags = new HashMap<String, Element>();

    // read the documented XML files
    SAXReader saxReader = new SAXReader();
    Document document = null;
    try {
        document = saxReader.read(sourcePath);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    final String errorMsg = "Error processing '" + sourcePath + "': ";

    Element root = document.getRootElement();
    for (Element tag : getElementList(root)) {
        if (tag.getName().equals("description")) {
            // update makumba version place-holder
            tag.setText(tag.getText().replace("@version@", version.getVersion()));
        }
        if (StringUtils.equalsAny(tag.getName(), "tag", "function")) {
            boolean isTag = tag.getName().equals("tag");
            String tagName = tag.element(getTagName()).getText();

            for (Element tagContent : getElementList(tag)) {

                if (tagContent.getName().equals("attribute")) {
                    if (tagContent.attributeValue("name") != null
                            && tagContent.attributeValue("specifiedIn") != null) { // have a referring attribute
                        replaceReferencedAttribute(processedTags, errorMsg, tagName, tagContent);
                    } else { // normal attribute
                        for (Element attributeContent : getElementList(tagContent)) {
                            String inheritedFrom = null;
                            if (attributeContent.getName().equals("inheritedFrom")) {
                                inheritedFrom = attributeContent.getText();
                            }

                            // remove all the tags for makumba documentation generation inside <attribute> elements
                            if (StringUtils.equalsAny(attributeContent.getName(), "comments", "deprecated",
                                    "descriptionPage", "commentsPage", "inheritedFrom")) {
                                attributeContent.getParent().remove(attributeContent);
                            }

                            // generate description and comment pages for an attribute
                            if (attributeContent.getName().equals("description")) {

                                // insert the description
                                String descriptionFileName = "";
                                if (inheritedFrom != null) {
                                    descriptionFileName += org.apache.commons.lang.StringUtils
                                            .capitalize(inheritedFrom) + (isTag ? "Tag" : "Function");
                                } else {
                                    descriptionFileName += org.apache.commons.lang.StringUtils
                                            .capitalize(tagName) + (isTag ? "Tag" : "Function");
                                }
                                descriptionFileName += "Attribute" + org.apache.commons.lang.StringUtils
                                        .capitalize(tagContent.elementText("name")) + "AttributeDescription";

                                File d = new File(
                                        documentationPath + File.separator + descriptionFileName + ".txt");
                                if (!d.exists()) {
                                    System.err.println("Could not find attribute description file " + d);
                                }

                                String desc = "";

                                if (d.exists()) {
                                    try {
                                        desc = readFileAsString(d.getAbsolutePath());
                                    } catch (IOException e) {
                                        System.err.println("Could not read attribute description file " + d);
                                    }
                                }
                                attributeContent.setText(desc.trim());
                            }
                        }
                    }
                }

                // remove the invalid tags
                if (StringUtils.equalsAny(tagContent.getName(), "see", "example")) {
                    tagContent.getParent().remove(tagContent);
                }

                // if we have a descriptionPage instead of a raw text, use the content of that page
                if (tagContent.getName().equals("descriptionPage")) {
                    String descriptionFileName = org.apache.commons.lang.StringUtils.capitalize(tagName)
                            + (isTag ? "Tag" : "Function") + "Description";
                    String desc = "";
                    try {
                        desc = readFileAsString(
                                documentationPath + File.separator + descriptionFileName + ".txt");
                    } catch (IOException e1) {
                        System.err.println("Could not read tag description file " + documentationPath
                                + File.separator + descriptionFileName + ".txt");
                    }
                    Element d = null;
                    if ((d = tagContent.getParent().element("description")) == null) {
                        d = tagContent.getParent().addElement("description");
                    }
                    d.setText(desc.trim());
                    tagContent.getParent().remove(tagContent);
                }
            }
            processedTags.put(tagName, tag);
        }
    }

    // generate the clean TLD
    System.out.println("Writing general Makumba TLD at path " + jspTldPath);
    try {
        File path = new File(jspTldPath);
        path.getParentFile().mkdirs();
        XMLWriter output = new XMLWriter(new FileWriter(path), new OutputFormat("", false));
        output.write(document);
        output.close();
    } catch (IOException e1) {
        System.out.println(e1.getMessage());
    }

    // generate hibernate TLD

    Document hibernateTLD = document;
    hibernateTLD.getRootElement().element("uri").setText(HIBERNATE_TLD_URI);

    System.out.println("Writing hibernate Makumba TLD at path " + jspTldPathHibernate);
    try {
        XMLWriter output = new XMLWriter(new FileWriter(new File(jspTldPathHibernate)),
                new OutputFormat("", false));
        output.write(document);
        output.close();
    } catch (IOException e1) {
        System.out.println(e1.getMessage());
    }

    // here we could now also generate the list-hql, forms-hql, ... TLDs
    // this would be easily done by defining an array of tags that should be in each of them, iterate over all the
    // tags in the doc
    // and take only the right ones
    // and then write this with the right URL

}

From source file:org.neo4j.neoclipse.connection.Alias.java

License:Apache License

/**
 * Constructs an Alias from XML, previously obtained from describeAsXml()
 * //w w  w  .  ja v  a2  s  . c o m
 * @param root
 */
public Alias(Element root) {
    name = root.elementText(NAME);
    uri = root.elementText(URI);
    connectionMode = ConnectionMode.getValue(uri);
    String user = root.elementText(USER_NAME);
    String pass = root.elementText(PASSWORD);
    if (!ApplicationUtil.isBlank(user)) {
        userName = user;
    }
    if (!ApplicationUtil.isBlank(pass)) {
        password = pass;
    }

    Element configurationsElement = root.element(CONFIGURATIONS);
    if (configurationsElement != null) {
        List<Element> elements = configurationsElement.elements(CONFIG);
        for (Element config : elements) {
            String configName = config.attributeValue(CONFIG_NAME);
            String configValue = config.attributeValue(CONFIG_VALUE);
            addConfiguration(configName, configValue);
        }
    }
}