Example usage for org.dom4j QName get

List of usage examples for org.dom4j QName get

Introduction

In this page you can find the example usage for org.dom4j QName get.

Prototype

public static QName get(String qualifiedName, String uri) 

Source Link

Usage

From source file:org.onesocialweb.openfire.handler.profile.IQProfilePublishHandler.java

License:Apache License

@SuppressWarnings("deprecation")
@Override/*from w w  w. j  av a 2  s  . c  om*/
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    final JID sender = packet.getFrom();
    final JID recipient = packet.getTo();

    // Process the request inside a try/catch so that unhandled exceptions
    // (oufofbounds etc...) can trigger a server error and we can send a
    // error result packet
    try {

        // A valid request is an IQ of type set, 
        if (!packet.getType().equals(IQ.Type.set)) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // If a recipient is specified, it must be equal to the sender
        // bareJID
        if (recipient != null && !recipient.toString().equals(sender.toBareJID())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // Only a local user can publish its profile
        if (!userManager.isRegisteredUser(sender.getNode())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // A valid submit requets must contain a vcard4 entry
        Element request = packet.getChildElement();
        Element e_profile = request.element(QName.get(VCard4.VCARD_ELEMENT, VCard4.NAMESPACE));
        if (e_profile == null) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // Parse the profile
        VCard4DomReader reader = new PersistentVCard4DomReader();
        Profile profile = reader.readProfile(new ElementAdapter(e_profile));

        // Commit the profile (this will also trigger the messages)
        try {
            ProfileManager.getInstance().publishProfile(sender.toBareJID(), profile);
        } catch (UserNotFoundException e) {
            // We know this cannot happen
        }

        // Send a success result
        // TODO should this contain more, like the ID of the new activities ?
        IQ result = IQ.createResultIQ(packet);
        return result;

    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.internal_server_error);
        return result;
    }
}

From source file:org.onesocialweb.openfire.handler.relation.IQRelationSetupHandler.java

License:Apache License

@SuppressWarnings({ "deprecation", "unchecked" })
@Override/* w  w w .jav a2  s  . c o m*/
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    final JID sender = packet.getFrom();
    final JID recipient = packet.getTo();

    // Process the request inside a try/catch so that unhandled exceptions
    // (oufofbounds etc...) can trigger a server error and we can send a
    // error result packet
    try {

        // A valid request is an IQ of type set, 
        if (!packet.getType().equals(IQ.Type.set)) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // If a recipient is specified, it must be equal to the sender
        // bareJID
        if (recipient != null && !recipient.toString().equals(sender.toBareJID())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // Only a local user can publish an activity to his stream
        if (!userManager.isRegisteredUser(sender.getNode())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // A valid submit requets must contain one relation item
        Element request = packet.getChildElement();
        Iterator<Element> i_entry = request.elementIterator(
                QName.get(Onesocialweb.RELATION_ELEMENT, Namespace.get(Onesocialweb.NAMESPACE)));
        if (!i_entry.hasNext()) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // Parse the relation
        RelationDomReader reader = new PersistentRelationDomReader();
        Element e_entry = i_entry.next();
        PersistentRelation relation = (PersistentRelation) reader.readElement(new ElementAdapter(e_entry));
        Log.debug("IQRelationSetup received request: " + relation);

        // Setup the relation (this will also trigger the notification to the user)
        relationManager.setupRelation(sender.toBareJID(), relation);

        // Send a success result
        IQ result = IQ.createResultIQ(packet);
        return result;

    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.internal_server_error);
        return result;
    }
}

From source file:org.onesocialweb.openfire.handler.relation.IQRelationUpdateHandler.java

License:Apache License

