Пример #1
0
 protected void createRoom(Map<String, Object> roomSpec, String serviceName) throws Exception {
   List<String> owners = (List) roomSpec.get("owners");
   JID owner = XMPPServer.getInstance().createJID("admin", null);
   if (owners != null && owners.size() > 0) {
     owner = new JID(owners.get(0));
   } else {
     owners = new ArrayList<String>();
     owners.add(owner.toBareJID());
     roomSpec.put("owners", owners);
   }
   String roomName = (String) roomSpec.get("roomName");
   Boolean isPersistent = (Boolean) roomSpec.get("persistent");
   MUCRoom room =
       XMPPServer.getInstance()
           .getMultiUserChatManager()
           .getMultiUserChatService(serviceName)
           .getChatRoom(roomName.toLowerCase(), owner);
   IntrospectionSupport.setProperties(room, roomSpec);
   room.setRolesToBroadcastPresence(new ArrayList<String>());
   setRoles(room, roomSpec);
   room.setCreationDate(new Date());
   room.setModificationDate(new Date());
   // Unlock the room, because the default configuration lock the room.
   room.unlock(room.getRole());
   System.out.println("isPersistent:" + isPersistent);
   if (isPersistent == null) {
     room.setPersistent(true);
   }
   if (room.isPersistent()) {
     room.saveToDB();
   }
 }
  /**
   * Adds the new user to others roster.
   *
   * @param newUser the new user
   * @param otherItem the other item
   * @param currentUser the current user
   * @throws ServiceException the service exception
   */
  private static void addNewUserToOthersRoster(
      User newUser, RosterItem otherItem, String currentUser) throws ServiceException {
    otherItem.getJid();
    UserManager userManager = UserManager.getInstance();

    // Is this user registered with our OF server?
    String username = otherItem.getJid().getNode();
    if (username != null
        && username.length() > 0
        && userManager.isRegisteredUser(username)
        && XMPPServer.getInstance()
            .isLocal(XMPPServer.getInstance().createJID(currentUser, null))) {
      try {
        User otherUser = userManager.getUser(username);
        Roster otherRoster = otherUser.getRoster();
        RosterItem oldUserOnOthersRoster =
            otherRoster.getRosterItem(XMPPServer.getInstance().createJID(currentUser, null));

        try {
          if (!oldUserOnOthersRoster.isOnlyShared()) {

            RosterItem justCreated =
                otherRoster.createRosterItem(
                    XMPPServer.getInstance().createJID(newUser.getUsername(), null),
                    oldUserOnOthersRoster.getNickname(),
                    oldUserOnOthersRoster.getGroups(),
                    true,
                    true);
            justCreated.setAskStatus(oldUserOnOthersRoster.getAskStatus());
            justCreated.setRecvStatus(oldUserOnOthersRoster.getRecvStatus());
            justCreated.setSubStatus(oldUserOnOthersRoster.getSubStatus());
            otherRoster.updateRosterItem(justCreated);
          }
        } catch (UserAlreadyExistsException e) {
          throw new ServiceException(
              "Could not create roster item for user ",
              newUser.getUsername(),
              ExceptionType.USER_ALREADY_EXISTS_EXCEPTION,
              Response.Status.CONFLICT,
              e);
        } catch (SharedGroupException e) {
          throw new ServiceException(
              "Could not create roster item, because it is a contact from a shared group",
              newUser.getUsername(),
              ExceptionType.USER_ALREADY_EXISTS_EXCEPTION,
              Response.Status.BAD_REQUEST,
              e);
        }
      } catch (UserNotFoundException e) {
        throw new ServiceException(
            "Could not create roster item for user "
                + newUser.getUsername()
                + "  because it is a contact from a shared group.",
            newUser.getUsername(),
            ExceptionType.USER_NOT_FOUND_EXCEPTION,
            Response.Status.NOT_FOUND,
            e);
      }
    }
  }
