Java Code Examples for org.xmpp.packet.Message#setFrom()
The following examples show how to use
org.xmpp.packet.Message#setFrom() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocalMUCRoom.java From Openfire with Apache License 2.0 | 6 votes |
@Override public void changeSubject(Message packet, MUCRole role) throws ForbiddenException { if ((canOccupantsChangeSubject() && role.getRole().compareTo(MUCRole.Role.visitor) < 0) || MUCRole.Role.moderator == role.getRole()) { // Set the new subject to the room subject = packet.getSubject(); MUCPersistenceManager.updateRoomSubject(this); // Notify all the occupants that the subject has changed packet.setFrom(role.getRoleAddress()); send(packet, role); // Fire event signifying that the room's subject has changed. MUCEventDispatcher.roomSubjectChanged(getJID(), role.getUserAddress(), subject); // Let other cluster nodes that the room has been updated CacheFactory.doClusterTask(new RoomUpdatedEvent(this)); } else { throw new ForbiddenException(); } }
Example 2
Source File: LocalMUCRoom.java From Openfire with Apache License 2.0 | 6 votes |
@Override public void sendInvitationRejection(JID to, String reason, JID sender) { if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) { switch(((MultiUserChatServiceImpl)mucService).getMUCDelegate().sendingInvitationRejection(this, to, sender, reason)) { case HANDLED_BY_DELEGATE: //if the delegate is taking care of it, there's nothing for us to do return; case HANDLED_BY_OPENFIRE: //continue as normal if we're asked to handle it break; } } Message message = new Message(); message.setFrom(role.getRoleAddress()); message.setTo(to); Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user"); frag.addElement("decline").addAttribute("from", sender.toBareJID()); if (reason != null && reason.length() > 0) { frag.element("decline").addElement("reason").setText(reason); } // Send the message with the invitation router.route(message); }
Example 3
Source File: MessageRouter.java From Openfire with Apache License 2.0 | 5 votes |
private void bounce(Message message) { // The bouncing behavior as implemented beyond this point was introduced as part // of OF-1852. This kill-switch allows it to be disabled again in case it // introduces unwanted side-effects. if ( !JiveGlobals.getBooleanProperty( "xmpp.message.bounce", true ) ) { log.trace( "Not bouncing a message stanza, as bouncing is disabled by configuration." ); return; } // Do nothing if the packet included an error. This intends to prevent scenarios // where a stanza that is bounced itself gets bounced, causing a loop. if (message.getError() != null) { log.trace( "Not bouncing a stanza that included an error (to prevent never-ending loops of bounces-of-bounces)." ); return; } // Do nothing if the sender was the server itself if (message.getFrom() == null || message.getFrom().toString().equals( serverName )) { log.trace( "Not bouncing a stanza that was sent by the server itself." ); return; } try { log.trace( "Bouncing a message stanza." ); // Generate a rejection response to the sender final Message errorResponse = message.createCopy(); // return an error stanza to the sender, which SHOULD be <service-unavailable/> errorResponse.setError(PacketError.Condition.service_unavailable); errorResponse.setFrom(message.getTo()); errorResponse.setTo(message.getFrom()); // Send the response route(errorResponse); } catch (Exception e) { log.error("An exception occurred while trying to bounce a message.", e); } }
Example 4
Source File: ComponentStanzaHandler.java From Openfire with Apache License 2.0 | 5 votes |
@Override protected void processMessage(Message packet) throws UnauthorizedException { if (session.getStatus() != Session.STATUS_AUTHENTICATED) { // Session is not authenticated so return error Message reply = new Message(); reply.setID(packet.getID()); reply.setTo(packet.getFrom()); reply.setFrom(packet.getTo()); reply.setError(PacketError.Condition.not_authorized); session.process(reply); return; } super.processMessage(packet); }
Example 5
Source File: PEPService.java From Openfire with Apache License 2.0 | 5 votes |
@Override public void broadcast(Node node, Message message, Collection<JID> jids) { if ( Log.isTraceEnabled() ) { Log.trace( "Service '{}' is broadcasting a notification on node '{}' to a collection of JIDs: {}", this.getServiceID(), node.getUniqueIdentifier().getNodeId(), jids.stream().map(JID::toString).collect(Collectors.joining(", ")) ); } message.setFrom(getAddress()); for (JID jid : jids) { message.setTo(jid); message.setID(StringUtils.randomString(8)); router.route(message); } }
Example 6
Source File: SessionManager.java From Openfire with Apache License 2.0 | 5 votes |
private Message createServerMessage(String subject, String body) { Message message = new Message(); message.setFrom(serverAddress); if (subject != null) { message.setSubject(subject); } message.setBody(body); return message; }
Example 7
Source File: NodeSubscription.java From Openfire with Apache License 2.0 | 5 votes |
/** * Sends an request to authorize the pending subscription to the specified owner. * * @param owner the JID of the user that will get the authorization request. */ public void sendAuthorizationRequest(JID owner) { Message authRequest = new Message(); authRequest.addExtension(node.getAuthRequestForm(this)); authRequest.setTo(owner); authRequest.setFrom(node.getService().getAddress()); // Send authentication request to node owners node.getService().send(authRequest); }
Example 8
Source File: PubSubModule.java From Openfire with Apache License 2.0 | 5 votes |
@Override public void sendNotification(Node node, Message message, JID jid) { message.setFrom(getAddress()); message.setTo(jid); message.setID(StringUtils.randomString(8)); router.route(message); }
Example 9
Source File: PubSubModule.java From Openfire with Apache License 2.0 | 5 votes |
@Override public void broadcast(Node node, Message message, Collection<JID> jids) { // TODO Possibly use a thread pool for sending packets (based on the jids size) message.setFrom(getAddress()); for (JID jid : jids) { message.setTo(jid); message.setID(StringUtils.randomString(8)); router.route(message); } }
Example 10
Source File: LocalMUCRoom.java From Openfire with Apache License 2.0 | 5 votes |
@Override public void sendPublicMessage(Message message, MUCRole senderRole) throws ForbiddenException { // Check that if the room is moderated then the sender of the message has to have voice if (isModerated() && senderRole.getRole().compareTo(MUCRole.Role.participant) > 0) { throw new ForbiddenException(); } // Send the message to all occupants message.setFrom(senderRole.getRoleAddress()); send(message, senderRole); // Fire event that message was received by the room MUCEventDispatcher.messageReceived(getRole().getRoleAddress(), senderRole.getUserAddress(), senderRole.getNickname(), message); }
Example 11
Source File: LocalMUCRoom.java From Openfire with Apache License 2.0 | 5 votes |
@Override public void serverBroadcast(String msg) { Message message = new Message(); message.setType(Message.Type.groupchat); message.setBody(msg); message.setFrom(role.getRoleAddress()); broadcast(message, role); }
Example 12
Source File: IQMUCvCardHandler.java From Openfire with Apache License 2.0 | 5 votes |
private void sendConfigChangeNotification( final MUCRoom room ) { Log.debug("Sending configuration change notification to all occupants of room {}", room.getName()); final Message notification = new Message(); notification.setType(Message.Type.groupchat); notification.setFrom(room.getJID()); final Element x = notification.addChildElement("x", "http://jabber.org/protocol/muc#user"); final Element status = x.addElement("status"); status.addAttribute("code", "104"); for ( final MUCRole occupant : room.getOccupants() ) { occupant.send(notification); } }
Example 13
Source File: PacketCopier.java From Openfire with Apache License 2.0 | 4 votes |
private void processPackets() { List<InterceptedPacket> packets = new ArrayList<>(packetQueue.size()); packetQueue.drainTo(packets); for (InterceptedPacket interceptedPacket : packets) { for (Map.Entry<String, Subscription> entry : subscribers.entrySet()) { boolean notify = false; String componentJID = entry.getKey(); Subscription subscription = entry.getValue(); if (subscription.isIncoming() == interceptedPacket.isIncoming() && subscription.isProcessed() == interceptedPacket.isProcessed()) { Class packetClass = interceptedPacket.getPacketClass(); if (subscription.isPresenceEnabled() && packetClass == Presence.class) { notify = true; } else if (subscription.isMessageEnabled() && packetClass == Message.class) { notify = true; } else if (subscription.isIQEnabled() && packetClass == IQ.class) { notify = true; } } if (notify) { try { Message message = new Message(); message.setFrom(serverName); message.setTo(componentJID); Element childElement = message.addChildElement("copy", "http://jabber.org/protocol/packet#event"); childElement.addAttribute("incoming", subscription.isIncoming() ? "true" : "false"); childElement.addAttribute("processed", subscription.isProcessed() ? "true" : "false"); childElement.addAttribute("date", XMPPDateTimeFormat.format(interceptedPacket.getCreationDate())); childElement.add(interceptedPacket.getElement().createCopy()); // Send message notification to subscribed component routingTable.routePacket(message.getTo(), message, true); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } }
Example 14
Source File: WeatherComponent.java From Whack with Apache License 2.0 | 4 votes |
/** * Handle the receied packet and answer the weather information of the requested station id. * The request must be made using Message packets where the body of the message should be the * station id.<p> * * Note: I don't know the list of valid station ids so if you find the list please send it to me * so I can add it to this example. * * @param packet the Message requesting information about a certain station id. */ public void processPacket(Packet packet) { System.out.println("Received package:"+packet.toXML()); // Only process Message packets if (packet instanceof Message) { // Get the requested station to obtain it's weather information Message message = (Message) packet; String station = message.getBody(); // Send the request and get the weather information Metar metar = Weather.getMetar(station, 5000); // Build the answer Message reply = new Message(); reply.setTo(message.getFrom()); reply.setFrom(message.getTo()); reply.setType(message.getType()); reply.setThread(message.getThread()); // Append the discovered information if something was found if (metar != null) { StringBuilder sb = new StringBuilder(); sb.append("station id : " + metar.getStationID()); sb.append("\rwind dir : " + metar.getWindDirection() + " degrees"); sb.append("\rwind speed : " + metar.getWindSpeedInMPH() + " mph, " + metar.getWindSpeedInKnots() + " knots"); if (!metar.getVisibilityLessThan()) { sb.append("\rvisibility : " + metar.getVisibility() + " mile(s)"); } else { sb.append("\rvisibility : < " + metar.getVisibility() + " mile(s)"); } sb.append("\rpressure : " + metar.getPressure() + " in Hg"); sb.append("\rtemperaturePrecise: " + metar.getTemperaturePreciseInCelsius() + " C, " + metar.getTemperaturePreciseInFahrenheit() + " F"); sb.append("\rtemperature: " + metar.getTemperatureInCelsius() + " C, " + metar.getTemperatureInFahrenheit() + " F"); sb.append("\rtemperatureMostPrecise: " + metar.getTemperatureMostPreciseInCelsius() + " C, " + metar.getTemperatureMostPreciseInFahrenheit() + " F"); reply.setBody(sb.toString()); } else { // Answer that the requested station id does not exist reply.setBody("Unknown station ID"); } // Send the response to the sender of the request try { ComponentManagerFactory.getComponentManager().sendPacket(this, reply); } catch (ComponentException e) { e.printStackTrace(); } } }
Example 15
Source File: MUCRoomHistory.java From Openfire with Apache License 2.0 | 4 votes |
/** * Creates a new message and adds it to the history. The new message will be created based on * the provided information. This information will likely come from the database when loading * the room history from the database. * * @param senderJID the sender's JID of the message to add to the history. * @param nickname the sender's nickname of the message to add to the history. * @param sentDate the date when the message was sent to the room. * @param subject the subject included in the message. * @param body the body of the message. * @param stanza the stanza to add */ public void addOldMessage(String senderJID, String nickname, Date sentDate, String subject, String body, String stanza) { Message message = new Message(); message.setType(Message.Type.groupchat); if (stanza != null) { // payload initialized as XML string from DB SAXReader xmlReader = new SAXReader(); xmlReader.setEncoding("UTF-8"); try { Element element = xmlReader.read(new StringReader(stanza)).getRootElement(); for (Element child : (List<Element>)element.elements()) { Namespace ns = child.getNamespace(); if (ns == null || ns.getURI().equals("jabber:client") || ns.getURI().equals("jabber:server")) { continue; } Element added = message.addChildElement(child.getName(), child.getNamespaceURI()); if (!child.getText().isEmpty()) { added.setText(child.getText()); } for (Attribute attr : (List<Attribute>)child.attributes()) { added.addAttribute(attr.getQName(), attr.getValue()); } for (Element el : (List<Element>)child.elements()) { added.add(el.createCopy()); } } if (element.attribute("id") != null) { message.setID(element.attributeValue("id")); } } catch (Exception ex) { Log.error("Failed to parse payload XML", ex); } } message.setSubject(subject); message.setBody(body); // Set the sender of the message if (nickname != null && nickname.trim().length() > 0) { JID roomJID = room.getRole().getRoleAddress(); // Recreate the sender address based on the nickname and room's JID message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname, true)); } else { // Set the room as the sender of the message message.setFrom(room.getRole().getRoleAddress()); } // Add the delay information to the message Element delayInformation = message.addChildElement("delay", "urn:xmpp:delay"); delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate)); if (room.canAnyoneDiscoverJID()) { // Set the Full JID as the "from" attribute delayInformation.addAttribute("from", senderJID); } else { // Set the Room JID as the "from" attribute delayInformation.addAttribute("from", room.getRole().getRoleAddress().toString()); } historyStrategy.addMessage(message); }
Example 16
Source File: LocalMUCRoom.java From Openfire with Apache License 2.0 | 4 votes |
@Override public void sendInvitation(JID to, String reason, MUCRole senderRole, List<Element> extensions) throws ForbiddenException, CannotBeInvitedException { if (!isMembersOnly() || canOccupantsInvite() || MUCRole.Affiliation.admin == senderRole.getAffiliation() || MUCRole.Affiliation.owner == senderRole.getAffiliation()) { // If the room is not members-only OR if the room is members-only and anyone can send // invitations or the sender is an admin or an owner, then send the invitation Message message = new Message(); message.setFrom(role.getRoleAddress()); message.setTo(to); if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) { switch(((MultiUserChatServiceImpl)mucService).getMUCDelegate().sendingInvitation(this, to, senderRole.getUserAddress(), reason)) { case HANDLED_BY_DELEGATE: //if the delegate is taking care of it, there's nothing for us to do return; case HANDLED_BY_OPENFIRE: //continue as normal if we're asked to handle it break; case REJECTED: //we can't invite that person throw new CannotBeInvitedException(); } } // Add a list of extensions sent with the original message invitation (if any) if (extensions != null) { for(Element element : extensions) { element.setParent(null); message.getElement().add(element); } } Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user"); // ChatUser will be null if the room itself (ie. via admin console) made the request if (senderRole.getUserAddress() != null) { frag.addElement("invite").addAttribute("from", senderRole.getUserAddress().toBareJID()); } if (reason != null && reason.length() > 0) { Element invite = frag.element("invite"); if (invite == null) { invite = frag.addElement("invite"); } invite.addElement("reason").setText(reason); } if (isPasswordProtected()) { frag.addElement("password").setText(getPassword()); } // Include the jabber:x:conference information for backward compatibility frag = message.addChildElement("x", "jabber:x:conference"); frag.addAttribute("jid", role.getRoleAddress().toBareJID()); // Send the message with the invitation router.route(message); } else { throw new ForbiddenException(); } }
Example 17
Source File: RoutingTableImpl.java From Openfire with Apache License 2.0 | 4 votes |
private void ccMessage(JID originalRecipient, Message message) { // We don't want to CC a message that is already a CC final Element receivedElement = message.getChildElement(Received.NAME, Received.NAMESPACE); final boolean isCC = receivedElement != null; if (message.getType() == Message.Type.chat && !isCC) { List<JID> routes = getRoutes(originalRecipient.asBareJID(), null); for (JID ccJid : routes) { // The receiving server MUST NOT send a forwarded copy to the full JID the original <message/> stanza was addressed to, as that recipient receives the original <message/> stanza. if (!ccJid.equals(originalRecipient)) { ClientSession clientSession = getClientRoute(ccJid); if (clientSession.isMessageCarbonsEnabled()) { Message carbon = new Message(); // The wrapping message SHOULD maintain the same 'type' attribute value; carbon.setType(message.getType()); // the 'from' attribute MUST be the Carbons-enabled user's bare JID carbon.setFrom(ccJid.asBareJID()); // and the 'to' attribute MUST be the full JID of the resource receiving the copy carbon.setTo(ccJid); // The content of the wrapping message MUST contain a <received/> element qualified by the namespace "urn:xmpp:carbons:2", which itself contains a <forwarded/> element qualified by the namespace "urn:xmpp:forward:0" that contains the original <message/>. carbon.addExtension(new Received(new Forwarded(message))); try { final RoutableChannelHandler localRoute = localRoutingTable.getRoute(ccJid); if (localRoute != null) { // This session is on a local cluster node localRoute.process(carbon); } else { // The session is not on a local cluster node, so try a remote final ClientRoute remoteRoute = getClientRouteForLocalUser(ccJid); if (remotePacketRouter != null // If we're in a cluster && remoteRoute != null // and we've found a route to the other node && !remoteRoute.getNodeID().equals(XMPPServer.getInstance().getNodeID())) { // and it really is a remote node // Try and route the packet to the remote session remotePacketRouter.routePacket(remoteRoute.getNodeID().toByteArray(), ccJid, carbon); } else { Log.warn("Unable to find route to CC remote user {}", ccJid); } } } catch (UnauthorizedException e) { Log.error("Unable to route packet {}", message, e); } } } } } }
Example 18
Source File: OfflineMessageStrategy.java From Openfire with Apache License 2.0 | 4 votes |
public void storeOffline(Message message) { if (message != null) { // Do nothing if the message was sent to the server itself, an anonymous user or a non-existent user // Also ignore message carbons JID recipientJID = message.getTo(); if (recipientJID == null || serverAddress.equals(recipientJID) || recipientJID.getNode() == null || message.getExtension("received", "urn:xmpp:carbons:2") != null || !UserManager.getInstance().isRegisteredUser(recipientJID.getNode())) { return; } // Do not store messages if communication is blocked PrivacyList list = PrivacyListManager.getInstance().getDefaultPrivacyList(recipientJID.getNode()); if (list != null && list.shouldBlockPacket(message)) { Message result = message.createCopy(); result.setTo(message.getFrom()); result.setFrom(message.getTo()); result.setError(PacketError.Condition.service_unavailable); XMPPServer.getInstance().getRoutingTable().routePacket(message.getFrom(), result, true); return; } // 8.5.2. localpart@domainpart // 8.5.2.2. No Available or Connected Resources if (recipientJID.getResource() == null) { if (message.getType() == Message.Type.headline || message.getType() == Message.Type.error) { // For a message stanza of type "headline" or "error", the server MUST silently ignore the message. return; } // // For a message stanza of type "groupchat", the server MUST return an error to the sender, which SHOULD be <service-unavailable/>. else if (message.getType() == Message.Type.groupchat) { bounce(message); return; } } else { // 8.5.3. localpart@domainpart/resourcepart // 8.5.3.2.1. Message // For a message stanza of type "normal", "groupchat", or "headline", the server MUST either (a) silently ignore the stanza // or (b) return an error stanza to the sender, which SHOULD be <service-unavailable/>. if (message.getType() == Message.Type.normal || message.getType() == Message.Type.groupchat || message.getType() == Message.Type.headline) { // Depending on the OfflineMessageStragey, we may silently ignore or bounce if (type == Type.bounce) { bounce(message); } // Either bounce or silently ignore, never store such messages return; } // For a message stanza of type "error", the server MUST silently ignore the stanza. else if (message.getType() == Message.Type.error) { return; } } switch (type) { case bounce: bounce(message); break; case store: store(message); break; case store_and_bounce: if (underQuota(message)) { store(message); } else { Log.debug( "Unable to store, as user is over storage quota. Bouncing message instead: " + message.toXML() ); bounce(message); } break; case store_and_drop: if (underQuota(message)) { store(message); } else { Log.debug( "Unable to store, as user is over storage quota. Silently dropping message: " + message.toXML() ); } break; case drop: // Drop essentially means silently ignore/do nothing break; } } }
Example 19
Source File: ClientStanzaHandler.java From Openfire with Apache License 2.0 | 4 votes |
@Override protected void processMessage(Message packet) throws UnauthorizedException { // Overwrite the FROM attribute to avoid spoofing packet.setFrom(session.getAddress()); super.processMessage(packet); }
Example 20
Source File: WeatherComponent.java From Whack with Apache License 2.0 | 4 votes |
/** * Handle a receied message and answer the weather information of the requested station id. * The request must be made using Message packets where the body of the message should be the * station id.<p> * * Note: I don't know the list of valid station ids so if you find the list please send it to me * so I can add it to this example. * * @param message the Message requesting information about a certain station id. */ @Override protected void handleMessage(Message message) { System.out.println("Received message:"+message.toXML()); // Get the requested station to obtain it's weather information String station = message.getBody(); // Send the request and get the weather information Metar metar = Weather.getMetar(station, 5000); // Build the answer Message reply = new Message(); reply.setTo(message.getFrom()); reply.setFrom(message.getTo()); reply.setType(message.getType()); reply.setThread(message.getThread()); // Append the discovered information if something was found if (metar != null) { StringBuilder sb = new StringBuilder(); sb.append("station id : " + metar.getStationID()); sb.append("\rwind dir : " + metar.getWindDirection() + " degrees"); sb.append("\rwind speed : " + metar.getWindSpeedInMPH() + " mph, " + metar.getWindSpeedInKnots() + " knots"); if (!metar.getVisibilityLessThan()) { sb.append("\rvisibility : " + metar.getVisibility() + " mile(s)"); } else { sb.append("\rvisibility : < " + metar.getVisibility() + " mile(s)"); } sb.append("\rpressure : " + metar.getPressure() + " in Hg"); sb.append("\rtemperaturePrecise: " + metar.getTemperaturePreciseInCelsius() + " C, " + metar.getTemperaturePreciseInFahrenheit() + " F"); sb.append("\rtemperature: " + metar.getTemperatureInCelsius() + " C, " + metar.getTemperatureInFahrenheit() + " F"); sb.append("\rtemperatureMostPrecise: " + metar.getTemperatureMostPreciseInCelsius() + " C, " + metar.getTemperatureMostPreciseInFahrenheit() + " F"); reply.setBody(sb.toString()); } else { // Answer that the requested station id does not exist reply.setBody("Unknown station ID"); } // Send the response to the sender of the request send(reply); }