@SuppressWarnings({ "deprecation", "unchecked" })
@Override/*w ww. ja  v  a  2 s .c  o m*/
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    final JID sender = packet.getFrom();
    final JID recipient = packet.getTo();

    // Process the request inside a try/catch so that unhandled exceptions
    // (oufofbounds etc...) can trigger a server error and we can send a
    // error result packet
    try {

        // Only a local user can request to update a relation
        if (!userManager.isRegisteredUser(sender.getNode())) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.not_authorized);
            return result;
        }

        // A valid request is an IQ of type set, sent to the bare server
        if ((!packet.getType().equals(IQ.Type.set) || (recipient != null && recipient.getNode() != null))) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // A valid submit requets must contain one relation item
        Element request = packet.getChildElement();
        Iterator<Element> i_entry = request.elementIterator(
                QName.get(Onesocialweb.RELATION_ELEMENT, Namespace.get(Onesocialweb.NAMESPACE)));
        if (!i_entry.hasNext()) {
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.bad_request);
            return result;
        }

        // Parse the relation
        RelationDomReader reader = new PersistentRelationDomReader();
        Element e_entry = i_entry.next();
        PersistentRelation relation = (PersistentRelation) reader.readElement(new ElementAdapter(e_entry));
        Log.debug("IQRelationUpdate received request: " + relation);

        // Setup the relation (this will also trigger the notification to the user)
        relationManager.updateRelation(sender.toBareJID(), relation);

        // Send a success result
        IQ result = IQ.createResultIQ(packet);
        return result;

    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.internal_server_error);
        return result;
    }
}

From source file:org.onesocialweb.openfire.registration.handler.IQRegisterHandler.java

License:Open Source License

public void initialize(XMPPServer server) {
    super.initialize(server);
    userManager = server.getUserManager();
    rosterManager = server.getRosterManager();

    if (probeResult == null) {
        // Create the basic element of the probeResult which contains the basic registration
        // information (e.g. username, passoword and email)
        probeResult = DocumentHelper.createElement(QName.get("query", "jabber:iq:register"));
        probeResult.addElement("username");
        probeResult.addElement("password");
        probeResult.addElement("email");
        probeResult.addElement("name");
        probeResult.addElement("code");

        // Create the registration form to include in the probeResult. The form will include
        // the basic information plus name and visibility of name and email.
        // TODO Future versions could allow plugin modules to add new fields to the form 
        XDataFormImpl registrationForm = new XDataFormImpl(DataForm.TYPE_FORM);
        registrationForm.setTitle("XMPP Client Registration");
        registrationForm.addInstruction("Please provide the following information");

        XFormFieldImpl field = new XFormFieldImpl("FORM_TYPE");
        field.setType(FormField.TYPE_HIDDEN);
        field.addValue("jabber:iq:register");
        registrationForm.addField(field);

        field = new XFormFieldImpl("username");
        field.setType(FormField.TYPE_TEXT_SINGLE);
        field.setLabel("Username");
        field.setRequired(true);//from   w  w w . j  a v  a 2s  . c om
        registrationForm.addField(field);

        field = new XFormFieldImpl("name");
        field.setType(FormField.TYPE_TEXT_SINGLE);
        field.setLabel("Full name");
        if (UserManager.getUserProvider().isNameRequired()) {
            field.setRequired(true);
        }
        registrationForm.addField(field);

        field = new XFormFieldImpl("email");
        field.setType(FormField.TYPE_TEXT_SINGLE);
        field.setLabel("Email");
        if (UserManager.getUserProvider().isEmailRequired()) {
            field.setRequired(true);
        }
        registrationForm.addField(field);

        field = new XFormFieldImpl("password");
        field.setType(FormField.TYPE_TEXT_PRIVATE);
        field.setLabel("Password");
        field.setRequired(true);
        registrationForm.addField(field);

        field = new XFormFieldImpl("code");
        field.setType(FormField.TYPE_TEXT_SINGLE);
        field.setLabel("Invite Code");
        field.setRequired(true);
        registrationForm.addField(field);

        // Add the registration form to the probe result.
        probeResult.add(registrationForm.asXMLElement());
    }
    // See if in-band registration should be enabled (default is true).
    registrationEnabled = JiveGlobals.getBooleanProperty("register.inband", true);
    // See if users can change their passwords (default is true).
    canChangePassword = JiveGlobals.getBooleanProperty("register.password", true);
}

