Example usage for org.jdom2 Element getNamespace

List of usage examples for org.jdom2 Element getNamespace

Introduction

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

Prototype

public Namespace getNamespace() 

Source Link

Document

Returns the element's Namespace .

Usage

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

License:Apache License

/**
 * Sends a room message to a room./*  w w  w  .  j  a va  2  s. c  o  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.KixmppWebSocketCodec.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    WebSocketFrame frame = null;/*  w  ww .  j av  a2  s  .c om*/

    if (msg instanceof Element) {
        Element element = (Element) msg;

        if (element.getNamespace() == null || element.getNamespace() == Namespace.NO_NAMESPACE) {
            if ("stream".equals(element.getNamespacePrefix())) {
                element.setNamespace(Namespace.getNamespace("http://etherx.jabber.org/streams"));
            } else {
                element.setNamespace(Namespace.getNamespace("jabber:client"));

                IteratorIterable<Content> descendants = element.getDescendants();

                while (descendants.hasNext()) {
                    Content content = descendants.next();

                    if (content instanceof Element) {
                        Element descendantElement = (Element) content;
                        if (descendantElement.getNamespace() == null
                                || descendantElement.getNamespace() == Namespace.NO_NAMESPACE) {
                            descendantElement.setNamespace(element.getNamespace());
                        }
                    }
                }
            }
        }

        ByteBuf binaryData = ctx.alloc().buffer();
        new XMLOutputter().output((Element) msg, new ByteBufOutputStream(binaryData));

        frame = new TextWebSocketFrame(binaryData);
    } else if (msg instanceof KixmppStreamStart) {
        KixmppStreamStart streamStart = (KixmppStreamStart) msg;

        StringWriter writer = new StringWriter();

        if (streamStart.doesIncludeXmlHeader()) {
            writer.append("<?xml version='1.0' encoding='UTF-8'?>");
        }
        writer.append("<stream:stream ");
        if (streamStart.getId() != null) {
            writer.append(String.format("id=\"%s\" ", streamStart.getId()));
        }
        if (streamStart.getFrom() != null) {
            writer.append(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid()));
        }
        if (streamStart.getTo() != null) {
            writer.append(String.format("to=\"%s\" ", streamStart.getTo()));
        }
        writer.append(
                "version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">");

        frame = new TextWebSocketFrame(writer.toString());
    } else if (msg instanceof KixmppStreamEnd) {
        frame = new TextWebSocketFrame("</stream:stream>");
    } else if (msg instanceof String) {
        frame = new TextWebSocketFrame((String) msg);
    } else if (msg instanceof ByteBuf) {
        frame = new TextWebSocketFrame((ByteBuf) msg);
    }

    if (frame != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Sending: [{}]", frame.content().toString(StandardCharsets.UTF_8));
        }

        out.add(frame);
    }
}

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

License:Apache License

