public static JID full(String jid) {
   jid = StringUtils.defaultString(jid);
   return new JID(
       XmppStringUtils.parseLocalpart(jid),
       XmppStringUtils.parseDomain(jid),
       XmppStringUtils.parseResource(jid));
 }
  private void showInvitationInChat(final GameOfferPacket invitation) {
    invitation.setType(IQ.Type.result);
    invitation.setTo(invitation.getFrom());

    final ChatRoom room =
        SparkManager.getChatManager()
            .getChatRoom(XmppStringUtils.parseBareJid(invitation.getFrom()));

    String name = XmppStringUtils.parseLocalpart(invitation.getFrom());
    final JPanel panel = new JPanel();
    JLabel text = new JLabel("Game request from" + name);
    JLabel game = new JLabel("Battleships");
    game.setFont(new Font("Dialog", Font.BOLD, 24));
    game.setForeground(Color.RED);
    JButton accept = new JButton(Res.getString("button.accept").replace("&", ""));
    JButton decline = new JButton(Res.getString("button.decline").replace("&", ""));
    panel.add(text);
    panel.add(game);
    panel.add(accept);
    panel.add(decline);
    room.getTranscriptWindow().addComponent(panel);

    accept.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              SparkManager.getConnection().sendStanza(invitation);
            } catch (SmackException.NotConnectedException e1) {
              Log.warning("Unable to send invitation accept to " + invitation.getTo(), e1);
            }
            invitation.setStartingPlayer(!invitation.isStartingPlayer());
            ChatRoomOpeningListener.createWindow(invitation, invitation.getFrom());
            panel.remove(3);
            panel.remove(2);
            panel.repaint();
            panel.revalidate();
          }
        });

    decline.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            invitation.setType(IQ.Type.error);
            try {
              SparkManager.getConnection().sendStanza(invitation);
            } catch (SmackException.NotConnectedException e1) {
              Log.warning("Unable to send invitation decline to " + invitation.getTo(), e1);
            }
            panel.remove(3);
            panel.remove(2);
            panel.repaint();
            panel.revalidate();
          }
        });
  }
Example #3
0
 /**
  * Creates a new identity for an XMPP entity. 'category' and 'type' are required by <a
  * href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
  *
  * @param category the entity's category (required as per XEP-30).
  * @param type the entity's type (required as per XEP-30).
  * @param name the entity's name.
  * @param lang the entity's lang.
  */
 public Identity(String category, String type, String name, String lang) {
   this.category = StringUtils.requireNotNullOrEmpty(category, "category cannot be null");
   this.type = StringUtils.requireNotNullOrEmpty(type, "type cannot be null");
   this.key = XmppStringUtils.generateKey(category, type);
   this.name = name;
   this.lang = lang;
 }
Example #4
0
 /**
  * Adds a stanza(/packet) extension to the packet. Does nothing if extension is null.
  *
  * @param extension a stanza(/packet) extension.
  */
 public void addExtension(ExtensionElement extension) {
   if (extension == null) return;
   String key = XmppStringUtils.generateKey(extension.getElementName(), extension.getNamespace());
   synchronized (packetExtensions) {
     packetExtensions.put(key, extension);
   }
 }
Example #5
0
 /**
  * Check if a stanza(/packet) extension with the given element and namespace exists.
  *
  * <p>The argument <code>elementName</code> may be null.
  *
  * @param elementName
  * @param namespace
  * @return true if a stanza(/packet) extension exists, false otherwise.
  */
 public boolean hasExtension(String elementName, String namespace) {
   if (elementName == null) {
     return hasExtension(namespace);
   }
   String key = XmppStringUtils.generateKey(elementName, namespace);
   synchronized (packetExtensions) {
     return packetExtensions.containsKey(key);
   }
 }
