public void init() throws XMPPException { new TrackRooms().addTo(conn); new TrackStatus(getMonitorRoomJID().toLowerCase()).addTo(conn); new ListenForChat().addTo(conn); monitorRoom = new MultiUserChat(conn, getMonitorRoomJID()); monitorRoom.addMessageListener(this); monitorRoom.addParticipantStatusListener(this); monitorRoom.join(StringUtils.parseName(conn.getUser())); try { // This is necessary to create the room if it doesn't already exist monitorRoom.sendConfigurationForm(new Form(Form.TYPE_SUBMIT)); } catch (XMPPException ex) { // 403 code means the room already exists and user is not an owner if (ex.getXMPPError().getCode() != 403) { throw ex; } } sendStatus(me); }
/** * 修改用户头像 * @param xmppConnection * @param file */ public static boolean changeUserImage(XMPPConnection xmppConnection,File file) { try { VCard vcard = new VCard(); vcard.load(xmppConnection); byte[] bytes= MyFileUtil.getFileBytes(file); String encodedImage = StringUtils.encodeBase64(bytes); vcard.setAvatar(bytes, encodedImage); vcard.setEncodedImage(encodedImage); vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>" + encodedImage + "</BINVAL>", true); vcard.save(xmppConnection); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
/** * 修改用户头像 * * @param xmppConnection * @param file */ public static boolean changeUserImage(XMPPConnection xmppConnection, File file) { try { VCard vcard = new VCard(); vcard.load(xmppConnection); byte[] bytes = MyFileUtil.getFileBytes(file); String encodedImage = StringUtils.encodeBase64(bytes); vcard.setAvatar(bytes, encodedImage); vcard.setEncodedImage(encodedImage); vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>" + encodedImage + "</BINVAL>", true); vcard.save(xmppConnection); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
@Override protected IQChildElementXmlStringBuilder getIQHoxtChildElementBuilder(IQChildElementXmlStringBuilder builder) { builder.append(" "); builder.append("method='").append(method.toString()).append("'"); builder.append(" "); builder.append("resource='").append(StringUtils.escapeForXML(resource)).append("'"); builder.append(" "); builder.append("version='").append(StringUtils.escapeForXML(version)).append("'"); if (maxChunkSize != 0) { builder.append(" "); builder.append("maxChunkSize='").append(Integer.toString(maxChunkSize)).append("'"); } builder.append(" "); builder.append("sipub='").append(Boolean.toString(sipub)).append("'"); builder.append(" "); builder.append("ibb='").append(Boolean.toString(ibb)).append("'"); builder.append(" "); builder.append("jingle='").append(Boolean.toString(jingle)).append("'"); builder.append(">"); return builder; }
public StreamError(Condition condition, String conditionText, Map<String, String> descriptiveTexts, List<ExtensionElement> extensions) { super(descriptiveTexts, extensions); // Some implementations may send the condition as non-empty element containing the empty string, that is // <condition xmlns='foo'></condition>, in this case the parser may calls this constructor with the empty string // as conditionText, therefore reset it to null if it's the empty string if (StringUtils.isNullOrEmpty(conditionText)) { conditionText = null; } if (conditionText != null) { switch (condition) { case see_other_host: break; default: throw new IllegalArgumentException("The given condition '" + condition + "' can not contain a conditionText"); } } this.condition = condition; this.conditionText = conditionText; }
public StreamOpen(CharSequence to, CharSequence from, String id, String lang, StreamContentNamespace ns) { this.to = StringUtils.maybeToString(to); this.from = StringUtils.maybeToString(from); this.id = id; this.lang = lang; switch (ns) { case client: this.contentNamespace = CLIENT_NAMESPACE; break; case server: this.contentNamespace = SERVER_NAMESPACE; break; default: throw new IllegalStateException(); } }
/** * Serializes a Map of String name/value pairs into the meta-data XML format. * * @param metaData the Map of meta-data as Map<String,List<String>> * @return the meta-data values in XML form. */ public static String serializeMetaData(Map<String, List<String>> metaData) { StringBuilder buf = new StringBuilder(); if (metaData != null && metaData.size() > 0) { buf.append("<metadata xmlns=\"http://jivesoftware.com/protocol/workgroup\">"); for (Iterator<String> i = metaData.keySet().iterator(); i.hasNext();) { String key = i.next(); List<String> value = metaData.get(key); for (Iterator<String> it = value.iterator(); it.hasNext();) { String v = it.next(); buf.append("<value name=\"").append(key).append("\">"); buf.append(StringUtils.escapeForXML(v)); buf.append("</value>"); } } buf.append("</metadata>"); } return buf.toString(); }
/** * Changes the occupant's availability status within the room. The presence type * will remain available but with a new status that describes the presence update and * a new presence mode (e.g. Extended away). * * @param status a text message describing the presence update. * @param mode the mode type for the presence update. * @throws NotConnectedException */ public void changeAvailabilityStatus(String status, Presence.Mode mode) throws NotConnectedException { StringUtils.requireNotNullOrEmpty(nickname, "Nickname must not be null or blank."); // Check that we already have joined the room before attempting to change the // availability status. if (!joined) { throw new IllegalStateException( "Must be logged into the room to change the " + "availability status."); } // We change the availability status by sending a presence packet to the room with the // new presence status and mode Presence joinPresence = new Presence(Presence.Type.available); joinPresence.setStatus(status); joinPresence.setMode(mode); joinPresence.setTo(room + "/" + nickname); // Send join packet. connection.sendStanza(joinPresence); }
/** * Returns the SHA-1 Hash of the Avatar image. * * @return the SHA-1 Hash of the Avatar image. */ public String getAvatarHash() { byte[] bytes = getAvatar(); if (bytes == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.SEVERE, "Failed to get message digest", e); return null; } digest.update(bytes); return StringUtils.encodeHex(digest.digest()); }
private void testSimpleDirectoryCache(StringEncoder stringEncoder) throws IOException { EntityCapsPersistentCache cache = new SimpleDirectoryPersistentCache(createTempDirectory()); EntityCapsManager.setPersistentCache(cache); DiscoverInfo di = createComplexSamplePacket(); CapsVersionAndHash versionAndHash = EntityCapsManager.generateVerificationString(di, StringUtils.SHA1); String nodeVer = di.getNode() + "#" + versionAndHash.version; // Save the data in EntityCapsManager EntityCapsManager.addDiscoverInfoByNode(nodeVer, di); // Lose all the data EntityCapsManager.clearMemoryCache(); DiscoverInfo restored_di = EntityCapsManager.getDiscoveryInfoByNodeVer(nodeVer); assertNotNull(restored_di); assertEquals(di.toXML().toString(), restored_di.toXML().toString()); }
private String calcResponse(DigestType digestType) { StringBuilder a2 = new StringBuilder(); if (digestType == DigestType.ClientResponse) { a2.append("AUTHENTICATE"); } a2.append(':'); a2.append(digestUri); String hex_hashed_a2 = StringUtils.encodeHex(MD5.bytes(a2.toString())); StringBuilder kd_argument = new StringBuilder(); kd_argument.append(hex_hashed_a1); kd_argument.append(':'); kd_argument.append(nonce); kd_argument.append(':'); kd_argument.append(INITAL_NONCE); kd_argument.append(':'); kd_argument.append(cnonce); kd_argument.append(':'); kd_argument.append(QOP_VALUE); kd_argument.append(':'); kd_argument.append(hex_hashed_a2); byte[] kd = MD5.bytes(kd_argument.toString()); String responseValue = StringUtils.encodeHex(kd); return responseValue; }
@Override public void presenceChanged(Presence presence) { log.fine("Presence change from " + presence.getFrom()); String name = StringUtils.parseName(presence.getFrom()); if (!isMultiplicityDevice(name)) { return; } if (presence.isAvailable()) { notifyDeviceAvailable(name); } else { notifyDeviceUnavailable(name); } }
public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<item jid=\"").append(user).append("\""); if (name != null) { buf.append(" name=\"").append(StringUtils.escapeForXML(name)).append("\""); } if (itemType != null) { buf.append(" subscription=\"").append(itemType).append("\""); } if (itemStatus != null) { buf.append(" ask=\"").append(itemStatus).append("\""); } buf.append(">"); for (String groupName : groupNames) { buf.append("<group>").append(StringUtils.escapeForXML(groupName)).append("</group>"); } buf.append("</item>"); return buf.toString(); }
/** * Changes the password of the currently logged-in account. This operation can only * be performed after a successful login operation has been completed. Not all servers * support changing passwords; an XMPPException will be thrown when that is the case. * * @throws IllegalStateException if not currently logged-in to the server. * @throws XMPPException if an error occurs when changing the password. */ public void changePassword(String newPassword) throws XMPPException { Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); Map<String, String> map = new HashMap<String, String>(); map.put("username",StringUtils.parseName(connection.getUser())); map.put("password",newPassword); reg.setAttributes(map); PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = connection.createPacketCollector(filter); connection.sendPacket(reg); IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } }
/** * Creates a ChatNote that will be mapped to the given chat session. * * @param sessionID the session id of a Chat Session. * @param note the chat note to add. * @throws XMPPException is thrown if an error occurs while adding the note. */ public void setNote(String sessionID, String note) throws XMPPException { note = ChatNotes.replace(note, "\n", "\\n"); note = StringUtils.escapeForXML(note); ChatNotes notes = new ChatNotes(); notes.setType(IQ.Type.SET); notes.setTo(workgroupJID); notes.setSessionID(sessionID); notes.setNotes(note); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(notes.getPacketID())); // Send the request connection.sendPacket(notes); IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } }
public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<identity"); // Check if this packet has 'lang' set and maybe append it to the resulting string if (lang != null) buf.append(" xml:lang=\"").append(StringUtils.escapeForXML(lang)).append("\""); // Category must always be set buf.append(" category=\"").append(StringUtils.escapeForXML(category)).append("\""); // Name must always be set buf.append(" name=\"").append(StringUtils.escapeForXML(name)).append("\""); // Check if this packet has 'type' set and maybe append it to the resulting string if (type != null) { buf.append(" type=\"").append(StringUtils.escapeForXML(type)).append("\""); } buf.append("/>"); return buf.toString(); }
public String getChildElementXML() { StringBuilder buf = new StringBuilder(); buf.append("<").append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">"); if (isPersonal()) { buf.append("<personal>true</personal>"); } if (getPersonalMacroGroup() != null) { buf.append("<personalMacro>"); buf.append(StringUtils.escapeForXML(getPersonalMacroGroup().toXML())); buf.append("</personalMacro>"); } buf.append("</").append(ELEMENT_NAME).append("> "); return buf.toString(); }
private synchronized void flushBuffer() throws IOException { // do nothing if no data to send available if (bufferPointer == 0) { return; } // create data packet String enc = StringUtils.encodeBase64(buffer, 0, bufferPointer, false); DataPacketExtension data = new DataPacketExtension(byteStreamRequest.getSessionID(), this.seq, enc); // write to XMPP stream writeToXML(data); // reset buffer pointer bufferPointer = 0; // increment sequence, considering sequence overflow this.seq = (this.seq + 1 == 65535 ? 0 : this.seq + 1); }
/** * Returns the decoded data or null if data could not be decoded. * <p> * The encoded data is invalid if it contains bad Base64 input characters or * if it contains the pad ('=') character on a position other than the last * character(s) of the data. See <a * href="http://xmpp.org/extensions/xep-0047.html#sec">XEP-0047</a> Section * 6. * * @return the decoded data */ public byte[] getDecodedData() { // return cached decoded data if (this.decodedData != null) { return this.decodedData; } // data must not contain the pad (=) other than end of data if (data.matches(".*={1,2}+.+")) { return null; } // decodeBase64 will return null if bad characters are included this.decodedData = StringUtils.decodeBase64(data); return this.decodedData; }
/** * Returns the SHA-1 Hash of the Avatar image. * * @return the SHA-1 Hash of the Avatar image. */ public String getAvatarHash() { byte[] bytes = getAvatar(); if (bytes == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } digest.update(bytes); return StringUtils.encodeHex(digest.digest()); }
@Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( "\""); buf.append(" stamp=\""); buf.append(StringUtils.formatXEP0082Date(getStamp())); buf.append("\""); if (getFrom() != null && getFrom().length() > 0) { buf.append(" from=\"").append(getFrom()).append("\""); } buf.append(">"); if (getReason() != null && getReason().length() > 0) { buf.append(getReason()); } buf.append("</").append(getElementName()).append(">"); return buf.toString(); }
@Override public void onMessage(String from, JsonObject jData) { if (jData.has("action")) { String action = jData.get("action").getAsString(); if (action.equals(REGISTER_NEW_CLIENT)) { registerNewClient(jData); } else if (action.equals("ping_client")) { String toToken = jData.get("to").getAsString(); String senderToken = jData.get("sender").getAsString(); if (StringUtils.isNotEmpty(toToken) && StringUtils.isNotEmpty(senderToken)) { pingClient(toToken, senderToken); } else { logger.info("Unable to ping unless to and sender tokens are available."); } } } else { logger.info("No action found. Message received missing action."); } }
/** * Changes the password of the currently logged-in account. This operation can only * be performed after a successful login operation has been completed. Not all servers * support changing passwords; an XMPPException will be thrown when that is the case. * * @throws IllegalStateException if not currently logged-in to the server. * @throws XMPPException if an error occurs when changing the password. */ public void changePassword(String newPassword) throws XMPPException { Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); reg.setUsername(StringUtils.parseName(connection.getUser())); reg.setPassword(newPassword); PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = connection.createPacketCollector(filter); connection.sendPacket(reg); IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } }
public String getChildElementXML() { StringBuilder buf = new StringBuilder(); buf.append("<query xmlns=\"" + NAMESPACE + "\""); if (getNode() != null) { buf.append(" node=\""); buf.append(StringUtils.escapeForXML(getNode())); buf.append("\""); } buf.append(">"); synchronized (identities) { for (Identity identity : identities) { buf.append(identity.toXML()); } } synchronized (features) { for (Feature feature : features) { buf.append(feature.toXML()); } } // Add packet extensions, if any are defined. buf.append(getExtensionsXML()); buf.append("</query>"); return buf.toString(); }
/** * Retrieve the last activity of a particular jid. * @param con the current Connection. * @param jid the JID of the user. * @return the LastActivity packet of the jid. * @throws XMPPException thrown if a server error has occured. * @deprecated This method only retreives the lapsed time since the last logout of a particular jid. * Replaced by {@link org.jivesoftware.smackx.LastActivityManager#getLastActivity(Connection, String) getLastActivity} */ public static LastActivity getLastActivity(Connection con, String jid) throws XMPPException { LastActivity activity = new LastActivity(); jid = StringUtils.parseBareAddress(jid); activity.setTo(jid); PacketCollector collector = con.createPacketCollector(new PacketIDFilter(activity.getPacketID())); con.sendPacket(activity); LastActivity response = (LastActivity) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return response; }
/** * Creates an OutgoingFileTransfer to send a file to another user. * * @param userID * The fully qualified jabber ID (i.e. full JID) with resource of the user to * send the file to. * @return The send file object on which the negotiated transfer can be run. * @exception IllegalArgumentException if userID is null or not a full JID */ public OutgoingFileTransfer createOutgoingFileTransfer(String userID) { if (userID == null) { throw new IllegalArgumentException("userID was null"); } // We need to create outgoing file transfers with a full JID since this method will later // use XEP-0095 to negotiate the stream. This is done with IQ stanzas that need to be addressed to a full JID // in order to reach an client entity. else if (!StringUtils.isFullJID(userID)) { throw new IllegalArgumentException("The provided user id was not a full JID (i.e. with resource part)"); } return new OutgoingFileTransfer(connection.getUser(), userID, fileTransferNegotiator.getNextStreamID(), fileTransferNegotiator); }
public static String xmppAddressToJid(String participant) { final String address = StringUtils.parseServer(participant); final String[] parts = address.split("\\."); //$NON-NLS-1$ final String server = parts[parts.length-1]; final String nick = StringUtils.parseResource(participant); return nick+"@"+server+JabberClient.JID_RESOURCE; //$NON-NLS-1$ }
public MultiUserChat join(JabberClient client, JabberPlayer me) throws XMPPException { MultiUserChat chat = new MultiUserChat(client.getConnection(), getJID()); chat.join(StringUtils.parseName(me.getJid())); if (!chat.isJoined()) { return null; } try { // This is necessary to create the room if it doesn't already exist // Configure the options we needs explicitly, don't depend on the server supplied defaults final Form configForm = chat.getConfigurationForm().createAnswerForm(); configForm.setAnswer(JABBER_MEMBERSONLY, isStartLocked()); configForm.setAnswer(JABBER_ALLOW_INVITES, false); configForm.setAnswer(JABBER_CHANGE_SUBJECT, false); configForm.setAnswer(JABBER_MODERATED, false); configForm.setAnswer(JABBER_PASSWORD_PROTECTED, false); configForm.setAnswer(JABBER_PERSISTENT, false); configForm.setAnswer(JABBER_PUBLIC_ROOM, true); chat.sendConfigurationForm(configForm); ownedByMe = true; owners.clear(); addOwner(jid); } catch (XMPPException e) { // 403 code means the room already exists and user is not an owner if (e.getXMPPError() != null && e.getXMPPError().getCode() != 403) { throw e; } } chat.addMessageListener(client); return chat; }
public synchronized JabberRoom getRoomByName(JabberClient client, String name) { String jid = StringUtils.escapeNode(client.getModule() + "-" + name).toLowerCase() + "@" + client.getConferenceService(); //$NON-NLS-1$ //$NON-NLS-2$ JabberRoom room = jidToRoom.get(jid); if (room == null) { room = new JabberRoom(name, jid, null, client); jidToRoom.put(jid, room); } return room; }