Beispiel #1
0
 void checkHealth() {
   // Check that the sending operation is still active
   if (writeStarted > -1
       && System.currentTimeMillis() - writeStarted
           > JiveGlobals.getIntProperty("xmpp.session.sending-limit", 60000)) {
     // Close the socket
     if (Log.isDebugEnabled()) {
       Log.debug(
           "Closing connection: "
               + this
               + " that started sending data at: "
               + new Date(writeStarted));
     }
     forceClose();
   } else {
     // Check if the connection has been idle. A connection is considered idle if the client
     // has not been receiving data for a period. Sending data to the client is not
     // considered as activity.
     if (idleTimeout > -1
         && socketReader != null
         && System.currentTimeMillis() - socketReader.getLastActive() > idleTimeout) {
       // Close the socket
       if (Log.isDebugEnabled()) {
         Log.debug("Closing connection that has been idle: " + this);
       }
       forceClose();
     }
   }
 }
  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 synchronized void startClearspaceConfig() {
    // If the task is running, stop it
    if (configClearspaceTask != null) {
      configClearspaceTask.cancel();
      Log.debug("Stopping previous configuration Clearspace task.");
    }

    // Create and schedule a confi task every minute
    configClearspaceTask = new ConfigClearspaceTask();
    // Wait some time to start the task until Openfire has binding address
    TaskEngine.getInstance()
        .schedule(configClearspaceTask, JiveConstants.SECOND * 30, JiveConstants.MINUTE);
    Log.debug("Starting configuration Clearspace task in 10 seconds.");
  }
Beispiel #4
0
  public void sendNewPostMessage(User recipient, Post post) {
    // Short-circuit message creation
    if (!userIsPresent(recipient.getGuid())) return;

    String title = post.getTitle();
    String url = post.getUrl() != null ? post.getUrl().toExternalForm() : null;

    if (url == null) {
      // this particular jabber message protocol has no point without an url
      Log.debug("no url found on post, not sending xmpp message");
      return;
    }

    Viewpoint viewpoint = new UserViewpoint(recipient);

    PostView postView = postingBoard.getPostView(viewpoint, post);
    Set<EntityView> referenced = postingBoard.getReferencedEntities(viewpoint, post);

    Message message = new Message();
    message.setType(Message.Type.normal);
    message.setBody(String.format("%s\n%s", title, url));
    addNewPostExtension(message, postView, referenced);

    sendMessage(recipient.getGuid(), message);
  }
  /*
   * (non-Javadoc)
   *
   * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
   */
  @Override
  protected void append(LoggingEvent event) {
    final Level l = event.getLevel();
    final String message = (event.getMessage() != null ? event.getMessage().toString() : "");

    Throwable throwable = null;
    if (event.getThrowableInformation() != null) {
      throwable = event.getThrowableInformation().getThrowable();
    }

    switch (l.toInt()) {
      case Priority.OFF_INT:
        // Logging turned off - do nothing.
        break;

      case Priority.FATAL_INT:
      case Priority.ERROR_INT:
        Log.error(message, throwable);
        break;

      case Priority.WARN_INT:
        Log.warn(message, throwable);
        break;

      case Priority.INFO_INT:
        Log.info(message, throwable);
        break;

      default:
        // DEBUG and below (trace, all)
        Log.debug(message, throwable);
        break;
    }
  }
Beispiel #6
0
 public void deliver(Packet packet) throws UnauthorizedException, PacketException {
   if (isClosed()) {
     deliverer.deliver(packet);
   } else {
     try {
       // Invoke the interceptors before we send the packet
       InterceptorManager.getInstance().invokeInterceptors(packet, session, false, false);
       boolean errorDelivering = false;
       synchronized (writer) {
         try {
           xmlSerializer.write(packet.getElement());
           if (flashClient) {
             writer.write('\0');
           }
           xmlSerializer.flush();
         } catch (IOException e) {
           Log.debug("Error delivering packet" + "\n" + this.toString(), e);
           errorDelivering = true;
         }
       }
       if (errorDelivering) {
         close();
         // Retry sending the packet again. Most probably if the packet is a
         // Message it will be stored offline
         deliverer.deliver(packet);
       } else {
         // Invoke the interceptors after we have sent the packet
         InterceptorManager.getInstance().invokeInterceptors(packet, session, false, true);
         session.incrementServerPacketCount();
       }
     } catch (PacketRejectedException e) {
       // An interceptor rejected the packet so do nothing
     }
   }
 }