From source file:org.onesocialweb.openfire.registration.handler.IQRegisterHandler.java

License:Open Source License

public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
    ClientSession session = sessionManager.getSession(packet.getFrom());
    IQ reply = null;//from w ww.ja  v a2 s  .com
    // 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 {
            //registration!!!
            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;
                String code = null;
                User newUser;
                XDataFormImpl 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 XDataFormImpl();
                    registrationForm.parse(formElement);
                    // Get the username sent in the form
                    Iterator<String> values = registrationForm.getField("username").getValues();
                    username = (values.hasNext() ? values.next() : " ");
                    // Get the password sent in the form
                    field = registrationForm.getField("password");
                    if (field != null) {
                        values = field.getValues();
                        password = (values.hasNext() ? values.next() : " ");
                    }
                    // Get the email sent in the form
                    field = registrationForm.getField("email");
                    if (field != null) {
                        values = field.getValues();
                        email = (values.hasNext() ? values.next() : " ");
                    }
                    // Get the name sent in the form
                    field = registrationForm.getField("name");
                    if (field != null) {
                        values = field.getValues();
                        name = (values.hasNext() ? values.next() : " ");
                    }
                    field = registrationForm.getField("code");
                    if (field != null) {
                        values = field.getValues();
                        code = (values.hasNext() ? values.next() : " ");
                        if ((code == null) || (code.length() == 0) || !(isValid(code)))
                            throw new InvalidCodeException();
                    } else
                        throw new IllegalArgumentException("No Invitation Code was provided");
                } 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"); */
                    throw new Exception("Registration elements should be provided in a Data Form");
                }
                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 && !session.isAnonymousUser()) {
                    // 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 {
                        // here...Create the new account!!
                        if (DBManager.getInstance().emailMatches(code, email)) {
                            newUser = userManager.createUser(username, password, name, email);
                            DBManager.getInstance().increaseUsed(code);
                        } else
                            throw new EmailDoesntMatchException();
                    }
                }
                // 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 (InvalidCodeException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(
                    new PacketError(PacketError.Condition.conflict, PacketError.Type.cancel, e.getMessage()));
        } catch (EmailDoesntMatchException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(
                    new PacketError(PacketError.Condition.conflict, PacketError.Type.cancel, e.getMessage()));
        } catch (UserAlreadyExistsException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(
                    new PacketError(PacketError.Condition.conflict, PacketError.Type.cancel, e.getMessage()));
        } 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);
        } 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);
        }
    }
    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.onesocialweb.xml.dom4j.ElementAdapter.java

License:Apache License

@Override
public String getAttributeNS(String namespaceURI, String localName) throws DOMException {
    return element.attributeValue(QName.get(localName, namespaceURI));
}

From source file:org.onesocialweb.xml.dom4j.ElementAdapter.java

License:Apache License

@Override
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException {
    NodeListAdapter nodeList = new NodeListAdapter();
    List<?> nodes = element.elements(QName.get(localName, namespaceURI));
    for (Object object : nodes) {
        Element e = new ElementAdapter((org.dom4j.Element) object);
        nodeList.addElement(e);/* w w  w  . j av a 2 s .c om*/
    }
    return nodeList;
}

From source file:org.onesocialweb.xml.dom4j.ElementAdapter.java

License:Apache License

@Override
public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException {
    return element.attributeValue(QName.get(localName, namespaceURI)) != null;
}

From source file:org.orbeon.oxf.xforms.analysis.XFormsExtractor.java

License:Open Source License