Пример #3
0
 public PubSubService getService() {
   if (XMPPServer.getInstance().getPubSubModule().getServiceID().equals(serviceId))
     return XMPPServer.getInstance().getPubSubModule();
   else {
     PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager();
     return serviceMgr.hasCachedService(new JID(serviceId))
         ? serviceMgr.getPEPService(serviceId)
         : null;
   }
 }
  /**
   * Login to the XMPP server and establish a non-anonymous user session using the given username
   * and resource. When <tt>createIfNotExist</tt> is <tt>true</tt>, a new user with the username
   * will be created and stored in the database if it does not exist. When <tt>false</tt>, and the
   * user does not exist, the method will not attempt the login. Whenever there's an error, the bot
   * will not login.
   *
   * @param username Username to login with.
   * @param resource The resource the user will bind to.
   * @param createIfNotExist When specified as <tt>true</tt>, a new user will be created and stored
   *     in the database if it does not exist.
   * @throws SessionAlreadyExistsException If the bot's session already exists.
   * @throws UserNotFoundException If it fails to create the user.
   */
  public void login(String username, String resource, boolean createIfNotExist)
      throws SessionAlreadyExistsException, UserNotFoundException {
    LOGGER.debug("Bot login with username:{} with resource:{}", username, resource);

    if (isClosed()) throw new SessionAlreadyExistsException();

    JID jid =
        new JID(
            username.toLowerCase(),
            XMPPServer.getInstance().getServerInfo().getXMPPDomain(),
            resource);
    ClientSession oldSession = SessionManager.getInstance().getSession(jid);

    // Check for session conflict
    if (oldSession != null) {
      try {
        int count = oldSession.incrementConflictCount();
        int conflictLimit = SessionManager.getInstance().getConflictKickLimit();
        if (conflictLimit != SessionManager.NEVER_KICK && count > conflictLimit) {
          // Kick out the old connection that is conflicting with the
          // new one
          StreamError error = new StreamError(StreamError.Condition.conflict);
          oldSession.deliverRawText(error.toXML());
          oldSession.close();
        } else throw new SessionAlreadyExistsException();
      } catch (Exception e) {
        LOGGER.error("Error during login", e);
      }
    }

    if (!XMPPServer.getInstance().getUserManager().isRegisteredUser(jid.getNode())) {
      if (createIfNotExist) {
        try {
          // Bot doesn't care of whatever password it is.
          XMPPServer.getInstance()
              .getUserManager()
              .createUser(jid.getNode(), StringUtils.randomString(15), null, null);
        } catch (UserAlreadyExistsException e) {
          // Ignore
        }
      } else {
        throw new UserNotFoundException();
      }
    }

    localClientSession = SessionManager.getInstance().createClientSession(this);

    localClientSession.setAuthToken(new AuthToken(jid.getNode()), jid.getResource());

    if (packetProcessor != null) {
      packetProcessor.initialize(this);
      initProcessor = true;
    }
  }
Пример #5
0
 @Override
 public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
   byte[] bytes = ExternalizableUtil.getInstance().readByteArray(in);
   // Retrieve the NodeID but try to use the singleton instance
   if (XMPPServer.getInstance().getNodeID().equals(bytes)) {
     nodeID = XMPPServer.getInstance().getNodeID();
   } else {
     nodeID = NodeID.getInstance(bytes);
   }
   available = ExternalizableUtil.getInstance().readBoolean(in);
 }