Beispiel #7
0
 public void deliverRawText(String text) {
   if (!isClosed()) {
     boolean errorDelivering = false;
     synchronized (writer) {
       try {
         // Register that we started sending data on the connection
         writeStarted();
         writer.write(text);
         if (flashClient) {
           writer.write('\0');
         }
         writer.flush();
       } catch (IOException e) {
         Log.debug("Error delivering raw text" + "\n" + this.toString(), e);
         errorDelivering = true;
       } finally {
         // Register that we finished sending data on the connection
         writeFinished();
       }
     }
     if (errorDelivering) {
       close();
     }
   }
 }
Beispiel #8
0
 protected void handleStateChange(ClientConnEvent e) {
   Log.debug("OSCAR bos service state change from " + e.getOldState() + " to " + e.getNewState());
   if (e.getNewState() == ClientFlapConn.STATE_NOT_CONNECTED
       && e.getOldState() == ClientFlapConn.STATE_CONNECTED
       && getMainSession().isLoggedIn()) {
     getMainSession().bosDisconnected();
   }
 }
Beispiel #9
0
 /**
  * Returns a media proxy session with the specified ID.
  *
  * @param sid the session ID.
  * @return the session or <tt>null</tt> if the session doesn't exist.
  */
 public MediaProxySession getSession(String sid) {
   MediaProxySession proxySession = sessions.get(sid);
   if (proxySession != null) {
     if (Log.isDebugEnabled()) {
       Log.debug("MediaProxy: SID: " + sid + " agentSID: " + proxySession.getSID());
       return proxySession;
     }
   }
   return null;
 }
  @Override
  public IQ handleIQ(IQ packet) throws UnauthorizedException {
    Log.debug("handling IQ packet " + packet);
    IQ reply = IQ.createResultIQ(packet);
    Element iq = packet.getChildElement();
    String method = iq.attributeValue("name");
    List<String> args = new ArrayList<String>();

    // TODO Don't look this up each time
    // We currently do this to avoid problems during development
    // from reloading Jive - later we probably want to move this to
    // constructor
    XMPPMethods methods = EJBUtil.defaultLookup(XMPPMethods.class);
    SimpleAnnotatedInvoker xmppInvoker =
        new SimpleAnnotatedInvoker(XMPPRemoted.class, methods, new PersonArgumentPrepender());

    for (Object argObj : iq.elements()) {
      Node arg = (Node) argObj;
      Log.debug("parsing expected arg node " + arg);
      if (arg.getNodeType() == Node.ELEMENT_NODE) {
        String argValue = arg.getText();
        Log.debug("Adding arg value" + argValue);
        args.add(argValue);
      }
    }

    try {
      Log.debug(
          "invoking method "
              + method
              + " with ("
              + args.size()
              + ") args "
              + Arrays.toString(args.toArray()));
      @SuppressWarnings("unused")
      String replyStr = xmppInvoker.invoke(method, args, packet.getFrom());
      // Don't do anything with this yet
    } catch (Exception e) {
      Log.debug("Caught exception during client method invocation", e);
    }
    return reply;
  }
Beispiel #11
0
  protected void handleSnacPacket(SnacPacketEvent e) {
    Log.debug("OSCAR bos snac packet received: " + e);
    super.handleSnacPacket(e);

    SnacCommand cmd = e.getSnacCommand();

    if (cmd instanceof ServerReadyCmd) {
      request(new ParamInfoRequest());
      request(new LocRightsRequest());
      request(new SsiRightsRequest());
      request(new SsiDataRequest());
    }
  }
