Example usage for org.jdom2 Element setAttribute

List of usage examples for org.jdom2 Element setAttribute

Introduction

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

Prototype

public Element setAttribute(final String name, final String value) 

Source Link

Document

This sets an attribute value for this element.

Usage

From source file:com.init.octo.schema.XSDSchema.java

License:Open Source License

/**
 * // ww  w.  ja  v  a 2 s.  c om
 * @param elementSpec
 * @param schemaElement
 * @param element
 */
private void addMandatoryElementToDocument(XSDElement schemaElement, String elementSpec, Element element) {
    String[] eSpec = elementSpec.split("\\.");

    if (eSpec[0].equals(element.getName()) == false) {
        log.warn("The parent element [" + element.getName() + "] does not match the element spec ["
                + elementSpec + "]");
        return;
    }

    int idx = 1;
    while (idx < eSpec.length) {

        if (isAttribute(eSpec[idx])) {
            String attname = eSpec[idx].substring(1, eSpec[idx].length());
            Attribute att = element.getAttribute(attname);

            if (att == null) {
                /** Mandatory attribute does not exist so add it.. **/
                element.setAttribute(attname, schemaElement.getDefaultAttValue(attname));
            }

            return;
        }

        StringBuffer tmp = new StringBuffer();
        for (int i = idx; i < eSpec.length; i++) {
            if (tmp.length() != 0) {
                tmp.append(".");
            }
            tmp.append(eSpec[i]);
        }

        Iterator<?> it = element.getChildren(eSpec[idx]).iterator();

        /**
         * If the document does not have the specified child element and we
         * are at the end
         **/
        /**
         * of the chain then this is a mandatory element that needs to be
         * added...
         **/
        if (it.hasNext() == false && idx == eSpec.length - 1) {

            Element newel = new Element(eSpec[idx]);

            addElementToDocument(schemaElement, element, newel);

            return;
        }

        /**
         * If the document does not have the specified child element and
         * that element is
         **/
        /** just part of the chain, then no need to carry on.. **/
        if (it.hasNext() == false) {
            return;
        }

        /**
         * If the document does have the specified child element and we are
         * at the end of the chain then every thing is ok, so just return **/
        if (idx == eSpec.length - 1) {
            return;
        } else {
            /** We have to follow every one of the elements down the tree.. **/
            while (it.hasNext()) {
                addMandatoryElementToDocument(schemaElement, tmp.toString(), (Element) it.next());
            }
            return;
        }
    }
}

From source file:com.khodev.oradiff.io.XmlSchemaWriter.java

License:Open Source License