Пример #6
0
  public void createChatRoom(
      String domain,
      String ownerJid,
      String roomName,
      boolean listRoomInDirectory,
      boolean makeRoomModerated,
      boolean makeRoomMembersOnly,
      boolean allowOccupantsToInviteOthers,
      boolean isPublicRoom,
      boolean logRoomConversations,
      boolean isPersistent,
      String password,
      String description,
      String conferenceExtension)
      throws Exception {
    MultiUserChatService mucService =
        XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(domain);
    if (mucService == null) {
      mucService =
          XMPPServer.getInstance()
              .getMultiUserChatManager()
              .createMultiUserChatService(domain, description, false);
      Collection<JID> admins = XMPPServer.getInstance().getAdmins();
      JID admin = admins.iterator().next();
      mucService.addUserAllowedToCreate(admin.toBareJID());
    }
    MUCRoom mucRoom = mucService.getChatRoom(roomName, new JID(ownerJid));

    mucRoom.setPersistent(isPersistent);
    mucRoom.setCanAnyoneDiscoverJID(true);
    mucRoom.setChangeNickname(true);
    mucRoom.setModerated(makeRoomModerated);
    mucRoom.setMembersOnly(makeRoomMembersOnly);
    mucRoom.setRegistrationEnabled(true);
    mucRoom.setPublicRoom(isPublicRoom);
    mucRoom.setCanAnyoneDiscoverJID(true);
    mucRoom.setCanOccupantsInvite(allowOccupantsToInviteOthers);
    mucRoom.setDescription(description);
    mucRoom.setPassword(password);
    mucRoom.setCanOccupantsChangeSubject(true);
    mucRoom.setChangeNickname(true);
    mucRoom.setLogEnabled(logRoomConversations);

    mucRoom.setDescription(description);

    mucRoom.setPassword(password);
    /* The conference extension is the voice conf bridge extension */
    this.roomNameToConferenceExtensionMap.put(domain + "." + roomName, conferenceExtension);
  }