Beispiel #12
0
    public void publish(LogRecord record) {

      Level level = record.getLevel();
      Throwable throwable = record.getThrown();

      if (Level.SEVERE.equals(level)) {

        if (throwable != null) {
          Log.error(record.getMessage(), throwable);
        } else {
          Log.error(record.getMessage());
        }

      } else if (Level.WARNING.equals(level)) {

        if (throwable != null) {
          Log.warn(record.getMessage(), throwable);
        } else {
          Log.warn(record.getMessage());
        }

      } else if (Level.INFO.equals(level)) {

        if (throwable != null) {
          Log.info(record.getMessage(), throwable);
        } else {
          Log.info(record.getMessage());
        }

      } else {
        // else FINE,FINER,FINEST

        if (throwable != null) {
          Log.debug(record.getMessage(), throwable);
        } else {
          Log.debug(record.getMessage());
        }
      }
    }
 public void run() {
   try {
     Log.debug("Trying to configure Clearspace.");
     doConfigClearspace();
     updateClearspaceClientSettings();
   } catch (UnauthorizedException e) {
     Log.warn(
         "Unauthorization problem trying to configure Clearspace, trying again in 1 minute", e);
     // TODO: Mark that there is an authorization problem
   } catch (Exception e) {
     Log.warn("Unknown problem trying to configure Clearspace, trying again in 1 minute", e);
   }
 }
Beispiel #14
0
 /**
  * Make sure that the received packet has a TO and FROM values defined and that it was sent from a
  * previously validated domain. If the packet does not matches any of the above conditions then a
  * PacketRejectedException will be thrown.
  *
  * @param packet the received packet.
  * @throws PacketRejectedException if the packet does not include a TO or FROM or if the packet
  *     was sent from a domain that was not previously validated.
  */
 private void packetReceived(Packet packet) throws PacketRejectedException {
   if (packet.getTo() == null || packet.getFrom() == null) {
     Log.debug(
         "Closing IncomingServerSession due to packet with no TO or FROM: " + packet.toXML());
     // Send a stream error saying that the packet includes no TO or FROM
     StreamError error = new StreamError(StreamError.Condition.improper_addressing);
     connection.deliverRawText(error.toXML());
     // Close the underlying connection
     connection.close();
     open = false;
     throw new PacketRejectedException("Packet with no TO or FROM attributes");
   } else if (!((IncomingServerSession) session).isValidDomain(packet.getFrom().getDomain())) {
     Log.debug(
         "Closing IncomingServerSession due to packet with invalid domain: " + packet.toXML());
     // Send a stream error saying that the packet includes an invalid FROM
     StreamError error = new StreamError(StreamError.Condition.invalid_from);
     connection.deliverRawText(error.toXML());
     // Close the underlying connection
     connection.close();
     open = false;
     throw new PacketRejectedException("Packet with no TO or FROM attributes");
   }
 }
  public void authenticate(String username, String password) throws UnauthorizedException {
    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 {
      // Some native authentication mechanisms appear to not handle high load
      // very well. Therefore, synchronize access to Shaj to throttle auth checks.
      synchronized (this) {
        if (!Shaj.checkPassword(domain, username, password)) {
          throw new UnauthorizedException();
        }
      }
    } catch (UnauthorizedException ue) {
      throw ue;
    } catch (Exception e) {
      throw new UnauthorizedException(e);
    }

    // See if the user exists in the database. If not, automatically create them.
    UserManager userManager = UserManager.getInstance();
    try {
      userManager.getUser(username);
    } catch (UserNotFoundException unfe) {
      try {
        Log.debug("Automatically creating new user account for " + username);
        // Create user; use a random password for better safety in the future.
        // Note that we have to go to the user provider directly -- because the
        // provider is read-only, UserManager will usually deny access to createUser.
        UserProvider provider = UserManager.getUserProvider();
        if (!(provider instanceof NativeUserProvider)) {
          Log.error(
              "Error: not using NativeUserProvider so authentication with "
                  + "NativeAuthProvider will likely fail. Using: "
                  + provider.getClass().getName());
        }
        UserManager.getUserProvider().createUser(username, StringUtils.randomString(8), null, null);
      } catch (UserAlreadyExistsException uaee) {
        // Ignore.
      }
    }
  }