Example #6
0
 /**
  * Returns the first extension that matches the specified element name and namespace, or
  * <tt>null</tt> if it doesn't exist. If the provided elementName is null, only the namespace is
  * matched. Extensions are are arbitrary XML elements in standard XMPP stanzas.
  *
  * @param elementName the XML element name of the extension. (May be null)
  * @param namespace the XML element namespace of the extension.
  * @return the extension, or <tt>null</tt> if it doesn't exist.
  */
 @SuppressWarnings("unchecked")
 public <PE extends ExtensionElement> PE getExtension(String elementName, String namespace) {
   if (namespace == null) {
     return null;
   }
   String key = XmppStringUtils.generateKey(elementName, namespace);
   ExtensionElement packetExtension;
   synchronized (packetExtensions) {
     packetExtension = packetExtensions.getFirst(key);
   }
   if (packetExtension == null) {
     return null;
   }
   return (PE) packetExtension;
 }
  /**
   * Calls an individual user by their VCard information.
   *
   * @param jid the users JID.
   */
  public void callByJID(String jid) {
    if (getStatus() == SipRegisterStatus.Registered) {
      final VCard vcard =
          SparkManager.getVCardManager().getVCard(XmppStringUtils.parseBareJid(jid));

      if (vcard != null) {
        String number = vcard.getPhoneWork("VOICE");
        if (!ModelUtil.hasLength(number)) {
          number = vcard.getPhoneHome("VOICE");
        }

        if (ModelUtil.hasLength(number)) {
          getDefaultGuiManager().dial(number);
        }
      }
    }
  }
Example #8
0
  /**
   * 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 (!XmppStringUtils.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 String string() {
   return XmppStringUtils.completeJidFrom(mLocal, mDomain, mResource);
 }
 public static JID bare(String jid) {
   jid = StringUtils.defaultString(jid);
   return new JID(XmppStringUtils.parseLocalpart(jid), XmppStringUtils.parseDomain(jid), "");
 }
Example #11
0
 /**
  * Remove the stanza(/packet) extension with the given elementName and namespace.
  *
  * @param elementName
  * @param namespace
  * @return the removed stanza(/packet) extension or null.
  */
 public ExtensionElement removeExtension(String elementName, String namespace) {
   String key = XmppStringUtils.generateKey(elementName, namespace);
   synchronized (packetExtensions) {
     return packetExtensions.remove(key);
   }
 }
Example #12
0
 /**
  * Return a list of all extensions with the given element name <em>and</em> namespace.
  *
  * <p>Changes to the returned set will update the stanza(/packet) extensions, if the returned set
  * is not the empty set.
  *
  * @param elementName the element name, must not be null.
  * @param namespace the namespace of the element(s), must not be null.
  * @return a set of all matching extensions.
  * @since 4.1
  */
 public List<ExtensionElement> getExtensions(String elementName, String namespace) {
   requireNotNullOrEmpty(elementName, "elementName must not be null or empty");
   requireNotNullOrEmpty(namespace, "namespace must not be null or empty");
   String key = XmppStringUtils.generateKey(elementName, namespace);
   return packetExtensions.getAll(key);
 }