/**
 * A user requests to join the room./*from   w ww .j av  a 2  s .  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));
}

From source file:com.rometools.modules.base.io.CustomTagParser.java

License:Open Source License

@Override
public Module parse(final Element element, final Locale locale) {
    final CustomTags module = new CustomTagsImpl();
    final ArrayList<CustomTag> tags = new ArrayList<CustomTag>();
    final List<Element> elements = element.getChildren();
    final Iterator<Element> it = elements.iterator();
    while (it.hasNext()) {
        final Element child = it.next();
        if (child.getNamespace().equals(NS)) {
            final String type = child.getAttributeValue("type");
            try {
                if (type == null) {
                    continue;
                } else if (type.equals("string")) {
                    tags.add(new CustomTagImpl(child.getName(), child.getText()));
                } else if (type.equals("int")) {
                    tags.add(new CustomTagImpl(child.getName(), new Integer(child.getTextTrim())));
                } else if (type.equals("float")) {
                    tags.add(new CustomTagImpl(child.getName(), new Float(child.getTextTrim())));
                } else if (type.equals("intUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new IntUnit(child.getTextTrim())));
                } else if (type.equals("floatUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new FloatUnit(child.getTextTrim())));
                } else if (type.equals("date")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new ShortDate(GoogleBaseParser.SHORT_DT_FMT.parse(child.getTextTrim()))));
                    } catch (final ParseException e) {
                        LOG.warn("Unable to parse date type on " + child.getName(), e);
                    }//  w w w.  ja v a 2 s  . c om
                } else if (type.equals("dateTime")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                GoogleBaseParser.LONG_DT_FMT.parse(child.getTextTrim())));
                    } catch (final ParseException e) {
                        LOG.warn("Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("dateTimeRange")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new DateTimeRange(
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("start", CustomTagParser.NS).getText().trim()),
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("end", CustomTagParser.NS).getText().trim()))));
                    } catch (final Exception e) {
                        LOG.warn("Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("url")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(), new URL(child.getTextTrim())));
                    } catch (final MalformedURLException e) {
                        LOG.warn("Unable to parse URL type on " + child.getName(), e);
                    }
                } else if (type.equals("boolean")) {
                    tags.add(
                            new CustomTagImpl(child.getName(), new Boolean(child.getTextTrim().toLowerCase())));
                } else if (type.equals("location")) {
                    tags.add(new CustomTagImpl(child.getName(), new CustomTagImpl.Location(child.getText())));
                } else {
                    throw new Exception("Unknown type: " + type);
                }
            } catch (final Exception e) {
                LOG.warn("Unable to parse type on " + child.getName(), e);
            }
        }
    }
    module.setValues(tags);
    return module;
}

From source file:com.rometools.modules.base.io.GoogleBaseParser.java

License:Open Source License

@Override
public Module parse(final Element element, final Locale locale) {
    final HashMap<String, PropertyDescriptor> tag2pd = new HashMap<String, PropertyDescriptor>();
    final GoogleBaseImpl module = new GoogleBaseImpl();

    try {//from ww w  .j a v a2s. co  m
        for (final PropertyDescriptor pd : pds) {
            final String tagName = GoogleBaseParser.PROPS2TAGS.getProperty(pd.getName());

            if (tagName == null) {
                LOG.debug("Property: {} doesn't have a tag mapping.", pd.getName());
            } else {
                tag2pd.put(tagName, pd);
            }
        }
    } catch (final Exception e) {
        throw new RuntimeException("Exception building tag to property mapping. ", e);
    }

    final List<Element> children = element.getChildren();
    final Iterator<Element> it = children.iterator();

    while (it.hasNext()) {
        final Element child = it.next();

        if (child.getNamespace().equals(GoogleBaseParser.NS)) {
            final PropertyDescriptor pd = tag2pd.get(child.getName());

            if (pd != null) {
                try {
                    handleTag(child, pd, module);
                } catch (final Exception e) {
                    LOG.warn("Unable to handle tag: " + child.getName(), e);
                    e.printStackTrace();
                }
            }
        }
    }

    return module;
}

From source file:com.rometools.modules.cc.io.CCModuleGenerator.java

License:Open Source License

@Override
public void generate(final Module module, final Element element) {
    Element root = element;
    while (root.getParentElement() != null) {
        root = root.getParentElement();//from www . ja  v  a2s  .  c o  m
    }
    if (root.getNamespace().equals(RDF) || root.getNamespace().equals(RSS)) {
        generateRSS1((CreativeCommons) module, element);
    } else {
        generateRSS2((CreativeCommons) module, element);
    }
}

From source file:com.rometools.modules.mediarss.io.RSS20YahooParser.java

License:Open Source License

/**
 * Indicates if a JDom document is an RSS instance that can be parsed with the parser.
 * <p/>/*from  w ww.j a v  a  2s  . c o  m*/
 * It checks for RDF ("http://www.w3.org/1999/02/22-rdf-syntax-ns#") and RSS
 * ("http://purl.org/rss/1.0/") namespaces being defined in the root element.
 *
 * @param document document to check if it can be parsed with this parser implementation.
 * @return <b>true</b> if the document is RSS1., <b>false</b> otherwise.
 */
@Override
public boolean isMyType(final Document document) {
    boolean ok = false;

    final Element rssRoot = document.getRootElement();
    final Namespace defaultNS = rssRoot.getNamespace();

    ok = defaultNS != null && defaultNS.equals(getRSSNamespace());

    return ok;
}

From source file:com.rometools.modules.photocast.io.Parser.java

License:Open Source License