@Override
public void startElement(String uri, String localname, String qName, Attributes attributes)
        throws SAXException {
    namespaceContext.startElement();//from  w w  w .  j a v a 2s  . co m

    // Handle location data
    if (locationData == null && locator != null && mustOutputFirstElement) {
        final String systemId = locator.getSystemId();
        if (systemId != null)
            locationData = new LocationData(systemId, locator.getLineNumber(), locator.getColumnNumber());
    }

    // Check for XForms or extension namespaces
    final boolean isXForms = XFormsConstants.XFORMS_NAMESPACE_URI.equals(uri);
    final boolean isXXForms = XFormsConstants.XXFORMS_NAMESPACE_URI.equals(uri);
    final boolean isEXForms = XFormsConstants.EXFORMS_NAMESPACE_URI.equals(uri);
    final boolean isXBL = XFormsConstants.XBL_NAMESPACE_URI.equals(uri);
    final boolean isXXBL = XFormsConstants.XXBL_NAMESPACE_URI.equals(uri); // for xxbl:global

    final boolean isExtension = metadata.isXBLBinding(uri, localname);
    final boolean isXFormsOrExtension = isXForms || isXXForms || isEXForms || isXBL || isXXBL || isExtension;

    final XMLElementDetails parentElementDetails = elementStack.peek();

    // Handle outer xml:base and xml:lang
    if (!inPreserve && !inForeign) {
        final String xmlBaseAttribute = attributes.getValue(XMLConstants.XML_URI, "base");
        final String xmlLangAttribute = attributes.getValue(XMLConstants.XML_URI, "lang");
        final String xblScopeAttribute = attributes.getValue(XFormsConstants.XXBL_SCOPE_QNAME.getNamespaceURI(),
                XFormsConstants.XXBL_SCOPE_QNAME.getName());

        final String id = attributes.getValue("", "id");

        // Extract xbl:base
        final URI newBase;
        if (xmlBaseAttribute != null) {
            try {
                // Resolve
                newBase = parentElementDetails.xmlBase.resolve(new URI(xmlBaseAttribute)).normalize();// normalize to remove "..", etc.
            } catch (URISyntaxException e) {
                throw new ValidationException("Error creating URI from: '" + parentElementDetails + "' and '"
                        + xmlBaseAttribute + "'.", e, LocationData.createIfPresent(locator));
            }
        } else {
            newBase = parentElementDetails.xmlBase;
        }

        // Extract xml:lang
        final String newLang;
        final String xmlLangAvtId;
        if (xmlLangAttribute != null) {
            newLang = xmlLangAttribute;
            if (XFormsUtils.maybeAVT(newLang))
                xmlLangAvtId = id;
            else
                xmlLangAvtId = parentElementDetails.xmlLangAvtId;
        } else {
            newLang = parentElementDetails.xmlLang;
            xmlLangAvtId = parentElementDetails.xmlLangAvtId;
        }

        final XFormsConstants.XXBLScope newScope;
        if (xblScopeAttribute != null) {
            newScope = XFormsConstants.XXBLScope.valueOf(xblScopeAttribute);
        } else {
            newScope = parentElementDetails.scope;
        }

        elementStack.push(new XMLElementDetails(id, newBase, newLang, xmlLangAvtId, newScope,
                isXForms && localname.equals("model")));
    }

    // Handle properties of the form @xxf:* when outside of models or controls
    if (!inXFormsOrExtension && !isXFormsOrExtension) {
        handleProperties(attributes);
    }

    if (level == 0 && isTopLevel) {
        isHTMLDocument = "html".equals(localname)
                && (uri == null || uri.length() == 0 || XMLConstants.XHTML_NAMESPACE_URI.equals(uri));
    }

    if (level > 0 || !ignoreRootElement) {

        // Start extracting model or controls
        if (!inXFormsOrExtension && isXFormsOrExtension) {

            inXFormsOrExtension = true;
            xformsLevel = level;

            // Handle properties on top-level model elements
            if (isXForms && localname.equals("model")) {
                handleProperties(attributes);
            }

            outputFirstElementIfNeeded();

            // Add xml:base on element
            attributes = XMLUtils.addOrReplaceAttribute(attributes, XMLConstants.XML_URI, "xml", "base",
                    getCurrentBaseURI());

            // Add xml:lang on element if found
            final String xmlLang = elementStack.peek().xmlLang;
            if (xmlLang != null) {
                final String newXMLLang;
                final String xmlLangAvtId = elementStack.peek().xmlLangAvtId;
                if (XFormsUtils.maybeAVT(xmlLang) && xmlLangAvtId != null) {
                    // In this case the latest xml:lang on the stack might be an AVT and we set a special value for
                    // xml:lang containing the id of the control that evaluates the runtime value.
                    newXMLLang = "#" + xmlLangAvtId;
                } else {
                    // No AVT
                    newXMLLang = xmlLang;
                }

                attributes = XMLUtils.addOrReplaceAttribute(attributes, XMLConstants.XML_URI, "xml", "lang",
                        newXMLLang);
            }

            sendStartPrefixMappings();
        }

        // Check for preserved, foreign, or LHHA content
        if (inXFormsOrExtension && !inPreserve && !inForeign) {
            // TODO: Just warn?
            if (isXXForms) {
                // Check that we are getting a valid xxf:* element
                if (!XFormsConstants.ALLOWED_XXFORMS_ELEMENTS.contains(localname)
                        && !XFormsActions.isAction(QName.get(localname, XFormsConstants.XXFORMS_NAMESPACE)))
                    throw new ValidationException("Invalid extension element in XForms document: " + qName,
                            LocationData.createIfPresent(locator));
            } else if (isEXForms) {
                // Check that we are getting a valid exf:* element
                if (!XFormsConstants.ALLOWED_EXFORMS_ELEMENTS.contains(localname))
                    throw new ValidationException("Invalid eXForms element in XForms document: " + qName,
                            LocationData.createIfPresent(locator));
            } else if (isXBL) {
                // Check that we are getting a valid xbl:* element
                if (!XFormsConstants.ALLOWED_XBL_ELEMENTS.contains(localname))
                    throw new ValidationException("Invalid XBL element in XForms document: " + qName,
                            LocationData.createIfPresent(locator));
            }

            // Preserve as is the content of labels, etc., instances, and schemas
            if (!inLHHA) {
                if (XFormsConstants.LABEL_HINT_HELP_ALERT_ELEMENT.contains(localname) && isXForms) {// labels, etc. may contain XHTML)
                    inLHHA = true;
                    preserveOrLHHAOrForeignLevel = level;
                } else if ("instance".equals(localname) && isXForms // XForms instance
                        || "schema".equals(localname) && XMLConstants.XSD_URI.equals(uri) // XML schema
                        || "xbl".equals(localname) && isXBL // preserve everything under xbl:xbl so that templates may be processed by static state
                        || isExtension) {
                    inPreserve = true;
                    preserveOrLHHAOrForeignLevel = level;
                }
            }

            // Callback for elements of interest
            if (isXFormsOrExtension || inLHHA) {
                // NOTE: We call this also for HTML elements within LHHA so we can gather scope information for AVTs
                startXFormsOrExtension(uri, localname, attributes, elementStack.peek().scope);
            }
        }

        if (inXFormsOrExtension && !inForeign && (inPreserve || inLHHA || isXFormsOrExtension)) {
            // We are within preserved content or we output regular XForms content
            super.startElement(uri, localname, qName, attributes);
        } else if (inXFormsOrExtension && !isXFormsOrExtension && parentElementDetails.isModel) {
            // Start foreign content in the model
            inForeign = true;
            preserveOrLHHAOrForeignLevel = level;
        }
    } else {
        // Just open the root element
        outputFirstElementIfNeeded();
        sendStartPrefixMappings();
        super.startElement(uri, localname, qName, attributes);
    }

    level++;
}