Beispiel #16
0
 /**
  * Processes the packet in another thread if the packet has not been rejected.
  *
  * @param packet the received packet.
  */
 protected void processIQ(final IQ packet) throws UnauthorizedException {
   try {
     packetReceived(packet);
     // Process the packet in another thread
     threadPool.execute(
         new Runnable() {
           public void run() {
             try {
               ServerSocketReader.super.processIQ(packet);
             } catch (UnauthorizedException e) {
               Log.error("Error processing packet", e);
             }
           }
         });
   } catch (PacketRejectedException e) {
     Log.debug("IQ rejected: " + packet.toXML(), e);
   }
 }
 public List<Object> interceptArgs(Method method, List<String> args, Object context)
     throws InvocationTargetException {
   Class[] paramTypes = method.getParameterTypes();
   List<Object> ret = new ArrayList<Object>();
   if (paramTypes.length > 0 && Guid.class.isAssignableFrom(paramTypes[0])) {
     try {
       JID from = (JID) context;
       String guid = from.getNode();
       if (guid != null) ret.add(new Guid(guid));
       else throw new RuntimeException("no from node");
     } catch (ParseException e) {
       throw new InvocationTargetException(e);
     }
   }
   ret.addAll(args);
   Log.debug("transformed args: " + Arrays.toString(ret.toArray()));
   return ret;
 }
  private void updateClearspaceClientSettings() {
    String xmppBoshSslPort = "0";
    String xmppBoshPort = "0";
    String xmppPort =
        String.valueOf(XMPPServer.getInstance().getConnectionManager().getClientListenerPort());
    if (JiveGlobals.getBooleanProperty(
        HttpBindManager.HTTP_BIND_ENABLED, HttpBindManager.HTTP_BIND_ENABLED_DEFAULT)) {
      int boshSslPort = HttpBindManager.getInstance().getHttpBindSecurePort();
      int boshPort = HttpBindManager.getInstance().getHttpBindUnsecurePort();
      try {
        if (HttpBindManager.getInstance().isHttpsBindActive()
            && LocalClientSession.getTLSPolicy()
                != org.jivesoftware.openfire.Connection.TLSPolicy.disabled) {
          xmppBoshSslPort = String.valueOf(boshSslPort);
        }
      } catch (Exception e) {
        // Exception while working with certificate
        Log.debug(
            "Error while checking SSL certificate.  Instructing Clearspace not to use SSL port.");
      }
      if (HttpBindManager.getInstance().isHttpBindActive() && boshPort > 0) {
        xmppBoshPort = String.valueOf(boshPort);
      }
    }

    try {
      String path = CHAT_URL_PREFIX + "updateClientSettings/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("updateClientSettings");
      rootE.addElement("boshSslPort").setText(xmppBoshSslPort);
      rootE.addElement("boshPort").setText(xmppBoshPort);
      rootE.addElement("tcpPort").setText(xmppPort);

      executeRequest(POST, path, groupDoc.asXML());
    } catch (UnauthorizedException ue) {
      Log.error("Error updating the client settings of Clearspace", ue);
    } catch (Exception e) {
      Log.error("Error updating the client settings of Clearspace", e);
    }
  }
  public synchronized boolean configClearspace() {
    // If the task is running, stop it
    if (configClearspaceTask != null) {
      configClearspaceTask.cancel();
      Log.debug("Stopping previous configuration Clearspace task.");
    }

    boolean configured = false;
    try {
      doConfigClearspace();
      updateClearspaceClientSettings();
      configured = true;
    } catch (UnauthorizedException e) {
      Log.info("Unauthorized to configure Clearspace.", e);
    } catch (UnsupportedOperationException e) {
      Log.info("Error configuring Clearspace.", e);
    }

    if (!configured) {
      startClearspaceConfig();
    }
    return configured;
  }