Пример #7
0
 public void authenticate(String username, String token, String digest)
     throws UnauthorizedException {
   if (username == null || token == null || digest == null) {
     throw new UnauthorizedException();
   }
   username = username.trim().toLowerCase();
   if (username.contains("@")) {
     // Check that the specified domain matches the server's domain
     int index = username.indexOf("@");
     String domain = username.substring(index + 1);
     if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
       username = username.substring(0, index);
     } else {
       // Unknown domain. Return authentication failed.
       throw new UnauthorizedException();
     }
   }
   try {
     String password = getPassword(username);
     String anticipatedDigest = AuthFactory.createDigest(token, password);
     if (!digest.equalsIgnoreCase(anticipatedDigest)) {
       throw new UnauthorizedException();
     }
   } catch (UserNotFoundException unfe) {
     throw new UnauthorizedException();
   }
   // Got this far, so the user must be authorized.
 }
  @Override
  public String getAvailableStreamFeatures() {
    // Offer authenticate and registration only if TLS was not required or if required
    // then the connection is already secured
    if (conn.getTlsPolicy() == Connection.TLSPolicy.required && !conn.isSecure()) {
      return null;
    }

    StringBuilder sb = new StringBuilder(200);

    // Include Stream Compression Mechanism
    if (conn.getCompressionPolicy() != Connection.CompressionPolicy.disabled
        && !conn.isCompressed()) {
      sb.append(
          "<compression xmlns=\"http://jabber.org/features/compress\"><method>zlib</method></compression>");
    }

    if (getAuthToken() == null) {
      // Advertise that the server supports Non-SASL Authentication
      sb.append("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
      // Advertise that the server supports In-Band Registration
      if (XMPPServer.getInstance().getIQRegisterHandler().isInbandRegEnabled()) {
        sb.append("<register xmlns=\"http://jabber.org/features/iq-register\"/>");
      }
    } else {
      // If the session has been authenticated then offer resource binding
      // and session establishment
      sb.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
      sb.append("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
    }
    return sb.toString();
  }
  /**
   * Retrieves user properties for a Clearspace user in XML format.
   *
   * @param username Username to look up.
   * @return XML Element including information about the user.
   * @throws UserNotFoundException The user was not found in the Clearspace database or there was an
   *     error.
   */
  private Element getUserByUsername(String username) throws UserNotFoundException {
    // Checks if the user is local
    if (username.contains("@")) {
      if (!XMPPServer.getInstance().isLocal(new JID(username))) {
        throw new UserNotFoundException("Cannot load user of remote server: " + username);
      }
      username = username.substring(0, username.lastIndexOf("@"));
    }

    try {
      // Un-escape username.
      username = JID.unescapeNode(username);
      // Encode potentially non-ASCII characters
      username = URLUTF8Encoder.encode(username);
      // Requests the user
      String path = USER_URL_PREFIX + "users/" + username;
      // return the response
      return ClearspaceManager.getInstance().executeRequest(GET, path);
    } catch (UserNotFoundException e) {
      throw e;
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UserNotFoundException
      throw new UserNotFoundException("Error loading the user from Clearspace: ", e);
    }
  }
Пример #10
0
  /**
   * Create a new role.
   *
   * @param chatserver the server hosting the role.
   * @param chatroom the room the role is valid in.
   * @param nickname the nickname of the user in the role.
   * @param role the role of the user in the room.
   * @param affiliation the affiliation of the user in the room.
   * @param chatuser the user on the chat server.
   * @param presence the presence sent by the user to join the room.
   * @param packetRouter the packet router for sending messages from this role.
   */
  public LocalMUCRole(
      MultiUserChatService chatserver,
      LocalMUCRoom chatroom,
      String nickname,
      MUCRole.Role role,
      MUCRole.Affiliation affiliation,
      LocalMUCUser chatuser,
      Presence presence,
      PacketRouter packetRouter) {
    this.room = chatroom;
    this.nick = nickname;
    this.user = chatuser;
    this.server = chatserver;
    this.router = packetRouter;
    this.role = role;
    this.affiliation = affiliation;
    // Cache the user's session (will only work for local users)
    this.session = XMPPServer.getInstance().getSessionManager().getSession(presence.getFrom());

    extendedInformation =
        DocumentHelper.createElement(QName.get("x", "http://jabber.org/protocol/muc#user"));
    calculateExtendedInformation();
    rJID = new JID(room.getName(), server.getServiceDomain(), nick);
    setPresence(presence);
    // Check if new occupant wants to be a deaf occupant
    Element element =
        presence.getElement().element(QName.get("x", "http://jivesoftware.org/protocol/muc"));
    if (element != null) {
      voiceOnly = element.element("deaf-occupant") != null;
    }
    // Add the new role to the list of roles
    user.addRole(room.getName(), this);
  }
Пример #11
0
 /**
  * Retrieves the last n conversations from the system that were created after the given
  * conversationID.
  *
  * @param count the count of conversations to return.
  * @param mostRecentConversationID the last conversationID that has been retrieved.
  * @return a List of Map objects.
  */
 public List<Map<String, Long>> getNLatestConversations(int count, long mostRecentConversationID) {
   // TODO Fix plugin name 2 lines below and missing classes
   List<Map<String, Long>> cons = new ArrayList<Map<String, Long>>();
   MonitoringPlugin plugin =
       (MonitoringPlugin)
           XMPPServer.getInstance().getPluginManager().getPlugin(MonitoringConstants.NAME);
   ConversationManager conversationManager =
       (ConversationManager) plugin.getModule(ConversationManager.class);
   Collection<Conversation> conversations = conversationManager.getConversations();
   List<Conversation> lConversations =
       Arrays.asList(conversations.toArray(new Conversation[conversations.size()]));
   Collections.sort(lConversations, conversationComparator);
   int counter = 0;
   for (Iterator<Conversation> i = lConversations.iterator(); i.hasNext() && counter < count; ) {
     Conversation con = i.next();
     if (mostRecentConversationID == con.getConversationID()) {
       break;
     } else {
       Map mCon = new HashMap();
       mCon.put("conversationid", con.getConversationID());
       String users[];
       int usersIdx = 0;
       if (con.getRoom() == null) {
         users = new String[con.getParticipants().size()];
         for (JID jid : con.getParticipants()) {
           String identifier = jid.toBareJID();
           try {
             identifier = UserNameManager.getUserName(jid, jid.toBareJID());
           } catch (UserNotFoundException e) {
             // Ignore
           }
           users[usersIdx++] = StringUtils.abbreviate(identifier, 20);
         }
       } else {
         users = new String[2];
         users[0] =
             LocaleUtils.getLocalizedString(
                 "dashboard.group_conversation", MonitoringConstants.NAME);
         try {
           users[1] =
               "(<i>"
                   + LocaleUtils.getLocalizedString("muc.room.summary.room")
                   + ": <a href='../../muc-room-occupants.jsp?roomName="
                   + URLEncoder.encode(con.getRoom().getNode(), "UTF-8")
                   + "'>"
                   + con.getRoom().getNode()
                   + "</a></i>)";
         } catch (UnsupportedEncodingException e) {
           Log.error(e.getMessage(), e);
         }
       }
       mCon.put("users", users);
       mCon.put("lastactivity", formatTimeLong(con.getLastActivity()));
       mCon.put("messages", con.getMessageCount());
       cons.add(0, mCon);
       counter++;
     }
   }
   return cons;
 }
Пример #12
0
  @Override
  public IQ query(Component component, IQ packet, long timeout) throws ComponentException {
    final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<>(8);
    XMPPServer.getInstance()
        .getIQRouter()
        .addIQResultListener(
            packet.getID(),
            new IQResultListener() {
              @Override
              public void receivedAnswer(IQ packet) {
                answer.offer(packet);
              }

              @Override
              public void answerTimeout(String packetId) {
                Log.warn(
                    "An answer to a previously sent IQ stanza was never received. Packet id: "
                        + packetId);
              }
            });
    sendPacket(component, packet);
    IQ reply = null;
    try {
      reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      // Ignore
    }
    return reply;
  }
Пример #13
0
 public PrivacyList(String username, String name, boolean isDefault, Element listElement) {
   this.userJID = XMPPServer.getInstance().createJID(username, null, true);
   this.name = name;
   this.isDefault = isDefault;
   // Set the new list items
   updateList(listElement);
 }
Пример #14
0
  public User loadUser(String username) throws UserNotFoundException {
    if (username.contains("@")) {
      if (!XMPPServer.getInstance().isLocal(new JID(username))) {
        throw new UserNotFoundException("Cannot load user of remote server: " + username);
      }
      username = username.substring(0, username.lastIndexOf("@"));
    }
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      con = DbConnectionManager.getConnection();
      pstmt = con.prepareStatement(LOAD_USER);
      pstmt.setString(1, username);
      rs = pstmt.executeQuery();
      if (!rs.next()) {
        throw new UserNotFoundException();
      }
      String name = rs.getString(1);
      String email = rs.getString(2);
      Date creationDate = new Date(Long.parseLong(rs.getString(3).trim()));
      Date modificationDate = new Date(Long.parseLong(rs.getString(4).trim()));

      return new User(username, name, email, creationDate, modificationDate);
    } catch (Exception e) {
      throw new UserNotFoundException(e);
    } finally {
      DbConnectionManager.closeConnection(rs, pstmt, con);
    }
  }
 public ClientSessionConnection(
     String connectionManagerName, String hostName, String hostAddress) {
   this.connectionManagerName = connectionManagerName;
   multiplexerManager = ConnectionMultiplexerManager.getInstance();
   serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
   this.hostName = hostName;
   this.hostAddress = hostAddress;
 }
Пример #16
0
  @Override
  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    plugin = (WixatPlugin) XMPPServer.getInstance().getPluginManager().getPlugin("wixat");

    // Exclude this servlet from requering the user to login
    AuthCheckFilter.addExclude("wixat/check");
  }