Example #13
0
 /**
  * Returns true if this DiscoverInfo contains at least one Identity of the given category and
  * type.
  *
  * @param category the category to look for.
  * @param type the type to look for.
  * @return true if this DiscoverInfo contains a Identity of the given category and type.
  */
 public boolean hasIdentity(String category, String type) {
   String key = XmppStringUtils.generateKey(category, type);
   return identitiesSet.contains(key);
 }
  public static void initialize(final XMPPConnection theConnection, final History h) {
    final String jid = XmppStringUtils.parseBareJid(theConnection.getUser());
    // Hash fetch service
    theConnection.registerIQRequestHandler(
        new IQRequestHandler() {

          @Override
          public IQ handleIQRequest(IQ iqRequest) {
            HistorySyncQuery query = (HistorySyncQuery) iqRequest;
            if (query.getType() != IQ.Type.get) {
              throw new Error();
            }
            if (!XmppStringUtils.parseBareJid(iqRequest.getFrom()).equals(jid)) {
              return error(query);
            }

            HistorySyncHashes response = query.reply(h);
            return response;
          }

          @Override
          public Mode getMode() {
            return Mode.async;
          }

          @Override
          public Type getType() {
            return Type.get;
          }

          @Override
          public String getElement() {
            return "query";
          }

          @Override
          public String getNamespace() {
            return "http://jlenet.de/histsync";
          }
        });

    // sync service
    theConnection.registerIQRequestHandler(
        new IQRequestHandler() {
          @Override
          public IQ handleIQRequest(IQ iqRequest) {
            HistorySyncSet sync = (HistorySyncSet) iqRequest;
            if (!XmppStringUtils.parseBareJid(iqRequest.getFrom()).equals(jid)) {
              return error(sync);
            }

            if (Debug.ENABLED) {
              System.out.println("sync pack");
            }
            HistoryLeafNode hln =
                (HistoryLeafNode) h.getAnyBlock(sync.getHour() * History.BASE, History.LEVELS);
            if (Debug.ENABLED) {
              System.out.println("Have: " + hln.getMessages().size());
              System.out.println("Got: " + sync.getMessages().size());
            }
            TreeSet<HistoryEntry> forMe = new TreeSet<HistoryEntry>();
            TreeSet<HistoryEntry> forOther = new TreeSet<HistoryEntry>();
            Iterator<HistoryEntry> have = hln.getMessages().iterator();
            Iterator<HistoryEntry> got = sync.getMessages().iterator();
            HistoryEntry currentGot = null;
            HistoryEntry currentHave = null;
            while (have.hasNext() || got.hasNext() || currentHave != null || currentGot != null) {
              if (currentGot == null && got.hasNext()) {
                currentGot = got.next();
              }
              if (currentHave == null && have.hasNext()) {
                currentHave = have.next();
              }
              if (currentHave == null && currentGot == null) {
                // Should never happen;
                System.out.println("this should never happen");
                break;
              }
              if (currentGot == null
                  || (currentHave != null && currentHave.compareTo(currentGot) < 0)) {
                // current Have is alone
                forOther.add(currentHave);
                currentHave = null;
              } else if (currentHave == null || currentHave.compareTo(currentGot) > 0) {
                // current Got is alone
                forMe.add(currentGot);
                currentGot = null;
              } else {
                currentHave = null;
                currentGot = null;
              }
            }
            hln.getMessages().addAll(forMe);
            h.modified(sync.getHour() * History.BASE);
            // Construct response
            HistorySyncSet hss =
                new HistorySyncSet(
                    sync.getHour(), History.beautifyChecksum(hln.getChecksum()), false);
            hss.setMessages(forOther);
            hss.setType(IQ.Type.result);
            hss.setTo(sync.getFrom());
            hss.setStanzaId(sync.getStanzaId());
            h.store();

            if (Debug.ENABLED) {
              System.out.println("now Have: " + hln.getMessages().size());
              System.out.println("adding: " + forMe.size());
              System.out.println("for other: " + forOther.size());
            }
            return hss;
          }

          @Override
          public Mode getMode() {
            return Mode.async;
          }

          @Override
          public Type getType() {
            return Type.set;
          }

          @Override
          public String getElement() {
            return "syncSet";
          }

          @Override
          public String getNamespace() {
            return "http://jlenet.de/histsync#syncSet";
          }
        });
    theConnection.registerIQRequestHandler(
        new IQRequestHandler() {

          @Override
          public IQ handleIQRequest(IQ iqRequest) {
            HistorySyncSet sync = (HistorySyncSet) iqRequest;
            if (!XmppStringUtils.parseBareJid(iqRequest.getFrom()).equals(jid)) {
              return error(sync);
            }
            HistoryLeafNode hln =
                (HistoryLeafNode) h.getAnyBlock(sync.getHour() * History.BASE, History.LEVELS);
            if (Debug.ENABLED) {
              System.out.println("Have: " + hln.getMessages().size());
              System.out.println("Got: " + sync.getMessages().size());
            }

            hln.getMessages().addAll(sync.getMessages());
            h.modified(sync.getHour() * History.BASE);
            h.store();

            byte[] myChecksum = hln.getChecksum();
            String status;
            if (!Arrays.equals(myChecksum, History.parseChecksum(sync.getChecksum()))) {
              status = "success";
            } else {
              status = "mismatch";
            }
            HistorySyncUpdateResponse hss = new HistorySyncUpdateResponse(status);
            hss.setType(IQ.Type.result);
            hss.setTo(sync.getFrom());
            hss.setStanzaId(sync.getStanzaId());
            if (Debug.ENABLED) {
              System.out.println("update was: " + status);
            }
            if (Debug.ENABLED) {
              System.out.println("now Have: " + hln.getMessages().size());
            }
            return hss;
          }

          @Override
          public Type getType() {
            return Type.set;
          }

          @Override
          public Mode getMode() {
            return Mode.async;
          }

          @Override
          public String getElement() {
            return "syncUpdate";
          }

          @Override
          public String getNamespace() {
            return "http://jlenet.de/histsync#syncUpdate";
          }
        });

    ProviderManager.addIQProvider(
        "query", "http://jlenet.de/histsync", new HistorySyncQueryProvider());
    ProviderManager.addIQProvider(
        "hashes", "http://jlenet.de/histsync#hashes", new HistorySyncResponseProvider());

    HistorySyncSetProvider setProvider = new HistorySyncSetProvider();
    ProviderManager.addIQProvider("syncSet", "http://jlenet.de/histsync#syncSet", setProvider);
    ProviderManager.addIQProvider(
        "syncUpdate", "http://jlenet.de/histsync#syncUpdate", setProvider);
    ProviderManager.addIQProvider(
        "syncStatus",
        "http://jlenet.de/histsync#syncStatus",
        new HistorySyncUpdateResponse.Provider());

    ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(theConnection);
    manager.addFeature("http://jlenet.de/histsync#disco");
  }
 /**
  * Sets the server name, also known as XMPP domain of the target server.
  *
  * @param serviceName the XMPP domain of the target server.
  */
 void setServiceName(String serviceName) {
   serviceName = XmppStringUtils.parseDomain(serviceName);
   this.serviceName = serviceName;
 }
  @Override
  public void processPacket(Stanza packet) {
    PublicKeyPublish p = (PublicKeyPublish) packet;

    if (p.getType() == IQ.Type.result) {
      byte[] _publicKey = p.getPublicKey();

      if (_publicKey != null) {
        String from = XmppStringUtils.parseBareJid(p.getFrom());
        boolean selfJid = Authenticator.isSelfJID(getContext(), from);

        // is this our key?
        if (selfJid) {
          byte[] bridgeCertData;
          try {
            PersonalKey key = getApplication().getPersonalKey();

            bridgeCertData =
                X509Bridge.createCertificate(_publicKey, key.getAuthKeyPair().getPrivateKey())
                    .getEncoded();
          } catch (Exception e) {
            Log.e(MessageCenterService.TAG, "error decoding key data", e);
            bridgeCertData = null;
          }

          if (bridgeCertData != null) {
            // store key data in AccountManager
            Authenticator.setDefaultPersonalKey(
                getContext(), _publicKey, null, bridgeCertData, null);
            // invalidate cached personal key
            getApplication().invalidatePersonalKey();

            Log.v(MessageCenterService.TAG, "personal key updated.");
          }
        }

        String id = p.getStanzaId();

        // broadcast key update
        Intent i = new Intent(ACTION_PUBLICKEY);
        i.putExtra(EXTRA_PACKET_ID, id);
        i.putExtra(EXTRA_FROM, p.getFrom());
        i.putExtra(EXTRA_TO, p.getTo());
        i.putExtra(EXTRA_PUBLIC_KEY, _publicKey);
        sendBroadcast(i);

        // if we are not syncing and this is not a response for the Syncer
        // save the key immediately
        if (!SyncAdapter.getIQPacketId().equals(id) || !SyncAdapter.isActive(getContext())) {

          // updating server key
          if (XmppStringUtils.parseDomain(from).equals(from)) {
            Log.v("pubkey", "Updating server key for " + from);
            try {
              Keyring.setKey(getContext(), from, _publicKey);
            } catch (Exception e) {
              // TODO warn user
              Log.e(MessageCenterService.TAG, "unable to update user key", e);
            }
          } else {
            try {
              Log.v("pubkey", "Updating key for " + from);
              Keyring.setKey(
                  getContext(), from, _publicKey, selfJid ? MyUsers.Keys.TRUST_VERIFIED : -1);

              // update display name with uid (if empty)
              PGPUserID keyUid = PGP.parseUserId(_publicKey, getConnection().getServiceName());
              if (keyUid != null && keyUid.getName() != null)
                UsersProvider.updateDisplayNameIfEmpty(getContext(), from, keyUid.getName());

              // invalidate cache for this user
              Contact.invalidate(from);
            } catch (Exception e) {
              // TODO warn user
              Log.e(MessageCenterService.TAG, "unable to update user key", e);
            }
          }
        }
      }
    }
  }