Beispiel #20
0
 /**
  * Implements Session Listener stopAgent event. Remove the stopped session from the sessions list.
  *
  * @param session the session that stopped
  */
 public void sessionClosed(MediaProxySession session) {
   sessions.remove(session.getSID());
   if (Log.isDebugEnabled()) {
     Log.debug("MediaProxy: Session: " + session.getSID() + " removed.");
   }
 }
 public ClientMethodIQHandler() {
   super("Dumbhippo IQ Method Handler");
   Log.debug("creating ClientMethodIQHandler");
   info = new IQHandlerInfo("method", "http://dumbhippo.com/protocol/servermethod");
 }
  /**
   * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
   * form /userService/users. If CS throws an exception it handled and transalated to a Openfire
   * exception if possible. This is done using the check fault method that tries to throw the best
   * maching exception.
   *
   * @param type Must be GET or DELETE
   * @param urlSuffix The url suffix of the rest request
   * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
   * @return The response as a xml doc.
   * @throws ConnectionException Thrown if there are issues perfoming the request.
   * @throws Exception Thrown if the response from Clearspace contains an exception.
   */
  public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
      throws ConnectionException, Exception {
    if (Log.isDebugEnabled()) {
      Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
    }

    String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

    String secret = getSharedSecret();

    HttpClient client = new HttpClient();
    HttpMethod method;

    // Configures the authentication
    client.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
    AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
    client.getState().setCredentials(scope, credentials);

    // Creates the method
    switch (type) {
      case GET:
        method = new GetMethod(wsUrl);
        break;
      case POST:
        PostMethod pm = new PostMethod(wsUrl);
        StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
        pm.setRequestEntity(requestEntity);
        method = pm;
        break;
      case PUT:
        PutMethod pm1 = new PutMethod(wsUrl);
        StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
        pm1.setRequestEntity(requestEntity1);
        method = pm1;
        break;
      case DELETE:
        method = new DeleteMethod(wsUrl);
        break;
      default:
        throw new IllegalArgumentException();
    }

    method.setRequestHeader("Accept", "text/xml");
    method.setDoAuthentication(true);

    try {
      // Executes the request
      client.executeMethod(method);

      // Parses the result
      String body = method.getResponseBodyAsString();
      if (Log.isDebugEnabled()) {
        Log.debug("Outgoing REST call results: " + body);
      }

      // Checks the http status
      if (method.getStatusCode() != 200) {
        if (method.getStatusCode() == 401) {
          throw new ConnectionException(
              "Invalid password to connect to Clearspace.",
              ConnectionException.ErrorType.AUTHENTICATION);
        } else if (method.getStatusCode() == 404) {
          throw new ConnectionException(
              "Web service not found in Clearspace.", ConnectionException.ErrorType.PAGE_NOT_FOUND);
        } else if (method.getStatusCode() == 503) {
          throw new ConnectionException(
              "Web service not avaible in Clearspace.",
              ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE);
        } else {
          throw new ConnectionException(
              "Error connecting to Clearspace, http status code: " + method.getStatusCode(),
              new HTTPConnectionException(method.getStatusCode()),
              ConnectionException.ErrorType.OTHER);
        }
      } else if (body.contains("Clearspace Upgrade Console")) {
        // TODO Change CS to send a more standard error message
        throw new ConnectionException(
            "Clearspace is in an update state.", ConnectionException.ErrorType.UPDATE_STATE);
      }

      Element response = localParser.get().parseDocument(body).getRootElement();

      // Check for exceptions
      checkFault(response);

      // Since there is no exception, returns the response
      return response;
    } catch (DocumentException e) {
      throw new ConnectionException(
          "Error parsing the response of Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } catch (HttpException e) {
      throw new ConnectionException(
          "Error performing http request to Clearspace", e, ConnectionException.ErrorType.OTHER);
    } catch (UnknownHostException e) {
      throw new ConnectionException(
          "Unknown Host " + getConnectionURI() + " trying to connect to Clearspace",
          e,
          ConnectionException.ErrorType.UNKNOWN_HOST);
    } catch (IOException e) {
      throw new ConnectionException(
          "Error peforming http request to Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } finally {
      method.releaseConnection();
    }
  }
Beispiel #23
0
 protected void handleFlapPacket(FlapPacketEvent e) {
   Log.debug("OSCAR bos flap packet received: " + e);
   super.handleFlapPacket(e);
 }
  private void init() {
    // Register the trust manager to use when using HTTPS
    Protocol easyhttps =
        new Protocol("https", (ProtocolSocketFactory) new SSLProtocolSocketFactory(this), 443);
    Protocol.registerProtocol("https", easyhttps);

    // Convert XML based provider setup to Database based
    JiveGlobals.migrateProperty("clearspace.uri");
    JiveGlobals.migrateProperty("clearspace.sharedSecret");

    // Make sure that all Clearspace components are set up, unless they were overridden
    // Note that the auth provider is our way of knowing that we are set up with Clearspace,
    // so don't bother checking to set it.
    if (isEnabled()) {
      if (JiveGlobals.getProperty("provider.user.className") == null) {
        JiveGlobals.setProperty(
            "provider.user.className",
            "org.jivesoftware.openfire.clearspace.ClearspaceUserProvider");
      }
      if (JiveGlobals.getProperty("provider.group.className") == null) {
        JiveGlobals.setProperty(
            "provider.group.className",
            "org.jivesoftware.openfire.clearspace.ClearspaceGroupProvider");
      }
      if (JiveGlobals.getProperty("provider.vcard.className") == null) {
        JiveGlobals.setProperty(
            "provider.vcard.className",
            "org.jivesoftware.openfire.clearspace.ClearspaceVCardProvider");
      }
      if (JiveGlobals.getProperty("provider.lockout.className") == null) {
        JiveGlobals.setProperty(
            "provider.lockout.className",
            "org.jivesoftware.openfire.clearspace.ClearspaceLockOutProvider");
      }
      if (JiveGlobals.getProperty("provider.securityAudit.className") == null) {
        JiveGlobals.setProperty(
            "provider.securityAudit.className",
            "org.jivesoftware.openfire.clearspace.ClearspaceSecurityAuditProvider");
      }
      if (JiveGlobals.getProperty("provider.admin.className") == null) {
        JiveGlobals.setProperty(
            "provider.admin.className",
            "org.jivesoftware.openfire.clearspace.ClearspaceAdminProvider");
      }
    }

    this.uri = properties.get("clearspace.uri");
    if (uri != null) {
      if (!this.uri.endsWith("/")) {
        this.uri = this.uri + "/";
      }
      // Updates the host/port attributes based on the uri
      updateHostPort();
    }
    sharedSecret = properties.get("clearspace.sharedSecret");

    // Creates the cache maps
    userIDCache = new DefaultCache<String, Long>("clearspace.userid", 1000, JiveConstants.DAY);
    groupIDCache = new DefaultCache<String, Long>("clearspace.groupid", 1000, JiveConstants.DAY);
    usernameCache = new DefaultCache<Long, String>("clearspace.username", 1000, JiveConstants.DAY);

    if (Log.isDebugEnabled()) {
      StringBuilder buf = new StringBuilder();
      buf.append("Created new ClearspaceManager() instance, fields:\n");
      buf.append("\t URI: ").append(uri).append("\n");
      buf.append("\t sharedSecret: ").append(sharedSecret).append("\n");

      Log.debug("ClearspaceManager: " + buf.toString());
    }

    // Init nonce cache
    nonceCache = CacheFactory.createCache("Clearspace SSO Nonce");
    // Init nonce generator
    nonceGenerator = new Random();
  }
Beispiel #25
0
  protected void handleSnacResponse(SnacResponseEvent e) {
    super.handleSnacResponse(e);

    Log.debug("OSCAR bos snac response received: " + e);

    SnacCommand cmd = e.getSnacCommand();

    if (cmd instanceof LocRightsCmd) {
      request(new SetInfoCmd(new InfoData("oscargateway", null, MY_CAPS, null)));
      request(new MyInfoRequest());
    } else if (cmd instanceof ParamInfoCmd) {
      ParamInfoCmd pic = (ParamInfoCmd) cmd;

      ParamInfo info = pic.getParamInfo();

      request(
          new SetParamInfoCmd(
              new ParamInfo(
                  0,
                  info.getFlags() | ParamInfo.FLAG_TYPING_NOTIFICATION,
                  8000,
                  info.getMaxSenderWarning(),
                  info.getMaxReceiverWarning(),
                  0)));
    } else if (cmd instanceof ServiceRedirect) {
      ServiceRedirect sr = (ServiceRedirect) cmd;

      oscarSession.connectToService(sr.getSnacFamily(), sr.getRedirectHost(), sr.getCookie());

    } else if (cmd instanceof SsiDataCmd) {
      SsiDataCmd sdc = (SsiDataCmd) cmd;

      List<SsiItem> items = sdc.getItems();
      for (SsiItem item : items) {
        SsiItemObj obj = itemFactory.getItemObj(item);
        if (obj instanceof BuddyItem) {
          Log.debug("AIM got buddy item " + obj);
          oscarSession.gotBuddy((BuddyItem) obj);
        } else if (obj instanceof GroupItem) {
          Log.debug("AIM got group item " + obj);
          oscarSession.gotGroup((GroupItem) obj);
        }
      }

      if (sdc.getLastModDate() != 0) {
        request(new ActivateSsiCmd());
        clientReady();

        Presence p = new Presence();
        p.setTo(oscarSession.getJID());
        p.setFrom(oscarSession.getTransport().getJID());
        oscarSession.getTransport().sendPacket(p);

        oscarSession.setLoginStatus(TransportLoginStatus.LOGGED_IN);
        oscarSession.gotCompleteSSI();
      }
    } else if (cmd instanceof OfflineMsgIcqCmd) {
      OfflineMsgIcqCmd omic = (OfflineMsgIcqCmd) cmd;

      String sn = String.valueOf(omic.getFromUIN());
      // String msg = "Offline message sent at "+new
      // Date(omic.getDate().getTime()).toString()+"\n"+OscarTools.stripHtml(omic.getContents()).trim();
      String msg =
          "Offline message received:\n"
              + StringUtils.unescapeFromXML(OscarTools.stripHtml(omic.getContents()).trim());
      EncodedStringInfo encmsg = MinimalEncoder.encodeMinimally(msg);
      InstantMessage imsg =
          new InstantMessage(
              encmsg.getImEncoding().getCharsetCode(), ByteBlock.wrap(encmsg.getData()));

      oscarSession
          .getTransport()
          .sendMessage(
              oscarSession.getJIDWithHighestPriority(),
              oscarSession.getTransport().convertIDToJID(sn),
              imsg.getMessage());
    } else if (cmd instanceof OfflineMsgDoneCmd) {
      request(new OfflineMsgIcqAckCmd(oscarSession.getUIN(), (int) oscarSession.nextIcqId()));
    } else if (cmd instanceof MetaShortInfoCmd) {
      //            MetaShortInfoCmd msic = (MetaShortInfoCmd)cmd;
      //            Log.debug("RECEIVED META SHORT INFO: "+msic);
      //            oscarSession.updateRosterNickname(String.valueOf(msic.getUIN()),
      // msic.getNickname());
    } else if (cmd instanceof BuddyAddedYouCmd) {
      BuddyAddedYouCmd bay = (BuddyAddedYouCmd) cmd;

      Presence p = new Presence();
      p.setType(Presence.Type.subscribe);
      p.setTo(oscarSession.getJID());
      p.setFrom(oscarSession.getTransport().convertIDToJID(bay.getUin()));
      oscarSession.getTransport().sendPacket(p);
    } else if (cmd instanceof BuddyAuthRequest) {
      BuddyAuthRequest bar = (BuddyAuthRequest) cmd;

      Presence p = new Presence();
      p.setType(Presence.Type.subscribe);
      p.setTo(oscarSession.getJID());
      p.setFrom(oscarSession.getTransport().convertIDToJID(bar.getScreenname()));
      oscarSession.getTransport().sendPacket(p);
    } else if (cmd instanceof AuthReplyCmd) {
      AuthReplyCmd ar = (AuthReplyCmd) cmd;

      if (ar.isAccepted()) {
        Presence p = new Presence();
        p.setType(Presence.Type.subscribed);
        p.setTo(oscarSession.getJID());
        p.setFrom(oscarSession.getTransport().convertIDToJID(ar.getSender()));
        oscarSession.getTransport().sendPacket(p);
      } else {
        Presence p = new Presence();
        p.setType(Presence.Type.unsubscribed);
        p.setTo(oscarSession.getJID());
        p.setFrom(oscarSession.getTransport().convertIDToJID(ar.getSender()));
        oscarSession.getTransport().sendPacket(p);
      }
    } else if (cmd instanceof AuthFutureCmd) {
      AuthFutureCmd af = (AuthFutureCmd) cmd;

      Presence p = new Presence();
      p.setType(Presence.Type.subscribe);
      p.setTo(oscarSession.getJID());
      p.setFrom(oscarSession.getTransport().convertIDToJID(af.getUin()));
      oscarSession.getTransport().sendPacket(p);
    }
  }