@Override
public Module parse(final Element element, final Locale locale) {
    if (element.getName().equals("channel") || element.getName().equals("feed")) {
        return new PhotocastModuleImpl();
    } else if (element.getChild("metadata", Parser.NS) == null
            && element.getChild("image", Parser.NS) == null) {
        return null;
    }//from w  ww. j a v  a 2 s  . c  o m
    final PhotocastModule pm = new PhotocastModuleImpl();
    final List<Element> children = element.getChildren();
    final Iterator<Element> it = children.iterator();
    while (it.hasNext()) {
        final Element e = it.next();
        if (!e.getNamespace().equals(Parser.NS)) {
            continue;
        }
        if (e.getName().equals("photoDate")) {
            try {
                pm.setPhotoDate(Parser.PHOTO_DATE_FORMAT.parse(e.getText()));
            } catch (final Exception ex) {
                LOG.warn("Unable to parse photoDate: " + e.getText(), ex);
            }
        } else if (e.getName().equals("cropDate")) {
            try {
                pm.setCropDate(Parser.CROP_DATE_FORMAT.parse(e.getText()));
            } catch (final Exception ex) {
                LOG.warn("Unable to parse cropDate: " + e.getText(), ex);
            }
        } else if (e.getName().equals("thumbnail")) {
            try {
                pm.setThumbnailUrl(new URL(e.getText()));
            } catch (final Exception ex) {
                LOG.warn("Unable to parse thumnail: " + e.getText(), ex);
            }
        } else if (e.getName().equals("image")) {
            try {
                pm.setImageUrl(new URL(e.getText()));
            } catch (final Exception ex) {
                LOG.warn("Unable to parse image: " + e.getText(), ex);
            }
        } else if (e.getName().equals("metadata")) {
            String comments = "";
            PhotoDate photoDate = null;
            if (e.getChildText("PhotoDate") != null) {
                try {
                    photoDate = new PhotoDate(Double.parseDouble(e.getChildText("PhotoDate")));
                } catch (final Exception ex) {
                    LOG.warn("Unable to parse PhotoDate: " + e.getText(), ex);
                }
            }
            if (e.getChildText("Comments") != null) {
                comments = e.getChildText("Comments");
            }
            pm.setMetadata(new Metadata(photoDate, comments));
        }
    }
    return pm;
}

From source file:com.rometools.modules.sle.io.ModuleParser.java

License:Apache License

/**
 * Parses the XML node (JDOM element) extracting module information.
 * <p>/*from  www.ja  v a 2s  .co  m*/
 *
 * @param element the XML node (JDOM element) to extract module information from.
 * @return a module instance, <b>null</b> if the element did not have module information.
 */
@Override
public Module parse(final Element element, final Locale locale) {
    if (element.getChild("treatAs", NS) == null) {
        return null;
    }

    final SimpleListExtension sle = new SimpleListExtensionImpl();
    sle.setTreatAs(element.getChildText("treatAs", NS));

    final Element listInfo = element.getChild("listinfo", NS);
    ArrayList<Object> values = new ArrayList<Object>();
    for (final Element ge : listInfo.getChildren("group", NS)) {
        final Namespace ns = ge.getAttribute("ns") == null ? element.getNamespace()
                : Namespace.getNamespace(ge.getAttributeValue("ns"));
        final String elementName = ge.getAttributeValue("element");
        final String label = ge.getAttributeValue("label");
        values.add(new Group(ns, elementName, label));
    }

    sle.setGroupFields(values.toArray(new Group[values.size()]));
    values = values.size() == 0 ? values : new ArrayList<Object>();

    for (final Element se : listInfo.getChildren("sort", NS)) {
        LOG.debug("Parse cf:sort {}{}", se.getAttributeValue("element"), se.getAttributeValue("data-type"));
        final Namespace ns = se.getAttributeValue("ns") == null ? element.getNamespace()
                : Namespace.getNamespace(se.getAttributeValue("ns"));
        final String elementName = se.getAttributeValue("element");
        final String label = se.getAttributeValue("label");
        final String dataType = se.getAttributeValue("data-type");
        final boolean defaultOrder = se.getAttributeValue("default") == null ? false
                : new Boolean(se.getAttributeValue("default")).booleanValue();
        values.add(new Sort(ns, elementName, dataType, label, defaultOrder));
    }

    sle.setSortFields(values.toArray(new Sort[values.size()]));
    insertValues(sle, element.getChildren());

    return sle;
}

From source file:com.rometools.rome.io.impl.Atom03Parser.java

License:Open Source License

@Override
public boolean isMyType(final Document document) {
    final Element rssRoot = document.getRootElement();
    final Namespace defaultNS = rssRoot.getNamespace();
    return defaultNS != null && defaultNS.equals(getAtomNamespace());
}