Пример #17
0
 /**
  * Returns the user's roster. A roster is a list of users that the user wishes to know if they are
  * online. Rosters are similar to buddy groups in popular IM clients.
  *
  * @return the user's roster.
  */
 public Roster getRoster() {
   try {
     return XMPPServer.getInstance().getRosterManager().getRoster(username);
   } catch (UserNotFoundException unfe) {
     Log.error(unfe.getMessage(), unfe);
     return null;
   }
 }
Пример #18
0
 /**
  * Returns the Clearspace user id the user by JID.
  *
  * @param user JID of user to retrieve ID of.
  * @return The ID number of the user in Clearspace.
  * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found.
  */
 protected long getUserID(JID user) throws UserNotFoundException {
   // User's id are only for local users
   XMPPServer server = XMPPServer.getInstance();
   if (!server.isLocal(user)) {
     throw new UserNotFoundException("Cannot load user of remote server: " + user.toString());
   }
   return getUserID(user.getNode());
 }
 /**
  * Copy to groups.
  *
  * @param currentUser the current user
  * @param newUser the new user
  */
 private static void copyToGroups(String currentUser, String newUser) {
   GroupManager groupManager = GroupManager.getInstance();
   for (Group group : groupManager.getGroups()) {
     if (group.isUser(currentUser)) {
       group.getMembers().add(XMPPServer.getInstance().createJID(newUser, null));
     }
   }
 }
