public Collection<User> findUsers(Set<String> fields, String query)
      throws UnsupportedOperationException {
    if (fields.isEmpty()) {
      return Collections.emptyList();
    }
    if (!getSearchFields().containsAll(fields)) {
      throw new IllegalArgumentException("Search fields " + fields + " are not valid.");
    }
    if (query == null || "".equals(query)) {
      return Collections.emptyList();
    }
    // SQL LIKE queries don't map directly into a keyword/wildcard search like we want.
    // Therefore, we do a best approximiation by replacing '*' with '%' and then
    // surrounding the whole query with two '%'. This will return more data than desired,
    // but is better than returning less data than desired.
    query = "%" + query.replace('*', '%') + "%";
    if (query.endsWith("%%")) {
      query = query.substring(0, query.length() - 1);
    }

    List<String> usernames = new ArrayList<String>(50);
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      con = DbConnectionManager.getConnection();
      stmt = con.createStatement();
      StringBuilder sql = new StringBuilder();
      sql.append("SELECT username FROM jiveUser WHERE");
      boolean first = true;
      if (fields.contains("Username")) {
        sql.append(" username LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
        first = false;
      }
      if (fields.contains("Name")) {
        if (!first) {
          sql.append(" AND");
        }
        sql.append(" name LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
        first = false;
      }
      if (fields.contains("Email")) {
        if (!first) {
          sql.append(" AND");
        }
        sql.append(" email LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
      }
      rs = stmt.executeQuery(sql.toString());
      while (rs.next()) {
        usernames.add(rs.getString(1));
      }
    } catch (SQLException e) {
      Log.error(e);
    } finally {
      DbConnectionManager.closeConnection(rs, stmt, con);
    }
    return new UserCollection(usernames.toArray(new String[usernames.size()]));
  }
  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);
    }
  }
  private List<String> getServerInterfaces() {

    List<String> bindInterfaces = new ArrayList<String>();

    String interfaceName = JiveGlobals.getXMLProperty("network.interface");
    String bindInterface = null;
    if (interfaceName != null) {
      if (interfaceName.trim().length() > 0) {
        bindInterface = interfaceName;
      }
    }

    int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);

    if (bindInterface == null) {
      try {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netInterface : Collections.list(nets)) {
          Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
          for (InetAddress address : Collections.list(addresses)) {
            if ("127.0.0.1".equals(address.getHostAddress())) {
              continue;
            }
            if (address.getHostAddress().startsWith("0.")) {
              continue;
            }
            Socket socket = new Socket();
            InetSocketAddress remoteAddress =
                new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort);
            try {
              socket.connect(remoteAddress);
              bindInterfaces.add(address.getHostAddress());
              break;
            } catch (IOException e) {
              // Ignore this address. Let's hope there is more addresses to validate
            }
          }
        }
      } catch (SocketException e) {
        // We failed to discover a valid IP address where the admin console is running
        return null;
      }
    } else {
      bindInterfaces.add(bindInterface);
    }

    return bindInterfaces;
  }
 public Collection<String> getUsernames() {
   List<String> usernames = new ArrayList<String>(500);
   Connection con = null;
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(ALL_USERS);
     rs = pstmt.executeQuery();
     // Set the fetch size. This will prevent some JDBC drivers from trying
     // to load the entire result set into memory.
     DbConnectionManager.setFetchSize(rs, 500);
     while (rs.next()) {
       usernames.add(rs.getString(1));
     }
   } catch (SQLException e) {
     Log.error(e);
   } finally {
     DbConnectionManager.closeConnection(rs, pstmt, con);
   }
   return usernames;
 }
  /**
   * 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;
  }
 public Collection<User> getUsers(int startIndex, int numResults) {
   List<String> usernames = new ArrayList<String>(numResults);
   Connection con = null;
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = DbConnectionManager.createScrollablePreparedStatement(con, ALL_USERS);
     rs = pstmt.executeQuery();
     DbConnectionManager.setFetchSize(rs, startIndex + numResults);
     DbConnectionManager.scrollResultSet(rs, startIndex);
     int count = 0;
     while (rs.next() && count < numResults) {
       usernames.add(rs.getString(1));
       count++;
     }
   } catch (SQLException e) {
     Log.error(e);
   } finally {
     DbConnectionManager.closeConnection(rs, pstmt, con);
   }
   return new UserCollection(usernames.toArray(new String[usernames.size()]));
 }
 public void componentInfoReceived(IQ iq) {
   // Check if it's a Clearspace component
   boolean isClearspace = false;
   Element childElement = iq.getChildElement();
   for (Iterator it = childElement.elementIterator("identity"); it.hasNext(); ) {
     Element identity = (Element) it.next();
     if ("component".equals(identity.attributeValue("category"))
         && "clearspace".equals(identity.attributeValue("type"))) {
       isClearspace = true;
     }
   }
   // If component is Clearspace then keep track of the component
   if (isClearspace) {
     clearspaces.add(iq.getFrom().getDomain());
   }
 }
 public void componentUnregistered(JID componentJID) {
   // Remove stored information about this component
   clearspaces.remove(componentJID.getDomain());
 }
 /**
  * Returns true if a given JID belongs to a known Clearspace component domain.
  *
  * @param address Address to check.
  * @return True if the specified address is a Clearspace component.
  */
 public boolean isFromClearspace(JID address) {
   return clearspaces.contains(address.getDomain());
 }
