001/** 002 * 003 * Copyright 2017 Florian Schmaus. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smack.chat2; 018 019import org.jivesoftware.smack.Manager; 020import org.jivesoftware.smack.SmackException.NotConnectedException; 021import org.jivesoftware.smack.XMPPConnection; 022import org.jivesoftware.smack.packet.Message; 023import org.jivesoftware.smack.packet.Presence; 024 025import org.jxmpp.jid.EntityBareJid; 026import org.jxmpp.jid.EntityFullJid; 027import org.jxmpp.jid.Jid; 028 029public final class Chat extends Manager { 030 031 private final EntityBareJid jid; 032 033 volatile EntityFullJid lockedResource; 034 035 Presence lastPresenceOfLockedResource; 036 037 Chat(final XMPPConnection connection, EntityBareJid jid) { 038 super(connection); 039 this.jid = jid; 040 } 041 042 public void send(CharSequence message) throws NotConnectedException, InterruptedException { 043 Message stanza = connection() 044 .getStanzaFactory() 045 .buildMessageStanza() 046 .ofType(Message.Type.chat) 047 .setBody(message) 048 .build(); 049 send(stanza); 050 } 051 052 public void send(Message message) throws NotConnectedException, InterruptedException { 053 switch (message.getType()) { 054 case normal: 055 case chat: 056 break; 057 default: 058 throw new IllegalArgumentException("Message must be of type 'normal' or 'chat'"); 059 } 060 061 Jid to = lockedResource; 062 if (to == null) { 063 to = jid; 064 } 065 message.setTo(to); 066 067 connection().sendStanza(message); 068 } 069 070 public EntityBareJid getXmppAddressOfChatPartner() { 071 return jid; 072 } 073 074 void unlockResource() { 075 lockedResource = null; 076 lastPresenceOfLockedResource = null; 077 } 078}