Пример #20
0
 @Override
 public void stop() {
   super.stop();
   if (getAddress() != null) {
     // Remove the route to this service
     XMPPServer.getInstance().getRoutingTable().removeComponentRoute(getAddress());
   }
 }
Пример #21
0
 private Roster getRoster() {
   try {
     return XMPPServer.getInstance().getRosterManager().getRoster(userJID.getNode());
   } catch (UserNotFoundException e) {
     Log.warn("Roster not found for user: " + userJID);
   }
   return null;
 }
 @Override
 public void addHostname(String hostname) {
   synchronized (hostnames) {
     hostnames.add(hostname);
   }
   // Add a new route for this new session
   XMPPServer.getInstance()
       .getRoutingTable()
       .addServerRoute(new JID(null, hostname, null, true), this);
 }
Пример #23
0
  public void stop() {
    super.stop();

    // Stops the Clearspace MUC transcript manager
    mucTranscriptManager.stop();

    // Unregister/shut down custom MUC service
    XMPPServer.getInstance()
        .getMultiUserChatManager()
        .unregisterMultiUserChatService(MUC_SUBDOMAIN);
  }
Пример #24
0
 private Map getUpdatedStat(String statkey, long[] timePeriod) {
   MonitoringPlugin plugin =
       (MonitoringPlugin)
           XMPPServer.getInstance().getPluginManager().getPlugin(MonitoringConstants.NAME);
   StatsViewer viewer = (StatsViewer) plugin.getModule(StatsViewer.class);
   String[] lowHigh = getLowAndHigh(statkey, timePeriod);
   Map stat = new HashMap();
   stat.put("low", lowHigh[0]);
   stat.put("high", lowHigh[1]);
   stat.put("count", (int) viewer.getCurrentValue(statkey)[0]);
   return stat;
 }
Пример #25
0
  @Override
  public void sendPacket(Component component, Packet packet) {
    if (packet != null && packet.getFrom() == null) {
      throw new IllegalArgumentException(
          "Packet with no FROM address was received from component.");
    }

    PacketRouter router = XMPPServer.getInstance().getPacketRouter();
    if (router != null) {
      router.route(packet);
    }
  }
Пример #26
0
 public LocalMUCRoom getRoom() {
   MultiUserChatService mucService =
       XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain);
   if (mucService == null) {
     throw new IllegalArgumentException("MUC service not found for subdomain: " + subdomain);
   }
   LocalMUCRoom room = (LocalMUCRoom) mucService.getChatRoom(roomName);
   if (room == null) {
     throw new IllegalArgumentException("Room not found: " + roomName);
   }
   return room;
 }
Пример #27
0
 public void process(Packet packet) {
   // Check that the requested packet can be processed
   if (canProcess(packet)) {
     // Perform the actual processing of the packet. This usually implies sending
     // the packet to the entity
     try {
       // Invoke the interceptors before we send the packet
       InterceptorManager.getInstance().invokeInterceptors(packet, this, false, false);
       deliver(packet);
       // Invoke the interceptors after we have sent the packet
       InterceptorManager.getInstance().invokeInterceptors(packet, this, false, true);
     } catch (PacketRejectedException e) {
       // An interceptor rejected the packet so do nothing
     } catch (Exception e) {
       Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
     }
   } else {
     // http://xmpp.org/extensions/xep-0016.html#protocol-error
     if (packet instanceof Message) {
       // For message stanzas, the server SHOULD return an error, which SHOULD be
       // <service-unavailable/>.
       Message message = (Message) packet;
       Message result = message.createCopy();
       result.setTo(message.getFrom());
       result.setError(PacketError.Condition.service_unavailable);
       XMPPServer.getInstance().getRoutingTable().routePacket(message.getFrom(), result, true);
     } else if (packet instanceof IQ) {
       // For IQ stanzas of type "get" or "set", the server MUST return an error, which SHOULD be
       // <service-unavailable/>.
       // IQ stanzas of other types MUST be silently dropped by the server.
       IQ iq = (IQ) packet;
       if (iq.getType() == IQ.Type.get || iq.getType() == IQ.Type.set) {
         IQ result = IQ.createResultIQ(iq);
         result.setError(PacketError.Condition.service_unavailable);
         XMPPServer.getInstance().getRoutingTable().routePacket(iq.getFrom(), result, true);
       }
     }
   }
 }