private static Element getXml(String tagName, DBObject object) {
    Element element = new Element(tagName);
    element.setAttribute("name", object.getName());
    if (object instanceof Constraint) {
        Constraint constraint = (Constraint) object;
        element.setAttribute("constraintType", constraint.getConstraintType());
        element.setAttribute("deferrable", constraint.getDeferrable());
        element.setAttribute("deferred", constraint.getDeferred());
        element.setAttribute("deleteRule", constraint.getDeleteRule());
        element.setAttribute("generated", constraint.getGenerated());
        element.setAttribute("refConstraintName", constraint.getRefConstraintName());
        element.setAttribute("refUserName", constraint.getRefUserName());
        element.setAttribute("searchCondition", constraint.getSearchCondition());
        element.setAttribute("status", constraint.getStatus());
        element.setAttribute("validated", constraint.getValidated());
        Element xmlColumns = new Element("columns");
        for (IndexColumn column : constraint.getColumns())
            xmlColumns.addContent(getXml("column", column));
        element.addContent(xmlColumns);//  w w  w  . ja  v  a 2s.c o  m
    }
    if (object instanceof TablespaceObject) {
        element.setAttribute("tablespace", ((TablespaceObject) object).getTablespace());
    }
    if (object instanceof Source) {
        Source source = (Source) object;
        Element xmlBody = new Element("body");
        String bodyStr = "";
        for (String line : source.getBody())
            bodyStr += line;
        xmlBody.setText(bodyStr);
        element.addContent(xmlBody);
    }
    if (object instanceof DBPackage) {
        DBPackage pkg = (DBPackage) object;
        Element xmlDeclaration = new Element("declaration");
        String bodyStr = "";
        for (String line : pkg.getDeclaration())
            bodyStr += line;
        xmlDeclaration.setText(bodyStr);
        element.addContent(xmlDeclaration);
    }
    if (object instanceof Sequence) {
        Sequence sequence = (Sequence) object;
        element.setAttribute("cacheSize", Integer.toString(sequence.getCacheSize()));
        element.setAttribute("cycleFlag", Boolean.toString(sequence.isCycleFlag()));
        element.setAttribute("incrementBy", sequence.getIncrementBy());
        element.setAttribute("lastNumber", sequence.getLastNumber());
        element.setAttribute("maxValue", sequence.getMaxValue());
        element.setAttribute("minValue", sequence.getMinValue());
        element.setAttribute("orderFlag", Boolean.toString(sequence.isOrderFlag()));
    }
    if (object instanceof Table) {
        Table table = (Table) object;
        element.setAttribute("comments", table.getComments());
        element.addContent(XmlSchemaWriter.convertToXml("columns", "column", table.getColumns()));
        element.addContent(XmlSchemaWriter.convertToXml("indexes", "index", table.getIndexes()));
        element.addContent(XmlSchemaWriter.convertToXml("constraints", "constraint", table.getConstraints()));
        element.addContent(XmlSchemaWriter.convertToXml("grants", "grant", table.getGrants()));
        element.addContent(
                XmlSchemaWriter.convertToXml("publicSynonyms", "publicSynonym", table.getPublicSynonyms()));
        return element;

    }
    if (object instanceof Trigger) {
        Trigger trigger = (Trigger) object;
        element.setAttribute("description", trigger.getDescription());
        element.setAttribute("event", trigger.getEvent());
        element.setAttribute("status", trigger.getStatus());
        element.setAttribute("table", trigger.getTable());
        element.setAttribute("type", trigger.getType());
        element.addContent(new Element("when").setText(trigger.getWhen()));
        element.addContent(new Element("body").setText(trigger.getBody()));
    }
    if (object instanceof View) {
        View view = (View) object;
        Element xmlColumns = new Element("columns");
        for (String column : view.getColumns())
            xmlColumns.addContent(new Element("column").setAttribute("name", column));
        element.addContent(xmlColumns);
        element.addContent(new Element("source").setText(view.getSource()));
    }
    if (object instanceof Column) {
        Column column = (Column) object;
        element.setAttribute("id", Integer.toString(column.getId()));
        element.setAttribute("type", column.getType());
        element.setAttribute("length", Integer.toString(column.getLength()));
        element.setAttribute("precision", Integer.toString(column.getPrecision()));
        element.setAttribute("scale", Integer.toString(column.getScale()));
        element.setAttribute("nullable", Boolean.toString(column.isNullable()));
        element.setAttribute("comments", column.getComment());
        element.setAttribute("defaultValue", column.getDefaultValue());
    }
    if (object instanceof Index) {
        Index index = (Index) object;
        element.setAttribute("type", index.getType());
        element.setAttribute("isUnique", Boolean.toString(index.isUnique()));
        element.setAttribute("compression", index.getCompression());
        Element xmlColumns = new Element("columns");
        for (IndexColumn column : index.getColumns())
            xmlColumns.addContent(getXml("column", column));
        element.addContent(xmlColumns);
    }
    if (object instanceof Grant) {
        Grant grant = (Grant) object;
        element.setAttribute("selectPriv", Boolean.toString(grant.isSelectPriv()));
        element.setAttribute("insertPriv", Boolean.toString(grant.isInsertPriv()));
        element.setAttribute("deletePriv", Boolean.toString(grant.isDeletePriv()));
        element.setAttribute("updatePriv", Boolean.toString(grant.isUpdatePriv()));
        element.setAttribute("referencesPriv", Boolean.toString(grant.isReferencesPriv()));
        element.setAttribute("alterPriv", Boolean.toString(grant.isAlterPriv()));
        element.setAttribute("indexPriv", Boolean.toString(grant.isIndexPriv()));
    }

    if (object instanceof IndexColumn) {
        IndexColumn indexColumn = (IndexColumn) object;
        element.setAttribute("position", Integer.toString(indexColumn.getPosition()));
    }
    return element;
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Performs auth./*w w  w  .ja  v a  2s  .c o  m*/
 */
private void performAuth() {
    byte[] authToken = ("\0" + jid.getNode() + "\0" + password).getBytes(StandardCharsets.UTF_8);

    Element auth = new Element("auth", "urn:ietf:params:xml:ns:xmpp-sasl");
    auth.setAttribute("mechanism", "PLAIN");

    ByteBuf rawCredentials = channel.get().alloc().buffer().writeBytes(authToken);
    ByteBuf encodedCredentials = Base64.encode(rawCredentials);
    String encodedCredentialsString = encodedCredentials.toString(StandardCharsets.UTF_8);
    encodedCredentials.release();
    rawCredentials.release();

    auth.setText(encodedCredentialsString);

    channel.get().writeAndFlush(auth);
}

From source file:com.kixeye.kixmpp.client.module.chat.MessageKixmppClientModule.java

License:Apache License

/**
 * Sends a private message./*from   w  ww . ja va2s .c  o m*/
 * 
 * @param toJid
 * @param body
 */
public void sendMessage(KixmppJid toJid, String body) {
    Element messageElement = new Element("message");
    messageElement.setAttribute("type", "chat");
    messageElement.setAttribute("from", client.getJid().getFullJid());
    messageElement.setAttribute("to", toJid.getBaseJid());

    Element bodyElement = new Element("body");
    bodyElement.setText(body);

    messageElement.addContent(bodyElement);

    client.sendStanza(messageElement);
}

From source file:com.kixeye.kixmpp.client.module.muc.MucKixmppClientModule.java

License:Apache License

/**
 * Joins a room.//from  w  w  w  . ja  va2s .  c  om
 * 
 * @param roomJid
 * @param nickname
 */
public void joinRoom(KixmppJid roomJid, String nickname, Integer maxStanzas, Integer maxChars, Integer seconds,
        DateTime since) {
    Element presence = new Element("presence");
    presence.setAttribute("from", client.getJid().getFullJid());
    presence.setAttribute("to", roomJid + "/" + nickname);

    Element x = new Element("x", "http://jabber.org/protocol/muc");
    presence.addContent(x);

    Element history = new Element("history", "http://jabber.org/protocol/muc");
    if (maxStanzas != null) {
        history.setAttribute("maxstanzas", maxStanzas.toString());
    }
    if (maxChars != null) {
        history.setAttribute("maxchars", maxChars.toString());
    }
    if (seconds != null) {
        history.setAttribute("seconds", seconds.toString());
    }
    if (since != null) {
        history.setAttribute("since", XmppDateUtils.format(since));
    }
    x.addContent(history);

    client.sendStanza(presence);
}

From source file:com.kixeye.kixmpp.client.module.muc.MucKixmppClientModule.java

License:Apache License

/**
 * Sends a room message to a room./*from ww  w .j a  va2  s . co  m*/
 * 
 * @param roomJid
 * @param roomMessage
 */
public void sendRoomMessage(KixmppJid roomJid, String roomMessage, String nickname) {
    Element message = new Element("message");
    message.setAttribute("from", client.getJid().toString());
    message.setAttribute("to", roomJid.toString());
    message.setAttribute("type", "groupchat");

    Element bodyElement = new Element("body", message.getNamespace());
    bodyElement.setText(roomMessage);
    message.addContent(bodyElement);

    client.sendStanza(message);
}

From source file:com.kixeye.kixmpp.client.module.presence.PresenceKixmppClientModule.java

License:Apache License

/**
 * Updates the current user's presence./*  www.j a  v  a  2  s.c  o  m*/
 *     
 * @param presence
 */
public void updatePresence(Presence presence) {
    Element presenceElement = new Element("presence");

    if (presence.getType() != null) {
        presenceElement.setAttribute("type", presence.getType());
    }

    if (presence.getStatus() != null) {
        Element statusElement = new Element("status");
        statusElement.setText(presence.getStatus());

        presenceElement.addContent(statusElement);
    }

    if (presence.getShow() != null) {
        Element showElement = new Element("show");
        showElement.setText(presence.getShow());

        presenceElement.addContent(showElement);
    }

    client.sendStanza(presenceElement);
}

From source file:com.kixeye.kixmpp.server.cluster.message.PrivateChatTask.java

License:Apache License

/**
 * @see org.fusesource.hawtdispatch.Task#run()
 *///  w w w .  ja v  a2  s.c o  m
public void run() {
    KixmppJid fromJid = KixmppJid.fromRawJid(this.fromJid);
    KixmppJid toJid = KixmppJid.fromRawJid(this.toJid);
    KixmppServer server = getKixmppServer();

    // broadcast message stanza to all channels of the recipient
    for (Channel toChannel : server.getChannels(toJid.getNode())) {
        Element messageElement = new Element("message");
        messageElement.setAttribute("type", "chat");
        messageElement.setAttribute("from", fromJid.getFullJid());
        messageElement.setAttribute("to", toJid.getFullJid());

        Element bodyElement = new Element("body");
        bodyElement.setText(body);

        messageElement.addContent(bodyElement);

        toChannel.writeAndFlush(messageElement);
    }

    // broadcast message stanza to all channels of the sender
    // except for the channel it was sent from
    for (Channel fromChannel : server.getChannels(fromJid.getNode())) {
        // skip the channel message was sent from
        if (fromChannel.attr(BindKixmppServerModule.JID).get().toString()
                .equalsIgnoreCase(fromJid.toString())) {
            continue;
        }
        Element messageElement = new Element("message");
        messageElement.setAttribute("type", "chat");
        messageElement.setAttribute("from", fromJid.getFullJid());
        messageElement.setAttribute("to", toJid.getFullJid());

        Element bodyElement = new Element("body");
        bodyElement.setText(body);

        messageElement.addContent(bodyElement);

        fromChannel.writeAndFlush(messageElement);
    }
}

From source file:com.kixeye.kixmpp.server.module.muc.DefaultMucRoomEventHandler.java

License:Apache License

private Element createMessage(String id, KixmppJid from, KixmppJid to, String type, String bodyText) {
    Element message = new Element("message");

    message.setAttribute("to", to.getFullJid());
    message.setAttribute("from", from.getFullJid());
    message.setAttribute("type", type);
    message.setAttribute("id", id);

    Element body = new Element("body");
    body.addContent(bodyText);/*from  ww  w  .ja v  a 2 s  .c om*/

    message.addContent(body);

    return message;
}

From source file:com.kixeye.kixmpp.server.module.muc.MucRoom.java

License:Apache License

/**
 * A user requests to join the room.//w ww.ja v a2s  . c  o m
 *
 * @param channel
 * @param nickname
 * @param mucStanza
 */
public void join(final Channel channel, String nickname, Element mucStanza) {
    KixmppJid jid = channel.attr(BindKixmppServerModule.JID).get();

    if (settings.isOpen() && !jidRoles.containsKey(jid.withoutResource())) {
        addUser(jid, nickname, MucRole.Participant, MucAffiliation.Member);
    }

    verifyMembership(jid.withoutResource());
    checkForNicknameInUse(nickname, jid);

    User user = usersByNickname.get(nickname);

    boolean existingUser = true;
    if (user == null) {
        user = new User(nickname, jid.withoutResource());
        usersByNickname.put(nickname, user);
        MucRoomEventHandler handler = service.getServer().getMucRoomEventHandler();
        if (handler != null) {
            handler.userAdded(this, user);
        }
        existingUser = false;
    }

    Client client = user.addClient(new Client(jid, nickname, channel));

    // xep-0045 7.2.3 begin
    // self presence
    KixmppJid fromRoomJid = roomJid.withResource(nickname);
    channel.writeAndFlush(createPresence(fromRoomJid, jid, MucRole.Participant, null));

    if (settings.isPresenceEnabled() && !existingUser) {
        // Send presence from existing occupants to new occupant
        sendExistingOccupantsPresenceToNewOccupant(user, channel);

        // Send new occupant's presence to all occupants
        broadcastPresence(fromRoomJid, MucRole.Participant, null);
    }
    // xep-0045 7.2.3 end

    if (settings.getSubject() != null) {
        Element message = new Element("message");
        message.setAttribute("id", UUID.randomUUID().toString());
        message.setAttribute("from", roomJid.withResource(nickname).toString());
        message.setAttribute("to", channel.attr(BindKixmppServerModule.JID).get().toString());
        message.setAttribute("type", "groupchat");

        message.addContent(new Element("subject").setText(settings.getSubject()));

        channel.writeAndFlush(message);
    }

    if (mucStanza != null) {
        Element history = mucStanza.getChild("history", mucStanza.getNamespace());

        if (history != null) {
            MucHistoryProvider historyProvider = mucModule.getHistoryProvider();

            if (historyProvider != null) {
                Integer maxChars = null;
                Integer maxStanzas = null;
                Integer seconds = null;

                String parsableString = history.getAttributeValue("maxchars");
                if (parsableString != null) {
                    try {
                        maxChars = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }
                parsableString = history.getAttributeValue("maxstanzas");
                if (parsableString != null) {
                    try {
                        maxStanzas = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }
                parsableString = history.getAttributeValue("seconds");
                if (parsableString != null) {
                    try {
                        seconds = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }

                String since = history.getAttributeValue("since");

                historyProvider.getHistory(roomJid, user.getBareJid(), maxChars, maxStanzas, seconds, since)
                        .addListener(new GenericFutureListener<Future<List<MucHistory>>>() {
                            @Override
                            public void operationComplete(Future<List<MucHistory>> future) throws Exception {
                                if (future.isSuccess()) {
                                    List<MucHistory> historyItems = future.get();
                                    if (historyItems != null) {
                                        for (MucHistory historyItem : historyItems) {
                                            Element message = new Element("message")
                                                    .setAttribute("id", UUID.randomUUID().toString())
                                                    .setAttribute("from",
                                                            roomJid.withResource(historyItem.getNickname())
                                                                    .toString())
                                                    .setAttribute("to",
                                                            channel.attr(BindKixmppServerModule.JID).get()
                                                                    .toString())
                                                    .setAttribute("type", "groupchat");
                                            message.addContent(
                                                    new Element("body").setText(historyItem.getBody()));

                                            Element addresses = new Element("addresses", Namespace
                                                    .getNamespace("http://jabber.org/protocol/address"));
                                            addresses
                                                    .addContent(new Element("address", addresses.getNamespace())
                                                            .setAttribute("type", "ofrom").setAttribute("jid",
                                                                    historyItem.getFrom().toString()));
                                            message.addContent(addresses);

                                            message.addContent(new Element("delay",
                                                    Namespace.getNamespace("urn:xmpp:delay"))
                                                            .setAttribute("from", roomJid.toString())
                                                            .setAttribute("stamp", XmppDateUtils
                                                                    .format(historyItem.getTimestamp())));

                                            channel.write(message);
                                        }
                                        channel.flush();
                                    }
                                }
                            }
                        });
            }
        }
    }

    channel.closeFuture().addListener(new CloseChannelListener(client));
}