From source file:org.orbeon.oxf.xforms.analysis.XFormsExtractorContentHandler.java

License:Open Source License

public void startElement(String uri, String localname, String qName, Attributes attributes)
        throws SAXException {

    namespaceSupport.startElement();//from  ww w  .j  a v  a 2 s .com

    // Handle location data
    if (locationData == null && locator != null && mustOutputFirstElement) {
        final String systemId = locator.getSystemId();
        if (systemId != null) {
            locationData = new LocationData(systemId, locator.getLineNumber(), locator.getColumnNumber());
        }
    }

    // Check for XForms or extension namespaces
    final boolean isXForms = XFormsConstants.XFORMS_NAMESPACE_URI.equals(uri);
    final boolean isXXForms = XFormsConstants.XXFORMS_NAMESPACE_URI.equals(uri);
    final boolean isEXForms = XFormsConstants.EXFORMS_NAMESPACE_URI.equals(uri);
    final boolean isXBL = XFormsConstants.XBL_NAMESPACE_URI.equals(uri);
    final boolean isXXBL = XFormsConstants.XXBL_NAMESPACE_URI.equals(uri); // for xxbl:global

    final boolean isExtension = metadata.isXBLBinding(uri, localname);
    final boolean isXFormsOrExtension = isXForms || isXXForms || isEXForms || isXBL || isXXBL || isExtension;

    // Handle outer xml:base and xml:lang
    if (!inPreserve) {
        final String xmlBaseAttribute = attributes.getValue(XMLConstants.XML_URI, "base");
        final String xmlLangAttribute = attributes.getValue(XMLConstants.XML_URI, "lang");
        final String xblScopeAttribute = attributes.getValue(XFormsConstants.XXBL_SCOPE_QNAME.getNamespaceURI(),
                XFormsConstants.XXBL_SCOPE_QNAME.getName());
        {
            final XMLElementDetails currentXMLElementDetails = elementStack.peek();
            final String id = attributes.getValue("", "id");

            // Extract xbl:base
            final URI newBase;
            if (xmlBaseAttribute != null) {
                try {
                    // Resolve
                    newBase = currentXMLElementDetails.xmlBase.resolve(new URI(xmlBaseAttribute)).normalize();// normalize to remove "..", etc.
                } catch (URISyntaxException e) {
                    throw new ValidationException("Error creating URI from: '" + elementStack.peek() + "' and '"
                            + xmlBaseAttribute + "'.", e, new LocationData(locator));
                }
            } else {
                newBase = currentXMLElementDetails.xmlBase;
            }

            // Extract xml:lang
            final String newLang;
            final String xmlLangAvtId;
            if (xmlLangAttribute != null) {
                newLang = xmlLangAttribute;
                if (XFormsUtils.maybeAVT(newLang))
                    xmlLangAvtId = id;
                else
                    xmlLangAvtId = currentXMLElementDetails.xmlLangAvtId;
            } else {
                newLang = currentXMLElementDetails.xmlLang;
                xmlLangAvtId = currentXMLElementDetails.xmlLangAvtId;
            }

            final XFormsConstants.XXBLScope newScope;
            if (xblScopeAttribute != null) {
                newScope = XFormsConstants.XXBLScope.valueOf(xblScopeAttribute);
            } else {
                newScope = currentXMLElementDetails.scope;
            }

            elementStack.push(new XMLElementDetails(id, newBase, newLang, xmlLangAvtId, newScope));
        }
    }

    // Handle properties of the form @xxforms:* when outside of models or controls
    if (!inXFormsOrExtension && !isXFormsOrExtension) {
        handleProperties(attributes);
    }

    if (level == 0 && isTopLevel) {
        isHTMLDocument = "html".equals(localname)
                && (uri == null || uri.length() == 0 || XMLConstants.XHTML_NAMESPACE_URI.equals(uri));
    }

    if (level > 0 || !ignoreRootElement) {

        // Start extracting model or controls
        if (!inXFormsOrExtension && isXFormsOrExtension) {

            inXFormsOrExtension = true;
            xformsLevel = level;

            // Handle properties on top-level model elements
            if (isXForms && localname.equals("model")) {
                handleProperties(attributes);
            }

            outputFirstElementIfNeeded();

            // Add xml:base on element
            attributes = XMLUtils.addOrReplaceAttribute(attributes, XMLConstants.XML_URI, "xml", "base",
                    getCurrentBaseURI());

            // Add xml:lang on element if found
            final String xmlLang = elementStack.peek().xmlLang;
            if (xmlLang != null) {
                final String newXMLLang;
                final String xmlLangAvtId = elementStack.peek().xmlLangAvtId;
                if (XFormsUtils.maybeAVT(xmlLang) && xmlLangAvtId != null) {
                    // In this case the latest xml:lang on the stack might be an AVT and we set a special value for
                    // xml:lang containing the id of the control that evaluates the runtime value.
                    newXMLLang = "#" + xmlLangAvtId;
                } else {
                    // No AVT
                    newXMLLang = xmlLang;
                }

                attributes = XMLUtils.addOrReplaceAttribute(attributes, XMLConstants.XML_URI, "xml", "lang",
                        newXMLLang);
            }

            sendStartPrefixMappings();
        }

        // Check for preserved content
        if (inXFormsOrExtension && !inPreserve) {
            // TODO: Just warn?
            if (isXXForms) {
                // Check that we are getting a valid xxforms:* element
                if (!XFormsConstants.ALLOWED_XXFORMS_ELEMENTS.contains(localname)
                        && !XFormsActions.isAction(QName.get(localname, XFormsConstants.XXFORMS_NAMESPACE)))
                    throw new ValidationException("Invalid extension element in XForms document: " + qName,
                            new LocationData(locator));
            } else if (isEXForms) {
                // Check that we are getting a valid exforms:* element
                if (!XFormsConstants.ALLOWED_EXFORMS_ELEMENTS.contains(localname))
                    throw new ValidationException("Invalid eXForms element in XForms document: " + qName,
                            new LocationData(locator));
            } else if (isXBL) {
                // Check that we are getting a valid xbl:* element
                if (!XFormsConstants.ALLOWED_XBL_ELEMENTS.contains(localname))
                    throw new ValidationException("Invalid XBL element in XForms document: " + qName,
                            new LocationData(locator));
            }

            // Preserve as is the content of labels, etc., instances, and schemas
            if (!inLHHA) {
                if (XFormsConstants.LABEL_HINT_HELP_ALERT_ELEMENT.contains(localname) && isXForms) {// labels, etc. may contain XHTML)
                    inLHHA = true;
                    preserveOrLHHALevel = level;
                } else if ("instance".equals(localname) && isXForms // XForms instance
                        || "schema".equals(localname) && XMLConstants.XSD_URI.equals(uri) // XML schema
                        || "xbl".equals(localname) && isXBL // preserve everything under xbl:xbl so that templates may be processed by static state
                        || isExtension) {
                    inPreserve = true;
                    preserveOrLHHALevel = level;
                }
            }

            // Callback for elements of interest
            if (isXFormsOrExtension || inLHHA) {
                // NOTE: We call this also for HTML elements within LHHA so we can gather scope information for AVTs
                startXFormsOrExtension(uri, localname, qName, attributes, elementStack.peek().scope);
            }
        }

        // We are within preserved content or we output regular XForms content
        if (inXFormsOrExtension && (inPreserve || inLHHA || isXFormsOrExtension)) {
            super.startElement(uri, localname, qName, attributes);
        }
    } else {
        // Just open the root element
        outputFirstElementIfNeeded();
        sendStartPrefixMappings();
        super.startElement(uri, localname, qName, attributes);
    }

    level++;
}