/**
  * 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;
 }
示例#2
0
 public void close() {
   boolean wasClosed = false;
   synchronized (this) {
     if (!isClosed()) {
       try {
         if (session != null) {
           session.setStatus(Session.STATUS_CLOSED);
         }
         synchronized (writer) {
           try {
             // Register that we started sending data on the connection
             writeStarted();
             writer.write("</stream:stream>");
             if (flashClient) {
               writer.write('\0');
             }
             writer.flush();
           } catch (IOException e) {
           } finally {
             // Register that we finished sending data on the connection
             writeFinished();
           }
         }
       } catch (Exception e) {
         Log.error(
             LocaleUtils.getLocalizedString("admin.error.close") + "\n" + this.toString(), e);
       }
       closeConnection();
       wasClosed = true;
     }
   }
   if (wasClosed) {
     notifyCloseListeners();
   }
 }
 /* (non-Javadoc)
  * @see org.jivesoftware.openfire.roster.RosterItemProvider#getItemCount(java.lang.String)
  */
 public int getItemCount(String username) {
   int count = 0;
   Connection con = null;
   PreparedStatement pstmt = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(COUNT_ROSTER_ITEMS);
     pstmt.setString(1, username);
     ResultSet rs = pstmt.executeQuery();
     if (rs.next()) {
       count = rs.getInt(1);
     }
   } catch (SQLException e) {
     Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
   } finally {
     try {
       if (pstmt != null) {
         pstmt.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
     try {
       if (con != null) {
         con.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
   }
   return count;
 }
 /* (non-Javadoc)
  * @see org.jivesoftware.openfire.roster.RosterItemProvider#getUsernames(java.lang.String)
  */
 public Iterator<String> getUsernames(String jid) {
   List<String> answer = new ArrayList<String>();
   Connection con = null;
   PreparedStatement pstmt = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(LOAD_USERNAMES);
     pstmt.setString(1, jid);
     ResultSet rs = pstmt.executeQuery();
     while (rs.next()) {
       answer.add(rs.getString(1));
     }
   } catch (SQLException e) {
     Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
   } finally {
     try {
       if (pstmt != null) {
         pstmt.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
     try {
       if (con != null) {
         con.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
   }
   return answer.iterator();
 }
 /**
  * Returns the approximate size (in bytes) of the XML messages stored for a particular user.
  *
  * @param username the username of the user.
  * @return the approximate size of stored messages (in bytes).
  */
 public int getSize(String username) {
   // See if the size is cached.
   if (sizeCache.containsKey(username)) {
     return sizeCache.get(username);
   }
   int size = 0;
   Connection con = null;
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(SELECT_SIZE_OFFLINE);
     pstmt.setString(1, username);
     rs = pstmt.executeQuery();
     if (rs.next()) {
       size = rs.getInt(1);
     }
     // Add the value to cache.
     sizeCache.put(username, size);
   } catch (Exception e) {
     Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
   } finally {
     DbConnectionManager.closeConnection(rs, pstmt, con);
   }
   return size;
 }
示例#6
0
 /**
  * Sends an event notification for the last published item to the subscriber. If the subscription
  * has not yet been authorized or is pending to be configured then no notification is going to be
  * sent.
  *
  * <p>Depending on the subscription configuration the event notification may or may not have a
  * payload, may not be sent if a keyword (i.e. filter) was defined and it was not matched.
  *
  * @param publishedItem the last item that was published to the node.
  */
 void sendLastPublishedItem(PublishedItem publishedItem) {
   // Check if the published item can be sent to the subscriber
   if (!canSendPublicationEvent(publishedItem.getNode(), publishedItem)) {
     return;
   }
   // Send event notification to the subscriber
   Message notification = new Message();
   Element event =
       notification.getElement().addElement("event", "http://jabber.org/protocol/pubsub#event");
   Element items = event.addElement("items");
   items.addAttribute("node", node.getNodeID());
   Element item = items.addElement("item");
   if (((LeafNode) node).isItemRequired()) {
     item.addAttribute("id", publishedItem.getID());
   }
   if (node.isPayloadDelivered() && publishedItem.getPayload() != null) {
     item.add(publishedItem.getPayload().createCopy());
   }
   // Add a message body (if required)
   if (isIncludingBody()) {
     notification.setBody(LocaleUtils.getLocalizedString("pubsub.notification.message.body"));
   }
   // Include date when published item was created
   notification
       .getElement()
       .addElement("delay", "urn:xmpp:delay")
       .addAttribute("stamp", fastDateFormat.format(publishedItem.getCreationDate()));
   // Send the event notification to the subscriber
   service.sendNotification(node, notification, jid);
 }
 /**
  * About as simple as it gets. The thread spins around an accept call getting sockets and creating
  * new reading threads for each new connection.
  */
 @Override
 public void run() {
   while (notTerminated) {
     try {
       Socket sock = serverSocket.accept();
       if (sock != null) {
         Log.debug("Connect " + sock.toString());
         SocketReader reader = connManager.createSocketReader(sock, false, serverPort, true);
         Thread thread = new Thread(reader, reader.getName());
         thread.setDaemon(true);
         thread.setPriority(Thread.NORM_PRIORITY);
         thread.start();
       }
     } catch (IOException ie) {
       if (notTerminated) {
         Log.error(LocaleUtils.getLocalizedString("admin.error.accept"), ie);
       }
     } catch (Throwable e) {
       Log.error(LocaleUtils.getLocalizedString("admin.error.accept"), e);
     }
   }
 }
示例#8
0
  /**
   * Handles all roster queries. There are two major types of queries:
   *
   * <ul>
   *   <li>Roster remove - A forced removal of items from a roster. Roster removals are the only
   *       roster queries allowed to directly affect the roster from another user.
   *   <li>Roster management - A local user looking up or updating their roster.
   * </ul>
   *
   * @param packet The update packet
   * @return The reply or null if no reply
   */
  public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    try {
      IQ returnPacket = null;
      org.xmpp.packet.Roster roster = (org.xmpp.packet.Roster) packet;

      JID recipientJID = packet.getTo();

      // The packet is bound for the server and must be roster management
      if (recipientJID == null
          || recipientJID.getNode() == null
          || !UserManager.getInstance().isRegisteredUser(recipientJID.getNode())) {
        returnPacket = manageRoster(roster);
      }
      // The packet must be a roster removal from a foreign domain user.
      else {
        removeRosterItem(roster);
      }
      return returnPacket;
    } catch (SharedGroupException e) {
      IQ result = IQ.createResultIQ(packet);
      result.setChildElement(packet.getChildElement().createCopy());
      result.setError(PacketError.Condition.not_acceptable);
      return result;
    } catch (Exception e) {
      if (e.getCause() instanceof IDNAException) {
        Log.warn(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.jid_malformed);
        return result;
      } else {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.internal_server_error);
        return result;
      }
    }
  }
示例#9
0
 private void closeConnection() {
   try {
     if (tlsStreamHandler == null) {
       socket.close();
     } else {
       // Close the channels since we are using TLS (i.e. NIO). If the channels implement
       // the InterruptibleChannel interface then any other thread that was blocked in
       // an I/O operation will be interrupted and an exception thrown
       tlsStreamHandler.close();
     }
   } catch (Exception e) {
     Log.error(LocaleUtils.getLocalizedString("admin.error.close") + "\n" + this.toString(), e);
   }
 }
  /**
   * Adds a message to this message store. Messages will be stored and made available for later
   * delivery.
   *
   * @param message the message to store.
   */
  public void addMessage(Message message) {
    if (message == null) {
      return;
    }
    if (!shouldStoreMessage(message)) {
      return;
    }
    JID recipient = message.getTo();
    String username = recipient.getNode();
    // If the username is null (such as when an anonymous user), don't store.
    if (username == null || !UserManager.getInstance().isRegisteredUser(recipient)) {
      return;
    } else if (!XMPPServer.getInstance()
        .getServerInfo()
        .getXMPPDomain()
        .equals(recipient.getDomain())) {
      // Do not store messages sent to users of remote servers
      return;
    }

    long messageID = SequenceManager.nextID(JiveConstants.OFFLINE);

    // Get the message in XML format.
    String msgXML = message.getElement().asXML();

    Connection con = null;
    PreparedStatement pstmt = null;
    try {
      con = DbConnectionManager.getConnection();
      pstmt = con.prepareStatement(INSERT_OFFLINE);
      pstmt.setString(1, username);
      pstmt.setLong(2, messageID);
      pstmt.setString(3, StringUtils.dateToMillis(new java.util.Date()));
      pstmt.setInt(4, msgXML.length());
      pstmt.setString(5, msgXML);
      pstmt.executeUpdate();
    } catch (Exception e) {
      Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    } finally {
      DbConnectionManager.closeConnection(pstmt, con);
    }

    // Update the cached size if it exists.
    if (sizeCache.containsKey(username)) {
      int size = sizeCache.get(username);
      size += msgXML.length();
      sizeCache.put(username, size);
    }
  }
 /**
  * Manage the subscription request. This method updates a user's roster state, storing any changes
  * made, and updating the roster owner if changes occured.
  *
  * @param target The roster target's jid (the item's jid to be changed)
  * @param isSending True if the request is being sent by the owner
  * @param type The subscription change type (subscribe, unsubscribe, etc.)
  * @param roster The Roster that is updated.
  * @return <tt>true</tt> if the subscription state has changed.
  */
 private boolean manageSub(JID target, boolean isSending, Presence.Type type, Roster roster)
     throws UserAlreadyExistsException, SharedGroupException {
   RosterItem item = null;
   RosterItem.AskType oldAsk;
   RosterItem.SubType oldSub = null;
   RosterItem.RecvType oldRecv;
   boolean newItem = false;
   try {
     if (roster.isRosterItem(target)) {
       item = roster.getRosterItem(target);
     } else {
       if (Presence.Type.unsubscribed == type
           || Presence.Type.unsubscribe == type
           || Presence.Type.subscribed == type) {
         // Do not create a roster item when processing a confirmation of
         // an unsubscription or receiving an unsubscription request or a
         // subscription approval from an unknown user
         return false;
       }
       item = roster.createRosterItem(target, false, true);
       newItem = true;
     }
     // Get a snapshot of the item state
     oldAsk = item.getAskStatus();
     oldSub = item.getSubStatus();
     oldRecv = item.getRecvStatus();
     // Update the item state based in the received presence type
     updateState(item, type, isSending);
     // Update the roster IF the item state has changed
     if (oldAsk != item.getAskStatus()
         || oldSub != item.getSubStatus()
         || oldRecv != item.getRecvStatus()) {
       roster.updateRosterItem(item);
     } else if (newItem) {
       // Do not push items with a state of "None + Pending In"
       if (item.getSubStatus() != RosterItem.SUB_NONE
           || item.getRecvStatus() != RosterItem.RECV_SUBSCRIBE) {
         roster.broadcast(item, false);
       }
     }
   } catch (UserNotFoundException e) {
     // Should be there because we just checked that it's an item
     Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
   }
   return oldSub != item.getSubStatus();
 }
示例#12
0
  /**
   * Closes the session, the virtual connection and notifies listeners that the connection has been
   * closed.
   */
  @Override
  public void close() {
    if (state.compareAndSet(State.OPEN, State.CLOSED)) {

      if (session != null) {
        session.setStatus(Session.STATUS_CLOSED);
      }

      try {
        closeVirtualConnection();
      } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error.close") + "\n" + toString(), e);
      }

      notifyCloseListeners();
    }
  }
  /* (non-Javadoc)
   * @see org.jivesoftware.openfire.roster.RosterItemProvider#updateItem(java.lang.String, org.jivesoftware.openfire.roster.RosterItem)
   */
  public void updateItem(String username, RosterItem item) throws UserNotFoundException {
    Connection con = null;
    PreparedStatement pstmt = null;
    long rosterID = item.getID();
    try {
      con = DbConnectionManager.getConnection();
      // Update existing roster item
      pstmt = con.prepareStatement(UPDATE_ROSTER_ITEM);
      pstmt.setInt(1, item.getSubStatus().getValue());
      pstmt.setInt(2, item.getAskStatus().getValue());
      pstmt.setInt(3, item.getRecvStatus().getValue());
      pstmt.setString(4, item.getNickname());
      pstmt.setLong(5, rosterID);
      pstmt.executeUpdate();
      // Close now the statement (do not wait to be GC'ed)
      pstmt.close();

      // Delete old group list
      pstmt = con.prepareStatement(DELETE_ROSTER_ITEM_GROUPS);
      pstmt.setLong(1, rosterID);
      pstmt.executeUpdate();

      insertGroups(rosterID, item.getGroups().iterator(), con);

    } catch (SQLException e) {
      Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    } finally {
      try {
        if (pstmt != null) {
          pstmt.close();
        }
      } catch (Exception e) {
        Log.error(e);
      }
      try {
        if (con != null) {
          con.close();
        }
      } catch (Exception e) {
        Log.error(e);
      }
    }
  }
 /**
  * Returns the approximate size (in bytes) of the XML messages stored for all users.
  *
  * @return the approximate size of all stored messages (in bytes).
  */
 public int getSize() {
   int size = 0;
   Connection con = null;
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(SELECT_SIZE_ALL_OFFLINE);
     rs = pstmt.executeQuery();
     if (rs.next()) {
       size = rs.getInt(1);
     }
   } catch (Exception e) {
     Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
   } finally {
     DbConnectionManager.closeConnection(rs, pstmt, con);
   }
   return size;
 }
 private void createWebAppContext() {
   ServletContextHandler context;
   // Add web-app. Check to see if we're in development mode. If so, we don't
   // add the normal web-app location, but the web-app in the project directory.
   if (Boolean.getBoolean("developmentMode")) {
     System.out.println(LocaleUtils.getLocalizedString("admin.console.devmode"));
     context =
         new WebAppContext(
             contexts,
             pluginDir.getParentFile().getParentFile().getParentFile().getParent()
                 + File.separator
                 + "src"
                 + File.separator
                 + "web",
             "/");
   } else {
     context =
         new WebAppContext(contexts, pluginDir.getAbsoluteFile() + File.separator + "webapp", "/");
   }
   context.setWelcomeFiles(new String[] {"index.jsp"});
 }
示例#16
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);
       }
     }
   }
 }
  /* (non-Javadoc)
   * @see org.jivesoftware.openfire.roster.RosterItemProvider#deleteItem(java.lang.String, long)
   */
  public void deleteItem(String username, long rosterItemID) {
    // Only try to remove the user if they exist in the roster already:
    Connection con = null;
    PreparedStatement pstmt = null;
    try {
      con = DbConnectionManager.getConnection();
      // Remove roster groups
      pstmt = con.prepareStatement(DELETE_ROSTER_ITEM_GROUPS);

      pstmt.setLong(1, rosterItemID);
      pstmt.executeUpdate();
      // Close now the statement (do not wait to be GC'ed)
      pstmt.close();

      // Remove roster
      pstmt = con.prepareStatement(DELETE_ROSTER_ITEM);

      pstmt.setLong(1, rosterItemID);
      pstmt.executeUpdate();
    } catch (SQLException e) {
      Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    } finally {
      try {
        if (pstmt != null) {
          pstmt.close();
        }
      } catch (Exception e) {
        Log.error(e);
      }
      try {
        if (con != null) {
          con.close();
        }
      } catch (Exception e) {
        Log.error(e);
      }
    }
  }
  private void logAdminConsolePorts() {
    // Log what ports the admin console is running on.
    String listening = LocaleUtils.getLocalizedString("admin.console.listening");
    String hostname =
        getBindInterface() == null
            ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
            : getBindInterface();
    boolean isPlainStarted = false;
    boolean isSecureStarted = false;
    for (Connector connector : adminServer.getConnectors()) {
      if (connector.getPort() == adminPort) {
        isPlainStarted = true;
      } else if (connector.getPort() == adminSecurePort) {
        isSecureStarted = true;
      }
    }

    if (isPlainStarted && isSecureStarted) {
      log(
          listening
              + ":"
              + System.getProperty("line.separator")
              + "  http://"
              + hostname
              + ":"
              + adminPort
              + System.getProperty("line.separator")
              + "  https://"
              + hostname
              + ":"
              + adminSecurePort);
    } else if (isSecureStarted) {
      log(listening + " https://" + hostname + ":" + adminSecurePort);
    } else if (isPlainStarted) {
      log(listening + " http://" + hostname + ":" + adminPort);
    }
  }