Exemple #10
0
  public void initializePlugin(PluginManager manager, File pluginDirectory) {
    Log.info("[" + NAME + "] initialize " + NAME + " plugin resources");

    try {
      openfire = new Openfire();
      openfire.start();
      JmxHelper.register(openfire, OBJECTNAME_OPENFIRE);
      Log.info("[" + NAME + "] .. started openfire server detector.");
    } catch (Exception e) {
      Log.debug("cannot start openfire server detector: " + e.getMessage(), e);
    }

    try {
      packetCounter = new PacketCounter();
      packetCounter.start();
      JmxHelper.register(packetCounter, OBJECTNAME_PACKET_COUNTER);

      Log.info("[" + NAME + "] .. started stanza counter.");
    } catch (Exception e) {
      Log.debug("cannot start stanza counter: " + e.getMessage(), e);
    }

    try {
      client =
          new CoreThreadPool(
              ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager())
                  .getSocketAcceptor());
      client.start();
      JmxHelper.register(client, OBJECTNAME_CORE_CLIENT_THREADPOOL);

      Log.info("[" + NAME + "] .. started client thread pool monitor.");
    } catch (Exception e) {
      Log.debug("cannot start client thread pool monitor: " + e.getMessage(), e);
    }

    try {
      database = new DatabasePool();
      database.start();
      JmxHelper.register(database, OBJECTNAME_DATABASEPOOL);

      Log.info("[" + NAME + "] .. started database pool monitor.");
    } catch (Exception e) {
      Log.debug("cannot start database pool monitor: " + e.getMessage(), e);
    }

    try {

      ContextHandlerCollection contexts = HttpBindManager.getInstance().getContexts();

      try {
        Log.info("[" + NAME + "] starting jolokia");
        WebAppContext context = new WebAppContext(contexts, pluginDirectory.getPath(), "/jolokia");

        final List<ContainerInitializer> initializers = new ArrayList<>();
        initializers.add(new ContainerInitializer(new JasperInitializer(), null));
        context.setAttribute("org.eclipse.jetty.containerInitializers", initializers);
        context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
        context.setWelcomeFiles(new String[] {"index.html"});

        Log.info("[" + NAME + "] starting hawtio");
        WebAppContext context2 =
            new WebAppContext(contexts, pluginDirectory.getPath() + "/hawtio", "/hawtio");
        final List<ContainerInitializer> initializers2 = new ArrayList<>();
        initializers2.add(new ContainerInitializer(new JasperInitializer(), null));
        context2.setAttribute("org.eclipse.jetty.containerInitializers", initializers2);
        context2.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
        context2.setWelcomeFiles(new String[] {"index.html"});

        if (JiveGlobals.getBooleanProperty("xmpp.jmx.secure", true)) {
          SecurityHandler securityHandler = basicAuth("jmxweb");
          if (securityHandler != null) context.setSecurityHandler(securityHandler);

          SecurityHandler securityHandler2 = basicAuth("jmxweb");
          if (securityHandler2 != null) context2.setSecurityHandler(securityHandler2);
        }

      } catch (Exception e) {
        Log.error("An error has occurred", e);
      }
    } catch (Exception e) {
      Log.error("Error initializing JmxWeb Plugin", e);
    }

    if (JiveGlobals.getBooleanProperty("jmxweb.email.monitoring", true)) {
      Log.info("[" + NAME + "] starting email monitoring");
      emailScheduler = new EmailScheduler();
      emailScheduler.startMonitoring();
      Log.info("[" + NAME + "] started monitoring");
    }
  }