Пример #28
0
  private synchronized void doConfigClearspace() throws UnauthorizedException {

    Log.debug("Starting Clearspace configuration.");

    List<String> bindInterfaces = getServerInterfaces();
    if (bindInterfaces.size() == 0) {
      // We aren't up and running enough to tell Clearspace what interfaces to bind to.
      Log.debug("No bind interfaces found to config Clearspace");
      throw new IllegalStateException("There are no binding interfaces.");
    }

    try {

      XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo();

      String path = IM_URL_PREFIX + "configureComponent/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("configureComponent");
      Element domainE = rootE.addElement("domain");
      domainE.setText(serverInfo.getXMPPDomain());
      for (String bindInterface : bindInterfaces) {
        Element hostsE = rootE.addElement("hosts");
        hostsE.setText(bindInterface);
      }
      Element portE = rootE.addElement("port");
      portE.setText(String.valueOf(ExternalComponentManager.getServicePort()));

      Log.debug(
          "Trying to configure Clearspace with: Domain: "
              + serverInfo.getXMPPDomain()
              + ", hosts: "
              + bindInterfaces.toString()
              + ", port: "
              + port);

      executeRequest(POST, path, rootE.asXML());

      // Done, Clearspace was configured correctly, clear the task
      Log.debug("Clearspace was configured, stopping the task.");
      TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask);
      configClearspaceTask = null;

    } catch (UnauthorizedException ue) {
      throw ue;
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UnsupportedOperationException
      throw new UnsupportedOperationException("Unexpected error", e);
    }
  }
Пример #29
0
  /**
   * Sends an IQ packet to the Clearspace external component and returns the IQ packet returned by
   * CS or <tt>null</tt> if no answer was received before the specified timeout.
   *
   * @param packet IQ packet to send.
   * @param timeout milliseconds to wait before timing out.
   * @return IQ packet returned by Clearspace responsing the packet we sent.
   */
  public IQ query(final IQ packet, int timeout) {
    // Complain if FROM is empty
    if (packet.getFrom() == null) {
      throw new IllegalStateException("IQ packets with no FROM cannot be sent to Clearspace");
    }
    // If CS is not connected then return null
    if (clearspaces.isEmpty()) {
      return null;
    }
    // Set the target address to the IQ packet. Roate list so we distribute load
    String component;
    synchronized (clearspaces) {
      component = clearspaces.get(0);
      Collections.rotate(clearspaces, 1);
    }
    packet.setTo(component);
    final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8);
    final IQRouter router = XMPPServer.getInstance().getIQRouter();
    router.addIQResultListener(
        packet.getID(),
        new IQResultListener() {
          public void receivedAnswer(IQ packet) {
            answer.offer(packet);
          }

          public void answerTimeout(String packetId) {
            Log.warn("No answer from Clearspace was received for IQ stanza: " + packet);
          }
        });
    XMPPServer.getInstance().getIQRouter().route(packet);
    IQ reply = null;
    try {
      reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      // Ignore
    }
    return reply;
  }
Пример #30
0
  @Override
  public void start() {
    // Set this ComponentManager as the current component manager
    ComponentManagerFactory.setComponentManager(instance);

    XMPPServer server = XMPPServer.getInstance();
    serverDomain = server.getServerInfo().getXMPPDomain();
    // Set the address of this internal service. component.[domain]
    serviceAddress = new JID(null, "component." + serverDomain, null);
    if (!server.isSetupMode()) {
      // Add a route to this service
      server.getRoutingTable().addComponentRoute(getAddress(), this);
    }
  }