示例#19
0
  public User createUser(String username, String password, String name, String email)
      throws UserAlreadyExistsException {
    if (isReadOnly()) {
      // Reject the operation since the provider is read-only
      throw new UnsupportedOperationException();
    }
    try {
      loadUser(username);
      // The user already exists since no exception, so:
      throw new UserAlreadyExistsException("Username " + username + " already exists");
    } catch (UserNotFoundException unfe) {
      // The user doesn't already exist so we can create a new user

      // Determine if the password should be stored as plain text or encrypted.
      boolean usePlainPassword = JiveGlobals.getBooleanProperty("user.usePlainPassword");
      String encryptedPassword = null;
      if (!usePlainPassword) {
        try {
          encryptedPassword = AuthFactory.encryptPassword(password);
          // Set password to null so that it's inserted that way.
          password = null;
        } catch (UnsupportedOperationException uoe) {
          // Encrypting the password may have failed if in setup mode. Therefore,
          // use the plain password.
        }
      }

      Date now = new Date();
      Connection con = null;
      PreparedStatement pstmt = null;
      try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(INSERT_USER);
        pstmt.setString(1, username);
        if (password == null) {
          pstmt.setNull(2, Types.VARCHAR);
        } else {
          pstmt.setString(2, password);
        }
        if (encryptedPassword == null) {
          pstmt.setNull(3, Types.VARCHAR);
        } else {
          pstmt.setString(3, encryptedPassword);
        }
        if (name == null) {
          pstmt.setNull(4, Types.VARCHAR);
        } else {
          pstmt.setString(4, name);
        }
        if (email == null) {
          pstmt.setNull(5, Types.VARCHAR);
        } else {
          pstmt.setString(5, email);
        }
        pstmt.setString(6, StringUtils.dateToMillis(now));
        pstmt.setString(7, StringUtils.dateToMillis(now));
        pstmt.execute();
      } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
      } finally {
        DbConnectionManager.closeConnection(pstmt, con);
      }
      return new User(username, name, email, now, now);
    }
  }
示例#20
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      pageContext =
          _jspxFactory.getPageContext(this, request, response, "../error.jsp", true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n\n\n\n\n\n\n\n");
      org.jivesoftware.admin.AdminPageBean info = null;
      synchronized (request) {
        info =
            (org.jivesoftware.admin.AdminPageBean)
                _jspx_page_context.getAttribute("info", PageContext.REQUEST_SCOPE);
        if (info == null) {
          info = new org.jivesoftware.admin.AdminPageBean();
          _jspx_page_context.setAttribute("info", info, PageContext.REQUEST_SCOPE);
        }
      }
      out.write('\n');
      out.write('\n');
      org.jivesoftware.util.WebManager webManager = null;
      synchronized (_jspx_page_context) {
        webManager =
            (org.jivesoftware.util.WebManager)
                _jspx_page_context.getAttribute("webManager", PageContext.PAGE_SCOPE);
        if (webManager == null) {
          webManager = new org.jivesoftware.util.WebManager();
          _jspx_page_context.setAttribute("webManager", webManager, PageContext.PAGE_SCOPE);
        }
      }
      out.write('\n');
      webManager.init(request, response, session, application, out);
      out.write('\n');
      out.write('\n');
      //  decorator:usePage
      com.opensymphony.module.sitemesh.taglib.decorator.UsePageTag _jspx_th_decorator_usePage_0 =
          (com.opensymphony.module.sitemesh.taglib.decorator.UsePageTag)
              _jspx_tagPool_decorator_usePage_id_nobody.get(
                  com.opensymphony.module.sitemesh.taglib.decorator.UsePageTag.class);
      _jspx_th_decorator_usePage_0.setPageContext(_jspx_page_context);
      _jspx_th_decorator_usePage_0.setParent(null);
      _jspx_th_decorator_usePage_0.setId("decoratedPage");
      int _jspx_eval_decorator_usePage_0 = _jspx_th_decorator_usePage_0.doStartTag();
      if (_jspx_th_decorator_usePage_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
        _jspx_tagPool_decorator_usePage_id_nobody.reuse(_jspx_th_decorator_usePage_0);
        return;
      }
      _jspx_tagPool_decorator_usePage_id_nobody.reuse(_jspx_th_decorator_usePage_0);
      com.opensymphony.module.sitemesh.Page decoratedPage = null;
      decoratedPage =
          (com.opensymphony.module.sitemesh.Page) _jspx_page_context.findAttribute("decoratedPage");
      out.write('\n');
      out.write('\n');

      String path = request.getContextPath();
      // Decorated pages will typically must set a pageID and optionally set a subPageID
      // and extraParams. Store these values as request attributes so that the tab and sidebar
      // handling tags can get at the data.
      request.setAttribute("pageID", decoratedPage.getProperty("meta.pageID"));
      request.setAttribute("subPageID", decoratedPage.getProperty("meta.subPageID"));
      request.setAttribute("extraParams", decoratedPage.getProperty("meta.extraParams"));

      // Message HTML can be passed in:
      String message = decoratedPage.getProperty("page.message");

      out.write("\n\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n\n");
      if (_jspx_meth_fmt_setBundle_0(_jspx_page_context)) return;
      out.write("\n<html>\n<head>\n    <title>");
      out.print(AdminConsole.getAppName());
      out.write(' ');
      if (_jspx_meth_fmt_message_0(_jspx_page_context)) return;
      out.write(':');
      out.write(' ');
      if (_jspx_meth_decorator_title_0(_jspx_page_context)) return;
      out.write(
          "</title>\n    <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"");
      out.print(path);
      out.write(
          "/style/global.css\">\n    <script language=\"JavaScript\" type=\"text/javascript\" src=\"");
      out.print(path);
      out.write(
          "/js/prototype.js\"></script>\n    <script language=\"JavaScript\" type=\"text/javascript\" src=\"");
      out.print(path);
      out.write(
          "/js/scriptaculous.js\"></script>\n    <script language=\"JavaScript\" type=\"text/javascript\" src=\"");
      out.print(path);
      out.write(
          "/js/cookies.js\"></script>\n    <script language=\"JavaScript\" type=\"text/javascript\">\n\n    </script>\n    <script type=\"text/javascript\" src=\"");
      out.print(path);
      out.write(
          "/js/behaviour.js\"></script>\n    <script type=\"text/javascript\">\n    // Add a nice little rollover effect to any row in a jive-table object. This will help\n    // visually link left and right columns.\n    /*\n    var myrules = {\n        '.jive-table TBODY TR' : function(el) {\n            el.onmouseover = function() {\n                this.style.backgroundColor = '#ffffee';\n            }\n            el.onmouseout = function() {\n                this.style.backgroundColor = '#ffffff';\n            }\n        }\n    };\n    Behaviour.register(myrules);\n    */\n    </script>\n    ");
      if (_jspx_meth_decorator_head_0(_jspx_page_context)) return;
      out.write(
          "\n</head>\n\n<body id=\"jive-body\">\n\n<!-- BEGIN main -->\n<div id=\"main\">\n\n    <div id=\"jive-header\">\n        <div id=\"jive-logo\">\n            <a href=\"/index.jsp\"><img src=\"/images/login_logo.gif\" alt=\"Openfire\" width=\"179\" height=\"53\" /></a>\n        </div>\n        <div id=\"jive-userstatus\">\n            ");
      out.print(AdminConsole.getAppName());
      out.write(' ');
      out.print(AdminConsole.getVersionString());
      out.write("<br/>\n            ");
      //  fmt:message
      org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_1 =
          (org.apache.taglibs.standard.tag.rt.fmt.MessageTag)
              _jspx_tagPool_fmt_message_key.get(
                  org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
      _jspx_th_fmt_message_1.setPageContext(_jspx_page_context);
      _jspx_th_fmt_message_1.setParent(null);
      _jspx_th_fmt_message_1.setKey("admin.logged_in_as");
      int _jspx_eval_fmt_message_1 = _jspx_th_fmt_message_1.doStartTag();
      if (_jspx_eval_fmt_message_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
        if (_jspx_eval_fmt_message_1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
          out = _jspx_page_context.pushBody();
          _jspx_th_fmt_message_1.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
          _jspx_th_fmt_message_1.doInitBody();
        }
        do {
          //  fmt:param
          org.apache.taglibs.standard.tag.rt.fmt.ParamTag _jspx_th_fmt_param_0 =
              (org.apache.taglibs.standard.tag.rt.fmt.ParamTag)
                  _jspx_tagPool_fmt_param_value_nobody.get(
                      org.apache.taglibs.standard.tag.rt.fmt.ParamTag.class);
          _jspx_th_fmt_param_0.setPageContext(_jspx_page_context);
          _jspx_th_fmt_param_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_fmt_message_1);
          _jspx_th_fmt_param_0.setValue(
              "<strong>"
                  + StringUtils.escapeHTMLTags(JID.unescapeNode(webManager.getUser().getUsername()))
                  + "</strong>");
          int _jspx_eval_fmt_param_0 = _jspx_th_fmt_param_0.doStartTag();
          if (_jspx_th_fmt_param_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
            _jspx_tagPool_fmt_param_value_nobody.reuse(_jspx_th_fmt_param_0);
            return;
          }
          _jspx_tagPool_fmt_param_value_nobody.reuse(_jspx_th_fmt_param_0);
          int evalDoAfterBody = _jspx_th_fmt_message_1.doAfterBody();
          if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break;
        } while (true);
        if (_jspx_eval_fmt_message_1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE)
          out = _jspx_page_context.popBody();
      }
      if (_jspx_th_fmt_message_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
        _jspx_tagPool_fmt_message_key.reuse(_jspx_th_fmt_message_1);
        return;
      }
      _jspx_tagPool_fmt_message_key.reuse(_jspx_th_fmt_message_1);
      out.write(" - <a href=\"");
      out.print(path);
      out.write("/index.jsp?logout=true\">");
      out.print(LocaleUtils.getLocalizedString("global.logout"));
      out.write(
          "</a>\n        </div>\n        <div id=\"jive-nav\">\n            <div id=\"jive-nav-left\"></div>\n            ");
      if (_jspx_meth_admin_tabs_0(_jspx_page_context)) return;
      out.write(
          "\n            <div id=\"jive-nav-right\"></div>\n        </div>\n        <div id=\"jive-subnav\">\n            ");
      if (_jspx_meth_admin_subnavbar_0(_jspx_page_context)) return;
      out.write(
          "\n        </div>\n    </div>\n\n    <div id=\"jive-main\">\n    <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n    <tbody>\n        <tr valign=\"top\">\n            <td width=\"1%\">\n                <div id=\"jive-sidebar-container\">\n                    <div id=\"jive-sidebar-box\">\n                        <div id=\"jive-sidebar\">\n                            ");
      if (_jspx_meth_admin_sidebar_0(_jspx_page_context)) return;
      out.write("\n                            <br>\n                            <img src=\"");
      out.print(path);
      out.write(
          "/images/blank.gif\" width=\"150\" height=\"1\" border=\"0\" alt=\"\">\n                        </div>\n                    </div>\n                </div>\n            </td>\n            <td width=\"99%\" id=\"jive-content\">\n\n\n                ");
      if (message != null) {
        out.write("\n\n                    ");
        out.print(message);
        out.write("\n\n                ");
      }
      out.write("\n\n                <h1>\n                    ");
      if (_jspx_meth_decorator_title_1(_jspx_page_context)) return;
      out.write(
          "\n                </h1>\n\n                <div id=\"jive-main-content\">\n                    ");
      if (_jspx_meth_decorator_body_0(_jspx_page_context)) return;
      out.write(
          "\n                </div>\n            </td>\n        </tr>\n    </tbody>\n    </table>\n    </div>\n\n</div>\n<!-- END main -->\n\n<!-- BEGIN footer -->\n\t<div id=\"jive-footer\">\n        <div class=\"jive-footer-nav\">\n            ");
      if (_jspx_meth_admin_tabs_1(_jspx_page_context)) return;
      out.write(
          "\n        </div>\n        <div class=\"jive-footer-copyright\">\n            Built by <a href=\"http://www.jivesoftware.com\">Jive Software</a> and the <a href=\"http://www.igniterealtime.org\">IgniteRealtime.org</a> community\n        </div>\n    </div>\n<!-- END footer -->\n\n</body>\n</html>\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
示例#21
0
 /** @see net.sf.kraken.BaseTransport#getTerminologyRegistration() */
 @Override
 public String getTerminologyRegistration() {
   return LocaleUtils.getLocalizedString(
       "gateway." + getType().toString() + ".registration", "kraken");
 }
示例#22
0
 /** @see net.sf.kraken.BaseTransport#getTerminologyPassword() */
 @Override
 public String getTerminologyPassword() {
   return LocaleUtils.getLocalizedString(
       "gateway." + getType().toString() + ".password", "kraken");
 }
示例#23
0
 /** @see net.sf.kraken.BaseTransport#getTerminologyUsername() */
 @Override
 public String getTerminologyUsername() {
   return LocaleUtils.getLocalizedString(
       "gateway." + getType().toString() + ".username", "kraken");
 }
示例#24
0
  private void init() {
    Element element =
        DocumentHelper.createElement(QName.get("query", "http://jabber.org/protocol/muc#owner"));

    configurationForm = new DataForm(DataForm.Type.form);
    configurationForm.setTitle(LocaleUtils.getLocalizedString("muc.form.conf.title"));
    List<String> params = new ArrayList<String>();
    params.add(room.getName());
    configurationForm.addInstruction(
        LocaleUtils.getLocalizedString("muc.form.conf.instruction", params));

    configurationForm
        .addField("FORM_TYPE", null, Type.hidden)
        .addValue("http://jabber.org/protocol/muc#roomconfig");

    configurationForm.addField(
        "muc#roomconfig_roomname",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomname"),
        Type.text_single);

    configurationForm.addField(
        "muc#roomconfig_roomdesc",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomdesc"),
        Type.text_single);

    configurationForm.addField(
        "muc#roomconfig_changesubject",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_changesubject"),
        Type.boolean_type);

    final FormField maxUsers =
        configurationForm.addField(
            "muc#roomconfig_maxusers",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_maxusers"),
            Type.list_single);
    maxUsers.addOption("10", "10");
    maxUsers.addOption("20", "20");
    maxUsers.addOption("30", "30");
    maxUsers.addOption("40", "40");
    maxUsers.addOption("50", "50");
    maxUsers.addOption(LocaleUtils.getLocalizedString("muc.form.conf.none"), "0");

    final FormField broadcast =
        configurationForm.addField(
            "muc#roomconfig_presencebroadcast",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_presencebroadcast"),
            Type.list_multi);
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.moderator"), "moderator");
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.participant"), "participant");
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.visitor"), "visitor");

    configurationForm.addField(
        "muc#roomconfig_publicroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_publicroom"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_persistentroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_persistentroom"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_moderatedroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_moderatedroom"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_membersonly",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_membersonly"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.allowinvitesfixed"));

    configurationForm.addField(
        "muc#roomconfig_allowinvites",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_allowinvites"),
        Type.boolean_type);

    configurationForm.addField(
        "muc#roomconfig_passwordprotectedroom",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_passwordprotectedroom"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomsecretfixed"));

    configurationForm.addField(
        "muc#roomconfig_roomsecret",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomsecret"),
        Type.text_private);

    final FormField whois =
        configurationForm.addField(
            "muc#roomconfig_whois",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_whois"),
            Type.list_single);
    whois.addOption(LocaleUtils.getLocalizedString("muc.form.conf.moderator"), "moderators");
    whois.addOption(LocaleUtils.getLocalizedString("muc.form.conf.anyone"), "anyone");

    configurationForm.addField(
        "muc#roomconfig_enablelogging",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_enablelogging"),
        Type.boolean_type);

    configurationForm.addField(
        "x-muc#roomconfig_reservednick",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_reservednick"),
        Type.boolean_type);

    configurationForm.addField(
        "x-muc#roomconfig_canchangenick",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_canchangenick"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.owner_registration"));

    configurationForm.addField(
        "x-muc#roomconfig_registration",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_registration"),
        Type.boolean_type);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomadminsfixed"));

    configurationForm.addField(
        "muc#roomconfig_roomadmins",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomadmins"),
        Type.jid_multi);

    configurationForm
        .addField(null, null, Type.fixed)
        .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomownersfixed"));

    configurationForm.addField(
        "muc#roomconfig_roomowners",
        LocaleUtils.getLocalizedString("muc.form.conf.owner_roomowners"),
        Type.jid_multi);

    // Create the probeResult and add the basic info together with the configuration form
    probeResult = element;
    probeResult.add(configurationForm.getElement());
  }
 /* (non-Javadoc)
  * @see org.jivesoftware.openfire.roster.RosterItemProvider#getItems(java.lang.String)
  */
 public Iterator<RosterItem> getItems(String username) {
   LinkedList<RosterItem> itemList = new LinkedList<RosterItem>();
   Connection con = null;
   Connection con2 = null;
   PreparedStatement pstmt = null;
   PreparedStatement gstmt = null;
   try {
     con2 = DbConnectionManager.getConnection();
     gstmt = con2.prepareStatement(LOAD_ROSTER_ITEM_GROUPS);
     // Load all the contacts in the roster
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(LOAD_ROSTER);
     pstmt.setString(1, username);
     ResultSet rs = pstmt.executeQuery();
     while (rs.next()) {
       // Create a new RosterItem (ie. user contact) from the stored information
       RosterItem item =
           new RosterItem(
               rs.getLong(2),
               new JID(rs.getString(1)),
               RosterItem.SubType.getTypeFromInt(rs.getInt(3)),
               RosterItem.AskType.getTypeFromInt(rs.getInt(4)),
               RosterItem.RecvType.getTypeFromInt(rs.getInt(5)),
               rs.getString(6),
               null);
       // Load the groups for the loaded contact
       ResultSet gs = null;
       gstmt.setLong(1, item.getID());
       gs = gstmt.executeQuery();
       while (gs.next()) {
         item.getGroups().add(gs.getString(1));
       }
       // Close the result set
       gs.close();
       // Add the loaded RosterItem (ie. user contact) to the result
       itemList.add(item);
     }
   } catch (SQLException e) {
     Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
   } finally {
     try {
       if (pstmt != null) {
         pstmt.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
     try {
       if (con != null) {
         con.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
     try {
       if (gstmt != null) {
         gstmt.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
     try {
       if (con2 != null) {
         con2.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
   }
   return itemList.iterator();
 }
  /** Starts the Jetty instance. */
  public void startup() {
    restartNeeded = false;

    // Add listener for certificate events
    certificateListener = new CertificateListener();
    CertificateManager.addListener(certificateListener);

    adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);
    adminServer = new Server();
    final QueuedThreadPool tp = new QueuedThreadPool(254);
    tp.setName("Jetty-QTP-AdminConsole");
    adminServer.setThreadPool(tp);

    // Do not send Jetty info in HTTP headers
    adminServer.setSendServerVersion(false);

    // Create connector for http traffic if it's enabled.
    if (adminPort > 0) {
      Connector httpConnector = new SelectChannelConnector();
      // Listen on a specific network interface if it has been set.
      String bindInterface = getBindInterface();
      httpConnector.setHost(bindInterface);
      httpConnector.setPort(adminPort);
      adminServer.addConnector(httpConnector);
    }

    // Create a connector for https traffic if it's enabled.
    sslEnabled = false;
    try {
      if (adminSecurePort > 0
          && CertificateManager.isRSACertificate(SSLConfig.getKeyStore(), "*")) {
        if (!CertificateManager.isRSACertificate(
            SSLConfig.getKeyStore(), XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
          Log.warn(
              "Admin console: Using RSA certificates but they are not valid for the hosted domain");
        }

        JiveSslConnector httpsConnector = new JiveSslConnector();
        String bindInterface = getBindInterface();
        httpsConnector.setHost(bindInterface);
        httpsConnector.setPort(adminSecurePort);

        httpsConnector.setTrustPassword(SSLConfig.gets2sTrustPassword());
        httpsConnector.setTruststoreType(SSLConfig.getStoreType());
        httpsConnector.setTruststore(SSLConfig.gets2sTruststoreLocation());
        httpsConnector.setNeedClientAuth(false);
        httpsConnector.setWantClientAuth(false);

        httpsConnector.setKeyPassword(SSLConfig.getKeyPassword());
        httpsConnector.setKeystoreType(SSLConfig.getStoreType());
        httpsConnector.setKeystore(SSLConfig.getKeystoreLocation());
        adminServer.addConnector(httpsConnector);

        sslEnabled = true;
      }
    } catch (Exception e) {
      Log.error(e.getMessage(), e);
    }

    // Make sure that at least one connector was registered.
    if (adminServer.getConnectors() == null || adminServer.getConnectors().length == 0) {
      adminServer = null;
      // Log warning.
      log(LocaleUtils.getLocalizedString("admin.console.warning"));
      return;
    }

    HandlerCollection collection = new HandlerCollection();
    adminServer.setHandler(collection);
    collection.setHandlers(new Handler[] {contexts, new DefaultHandler()});

    try {
      adminServer.start();
    } catch (Exception e) {
      Log.error("Could not start admin conosle server", e);
    }

    // Log the ports that the admin server is listening on.
    logAdminConsolePorts();
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n\n\n\n\n\n\n");

      boolean bookmarkCreated = request.getParameter("bookmarkCreated") != null;

      boolean delete = request.getParameter("delete") != null;
      final Collection<Bookmark> bookmarks = BookmarkManager.getBookmarks();

      out.write("\n\n<html>\n<head>\n    <title>");
      if (_jspx_meth_fmt_message_0(_jspx_page_context)) return;
      out.write(
          "</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"/style/global.css\">\n    <meta name=\"pageID\" content=\"groupchat-bookmarks\"/>\n    <script src=\"/js/prototype.js\" type=\"text/javascript\"></script>\n    <script src=\"/js/scriptaculous.js\" type=\"text/javascript\"></script>\n    <style type=\"text/css\">\n        .div-border {\n            border: 1px solid #CCCCCC;\n            -moz-border-radius: 3px;\n        }\n    </style>\n    <style type=\"text/css\">\n        @import \"style/style.css\";\n    </style>\n</head>\n\n<body>\n\n<p>\n    ");
      if (_jspx_meth_fmt_message_1(_jspx_page_context)) return;
      out.write("\n</p>\n\n");
      if (bookmarkCreated) {
        out.write("\n<div class=\"success\">\n   ");
        if (_jspx_meth_fmt_message_2(_jspx_page_context)) return;
        out.write("\n</div>\n");
      }
      out.write('\n');
      out.write('\n');
      if (delete) {
        out.write("\n<div class=\"success\">\n     ");
        if (_jspx_meth_fmt_message_3(_jspx_page_context)) return;
        out.write("\n</div>\n");
      }
      out.write(
          "\n\n<br/>\n\n    <div class=\"div-border\" style=\"padding: 12px; width: 95%;\">\n        <table class=\"jive-table\" cellspacing=\"0\" width=\"100%\">\n            <th>");
      if (_jspx_meth_fmt_message_4(_jspx_page_context)) return;
      out.write("</th><th>");
      if (_jspx_meth_fmt_message_5(_jspx_page_context)) return;
      out.write("</th><th>");
      if (_jspx_meth_fmt_message_6(_jspx_page_context)) return;
      out.write("</th><th>");
      if (_jspx_meth_fmt_message_7(_jspx_page_context)) return;
      out.write("</th><th>");
      if (_jspx_meth_fmt_message_8(_jspx_page_context)) return;
      out.write("</th><th>");
      if (_jspx_meth_fmt_message_9(_jspx_page_context)) return;
      out.write("</th>\n            ");

      boolean hasBookmarks = false;
      for (Bookmark bookmark : bookmarks) {
        String users = "";
        String groups = "";
        if (bookmark.getType() != Bookmark.Type.group_chat) {
          continue;
        } else {
          hasBookmarks = true;
          if (bookmark.isGlobalBookmark()) {
            users = "All";
            groups = "All";
          } else {
            users =
                bookmark.getUsers().size()
                    + " "
                    + LocaleUtils.getLocalizedString("group.chat.bookmark.users", "clientcontrol");
            groups =
                bookmark.getGroups().size()
                    + " "
                    + LocaleUtils.getLocalizedString("group.chat.bookmark.groups", "clientcontrol");
          }
        }

        out.write("\n            <tr style=\"border-left: none;\">\n                <td>");
        out.print(bookmark.getName());
        out.write("</td>\n                <td>");
        out.print(bookmark.getValue());
        out.write("</td>\n                <td>");
        out.print(users);
        out.write("</td>\n                <td>");
        out.print(groups);
        out.write("</td>\n                <td>");
        out.print(
            bookmark.getProperty("autojoin") != null ? "<img src='/images/check.gif'>" : "&nbsp;");
        out.write(
            "</td>\n                <td>\n                    <a href=\"create-bookmark.jsp?edit=true&bookmarkID=");
        out.print(bookmark.getBookmarkID());
        out.write(
            "\"><img src=\"/images/edit-16x16.gif\" border=\"0\" width=\"16\" height=\"16\" alt=\"Edit Bookmark\"/></a>\n                    <a href=\"confirm-bookmark-delete.jsp?bookmarkID=");
        out.print(bookmark.getBookmarkID());
        out.write(
            "\"><img src=\"/images/delete-16x16.gif\" border=\"0\" width=\"16\" height=\"16\" alt=\"Delete Bookmark\"/></a>\n\n                </td>\n            </tr>\n            ");
      }
      out.write("\n\n            ");
      if (!hasBookmarks) {
        out.write("\n            <tr>\n                <td colspan=\"6\" align=\"center\">");
        if (_jspx_meth_fmt_message_10(_jspx_page_context)) return;
        out.write("</td>\n            </tr>\n            ");
      }
      out.write(
          "\n            <tr>\n                <td colspan=\"6\">\n                    <a href=\"create-bookmark.jsp?type=group_chat\"><img src=\"/images/add-16x16.gif\" border=\"0\" align=\"texttop\" style=\"margin-right: 3px;\"/>");
      if (_jspx_meth_fmt_message_11(_jspx_page_context)) return;
      out.write(
          "</a>\n                </td>\n            </tr>\n        </table>\n    </div>\n\n</body>\n</html>\n\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
示例#28
0
  /**
   * Handles a IQ-register 'set' request, which is to be interpreted as a request to create a new
   * registration.
   *
   * @param packet the IQ-register 'set' stanza.
   * @throws UnauthorizedException if the user isn't allowed to register.
   */
  private void setRegistrationForm(IQ packet) throws UnauthorizedException {
    final JID from = packet.getFrom();

    final boolean registered;
    Collection<Registration> registrations =
        RegistrationManager.getInstance().getRegistrations(from, parent.transportType);
    if (registrations.iterator().hasNext()) {
      registered = true;
    } else {
      registered = false;
    }

    if (!registered && !parent.permissionManager.hasAccess(from)) {
      // User does not have permission to register with transport.
      // We want to allow them to change settings if they are already
      // registered.
      throw new UnauthorizedException(
          LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyacls", "kraken"));
    }

    // Parse the input variables
    String username = null;
    String password = null;
    String nickname = null;
    try {
      if (packet.getChildElement().element("x") != null) {
        final DataForm form = new DataForm(packet.getChildElement().element("x"));
        final List<FormField> fields = form.getFields();
        for (final FormField field : fields) {
          final String var = field.getVariable();
          if (var.equals("username")) {
            username = field.getValues().get(0);
          } else if (var.equals("password")) {
            password = field.getValues().get(0);
          } else if (var.equals("nick")) {
            nickname = field.getValues().get(0);
          }
        }
      }
    }
    // TODO: This shouldn't be done by catching an Exception - check for the
    // existence of elements instead. If we insist doing this with an
    // exception handler, prevent catching a generic Exception (catch more
    // specific subclasses instead).
    catch (Exception ex) {
      // No with data form apparently
      Log.info("Most likely, no dataform was present " + "in the IQ-register request.", ex);
    }

    // input variables could also exist in the non-extended elements
    final Element userEl = packet.getChildElement().element("username");
    final Element passEl = packet.getChildElement().element("password");
    final Element nickEl = packet.getChildElement().element("nick");
    if (userEl != null) {
      username = userEl.getTextTrim();
    }
    if (passEl != null) {
      password = passEl.getTextTrim();
    }
    if (nickEl != null) {
      nickname = nickEl.getTextTrim();
    }

    username = (username == null || username.equals("")) ? null : username;
    password = (password == null || password.equals("")) ? null : password;
    nickname = (nickname == null || nickname.equals("")) ? null : nickname;

    // verify that we've got wat we need.
    if (username == null
        || (parent.isPasswordRequired() && password == null)
        || (parent.isNicknameRequired() && nickname == null)) {
      // Invalid information from stanza, lets yell.
      Log.info(
          "Cannot process IQ register request, as it "
              + "fails to provide all data that's required: "
              + packet.toXML());
      final IQ result = IQ.createResultIQ(packet);
      result.setError(Condition.bad_request);
      parent.sendPacket(result);
      return;
    }

    // Check if the client supports our proprietary 'rosterless' mode.
    final boolean rosterlessMode;
    final Element x = packet.getChildElement().element("x");
    if (x != null
        && x.getNamespaceURI() != null
        && x.getNamespaceURI().equals(NameSpace.IQ_GATEWAY_REGISTER)) {
      rosterlessMode = true;
      Log.info("Registering " + packet.getFrom() + " as " + username + " in rosterless mode.");
    } else {
      rosterlessMode = false;
      Log.info(
          "Registering "
              + packet.getFrom()
              + " as "
              + username
              + " (without making use of rosterless mode).");
    }

    // Here's where the true magic lies: create the registration!
    try {
      addNewRegistration(from, username, password, nickname, rosterlessMode);

      registrations =
          RegistrationManager.getInstance().getRegistrations(from, parent.transportType);
      Registration registration = registrations.iterator().next();
      TransportSession session =
          parent.registrationLoggedIn(registration, from, PresenceType.available, "", -1);
      session.setRegistrationPacket(packet);
      session.detachSession();
      parent.getSessionManager().storeSession(from, session);

      // final IQ result = IQ.createResultIQ(packet);
      // I believe this shouldn't be included. Leaving it around just in
      // case.
      // Element response =
      // DocumentHelper.createElement(QName.get("query", IQ_REGISTER));
      // result.setChildElement(response);
      // parent.sendPacket(result);
    } catch (UserNotFoundException e) {
      Log.warn(
          "Someone attempted to register with the gateway "
              + "who is not registered with the server: "
              + from);
      final IQ eresult = IQ.createResultIQ(packet);
      eresult.setError(Condition.forbidden);
      parent.sendPacket(eresult);
      final Message em = new Message();
      em.setType(Message.Type.error);
      em.setTo(packet.getFrom());
      em.setFrom(packet.getTo());
      em.setBody(LocaleUtils.getLocalizedString("gateway.base.registrationdeniednoacct", "kraken"));
      parent.sendPacket(em);
    } catch (IllegalAccessException e) {
      Log.warn(
          "Someone who is not a user of this server "
              + "tried to register with the transport: "
              + from);
      final IQ eresult = IQ.createResultIQ(packet);
      eresult.setError(Condition.forbidden);
      parent.sendPacket(eresult);
      final Message em = new Message();
      em.setType(Message.Type.error);
      em.setTo(packet.getFrom());
      em.setFrom(packet.getTo());
      em.setBody(LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyhost", "kraken"));
      parent.sendPacket(em);
    } catch (IllegalArgumentException e) {
      Log.warn(
          "Someone attempted to register with the " + "gateway with an invalid username: "******"gateway.base.registrationdeniedbadusername", "kraken"));
      parent.sendPacket(em);
    }
  }
  /**
   * Returns a newly created session between the server and a client. The session will be created
   * and returned only if correct name/prefix (i.e. 'stream' or 'flash') and namespace were provided
   * by the client.
   *
   * @param serverName the name of the server where the session is connecting to.
   * @param xpp the parser that is reading the provided XML through the connection.
   * @param connection the connection with the client.
   * @return a newly created session between the server and a client.
   * @throws org.xmlpull.v1.XmlPullParserException if an error occurs while parsing incoming data.
   */
  public static LocalClientSession createSession(
      String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException {
    boolean isFlashClient = xpp.getPrefix().equals("flash");
    connection.setFlashClient(isFlashClient);

    // Conduct error checking, the opening tag should be 'stream'
    // in the 'etherx' namespace
    if (!xpp.getName().equals("stream") && !isFlashClient) {
      throw new XmlPullParserException(LocaleUtils.getLocalizedString("admin.error.bad-stream"));
    }

    if (!xpp.getNamespace(xpp.getPrefix()).equals(ETHERX_NAMESPACE)
        && !(isFlashClient && xpp.getNamespace(xpp.getPrefix()).equals(FLASH_NAMESPACE))) {
      throw new XmlPullParserException(LocaleUtils.getLocalizedString("admin.error.bad-namespace"));
    }

    if (!allowedIPs.isEmpty()) {
      String hostAddress = "Unknown";
      // The server is using a whitelist so check that the IP address of the client
      // is authorized to connect to the server
      try {
        hostAddress = connection.getHostAddress();
      } catch (UnknownHostException e) {
        // Do nothing
      }
      if (!isAllowed(connection)) {
        // Client cannot connect from this IP address so end the stream and
        // TCP connection
        Log.debug(
            "LocalClientSession: Closed connection to client attempting to connect from: "
                + hostAddress);
        // Include the not-authorized error in the response
        StreamError error = new StreamError(StreamError.Condition.not_authorized);
        connection.deliverRawText(error.toXML());
        // Close the underlying connection
        connection.close();
        return null;
      }
    }

    // Default language is English ("en").
    String language = "en";
    // Default to a version of "0.0". Clients written before the XMPP 1.0 spec may
    // not report a version in which case "0.0" should be assumed (per rfc3920
    // section 4.4.1).
    int majorVersion = 0;
    int minorVersion = 0;
    for (int i = 0; i < xpp.getAttributeCount(); i++) {
      if ("lang".equals(xpp.getAttributeName(i))) {
        language = xpp.getAttributeValue(i);
      }
      if ("version".equals(xpp.getAttributeName(i))) {
        try {
          int[] version = decodeVersion(xpp.getAttributeValue(i));
          majorVersion = version[0];
          minorVersion = version[1];
        } catch (Exception e) {
          Log.error(e.getMessage(), e);
        }
      }
    }

    // If the client supports a greater major version than the server,
    // set the version to the highest one the server supports.
    if (majorVersion > MAJOR_VERSION) {
      majorVersion = MAJOR_VERSION;
      minorVersion = MINOR_VERSION;
    } else if (majorVersion == MAJOR_VERSION) {
      // If the client supports a greater minor version than the
      // server, set the version to the highest one that the server
      // supports.
      if (minorVersion > MINOR_VERSION) {
        minorVersion = MINOR_VERSION;
      }
    }

    // Store language and version information in the connection.
    connection.setLanaguage(language);
    connection.setXMPPVersion(majorVersion, minorVersion);

    // Indicate the TLS policy to use for this connection
    if (!connection.isSecure()) {
      boolean hasCertificates = false;
      try {
        hasCertificates = SSLConfig.getKeyStore().size() > 0;
      } catch (Exception e) {
        Log.error(e.getMessage(), e);
      }
      Connection.TLSPolicy tlsPolicy = getTLSPolicy();
      if (Connection.TLSPolicy.required == tlsPolicy && !hasCertificates) {
        Log.error(
            "Client session rejected. TLS is required but no certificates " + "were created.");
        return null;
      }
      // Set default TLS policy
      connection.setTlsPolicy(hasCertificates ? tlsPolicy : Connection.TLSPolicy.disabled);
    } else {
      // Set default TLS policy
      connection.setTlsPolicy(Connection.TLSPolicy.disabled);
    }

    // Indicate the compression policy to use for this connection
    connection.setCompressionPolicy(getCompressionPolicy());

    // Create a ClientSession for this user.
    LocalClientSession session = SessionManager.getInstance().createClientSession(connection);

    // Build the start packet response
    StringBuilder sb = new StringBuilder(200);
    sb.append("<?xml version='1.0' encoding='");
    sb.append(CHARSET);
    sb.append("'?>");
    if (isFlashClient) {
      sb.append("<flash:stream xmlns:flash=\"http://www.jabber.com/streams/flash\" ");
    } else {
      sb.append("<stream:stream ");
    }
    sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"jabber:client\" from=\"");
    sb.append(serverName);
    sb.append("\" id=\"");
    sb.append(session.getStreamID().toString());
    sb.append("\" xml:lang=\"");
    sb.append(language);
    // Don't include version info if the version is 0.0.
    if (majorVersion != 0) {
      sb.append("\" version=\"");
      sb.append(majorVersion).append(".").append(minorVersion);
    }
    sb.append("\">");
    connection.deliverRawText(sb.toString());

    // If this is a "Jabber" connection, the session is now initialized and we can
    // return to allow normal packet parsing.
    if (majorVersion == 0) {
      return session;
    }
    // Otherwise, this is at least XMPP 1.0 so we need to announce stream features.

    sb = new StringBuilder(490);
    sb.append("<stream:features>");
    if (connection.getTlsPolicy() != Connection.TLSPolicy.disabled) {
      sb.append("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\">");
      if (connection.getTlsPolicy() == Connection.TLSPolicy.required) {
        sb.append("<required/>");
      }
      sb.append("</starttls>");
    }
    // Include available SASL Mechanisms
    sb.append(SASLAuthentication.getSASLMechanisms(session));
    // Include Stream features
    String specificFeatures = session.getAvailableStreamFeatures();
    if (specificFeatures != null) {
      sb.append(specificFeatures);
    }
    sb.append("</stream:features>");

    connection.deliverRawText(sb.toString());
    return session;
  }
示例#30
0
  /**
   * Handles a IQ-register 'get' request, which is to be interpreted as a request for a registration
   * form template. The template will be prefilled with data, if the requestee has a current
   * registration with the gateway.
   *
   * @param packet the IQ-register 'get' stanza.
   * @throws UnauthorizedException if the user is not allowed to make use of the gateway.
   */
  private void getRegistrationForm(IQ packet) throws UnauthorizedException {
    final JID from = packet.getFrom();
    final IQ result = IQ.createResultIQ(packet);

    // search for existing registrations
    String curUsername = null;
    String curPassword = null;
    String curNickname = null;
    Boolean registered = false;
    final Collection<Registration> registrations =
        RegistrationManager.getInstance().getRegistrations(from, parent.transportType);
    if (registrations.iterator().hasNext()) {
      Registration registration = registrations.iterator().next();
      curUsername = registration.getUsername();
      curPassword = registration.getPassword();
      curNickname = registration.getNickname();
      registered = true;
    }

    // Verify that the user is allowed to make use of the gateway.
    if (!registered && !parent.permissionManager.hasAccess(from)) {
      // User does not have permission to register with transport.
      // We want to allow them to change settings if they are already
      // registered.
      throw new UnauthorizedException(
          LocaleUtils.getLocalizedString("gateway.base.registrationdeniedbyacls", "kraken"));
    }

    // generate a template registration form.
    final Element response =
        DocumentHelper.createElement(QName.get("query", NameSpace.IQ_REGISTER));
    final DataForm form = new DataForm(DataForm.Type.form);
    form.addInstruction(parent.getTerminologyRegistration());

    final FormField usernameField = form.addField();
    usernameField.setLabel(parent.getTerminologyUsername());
    usernameField.setVariable("username");
    usernameField.setType(FormField.Type.text_single);
    if (curUsername != null) {
      usernameField.addValue(curUsername);
    }

    final FormField passwordField = form.addField();
    passwordField.setLabel(parent.getTerminologyPassword());
    passwordField.setVariable("password");
    passwordField.setType(FormField.Type.text_private);
    if (curPassword != null) {
      passwordField.addValue(curPassword);
    }

    final String nicknameTerm = parent.getTerminologyNickname();
    if (nicknameTerm != null) {
      FormField nicknameField = form.addField();
      nicknameField.setLabel(nicknameTerm);
      nicknameField.setVariable("nick");
      nicknameField.setType(FormField.Type.text_single);
      if (curNickname != null) {
        nicknameField.addValue(curNickname);
      }
    }

    response.add(form.getElement());
    response.addElement("instructions").addText(parent.getTerminologyRegistration());

    // prefill the template with existing data if a registration already
    // exists.
    if (registered) {
      response.addElement("registered");
      response.addElement("username").addText(curUsername);
      if (curPassword == null) {
        response.addElement("password");
      } else {
        response.addElement("password").addText(curPassword);
      }
      if (nicknameTerm != null) {
        if (curNickname == null) {
          response.addElement("nick");
        } else {
          response.addElement("nick").addText(curNickname);
        }
      }
    } else {
      response.addElement("username");
      response.addElement("password");
      if (nicknameTerm != null) {
        response.addElement("nick");
      }
    }

    // Add special indicator for rosterless gateway handling.
    response.addElement("x").addNamespace("", NameSpace.IQ_GATEWAY_REGISTER);

    result.setChildElement(response);

    parent.sendPacket(result);
  }