proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/admin/JDBCAdminProvider.java
JDBCAdminProvider
changeAdmins
class JDBCAdminProvider implements AdminProvider { private static final Logger Log = LoggerFactory.getLogger(JDBCAdminProvider.class); private final String getAdminsSQL; private final String insertAdminsSQL; private final String deleteAdminsSQL; private final String xmppDomain; private final boolean useConnectionProvider; private String connectionString; /** * Constructs a new JDBC admin provider. */ public JDBCAdminProvider() { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty("jdbcProvider.driver"); JiveGlobals.migrateProperty("jdbcProvider.connectionString"); JiveGlobals.migrateProperty("jdbcAdminProvider.getAdminsSQL"); xmppDomain = XMPPServerInfo.XMPP_DOMAIN.getValue(); useConnectionProvider = JiveGlobals.getBooleanProperty("jdbcAdminProvider.useConnectionProvider"); // Load database statement for reading admin list getAdminsSQL = JiveGlobals.getProperty("jdbcAdminProvider.getAdminsSQL"); insertAdminsSQL = JiveGlobals.getProperty("jdbcAdminProvider.insertAdminsSQL", ""); deleteAdminsSQL = JiveGlobals.getProperty("jdbcAdminProvider.deleteAdminsSQL", ""); // Load the JDBC driver and connection string if (!useConnectionProvider) { String jdbcDriver = JiveGlobals.getProperty("jdbcProvider.driver"); try { Class.forName(jdbcDriver).getDeclaredConstructor().newInstance(); } catch (Exception e) { Log.error("Unable to load JDBC driver: " + jdbcDriver, e); return; } connectionString = JiveGlobals.getProperty("jdbcProvider.connectionString"); } } /** * XMPP disallows some characters in identifiers, requiring them to be escaped. * * This implementation assumes that the database returns properly escaped identifiers, * but can apply escaping by setting the value of the 'jdbcAdminProvider.isEscaped' * property to 'false'. * * @return 'false' if this implementation needs to escape database content before processing. */ protected boolean assumePersistedDataIsEscaped() { return JiveGlobals.getBooleanProperty( "jdbcAdminProvider.isEscaped", true ); } @Override public synchronized List<JID> getAdmins() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<JID> jids = new ArrayList<>(); try { con = getConnection(); pstmt = con.prepareStatement(getAdminsSQL); rs = pstmt.executeQuery(); while (rs.next()) { // OF-1837: When the database does not hold escaped data, escape values before processing them further. final String username; if (assumePersistedDataIsEscaped()) { username = rs.getString(1); } else { username = JID.escapeNode( rs.getString(1) ); } jids.add(new JID(username + "@" + xmppDomain)); } return jids; } catch (SQLException e) { throw new RuntimeException(e); } finally { DbConnectionManager.closeConnection(rs, pstmt, con); } } private void changeAdmins(final Connection con, final String sql, final List<JID> admins) throws SQLException {<FILL_FUNCTION_BODY>} @Override public synchronized void setAdmins(List<JID> newAdmins) { if (isReadOnly()) { // Reject the operation since the provider is read-only throw new UnsupportedOperationException(); } final List<JID> currentAdmins = getAdmins(); // Get a list of everyone in the new list not in the current list final List<JID> adminsToAdd = new ArrayList<>(newAdmins); adminsToAdd.removeAll(currentAdmins); // Get a list of everyone in the current list not in the new list currentAdmins.removeAll(newAdmins); try (final Connection con = getConnection()) { changeAdmins(con, insertAdminsSQL, adminsToAdd); changeAdmins(con, deleteAdminsSQL, currentAdmins); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public boolean isReadOnly() { return insertAdminsSQL.isEmpty() || deleteAdminsSQL.isEmpty(); } private Connection getConnection() throws SQLException { if (useConnectionProvider) { return DbConnectionManager.getConnection(); } return DriverManager.getConnection(connectionString); } }
if (!admins.isEmpty()) { try (final PreparedStatement pstmt = con.prepareStatement(sql)) { for (final JID jid : admins) { // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause. final String queryValue = assumePersistedDataIsEscaped() ? jid.getNode() : JID.unescapeNode( jid.getNode() ); pstmt.setString(1, queryValue); pstmt.execute(); } } }
1,273
146
1,419
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/archive/ArchiveManager.java
ArchiveManager
destroy
class ArchiveManager extends BasicModule { /** * The number of threads to keep in the thread pool that writes messages to the database, even if they are idle. */ public static final SystemProperty<Integer> EXECUTOR_CORE_POOL_SIZE = SystemProperty.Builder.ofType(Integer.class) .setKey("xmpp.archivemanager.threadpool.size.core") .setMinValue(0) .setDefaultValue(0) .setDynamic(false) .build(); /** * The maximum number of threads to allow in the thread pool that writes messages to the database. */ public static final SystemProperty<Integer> EXECUTOR_MAX_POOL_SIZE = SystemProperty.Builder.ofType(Integer.class) .setKey("xmpp.archivemanager.threadpool.size.max") .setMinValue(1) .setDefaultValue(Integer.MAX_VALUE) .setDynamic(false) .build(); /** * The number of threads in the thread pool that writes messages to the database is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. */ public static final SystemProperty<Duration> EXECUTOR_POOL_KEEP_ALIVE = SystemProperty.Builder.ofType(Duration.class) .setKey("xmpp.archivemanager.threadpool.keepalive") .setChronoUnit(ChronoUnit.SECONDS) .setDefaultValue(Duration.ofSeconds(60)) .setDynamic(false) .build(); /** * A thread pool that writes messages to the database. */ private ThreadPoolExecutor executor; /** * Object name used to register delegate MBean (JMX) for the thread pool executor. */ private ObjectName objectName; /** * Currently running tasks. */ private final ConcurrentMap<String, Archiver> tasks = new ConcurrentHashMap<>(); public ArchiveManager() { super( "ArchiveManager" ); } /** * Initializes the manager, by instantiating a thread pool that is used to process archiving tasks. */ @Override public void initialize( final XMPPServer server ) { if ( executor != null ) { throw new IllegalStateException( "Already initialized." ); } executor = new ThreadPoolExecutor( EXECUTOR_CORE_POOL_SIZE.getValue(), EXECUTOR_MAX_POOL_SIZE.getValue(), EXECUTOR_POOL_KEEP_ALIVE.getValue().toSeconds(), TimeUnit.SECONDS, new SynchronousQueue<>(), new NamedThreadFactory( "archive-service-worker-", null, null, null ) ); if (JMXManager.isEnabled()) { final ThreadPoolExecutorDelegateMBean mBean = new ThreadPoolExecutorDelegate(executor); objectName = JMXManager.tryRegister(mBean, ThreadPoolExecutorDelegateMBean.BASE_OBJECT_NAME + "archive-manager"); } } /** * Destroys the module, by shutting down the thread pool that is being used to process archiving tasks. * * No new archive tasks will be accepted any longer, although previously scheduled tasks can continue * to be processed. */ @Override public void destroy() {<FILL_FUNCTION_BODY>} /** * Adds a new task, that is started immediately. * * @param archiver The task to be added. Cannot be null. */ public synchronized void add( final Archiver archiver ) { if (tasks.containsKey( archiver.getId() ) ) { throw new IllegalStateException( "A task with ID " + archiver.getId() + " has already been added." ); } executor.submit( archiver ); tasks.put( archiver.getId(), archiver ); } /** * Stops and removes an exiting task. No-op when the provided task is not managed by this manager. * * @param archiver The task to be added. Cannot be null. */ public synchronized void remove( final Archiver archiver ) { remove( archiver.getId() ); } /** * Stops and removes an existing task. No-op when the provided task is not managed by this manager. * * @param id The identifier of task to be added. Cannot be null. */ public synchronized void remove( final String id ) { final Archiver task = tasks.remove( id ); if ( task != null ) { task.stop(); } } public Duration availabilityETAOnLocalNode( final String id, final Instant instant ) { final Archiver task = tasks.get( id ); if (task == null ) { // When a node does not have a task, it has no pending data to write to it. return Duration.ZERO; } else { return task.availabilityETAOnLocalNode( instant ); } } }
if (objectName != null) { JMXManager.tryUnregister(objectName); objectName = null; } if ( executor != null ) { executor.shutdown(); executor = null; }
1,309
70
1,379
<methods>public void <init>(java.lang.String) ,public void destroy() ,public java.lang.String getName() ,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public void start() throws java.lang.IllegalStateException,public void stop() <variables>private java.lang.String name
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/archive/GetArchiveWriteETATask.java
GetArchiveWriteETATask
run
class GetArchiveWriteETATask implements ClusterTask<Duration> { private Instant instant; private String id; private Duration result; public GetArchiveWriteETATask() {} public GetArchiveWriteETATask( Instant instant, String id ) { this.instant = instant; this.id = id; } @Override public void run() {<FILL_FUNCTION_BODY>} @Override public Duration getResult() { return result; } @Override public void writeExternal( ObjectOutput out ) throws IOException { ExternalizableUtil.getInstance().writeSerializable( out, instant ); ExternalizableUtil.getInstance().writeSafeUTF( out, id ); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { instant = (Instant) ExternalizableUtil.getInstance().readSerializable( in ); id = ExternalizableUtil.getInstance().readSafeUTF( in ); } }
final ArchiveManager manager = XMPPServer.getInstance().getArchiveManager(); result = manager.availabilityETAOnLocalNode( id, instant );
269
40
309
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/audit/SessionEvent.java
SessionEvent
createAuthFailureEvent
class SessionEvent extends AuditEvent { /** * Session events use the code 1 */ public static final int SESSION_CODE = 1; // Session reasons public static final int SESSION_CONNECT = 1; public static final int SESSION_STREAM = 2; public static final int SESSION_AUTH_FAILURE = 3; public static final int SESSION_AUTH_SUCCESS = 4; public static final int SESSION_DISCONNECT = 10; /** * Session events can only be created using static factory methods. * * @param eventSession the session that this event is recording. * @param eventReason the reason the event is called. * @param data the data to associate with the event. */ private SessionEvent(Session eventSession, int eventReason, String data) { super(eventSession, new Date(), SESSION_CODE, eventReason, data); } /** * Create an event associated with the initial connection * of a session before the stream is created. * * @param session the session that was connected. * @return an event representing the connection event. */ public static SessionEvent createConnectEvent(Session session) { return new SessionEvent(session, SESSION_CONNECT, null); } /** * Create an event associated with the establishment of an XMPP session. * A connect event that is not followed by a stream event indicates * the connection was rejected. * * @param session the session that began streaming. * @return an event representing the connection event. */ public static SessionEvent createStreamEvent(Session session) { return new SessionEvent(session, SESSION_STREAM, null); } /** * Create an event associated with the failure of a session to authenticate. * * @param session the session that made the attempt * @param user the user that made the attempt * @param resource the resource used for the attempt * @return an event representing the connection event */ public static SessionEvent createAuthFailureEvent(Session session, String user, String resource) {<FILL_FUNCTION_BODY>} /** * Create an event associated with a successful authentication. * * @param session the session that authenticated. * @return an event representing the connection event. */ public static SessionEvent createAuthSuccessEvent(Session session) { return new SessionEvent(session, SESSION_AUTH_SUCCESS, null); } /** * Create an event associated with the closing of a session. * * @param session the session that was disconnected. * @return an event representing the connection event. */ public static SessionEvent createDisconnectEvent(Session session) { return new SessionEvent(session, SESSION_DISCONNECT, null); } }
return new SessionEvent(session, SESSION_AUTH_FAILURE, "User: " + user + " Resource: " + resource);
722
38
760
<methods>public void <init>(org.jivesoftware.openfire.session.Session, java.util.Date, int, int, java.lang.String) ,public int getCode() ,public java.lang.String getData() ,public int getReason() ,public org.jivesoftware.openfire.session.Session getSession() ,public java.util.Date getTimestamp() ,public void setCode(int) ,public void setData(java.lang.String) ,public void setReason(int) ,public void setSession(org.jivesoftware.openfire.session.Session) ,public void setTimestamp(java.util.Date) <variables>public static final int USER_CODES,private int code,private java.lang.String data,private int reason,private org.jivesoftware.openfire.session.Session session,private java.util.Date time
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/audit/spi/AuditManagerImpl.java
AuditorInterceptor
interceptPacket
class AuditorInterceptor implements PacketInterceptor { @Override public void interceptPacket(Packet packet, Session session, boolean read, boolean processed) {<FILL_FUNCTION_BODY>} }
if (!processed) { // Ignore packets sent or received by users that are present in the ignore list JID from = packet.getFrom(); JID to = packet.getTo(); if ((from == null || !ignoreList.contains(from.getNode())) && (to == null || !ignoreList.contains(to.getNode()))) { auditor.audit(packet, session); } }
57
110
167
<methods>public void <init>(java.lang.String) ,public void destroy() ,public java.lang.String getName() ,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public void start() throws java.lang.IllegalStateException,public void stop() <variables>private java.lang.String name
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/AuthToken.java
AuthToken
generateUserToken
class AuthToken { private final String username; /** * Constructs a new AuthToken that represents an authenticated user identified by * the provider username. * * @param username the username to create an authToken token with. * @return the auth token for the user */ public static AuthToken generateUserToken( String username ) {<FILL_FUNCTION_BODY>} /** * Constructs a new AuthToken that represents an authenticated, but anonymous user. * @return an anonymouse auth token */ public static AuthToken generateAnonymousToken() { return new AuthToken( null ); } /** * Constructs a new OneTimeAuthToken that represents an one time recovery user. * * @param token the one time token. * @return the newly generated auth token */ public static AuthToken generateOneTimeToken(String token) { return new OneTimeAuthToken(token); } /** * Constructs a new AuthToken with the specified username. * The username can be either a simple username or a full JID. * * @param jid the username or bare JID to create an authToken token with. */ protected AuthToken(String jid) { if (jid == null) { this.username = null; return; } int index = jid.indexOf("@"); if (index > -1) { this.username = jid.substring(0,index); } else { this.username = jid; } } /** * Returns the username associated with this AuthToken. A {@code null} value * means that the authenticated user is anonymous. * * @return the username associated with this AuthToken or null when using an anonymous user. */ public String getUsername() { return username; } /** * Returns true if this AuthToken is the Anonymous auth token. * * @return true if this token is the anonymous AuthToken. */ public boolean isAnonymous() { return username == null; } /** * A token that proves that a user uses a one time access token. * * @author ma1uta */ public static class OneTimeAuthToken extends AuthToken { public OneTimeAuthToken(String token) { super(token); } } }
if ( username == null || username.isEmpty() ) { throw new IllegalArgumentException( "Argument 'username' cannot be null." ); } return new AuthToken( username );
612
46
658
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/AuthorizationBasedAuthProviderMapper.java
AuthorizationBasedAuthProviderMapper
instantiateProvider
class AuthorizationBasedAuthProviderMapper implements AuthProviderMapper { /** * Name of the property of which the value is expected to be the classname of the AuthProvider which will serve the * administrative users. */ public static final String PROPERTY_ADMINPROVIDER_CLASSNAME = "authorizationBasedAuthMapper.adminProvider.className"; /** * Name of the property of which the value is expected to be the classname of the AuthProvider which will serve the * regular, non-administrative users. */ public static final String PROPERTY_USERPROVIDER_CLASSNAME = "authorizationBasedAuthMapper.userProvider.className"; /** * Serves the administrative users. */ protected final AuthProvider adminProvider; /** * Serves the regular, non-administrative users. */ protected final AuthProvider userProvider; public AuthorizationBasedAuthProviderMapper() { // Migrate properties. JiveGlobals.migrateProperty( PROPERTY_ADMINPROVIDER_CLASSNAME ); JiveGlobals.migrateProperty( PROPERTY_USERPROVIDER_CLASSNAME ); // Instantiate providers. adminProvider = instantiateProvider( PROPERTY_ADMINPROVIDER_CLASSNAME ); userProvider = instantiateProvider( PROPERTY_USERPROVIDER_CLASSNAME ); } protected static AuthProvider instantiateProvider( String propertyName ) {<FILL_FUNCTION_BODY>} @Override public AuthProvider getAuthProvider( String username ) { // TODO add optional caching, to prevent retrieving the administrative users upon every invocation. final JID jid = XMPPServer.getInstance().createJID( username, null ); final boolean isAdmin = AdminManager.getAdminProvider().getAdmins().contains( jid ); if ( isAdmin ) { return adminProvider; } else { return userProvider; } } @Override public Set<AuthProvider> getAuthProviders() { final Set<AuthProvider> result = new LinkedHashSet<>(); result.add( adminProvider ); result.add( userProvider ); return result; } }
final String className = JiveGlobals.getProperty( propertyName ); if ( className == null ) { throw new IllegalStateException( "A class name must be specified via openfire.xml or the system properties." ); } try { final Class c = ClassUtils.forName( className ); return (AuthProvider) c.newInstance(); } catch ( Exception e ) { throw new IllegalStateException( "Unable to create new instance of AuthProvider: " + className, e ); }
569
135
704
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/AuthorizationManager.java
AuthorizationManager
authorize
class AuthorizationManager { private static final Logger Log = LoggerFactory.getLogger(AuthorizationManager.class); private static final ArrayList<AuthorizationPolicy> authorizationPolicies = new ArrayList<>(); private static final ArrayList<AuthorizationMapping> authorizationMapping = new ArrayList<>(); static { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty("provider.authorization.classList"); JiveGlobals.migrateProperty("provider.authorizationMapping.classList"); String classList = JiveGlobals.getProperty("provider.authorization.classList"); if (classList != null) { StringTokenizer st = new StringTokenizer(classList, " ,\t\n\r\f"); while (st.hasMoreTokens()) { String s_provider = st.nextToken(); try { Class c_provider = ClassUtils.forName(s_provider); AuthorizationPolicy provider = (AuthorizationPolicy)(c_provider.newInstance()); Log.debug("AuthorizationManager: Loaded " + s_provider); authorizationPolicies.add(provider); } catch (Exception e) { Log.error("AuthorizationManager: Error loading AuthorizationProvider: " + s_provider + "\n" + e); } } } if (authorizationPolicies.isEmpty()) { Log.debug("AuthorizationManager: No AuthorizationProvider's found. Loading DefaultAuthorizationPolicy"); authorizationPolicies.add(new DefaultAuthorizationPolicy()); } classList = JiveGlobals.getProperty("provider.authorizationMapping.classList"); if (classList != null) { StringTokenizer st = new StringTokenizer(classList, " ,\t\n\r\f"); while (st.hasMoreTokens()) { String s_provider = st.nextToken(); try { Class c_provider = ClassUtils.forName(s_provider); Object o_provider = c_provider.newInstance(); if(o_provider instanceof AuthorizationMapping) { AuthorizationMapping provider = (AuthorizationMapping)(o_provider); Log.debug("AuthorizationManager: Loaded " + s_provider); authorizationMapping.add(provider); } else { Log.debug("AuthorizationManager: Unknown class type."); } } catch (Exception e) { Log.error("AuthorizationManager: Error loading AuthorizationMapping: " + s_provider + "\n" + e); } } } if (authorizationMapping.isEmpty()) { Log.debug("AuthorizationManager: No AuthorizationMapping's found. Loading DefaultAuthorizationMapping"); authorizationMapping.add(new DefaultAuthorizationMapping()); } } // static utility class; do not instantiate private AuthorizationManager() { } /** * Returns the currently-installed AuthorizationProvider. Warning: You * should not be calling the AuthorizationProvider directly to perform * authorizations, it will not take into account the policy selected in * the {@code openfire.xml}. Use @see{authorize} in this class, instead. * * @return the current AuthorizationProvider. */ public static Collection<AuthorizationPolicy> getAuthorizationPolicies() { return authorizationPolicies; } /** * Authorize the authenticated username (authcid, principal) to the requested username (authzid). * * This uses the selected AuthenticationProviders. * * @param authzid authorization identity (identity to act as). * @param authcid authentication identity (identity whose password will be used) * @return true if the user is authorized to act as the requested authorization identity. */ public static boolean authorize(String authzid, String authcid) {<FILL_FUNCTION_BODY>} /** * Map the authenticated username (authcid, principal) to the username to act as (authzid). * * If the authenticated username did not supply a username to act as, determine the default to use. * * @param authcid authentication identity (identity whose password will be used), for which to determine the username to act as (authzid). * @return The username to act as (authzid) for the provided authentication identity. */ public static String map(String authcid) { for (AuthorizationMapping am : authorizationMapping) { Log.trace("Trying if AuthorizationMapping {} provides an authzid that is different from the provided authcid {}", am.name(), authcid); String authzid = am.map(authcid); if(!authzid.equals(authcid)) { Log.trace("AuthorizationMapping {} provided an authzid {} for the provided authcid {}", am.name(), authzid, authcid); return authzid; } } return authcid; } }
for (AuthorizationPolicy ap : authorizationPolicies) { Log.trace("Trying if AuthorizationPolicy {} authorizes {} to act as {}", ap.name(), authcid, authzid); if (ap.authorize(authzid, authcid)) { // Authorized... but do you exist? try { UserManager.getUserProvider().loadUser(authzid); } catch (UserNotFoundException nfe) { Log.debug("User {} not found ", authzid, nfe); // Should we add the user? if(JiveGlobals.getBooleanProperty("xmpp.auth.autoadd",false)) { if (UserManager.getUserProvider().isReadOnly()) { return false; } if (UserManager.getUserProvider().isNameRequired() || UserManager.getUserProvider().isEmailRequired()) { // If these are required, there's no way we can arbitrarily auto-create this account. return false; } try { UserManager.getInstance().createUser(authzid, StringUtils.randomString(8), null, null); Log.info("AuthorizationManager: User {} created.", authzid); return true; } catch (UserAlreadyExistsException uaee) { // Somehow the user got created in this very short timeframe.. // To be safe, lets fail here. The user can always try again. Log.error("AuthorizationManager: User {} already exists while attempting to add user.", authzid, uaee); return false; } } return false; } // User exists return true; } } // Not authorized. return false;
1,226
432
1,658
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/DefaultAuthorizationMapping.java
DefaultAuthorizationMapping
map
class DefaultAuthorizationMapping implements AuthorizationMapping { private static final Logger Log = LoggerFactory.getLogger(DefaultAuthorizationMapping.class); /** * Returns the default authorization identity (the identity to act as) for a provided authentication identity * (or 'principal' - whose password is used). * * @param authcid authentication identity (or 'principal' whose password is used) * @return The name of the default authorization identity to use. */ @Override public String map(String authcid) {<FILL_FUNCTION_BODY>} /** * Returns the short name of the Policy * * @return The short name of the Policy */ @Override public String name() { return "Default Mapping"; } /** * Returns a description of the Policy * * @return The description of the Policy. */ @Override public String description() { return "Simply removes the realm of the requesting authentication identity ('principal') if and only if "+ "the realm matches the server's realm, the server's XMPP domain name, or any of the pre-approved "+ "realm names. Otherwise the input value (authentication identity) is returned as-is, causing it to " + "be used as the authorization identity (the identity to act as)."; } }
if(authcid.contains("@")) { String realm = authcid.substring(authcid.lastIndexOf('@')+1); String authzid = authcid.substring(0,authcid.lastIndexOf('@')); if(realm.length() > 0) { if(realm.equals(XMPPServerInfo.XMPP_DOMAIN.getValue())) { Log.debug("DefaultAuthorizationMapping: realm = " + XMPPServerInfo.XMPP_DOMAIN.getKey()); return authzid; } else if(realm.equals(SASLAuthentication.REALM.getValue())) { Log.debug("DefaultAuthorizationMapping: ream = sasl.realm"); return authzid; } else { for(String approvedRealm : SASLAuthentication.APPROVED_REALMS.getValue()) { if(realm.equals(approvedRealm)) { Log.debug("DefaultAuthorizationMapping: realm ("+realm+") = "+approvedRealm+" which is approved"); return authzid; } else { Log.debug("DefaultAuthorizationPolicy: realm ("+realm+") != "+approvedRealm+" which is approved"); } } } Log.debug("DefaultAuthorizationMapping: No approved mappings found."); return authcid; } else { Log.debug("DefaultAuthorizationMapping: Realm has no length"); } } else { Log.debug("DefaultAuthorizationMapping: No realm found"); } return authcid;
345
399
744
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/DefaultAuthorizationPolicy.java
DefaultAuthorizationPolicy
authorize
class DefaultAuthorizationPolicy implements AuthorizationPolicy { private static final Logger Log = LoggerFactory.getLogger(DefaultAuthorizationPolicy.class); public static final SystemProperty<Boolean> IGNORE_CASE = SystemProperty.Builder.ofType(Boolean.class) .setKey("xmpp.auth.ignorecase") .setDefaultValue(true) .setDynamic(true) .build(); /** * Returns true if the provided authentication identity (identity whose password will be used) is explicitly allowed * to the provided authorization identity (identity to act as). * * @param authzid authorization identity (identity to act as). * @param authcid authentication identity, or 'principal' (identity whose password will be used) * @return true if the authzid is explicitly allowed to be used by the user authenticated with the authcid. */ @Override public boolean authorize(String authzid, String authcid) {<FILL_FUNCTION_BODY>} /** * Returns the short name of the Policy * * @return The short name of the Policy */ @Override public String name() { return "Default Policy"; } /** * Returns a description of the Policy * * @return The description of the Policy. */ @Override public String description() { return "Different clients perform authentication differently, so this policy will authorize any authentication " + "identity, or 'principal' (identity whose password will be used) to a requested authorization identity " + "(identity to act as) that match specific conditions that are considered secure defaults for most installations."; } }
boolean authorized = false; String authzUser = authzid; String authzRealm = null; String authcUser = authcid; String authcRealm = null; if (authzid.contains("@")) { authzUser = authzid.substring(0, authzid.lastIndexOf("@")); authzRealm = authzid.substring((authzid.lastIndexOf("@")+1)); } if (authcid.contains("@")){ authcUser = authcid.substring(0,(authcid.lastIndexOf("@"))); authcRealm = authcid.substring((authcid.lastIndexOf("@")+1)); } if (!SASLAuthentication.PROXY_AUTH.getValue() || !AdminManager.getInstance().isUserAdmin(authcUser, true)) { if(!authzUser.equals(authcUser)) { // For this policy the user portion of both must match, so lets short circuit here if we can. if(IGNORE_CASE.getValue()) { if(!authzUser.equalsIgnoreCase(authcUser)){ Log.debug("Authorization username {} doesn't match authentication username {}", authzUser, authcUser); return false; } } else { Log.debug("Authorization username {} doesn't match authentication username {}", authzUser, authcUser); return false; } } } Log.debug("Checking authcRealm"); if(authcRealm != null) { if(authcRealm.equals(XMPPServerInfo.XMPP_DOMAIN.getValue())) { Log.trace("authcRealm = {}", XMPPServerInfo.XMPP_DOMAIN.getKey()); authorized = true; } else if(authcRealm.equals(SASLAuthentication.REALM.getValue())) { Log.trace("authcRealm = sasl.realm"); authorized = true; } else { for(String realm : SASLAuthentication.APPROVED_REALMS.getValue()) { if(authcRealm.equals(realm)) { Log.trace("authcRealm = {} which is approved", realm); authorized = true; } else { Log.trace("authcRealm != {} which is approved", realm); } } } } else { // no realm in the authcRealm authorized = true; } if(!authorized) { return false; } else { // reset for next round of tests authorized = false; } Log.debug("Checking authzRealm"); if(authzRealm != null) { if(authzRealm.equals(XMPPServerInfo.XMPP_DOMAIN.getValue())) { Log.trace("authcRealm = {}", XMPPServerInfo.XMPP_DOMAIN.getKey()); authorized = true; } else { if(authcRealm != null && authcRealm.equals(authzRealm)) { Log.trace("DefaultAuthorizationPolicy: authcRealm = {} which is approved", authcRealm); authorized = true; } } } else { authorized = true; } // no more checks return authorized;
418
859
1,277
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/MappedAuthProvider.java
MappedAuthProvider
isScramSupported
class MappedAuthProvider implements AuthProvider { /** * Name of the property of which the value is expected to be the classname of the AuthProviderMapper instance to be * used by instances of this class. */ public static final String PROPERTY_MAPPER_CLASSNAME = "mappedAuthProvider.mapper.className"; /** * Used to determine what provider is to be used to operate on a particular user. */ protected final AuthProviderMapper mapper; public MappedAuthProvider() { // Migrate properties. JiveGlobals.migrateProperty( PROPERTY_MAPPER_CLASSNAME ); // Instantiate mapper. final String mapperClass = JiveGlobals.getProperty( PROPERTY_MAPPER_CLASSNAME ); if ( mapperClass == null ) { throw new IllegalStateException( "A mapper must be specified via openfire.xml or the system properties." ); } try { final Class c = ClassUtils.forName( mapperClass ); mapper = (AuthProviderMapper) c.newInstance(); } catch ( Exception e ) { throw new IllegalStateException( "Unable to create new instance of AuthProviderMapper class: " + mapperClass, e ); } } @Override public void authenticate( String username, String password ) throws UnauthorizedException, ConnectionException, InternalUnauthenticatedException { final AuthProvider provider = mapper.getAuthProvider( username ); if ( provider == null ) { throw new UnauthorizedException(); } provider.authenticate( username, password ); } @Override public String getPassword( String username ) throws UserNotFoundException, UnsupportedOperationException { final AuthProvider provider = mapper.getAuthProvider( username ); if ( provider == null ) { throw new UserNotFoundException(); } return provider.getPassword( username ); } @Override public void setPassword( String username, String password ) throws UserNotFoundException, UnsupportedOperationException { final AuthProvider provider = mapper.getAuthProvider( username ); if ( provider == null ) { throw new UserNotFoundException(); } provider.setPassword( username, password ); } @Override public boolean supportsPasswordRetrieval() { // TODO Make calls concurrent for improved throughput. for ( final AuthProvider provider : mapper.getAuthProviders() ) { // If at least one provider supports password retrieval, so does this proxy. if ( provider.supportsPasswordRetrieval() ) { return true; } } return false; } @Override public boolean isScramSupported() {<FILL_FUNCTION_BODY>} @Override public String getSalt(String username) throws UserNotFoundException { final AuthProvider provider = mapper.getAuthProvider( username ); if ( provider == null ) { throw new UserNotFoundException(); } return provider.getSalt( username ); } @Override public int getIterations(String username) throws UserNotFoundException { final AuthProvider provider = mapper.getAuthProvider( username ); if ( provider == null ) { throw new UserNotFoundException(); } return provider.getIterations( username ); } @Override public String getServerKey(String username) throws UserNotFoundException { final AuthProvider provider = mapper.getAuthProvider( username ); if ( provider == null ) { throw new UserNotFoundException(); } return provider.getServerKey( username ); } @Override public String getStoredKey(String username) throws UserNotFoundException { final AuthProvider provider = mapper.getAuthProvider( username ); if ( provider == null ) { throw new UserNotFoundException(); } return provider.getStoredKey( username ); } }
// TODO Make calls concurrent for improved throughput. for ( final AuthProvider provider : mapper.getAuthProviders() ) { // If at least one provider supports SCRAM, so does this proxy. if ( provider.isScramSupported() ) { return true; } } return false;
1,018
88
1,106
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/NativeAuthProvider.java
NativeAuthProvider
authenticate
class NativeAuthProvider implements AuthProvider { private static final Logger Log = LoggerFactory.getLogger(NativeAuthProvider.class); private String domain; public NativeAuthProvider() { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty("nativeAuth.domain"); this.domain = JiveGlobals.getProperty("nativeAuth.domain"); // Configure the library path so that we can load the shaj native library // from the Openfire lib directory. // Find the root path of this class. try { String binaryPath = (new URL(Shaj.class.getProtectionDomain() .getCodeSource().getLocation(), ".")).openConnection() .getPermission().getName(); binaryPath = (new File(binaryPath)).getCanonicalPath(); // Add the binary path to "java.library.path". String newLibPath = binaryPath + File.pathSeparator + System.getProperty("java.library.path"); System.setProperty("java.library.path", newLibPath); Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths"); fieldSysPath.setAccessible(true); fieldSysPath.set(System.class.getClassLoader(), null); } catch (Exception e) { Log.error(e.getMessage(), e); } // Configure Shaj to log output to the Openfire logger. com.cenqua.shaj.log.Log.Factory.setInstance(new com.cenqua.shaj.log.Log() { @Override public boolean isDebug() { return Log.isDebugEnabled(); } @Override public void error(String string) { Log.error(string); } @Override public void error(String string, Throwable throwable) { Log.error(string, throwable); } @Override public void debug(String string) { Log.debug("NativeAuthProvider: "+string); } }); } @Override public void authenticate(String username, String password) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void setPassword(String username, String password) throws UserNotFoundException { throw new UnsupportedOperationException(); } @Override public boolean supportsPasswordRetrieval() { return false; } @Override public boolean isScramSupported() { // TODO Auto-generated method stub return false; } @Override public String getSalt(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public int getIterations(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getServerKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getStoredKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } }
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. } }
848
507
1,355
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/POP3AuthProvider.java
POP3AuthProvider
authenticate
class POP3AuthProvider implements AuthProvider { private static final Logger Log = LoggerFactory.getLogger(POP3AuthProvider.class); private Cache<String, String> authCache = null; private String host = null; private String domain = null; private int port = -1; private boolean useSSL = false; private boolean authRequiresDomain = false; private boolean debugEnabled; /** * Initialiazes the POP3AuthProvider with values from the global config file. */ public POP3AuthProvider() { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty("pop3.authCache.enabled"); JiveGlobals.migrateProperty("pop3.ssl"); JiveGlobals.migrateProperty("pop3.authRequiresDomain"); JiveGlobals.migrateProperty("pop3.host"); JiveGlobals.migrateProperty("pop3.debug"); JiveGlobals.migrateProperty("pop3.domain"); JiveGlobals.migrateProperty("pop3.port"); if (Boolean.valueOf(JiveGlobals.getProperty("pop3.authCache.enabled"))) { String cacheName = "POP3 Authentication"; authCache = CacheFactory.createCache(cacheName); } useSSL = Boolean.valueOf(JiveGlobals.getProperty("pop3.ssl")); authRequiresDomain = Boolean.valueOf(JiveGlobals.getProperty("pop3.authRequiresDomain")); host = JiveGlobals.getProperty("pop3.host"); if (host == null || host.length() < 1) { throw new IllegalArgumentException("pop3.host is null or empty"); } debugEnabled = Boolean.valueOf(JiveGlobals.getProperty("pop3.debug")); domain = JiveGlobals.getProperty("pop3.domain"); port = JiveGlobals.getIntProperty("pop3.port", useSSL ? 995 : 110); if (Log.isDebugEnabled()) { Log.debug("POP3AuthProvider: Created new POP3AuthProvider instance, fields:"); Log.debug("\t host: " + host); Log.debug("\t port: " + port); Log.debug("\t domain: " + domain); Log.debug("\t useSSL: " + useSSL); Log.debug("\t authRequiresDomain: " + authRequiresDomain); Log.debug("\t authCacheEnabled: " + (authCache != null)); if (authCache != null) { Log.debug("\t authCacheSize: " + authCache.getLongCacheSize()); Log.debug("\t authCacheMaxLifetime: " + authCache.getMaxLifetime()); } } } @Override public void authenticate(String username, String password) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void setPassword(String username, String password) throws UserNotFoundException { throw new UnsupportedOperationException(); } @Override public boolean supportsPasswordRetrieval() { return false; } @Override public boolean isScramSupported() { return false; } @Override public String getSalt(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public int getIterations(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getServerKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getStoredKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } }
if (username == null || password == null) { throw new 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(); } Log.debug("POP3AuthProvider.authenticate("+username+", ******)"); // If cache is enabled, see if the auth is in cache. if (authCache != null && authCache.containsKey(username)) { String hash = authCache.get(username); if (StringUtils.hash(password).equals(hash)) { return; } } Properties mailProps = new Properties(); mailProps.setProperty("mail.debug", String.valueOf(debugEnabled)); Session session = Session.getInstance(mailProps, null); Store store; try { store = session.getStore(useSSL ? "pop3s" : "pop3"); } catch(NoSuchProviderException e) { Log.error(e.getMessage(), e); throw new UnauthorizedException(e); } try { if (authRequiresDomain) { store.connect(host, port, username + "@" + domain, password); } else { store.connect(host, port, username, password); } } catch(Exception e) { Log.error(e.getMessage(), e); throw new UnauthorizedException(e); } if (! store.isConnected()) { throw new UnauthorizedException("Could not authenticate user"); } try { store.close(); } catch (Exception e) { // Ignore. } // If cache is enabled, add the item to cache. if (authCache != null) { authCache.put(username, StringUtils.hash(password)); } // See if the user exists in the database. If not, automatically create them. UserManager userManager = UserManager.getInstance(); try { userManager.getUser(username); } catch (UserNotFoundException unfe) { String email = username + "@" + (domain!=null?domain:host); try { Log.debug("POP3AuthProvider: 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. UserManager.getUserProvider().createUser(username, StringUtils.randomString(8), null, email); } catch (UserAlreadyExistsException uaee) { // Ignore. } }
1,039
781
1,820
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/PropertyBasedAuthProviderMapper.java
PropertyBasedAuthProviderMapper
getAuthProvider
class PropertyBasedAuthProviderMapper implements AuthProviderMapper { protected final Map<String, AuthProvider> providersByPrefix = new HashMap<>(); protected AuthProvider fallbackProvider; public PropertyBasedAuthProviderMapper() { // Migrate properties. JiveGlobals.migratePropertyTree( "propertyBasedAuthMapper" ); // Instantiate the fallback provider fallbackProvider = instantiateProvider( "propertyBasedAuthMapper.fallbackProvider.className" ); if ( fallbackProvider == null ) { throw new IllegalStateException( "Expected a AuthProvider class name in property 'propertyBasedAuthMapper.fallbackProvider.className'" ); } // Instantiate all sets final List<String> setProperties = JiveGlobals.getPropertyNames( "propertyBasedAuthMapper.set" ); for ( final String setProperty : setProperties ) { final AuthProvider provider = instantiateProvider( setProperty + ".provider.className" ); if ( provider == null ) { throw new IllegalStateException( "Expected a AuthProvider class name in property '" + setProperty + ".provider.className'" ); } providersByPrefix.put( setProperty, provider ); } } @Override public AuthProvider getAuthProvider( String username ) {<FILL_FUNCTION_BODY>} @Override public Set<AuthProvider> getAuthProviders() { final Set<AuthProvider> result = new LinkedHashSet<>(); result.addAll( providersByPrefix.values() ); result.add( fallbackProvider ); return result; } protected static AuthProvider instantiateProvider( String propertyName ) { final String className = JiveGlobals.getProperty( propertyName ); if ( className == null ) { throw new IllegalStateException( "A class name must be specified via openfire.xml or the system properties." ); } try { final Class c = ClassUtils.forName( className ); return (AuthProvider) c.newInstance(); } catch ( Exception e ) { throw new IllegalStateException( "Unable to create new instance of AuthProvider: " + className, e ); } } }
for ( final Map.Entry<String, AuthProvider> entry : providersByPrefix.entrySet() ) { final String usersProperty = JiveGlobals.getProperty( entry.getKey() + ".members.propertyName" ); if ( usersProperty != null ) { final List<String> usersInSet = JiveGlobals.getListProperty( usersProperty, Collections.<String>emptyList() ); if ( usersInSet.contains( username ) ) { return entry.getValue(); } } } return fallbackProvider;
556
146
702
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/auth/ScramUtils.java
ScramUtils
createSaltedPassword
class ScramUtils { public static final int DEFAULT_ITERATION_COUNT = 4096; private ScramUtils() {} public static byte[] createSaltedPassword(byte[] salt, String password, int iters) throws SaslException {<FILL_FUNCTION_BODY>} public static byte[] computeHmac(final byte[] key, final String string) throws SaslException { Mac mac = createSha1Hmac(key); mac.update(string.getBytes(StandardCharsets.UTF_8)); return mac.doFinal(); } public static Mac createSha1Hmac(final byte[] keyBytes) throws SaslException { try { SecretKeySpec key = new SecretKeySpec(keyBytes, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(key); return mac; } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new SaslException(e.getMessage(), e); } } }
Mac mac = createSha1Hmac(password.getBytes(StandardCharsets.UTF_8)); mac.update(salt); mac.update(new byte[]{0, 0, 0, 1}); byte[] result = mac.doFinal(); byte[] previous = null; for (int i = 1; i < iters; i++) { mac.update(previous != null ? previous : result); previous = mac.doFinal(); for (int x = 0; x < result.length; x++) { result[x] ^= previous[x]; } } return result;
272
162
434
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/cluster/ClusterMonitor.java
ClusterMonitor
leftCluster
class ClusterMonitor implements Module, ClusterEventListener { private static final Logger LOGGER = LoggerFactory.getLogger(ClusterMonitor.class); private static final SystemProperty<Boolean> ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("cluster-monitor.service-enabled") .setDynamic(true) .setDefaultValue(true) .build(); private static final String MODULE_NAME = "Cluster monitor"; private static final String UNKNOWN_NODE_NAME = "<unknown>"; // This contains a cache of node names - after a node leaves a cluster, it's too late to find out it's name. // So this map contains a cache of node names, populated on cluster joins private final Map<NodeID, String> nodeNames = new ConcurrentHashMap<>(); private boolean nodeHasLeftCluster = false; private XMPPServer xmppServer; @SuppressWarnings("WeakerAccess") public ClusterMonitor() { LOGGER.debug("{} has been instantiated", MODULE_NAME); } @Override public String getName() { return MODULE_NAME; } @Override public void initialize(final XMPPServer xmppServer) { this.xmppServer = xmppServer; LOGGER.debug("{} has been initialized", MODULE_NAME); } @Override public void start() { ClusterManager.addListener(this); LOGGER.debug("{} has been started", MODULE_NAME); } @Override public void stop() { ClusterManager.removeListener(this); LOGGER.debug("{} has been stopped", MODULE_NAME); } @Override public void destroy() { LOGGER.debug("{} has been destroyed", MODULE_NAME); } @Override public void joinedCluster() { ClusterManager.getNodesInfo().forEach(nodeName -> nodeNames.put(nodeName.getNodeID(), nodeName.getHostName())); LOGGER.info("This node ({}/{}) has joined the cluster [seniorMember={}]", xmppServer.getNodeID(), xmppServer.getServerInfo().getHostname(), getSeniorMember()); } @Override public void joinedCluster(final byte[] nodeIdBytes) { final String nodeName = getNodeName(nodeIdBytes); final NodeID nodeId = NodeID.getInstance(nodeIdBytes); nodeNames.put(nodeId, nodeName); LOGGER.info("Another node ({}/{}) has joined the cluster [seniorMember={}]", nodeId, nodeName, getSeniorMember()); if (ClusterManager.isSeniorClusterMember() && nodeHasLeftCluster) { sendMessageToAdminsIfEnabled(nodeName + " has joined the cluster - resilience is restored"); } } @Override public void leftCluster() {<FILL_FUNCTION_BODY>} @Override public void leftCluster(final byte[] nodeIdBytes) { nodeHasLeftCluster = true; final NodeID nodeID = NodeID.getInstance(nodeIdBytes); final String nodeName = Optional.ofNullable(nodeNames.remove(nodeID)).orElse(UNKNOWN_NODE_NAME); LOGGER.info("Another node ({}/{}) has left the cluster [seniorMember={}]", nodeID, nodeName, getSeniorMember()); if (ClusterManager.isSeniorClusterMember()) { final int clusterSize = ClusterManager.getNodesInfo().size(); final String conjunction; final String plural; if (clusterSize == 1) { conjunction = "is"; plural = ""; } else { conjunction = "are"; plural = "s"; } sendMessageToAdminsIfEnabled(nodeName + " has left the cluster - there " + conjunction + " now only " + clusterSize + " node" + plural + " in the cluster"); } } @Override public void markedAsSeniorClusterMember() { LOGGER.info("This node ({}/{}) is now the senior member", xmppServer.getNodeID(), xmppServer.getServerInfo().getHostname()); } private String getNodeName(final byte[] nodeID) { final Optional<ClusterNodeInfo> nodeInfo = ClusterManager.getNodeInfo(nodeID); return nodeInfo.map(ClusterNodeInfo::getHostName).orElse(UNKNOWN_NODE_NAME); } private void sendMessageToAdminsIfEnabled(final String message) { final Boolean enabled = ENABLED.getValue(); LOGGER.info("Sending message to admins: {} (enabled={})", message, enabled); if (enabled) { xmppServer.sendMessageToAdmins(message); } } private String getSeniorMember() { return ClusterManager.getNodeInfo(ClusterManager.getSeniorClusterMember()).map(ClusterNodeInfo::getHostName).orElse(UNKNOWN_NODE_NAME); } }
final String nodeName = xmppServer.getServerInfo().getHostname(); LOGGER.info("This node ({}/{}) has left the cluster", xmppServer.getNodeID(), nodeName); sendMessageToAdminsIfEnabled("The local node ('" + nodeName + "') has left the cluster - this node no longer has any resilience");
1,283
90
1,373
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/cluster/ClusterPacketRouter.java
ClusterPacketRouter
broadcastPacket
class ClusterPacketRouter implements RemotePacketRouter { private static Logger logger = LoggerFactory.getLogger(ClusterPacketRouter.class); public boolean routePacket(byte[] nodeID, JID receipient, Packet packet) { // Send the packet to the specified node and let the remote node deliver the packet to the recipient try { CacheFactory.doClusterTask(new RemotePacketExecution(receipient, packet), nodeID); return true; } catch (IllegalStateException e) { logger.warn("Error while routing packet to remote node: " + e); return false; } } public void broadcastPacket(Message packet) {<FILL_FUNCTION_BODY>} }
// Execute the broadcast task across the cluster CacheFactory.doClusterTask(new BroadcastMessage(packet));
188
31
219
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/cluster/GetBasicStatistics.java
GetBasicStatistics
run
class GetBasicStatistics implements ClusterTask<Map<String, Object>> { public static final String NODE = "node"; public static final String CLIENT = "client"; public static final String INCOMING = "incoming"; public static final String OUTGOING = "outgoing"; public static final String MEMORY_CURRENT = "memory_cur"; public static final String MEMORY_MAX = "memory_max"; private Map<String, Object> values; @Override public Map<String, Object> getResult() { return values; } @Override public void run() {<FILL_FUNCTION_BODY>} @Override public void writeExternal(ObjectOutput out) throws IOException { // Ignore } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // Ignore } }
SessionManager manager = SessionManager.getInstance(); values = new HashMap<>(); values.put(NODE, CacheFactory.getClusterMemberID()); // Collect number of authenticated users values.put(CLIENT, manager.getUserSessionsCount(true)); // Collect number of incoming server connections values.put(INCOMING, manager.getIncomingServerSessionsCount(true)); // Collect number of outgoing server connections values.put(OUTGOING, XMPPServer.getInstance().getRoutingTable().getServerSessionsCount()); // Calculate free and used memory Runtime runtime = Runtime.getRuntime(); double freeMemory = (double) runtime.freeMemory() / (1024 * 1024); double maxMemory = (double) runtime.maxMemory() / (1024 * 1024); double totalMemory = (double) runtime.totalMemory() / (1024 * 1024); double usedMemory = totalMemory - freeMemory; values.put(MEMORY_CURRENT, usedMemory); values.put(MEMORY_MAX, maxMemory);
227
277
504
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/cluster/GetClusteredVersions.java
GetClusteredVersions
run
class GetClusteredVersions implements ClusterTask<GetClusteredVersions> { private static final long serialVersionUID = -4081828933134021041L; private String openfireVersion; private Map<String, String> pluginVersions; public String getOpenfireVersion() { return openfireVersion; } public Map<String, String> getPluginVersions() { return pluginVersions; } @Override public GetClusteredVersions getResult() { return this; } @Override public void writeExternal(final ObjectOutput out) throws IOException { final ExternalizableUtil util = ExternalizableUtil.getInstance(); util.writeSafeUTF(out, openfireVersion); util.writeStringMap(out, pluginVersions); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { final ExternalizableUtil util = ExternalizableUtil.getInstance(); openfireVersion = util.readSafeUTF(in); pluginVersions = util.readStringMap(in); } @Override public void run() {<FILL_FUNCTION_BODY>} }
final XMPPServer xmppServer = XMPPServer.getInstance(); openfireVersion = xmppServer.getServerInfo().getVersion().toString(); pluginVersions = new HashMap<>(); pluginVersions = xmppServer.getPluginManager().getMetadataExtractedPlugins().values().stream() .filter(pluginMetadata -> !pluginMetadata.getCanonicalName().equals("admin")) .collect(Collectors.toMap( PluginMetadata::getName, pluginMetadata -> pluginMetadata.getVersion().toString()));
347
141
488
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/cluster/IQResultListenerTask.java
IQResultListenerTask
readExternal
class IQResultListenerTask implements ClusterTask<Void> { private static Logger Log = LoggerFactory.getLogger( IQResultListenerTask.class ); private IQ packet; public IQResultListenerTask() { } public IQResultListenerTask( IQ packet ) { this.packet = packet; } @Override public Void getResult() { return null; } @Override public void run() { if ( packet != null ) { XMPPServer.getInstance().getIQRouter().route( packet ); } } @Override public void writeExternal( ObjectOutput out ) throws IOException { StringWriter sw = new StringWriter(); XMLWriter writer = new XMLWriter( sw, OutputFormat.createCompactFormat() ); try { writer.write( packet.getElement() ); } catch ( Exception e ) { Log.warn( "Unable to serialize packet {}", packet, e ); } ExternalizableUtil.getInstance().writeSafeUTF( out, sw.toString() ); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final String xml = ExternalizableUtil.getInstance().readSafeUTF( in ); try { final Element el = DocumentHelper.parseText( xml ).getRootElement(); packet = new IQ( el ); } catch ( Exception e ) { Log.warn( "Unable to deserialize string '{}'", xml, e ); }
336
94
430
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/cluster/NodeID.java
NodeID
getInstance
class NodeID implements Externalizable { private static List<NodeID> instances = new ArrayList<>(); private byte[] nodeID; public static synchronized NodeID getInstance(byte[] nodeIdBytes) {<FILL_FUNCTION_BODY>} public static synchronized void deleteInstance(byte[] nodeIdBytes) { NodeID toDelete = null; for (NodeID nodeID : instances) { if (nodeID.equals(nodeIdBytes)) { toDelete = nodeID; break; } } if (toDelete != null) { instances.remove(toDelete); } } public NodeID() { } private NodeID(byte[] nodeIdBytes) { this.nodeID = nodeIdBytes; } public boolean equals(byte[] anotherID) { return Arrays.equals(nodeID, anotherID); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeID that = (NodeID) o; return Arrays.equals(nodeID, that.nodeID); } @Override public int hashCode() { return Arrays.hashCode(nodeID); } @Override public String toString() { return new String(nodeID, StandardCharsets.UTF_8); } public byte[] toByteArray() { return nodeID; } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeByteArray(out, nodeID); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { nodeID = ExternalizableUtil.getInstance().readByteArray(in); } }
for (NodeID nodeID : instances) { if (nodeID.equals(nodeIdBytes)) { return nodeID; } } NodeID answer = new NodeID(nodeIdBytes); instances.add(answer); return answer;
478
68
546
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/cluster/RemotePacketExecution.java
RemotePacketExecution
writeExternal
class RemotePacketExecution implements ClusterTask<Void> { private JID recipient; private Packet packet; public RemotePacketExecution() { } public RemotePacketExecution(JID recipient, Packet packet) { this.recipient = recipient; this.packet = packet; } public Void getResult() { return null; } public void run() { // Route packet to entity hosted by this node. If delivery fails then the routing table // will inform the proper router of the failure and the router will handle the error reply logic XMPPServer.getInstance().getRoutingTable().routePacket(recipient, packet); } public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { recipient = (JID) ExternalizableUtil.getInstance().readSerializable(in); int packetType = ExternalizableUtil.getInstance().readInt(in); Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in); switch (packetType) { case 1: packet = new IQ(packetElement, true); break; case 2: packet = new Message(packetElement, true); break; case 3: packet = new Presence(packetElement, true); break; } } public String toString() { return super.toString() + " recipient: " + recipient + "packet: " + packet; } }
ExternalizableUtil.getInstance().writeSerializable(out, recipient); if (packet instanceof IQ) { ExternalizableUtil.getInstance().writeInt(out, 1); } else if (packet instanceof Message) { ExternalizableUtil.getInstance().writeInt(out, 2); } else if (packet instanceof Presence) { ExternalizableUtil.getInstance().writeInt(out, 3); } ExternalizableUtil.getInstance().writeSerializable(out, (DefaultElement) packet.getElement());
406
137
543
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/AdHocCommandHandler.java
AdHocCommandHandler
addDefaultCommands
class AdHocCommandHandler extends IQHandler implements ServerFeaturesProvider, DiscoInfoProvider, DiscoItemsProvider { private static final String NAMESPACE = "http://jabber.org/protocol/commands"; private String serverName; private IQHandlerInfo info; private IQDiscoInfoHandler infoHandler; private IQDiscoItemsHandler itemsHandler; /** * Manager that keeps the list of ad-hoc commands and processing command requests. */ private AdHocCommandManager manager; public AdHocCommandHandler() { super("Ad-Hoc Commands Handler"); info = new IQHandlerInfo("command", NAMESPACE); manager = new AdHocCommandManager(); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException { return manager.process(packet); } @Override public IQHandlerInfo getInfo() { return info; } @Override public Iterator<String> getFeatures() { return Collections.singleton(NAMESPACE).iterator(); } @Override public Iterator<Element> getIdentities(String name, String node, JID senderJID) { Element identity = DocumentHelper.createElement("identity"); identity.addAttribute("category", "automation"); identity.addAttribute("type", NAMESPACE.equals(node) ? "command-list" : "command-node"); return Collections.singleton(identity).iterator(); } @Override public Iterator<String> getFeatures(String name, String node, JID senderJID) { return Arrays.asList(NAMESPACE, "jabber:x:data").iterator(); } @Override public Set<DataForm> getExtendedInfos(String name, String node, JID senderJID) { return new HashSet<>(); } @Override public boolean hasInfo(String name, String node, JID senderJID) { if (NAMESPACE.equals(node)) { return true; } else { // Only include commands that the sender can execute AdHocCommand command = manager.getCommand(node); return command != null && command.hasPermission(senderJID); } } @Override public Iterator<DiscoItem> getItems(String name, String node, JID senderJID) { List<DiscoItem> answer = new ArrayList<>(); if (!NAMESPACE.equals(node)) { answer = Collections.emptyList(); } else { for (AdHocCommand command : manager.getCommands()) { // Only include commands that the sender can invoke (i.e. has enough permissions) if (command.hasPermission(senderJID)) { final DiscoItem item = new DiscoItem(new JID(serverName), command.getLabel(), command.getCode(), null); answer.add(item); } } } return answer.iterator(); } @Override public void initialize(XMPPServer server) { super.initialize(server); serverName = server.getServerInfo().getXMPPDomain(); infoHandler = server.getIQDiscoInfoHandler(); itemsHandler = server.getIQDiscoItemsHandler(); } @Override public void start() throws IllegalStateException { super.start(); infoHandler.setServerNodeInfoProvider(NAMESPACE, this); itemsHandler.setServerNodeInfoProvider(NAMESPACE, this); // Add the "out of the box" commands addDefaultCommands(); } @Override public void stop() { super.stop(); infoHandler.removeServerNodeInfoProvider(NAMESPACE); itemsHandler.removeServerNodeInfoProvider(NAMESPACE); // Stop commands for (AdHocCommand command : manager.getCommands()) { stopCommand(command); } } /** * Adds a new command to the list of supported ad-hoc commands by this server. The new * command will appear in the discoverable items list and will be executed for those users * with enough permission. * * @param command the new ad-hoc command to add. */ public void addCommand(AdHocCommand command) { manager.addCommand(command); startCommand(command); } /** * Removes the command from the list of ad-hoc commands supported by this server. The command * will no longer appear in the discoverable items list. * * @param command the ad-hoc command to remove. */ public void removeCommand(AdHocCommand command) { if (manager.removeCommand(command)) { stopCommand(command); } } private void addDefaultCommands() {<FILL_FUNCTION_BODY>} private void startCommand(AdHocCommand command) { infoHandler.setServerNodeInfoProvider(command.getCode(), this); itemsHandler.setServerNodeInfoProvider(command.getCode(), this); } private void stopCommand(AdHocCommand command) { infoHandler.removeServerNodeInfoProvider(command.getCode()); itemsHandler.removeServerNodeInfoProvider(command.getCode()); } }
addCommand(new EditAdminList()); addCommand(new GetNumberRegisteredUsers()); addCommand(new GetNumberDisabledUsers()); addCommand(new GetNumberActiveUsers()); addCommand(new GetNumberOnlineUsers()); addCommand(new GetNumberIdleUsers()); addCommand(new GetNumberUserSessions()); addCommand(new GetListRegisteredUsers()); addCommand(new GetListActiveUsers()); addCommand(new GetListDisabledUsers()); addCommand(new GetListOnlineUsers()); addCommand(new GetUsersPresence()); addCommand(new GetListGroups()); addCommand(new GetListGroupUsers()); addCommand(new AddGroupUsers()); addCommand(new DeleteGroupUsers()); addCommand(new AddGroup()); addCommand(new UpdateGroup()); addCommand(new DeleteGroup()); addCommand(new AddUser()); addCommand(new DeleteUser()); addCommand(new DisableUser()); addCommand(new ReEnableUser()); addCommand(new EndUserSession()); addCommand(new GetUserRoster()); addCommand(new AuthenticateUser()); addCommand(new ChangeUserPassword()); addCommand(new UserProperties()); addCommand(new PacketsNotification()); addCommand(new GetServerStats()); addCommand(new HttpBindStatus()); addCommand(new UserCreated()); addCommand(new UserModified()); addCommand(new UserDeleting()); addCommand(new GroupCreated()); addCommand(new GroupDeleting()); addCommand(new GroupModified()); addCommand(new GroupMemberAdded()); addCommand(new GroupMemberRemoved()); addCommand(new GroupAdminAdded()); addCommand(new GroupAdminRemoved()); addCommand(new VCardCreated()); addCommand(new VCardDeleting()); addCommand(new VCardModified()); addCommand(new GetAdminConsoleInfo()); addCommand(new Ping()); addCommand(new EditBlockedList()); addCommand(new EditAllowedList()); addCommand(new SendAnnouncementToOnlineUsers());
1,355
518
1,873
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/SessionData.java
SessionData
isValidAction
class SessionData { private final ReentrantLock lock = new ReentrantLock(); private final Instant creationStamp; private final String id; private final JID owner; /** * Map that keeps the association of variables and values obtained in each stage. * Note: Key=stage number, Value=Map with key=variable name and value=variable values. */ private final Map<Integer, Map<String, List<String>>> stagesData = new HashMap<>(); /** * Keeps the default execution action to follow if the command requester does not include * an action in his command. */ private AdHocCommand.Action executeAction; private List<AdHocCommand.Action> allowedActions = new ArrayList<>(); /** * Indicates the current stage where the requester is located. Stages are numbered from 0. */ private int stage; public SessionData(String sessionid, JID owner) { this.id = sessionid; this.creationStamp = Instant.now(); this.stage = -1; this.owner = owner; } public String getId() { return id; } /** * Returns the JID of the entity that is executing the command. * * @return the JID of the entity that is executing the command. */ public JID getOwner() { return owner; } @Deprecated // replaced by getCreationInstant. Remove in Openfire 4.9.0 or later. public long getCreationStamp() { return creationStamp.toEpochMilli(); } public Instant getCreationInstant() { return creationStamp; } protected AdHocCommand.Action getExecuteAction() { return executeAction; } protected void setExecuteAction(AdHocCommand.Action executeAction) { this.executeAction = executeAction; } /** * Sets the valid actions that the user can follow from the current stage. * * @param allowedActions list of valid actions. */ protected void setAllowedActions(List<AdHocCommand.Action> allowedActions) { if (allowedActions == null) { allowedActions = new ArrayList<>(); } this.allowedActions = allowedActions; } /** * Returns true if the specified action is valid in the current stage. The action should have * previously been offered to the user. * * @param actionName the name of the action to validate. * @return true if the specified action is valid in the current stage. */ protected boolean isValidAction(String actionName) {<FILL_FUNCTION_BODY>} protected void addStageForm(Map<String, List<String>> data) { stagesData.put(stage, data); } /** * Returns a Map with all the variables and values obtained during all the command stages. * * @return a Map with all the variables and values obtained during all the command stages. */ public Map<String, List<String>> getData() { Map<String, List<String>> data = new HashMap<>(); for (Map<String, List<String>> stageData : stagesData.values()) { data.putAll(stageData); } return data; } /** * Returns the current stage where the requester is located. Stages are numbered from 0. A * stage with value 0 means that a command request has just been received and no data form * has been sent to the requester yet. The first sent data form of the first stage would be * represented as stage 1. * * @return the current stage where the requester is located. */ public int getStage() { return stage; } /** * Sets the current stage where the requester is located. Stages are numbered from 0. A * stage with value 0 means that a command request has just been received and no data form * has been sent to the requester yet. The first sent data form of the first stage would be * represented as stage 1. * * @param stage the current stage where the requester is located. */ protected void setStage(int stage) { this.stage = stage; } /** * Returns a mutex that should be obtained before accessing any immutable field of an instance of this class. * * @return A mutex. */ public Lock getLock() { return lock; } }
for (AdHocCommand.Action action : allowedActions) { if (actionName.equals(action.name())) { return true; } } return false;
1,153
49
1,202
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/EditAdminList.java
EditAdminList
execute
class EditAdminList extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#edit-admin"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.editadminlist.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.editadminlist.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.editadminlist.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.editadminlist.form.field.adminjids.label", preferredLocale)); field.setVariable("adminjids"); field.setRequired(true); for (final JID admin : AdminManager.getInstance().getAdminAccounts()) { field.addValue(admin); } // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); boolean requestError = false; final List<JID> listed = new ArrayList<>(); for ( final String adminjid : data.get( "adminjids" )) { try { listed.add(new JID(adminjid)); } catch (IllegalArgumentException npe) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editadminlist.note.jid-invalid", preferredLocale)); requestError = true; } } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. AdminManager.getInstance().setAdminJIDs(listed); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
606
314
920
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/EditAllowedList.java
EditAllowedList
addStageInformation
class EditAllowedList extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#edit-whitelist"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.editallowedlist.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); boolean requestError = false; final List<String> listed = new ArrayList<>(); for ( final String whitelistjid : data.get( "whitelistjids" )) { JID domain; try { domain = new JID( whitelistjid ); if (domain.getResource() != null || domain.getNode() != null) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editallowedlist.note.jid-domain-required", List.of(whitelistjid), preferredLocale)); requestError = true; } listed.add(domain.getDomain()); } catch ( NullPointerException npe ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editallowedlist.note.jid-required", preferredLocale)); requestError = true; } catch (IllegalArgumentException npe) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editallowedlist.note.jid-invalid", preferredLocale)); requestError = true; } } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. final Collection<RemoteServerConfiguration> allowedServers = RemoteServerManager.getAllowedServers(); for (final String domain : listed) { if (allowedServers.stream().noneMatch(s -> s.getDomain().equals(domain))) { final RemoteServerConfiguration configuration = new RemoteServerConfiguration( domain ); configuration.setPermission( RemoteServerConfiguration.Permission.allowed ); RemoteServerManager.allowAccess(configuration); } } for (final RemoteServerConfiguration allowedServer : allowedServers) { if ( !listed.contains(allowedServer.getDomain())) { // No longer on the list. RemoteServerManager.deleteConfiguration(allowedServer.getDomain()); } } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale)); } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.editallowedlist.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.editallowedlist.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.editallowedlist.form.field.whitelistjids.label", preferredLocale)); field.setVariable("whitelistjids"); field.setRequired(true); for (RemoteServerConfiguration allowed : RemoteServerManager.getAllowedServers()) { field.addValue(new JID(null, allowed.getDomain(), null)); } // Add the form to the command command.add(form.getElement());
958
325
1,283
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/EditBlockedList.java
EditBlockedList
execute
class EditBlockedList extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#edit-blacklist"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.editblockedlist.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.editblockedlist.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.editblockedlist.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.editblockedlist.form.field.blacklistjids.label", preferredLocale)); field.setVariable("blacklistjids"); field.setRequired(true); for (RemoteServerConfiguration blockedServer : RemoteServerManager.getBlockedServers()) { field.addValue(new JID(null, blockedServer.getDomain(), null)); } // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); boolean requestError = false; final List<String> listed = new ArrayList<>(); for ( final String blacklistjid : data.get( "blacklistjids" )) { JID domain; try { domain = new JID( blacklistjid ); if (domain.getResource() != null || domain.getNode() != null) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editblockedlist.note.jid-domain-required", List.of(blacklistjid), preferredLocale)); requestError = true; } if (XMPPServer.getInstance().isLocal(domain)) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editblockedlist.note.jid-self", List.of(blacklistjid), preferredLocale)); requestError = true; } listed.add(domain.getDomain()); } catch ( NullPointerException npe ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editblockedlist.note.jid-required", preferredLocale)); requestError = true; } catch (IllegalArgumentException npe) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.editblockedlist.note.jid-invalid", preferredLocale)); requestError = true; } } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. final Collection<RemoteServerConfiguration> blockedServers = RemoteServerManager.getBlockedServers(); for (final String domain : listed) { if (blockedServers.stream().noneMatch(s -> s.getDomain().equals(domain))) { RemoteServerManager.blockAccess(domain); } } for (final RemoteServerConfiguration blockedServer : blockedServers) { if ( !listed.contains(blockedServer.getDomain())) { // Unblock - no longer on the list. RemoteServerManager.deleteConfiguration(blockedServer.getDomain()); } } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
626
717
1,343
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetAdminConsoleInfo.java
GetAdminConsoleInfo
execute
class GetAdminConsoleInfo extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { //Do nothing since there are no stages } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public String getCode() { return "http://jabber.org/protocol/admin#get-console-info"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getadminconsoleinfo.label"); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 0; } /** * Returns if the requester can access this command. Only admins and components * are allowed to execute this command. * * @param requester the JID of the user requesting to execute this command. * @return true if the requester can access this command. */ @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); // Gets a valid bind interface PluginManager pluginManager = XMPPServer.getInstance().getPluginManager(); AdminConsolePlugin adminConsolePlugin = ((AdminConsolePlugin) pluginManager.getPlugin("admin")); String bindInterface = adminConsolePlugin.getBindInterface(); int adminPort = adminConsolePlugin.getAdminUnsecurePort(); int adminSecurePort = adminConsolePlugin.getAdminSecurePort(); if (bindInterface == null) { Enumeration<NetworkInterface> nets; try { nets = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { // We failed to discover a valid IP address where the admin console is running return; } for (NetworkInterface netInterface : Collections.list(nets)) { boolean found = false; Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); for (InetAddress address : Collections.list(addresses)) { if ("127.0.0.1".equals(address.getHostAddress()) || "0:0:0:0:0:0:0:1".equals(address.getHostAddress())) { continue; } InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort); try (Socket socket = new Socket()){ socket.connect(remoteAddress); bindInterface = address.getHostAddress(); found = true; break; } catch (IOException e) { // Ignore this address. Let's hope there is more addresses to validate } } if (found) { break; } } } // If there is no valid bind interface, return an error if (bindInterface == null) { Element note = command.addElement("note"); note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.getadminconsoleinfo.note.no-bind-interface", preferredLocale)); return; } // Add the bind interface field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getadminconsoleinfo.form.field.bindinterface.label", preferredLocale)); field.setVariable("bindInterface"); field.addValue(bindInterface); // Add the port field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getadminconsoleinfo.form.field.adminport.label", preferredLocale)); field.setVariable("adminPort"); field.addValue(adminPort); // Add the secure port field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getadminconsoleinfo.form.field.adminsecureport.label", preferredLocale)); field.setVariable("adminSecurePort"); field.addValue(adminSecurePort); command.add(form.getElement());
393
907
1,300
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetListActiveUsers.java
GetListActiveUsers
execute
class GetListActiveUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.getlistactiveusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.getlistactiveusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.global.operation.pagination.max_items", preferredLocale)); field.setVariable("max_items"); field.addOption("25", "25"); field.addOption("50", "50"); field.addOption("75", "75"); field.addOption("100", "100"); field.addOption("150", "150"); field.addOption("200", "200"); field.addOption(LocaleUtils.getLocalizedString("commands.global.operation.pagination.none", preferredLocale), "none"); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#get-active-users"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getlistactiveusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); int maxItems = -1; final List<String> max_items_data = data.getData().get("max_items"); if (max_items_data != null && !max_items_data.isEmpty()) { String max_items = max_items_data.get(0); if (max_items != null && !"none".equals(max_items)) { try { maxItems = Integer.parseInt(max_items); } catch (NumberFormatException e) { // Do nothing. Assume that all users are being requested } } } DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getlistactiveusers.form.field.activeuserjids.label", preferredLocale)); field.setVariable("activeuserjids"); // Get list of users (i.e. bareJIDs) that are connected to the server Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); Set<String> users = new HashSet<>(sessions.size()); for (ClientSession session : sessions) { if (session.getPresence().isAvailable()) { users.add(session.getAddress().toBareJID()); } if (maxItems > 0 && users.size() >= maxItems) { break; } } // Add users to the result for (String user : users) { field.addValue(user); } command.add(form.getElement());
642
502
1,144
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetListDisabledUsers.java
GetListDisabledUsers
execute
class GetListDisabledUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.getlistdisabledusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.getlistdisabledusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.global.operation.pagination.max_items", preferredLocale)); field.setVariable("max_items"); field.addOption("25", "25"); field.addOption("50", "50"); field.addOption("75", "75"); field.addOption("100", "100"); field.addOption("150", "150"); field.addOption("200", "200"); field.addOption(LocaleUtils.getLocalizedString("commands.global.operation.pagination.none", preferredLocale), "none"); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#get-disabled-users-list"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getlistdisabledusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); int maxItems = -1; final List<String> max_items_data = data.getData().get("max_items"); if (max_items_data != null && !max_items_data.isEmpty()) { String max_items = max_items_data.get(0); if (max_items != null && !"none".equals(max_items)) { try { maxItems = Integer.parseInt(max_items); } catch (NumberFormatException e) { // Do nothing. Assume that all users are being requested } } } DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getlistdisabledusers.form.field.disableduserjids.label", preferredLocale)); field.setVariable("disableduserjids"); // TODO improve on this, as this is not efficient on systems with large amounts of users. final LockOutManager lockOutManager = LockOutManager.getInstance(); for (final User user : UserManager.getInstance().getUsers()) { if (lockOutManager.isAccountDisabled(user.getUsername())) { field.addValue(XMPPServer.getInstance().createJID(user.getUsername(), null)); if (maxItems > 0 && field.getValues().size() >= maxItems) { break; } } } command.add(form.getElement());
645
476
1,121
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetListIdleUsers.java
GetListIdleUsers
execute
class GetListIdleUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.getlistidleusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.getlistidleusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.global.operation.pagination.max_items", preferredLocale)); field.setVariable("max_items"); field.addOption("25", "25"); field.addOption("50", "50"); field.addOption("75", "75"); field.addOption("100", "100"); field.addOption("150", "150"); field.addOption("200", "200"); field.addOption(LocaleUtils.getLocalizedString("commands.global.operation.pagination.none", preferredLocale), "none"); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#get-idle-users"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getlistidleusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); int maxItems = -1; final List<String> max_items_data = data.getData().get("max_items"); if (max_items_data != null && !max_items_data.isEmpty()) { String max_items = max_items_data.get(0); if (max_items != null && !"none".equals(max_items)) { try { maxItems = Integer.parseInt(max_items); } catch (NumberFormatException e) { // Do nothing. Assume that all users are being requested } } } DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getlistidleusers.form.field.activeuserjids.label", preferredLocale)); field.setVariable("activeuserjids"); // The XEP uses this variable ('active') rather than something like 'idleuserjids'. // Make sure that we are only counting based on bareJIDs and not fullJIDs Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); Set<String> users = new HashSet<>(sessions.size()); for (ClientSession session : sessions) { if (!session.getPresence().isAvailable()) { users.add(session.getAddress().toBareJID()); if (maxItems > 0 && users.size() >= maxItems) { break; } } } // Add users to the result for (String user : users) { field.addValue(user); } command.add(form.getElement());
647
525
1,172
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetListOnlineUsers.java
GetListOnlineUsers
execute
class GetListOnlineUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.getlistonlineusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.getlistonlineusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.global.operation.pagination.max_items", preferredLocale)); field.setVariable("max_items"); field.addOption("25", "25"); field.addOption("50", "50"); field.addOption("75", "75"); field.addOption("100", "100"); field.addOption("150", "150"); field.addOption("200", "200"); field.addOption(LocaleUtils.getLocalizedString("commands.global.operation.pagination.none", preferredLocale), "none"); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#get-online-users-list"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getlistonlineusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); int maxItems = -1; final List<String> max_items_data = data.getData().get("max_items"); if (max_items_data != null && !max_items_data.isEmpty()) { String max_items = max_items_data.get(0); if (max_items != null && !"none".equals(max_items)) { try { maxItems = Integer.parseInt(max_items); } catch (NumberFormatException e) { // Do nothing. Assume that all users are being requested } } } DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getlistonlineusers.form.field.onlineuserjids.label", preferredLocale)); field.setVariable("onlineuserjids"); // Get list of users (i.e. bareJIDs) that are connected to the server Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); Set<String> users = new HashSet<>(sessions.size()); for (ClientSession session : sessions) { users.add(session.getAddress().toBareJID()); if (maxItems > 0 && users.size() >= maxItems) { break; } } // Add users to the result for (String user : users) { field.addValue(user); } command.add(form.getElement());
644
485
1,129
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetListRegisteredUsers.java
GetListRegisteredUsers
execute
class GetListRegisteredUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.getlistregisteredusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.getlistregisteredusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.global.operation.pagination.max_items", preferredLocale)); field.setVariable("max_items"); field.addOption("25", "25"); field.addOption("50", "50"); field.addOption("75", "75"); field.addOption("100", "100"); field.addOption("150", "150"); field.addOption("200", "200"); field.addOption(LocaleUtils.getLocalizedString("commands.global.operation.pagination.none", preferredLocale), "none"); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#get-registered-users-list"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getlistregisteredusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); int maxItems = -1; final List<String> max_items_data = data.getData().get("max_items"); if (max_items_data != null && !max_items_data.isEmpty()) { String max_items = max_items_data.get(0); if (max_items != null && !"none".equals(max_items)) { try { maxItems = Integer.parseInt(max_items); } catch (NumberFormatException e) { // Do nothing. Assume that all users are being requested } } } DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getlistregisteredusers.form.field.registereduserjids.label", preferredLocale)); field.setVariable("registereduserjids"); // Get list of users (i.e. bareJIDs) that are registered on the server final Collection<User> users = UserManager.getInstance().getUsers(0, maxItems); // Add users to the result for (User user : users) { field.addValue(XMPPServer.getInstance().createJID(user.getUsername(), null)); } command.add(form.getElement());
649
436
1,085
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetNumberActiveUsers.java
GetNumberActiveUsers
execute
class GetNumberActiveUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { //Do nothing since there are no stages } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public String getCode() { return "http://jabber.org/protocol/admin#get-active-users-num"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getnumberactiveusers.label"); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 0; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getnumberactiveusers.form.field.activeusersnum.label", preferredLocale)); field.setVariable("activeusersnum"); // Make sure that we are only counting based on bareJIDs and not fullJIDs Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); Set<String> users = new HashSet<>(sessions.size()); for (ClientSession session : sessions) { if (session.getPresence().isAvailable()) { users.add(session.getAddress().toBareJID()); } } field.addValue(users.size()); command.add(form.getElement());
278
307
585
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetNumberDisabledUsers.java
GetNumberDisabledUsers
execute
class GetNumberDisabledUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { //Do nothing since there are no stages } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public String getCode() { return "http://jabber.org/protocol/admin#get-disabled-users-num"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getnumberdisabledusers.label"); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 0; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getnumberdisabledusers.form.field.disabledusersnum.label", preferredLocale)); field.setVariable("disabledusersnum"); // TODO improve on this, as this is not efficient on systems with large amounts of users. int count = 0; final LockOutManager lockOutManager = LockOutManager.getInstance(); for (final User user : UserManager.getInstance().getUsers()) { if (lockOutManager.isAccountDisabled(user.getUsername())) { count++; } } field.addValue(count); command.add(form.getElement());
279
292
571
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetNumberIdleUsers.java
GetNumberIdleUsers
execute
class GetNumberIdleUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { //Do nothing since there are no stages } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public String getCode() { return "http://jabber.org/protocol/admin#get-idle-users-num"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getnumberidleusers.label"); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 0; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getnumberidleusers.form.field.idleusersnum.label", preferredLocale)); field.setVariable("idleusersnum"); // Make sure that we are only counting based on bareJIDs and not fullJIDs Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); Set<String> users = new HashSet<>(sessions.size()); for (ClientSession session : sessions) { if (!session.getPresence().isAvailable()) { users.add(session.getAddress().toBareJID()); } } field.addValue(users.size()); command.add(form.getElement());
281
310
591
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetNumberOnlineUsers.java
GetNumberOnlineUsers
execute
class GetNumberOnlineUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { //Do nothing since there are no stages } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public String getCode() { return "http://jabber.org/protocol/admin#get-online-users-num"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getnumberonlineusers.label"); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 0; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getnumberonlineusers.form.field.onlineusersnum.label", preferredLocale)); field.setVariable("onlineusersnum"); // Make sure that we are only counting based on bareJIDs and not fullJIDs Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); Set<String> users = new HashSet<>(sessions.size()); for (ClientSession session : sessions) { users.add(session.getAddress().toBareJID()); } field.addValue(users.size()); command.add(form.getElement());
278
291
569
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetServerStats.java
GetServerStats
execute
class GetServerStats extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { //Do nothing since there are no stages } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public String getCode() { return "http://jabber.org/protocol/admin#get-server-stats"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getserverstats.label"); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { //Do nothing since there are no stages return null; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 0; } /** * Returns if the requester can access this command. Only admins and components * are allowed to execute this command. * * @param requester the JID of the user requesting to execute this command. * @return true if the requester can access this command. */ @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.server_name", preferredLocale)); field.setVariable("name"); field.addValue(AdminConsole.getAppName()); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.version", preferredLocale)); field.setVariable("version"); field.addValue(AdminConsole.getVersionString()); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.domain_name", preferredLocale)); field.setVariable("domain"); field.addValue(XMPPServer.getInstance().getServerInfo().getXMPPDomain()); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.jvm", preferredLocale)); field.setVariable("os"); String vmName = System.getProperty("java.vm.name"); if (vmName == null) { vmName = ""; } else { vmName = " -- " + vmName; } field.addValue(System.getProperty("java.version") + " " +System.getProperty("java.vendor") +vmName); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.uptime", preferredLocale)); field.setVariable("uptime"); field.addValue(XMPPDateTimeFormat.format(XMPPServer.getInstance().getServerInfo().getLastStarted())); DecimalFormat mbFormat = new DecimalFormat("#0.00"); DecimalFormat percentFormat = new DecimalFormat("#0.0"); Runtime runtime = Runtime.getRuntime(); double freeMemory = (double)runtime.freeMemory()/(1024*1024); double maxMemory = (double)runtime.maxMemory()/(1024*1024); double totalMemory = (double)runtime.totalMemory()/(1024*1024); double usedMemory = totalMemory - freeMemory; double percentFree = ((maxMemory - usedMemory)/maxMemory)*100.0; double percentUsed = 100 - percentFree; field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.memory", preferredLocale)); field.setVariable("memory"); field.addValue(mbFormat.format(usedMemory) + " MB of " + mbFormat.format(maxMemory) + " MB (" + percentFormat.format(percentUsed) + "%) used"); // Make sure that we are only counting based on bareJIDs and not fullJIDs Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); Set<String> users = new HashSet<>(sessions.size()); int availableSessions = 0; for (ClientSession session : sessions) { if (session.getPresence().isAvailable()) { users.add(session.getAddress().toBareJID()); availableSessions++; } } field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.available_users", preferredLocale)); field.setVariable("activeusersnum"); field.addValue(users.size()); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("index.available_users_sessions", preferredLocale)); field.setVariable("sessionsnum"); field.addValue(availableSessions); command.add(form.getElement());
391
1,136
1,527
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/GetUsersPresence.java
GetUsersPresence
addStageInformation
class GetUsersPresence extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public void execute(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); int maxItems = -1; final List<String> max_items_data = data.getData().get("max_items"); if (max_items_data != null && !max_items_data.isEmpty()) { String max_items = max_items_data.get(0); if (max_items != null && !"none".equals(max_items)) { try { maxItems = Integer.parseInt(max_items); } catch (NumberFormatException e) { // Do nothing. Assume that all users are being requested } } } DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.getuserspresence.form.field.activeuserpresences.label", preferredLocale)); field.setVariable("activeuserpresences"); // Get list of users (i.e. bareJIDs) that are connected to the server Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); int index = 1; for (ClientSession session : sessions) { if (session.getPresence().isAvailable()) { field.addValue(session.getPresence().toXML()); } if (maxItems > 0 && index >= maxItems) { break; } } command.add(form.getElement()); } @Override public String getCode() { return "http://jabber.org/protocol/admin#get-active-presences"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.getuserspresence.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } /** * Returns if the requester can access this command. Admins and components are allowed to * execute this command. * * @param requester the JID of the entity requesting to execute this command. * @return true if the requester can access this command. */ @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.getuserspresence.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.getuserspresence.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.global.operation.pagination.max_items", preferredLocale)); field.setVariable("max_items"); field.addOption("25", "25"); field.addOption("50", "50"); field.addOption("75", "75"); field.addOption("100", "100"); field.addOption("150", "150"); field.addOption("200", "200"); field.addOption(LocaleUtils.getLocalizedString("commands.global.operation.pagination.none", preferredLocale), "none"); // Add the form to the command command.add(form.getElement());
828
388
1,216
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/HttpBindStatus.java
HttpBindStatus
execute
class HttpBindStatus extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#status-http-bind"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.httpbindstatus.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 0; } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { // no stages, do nothing. } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.emptyList(); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return null; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); HttpBindManager manager = HttpBindManager.getInstance(); boolean isEnabled = manager.isHttpBindEnabled(); field = form.addField(); field.setType(FormField.Type.boolean_type); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.httpbindstatus.form.field.httpbindenabled.label", preferredLocale)); field.setVariable("httpbindenabled"); field.addValue(String.valueOf(isEnabled)); if (isEnabled) { field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.httpbindstatus.form.field.httpbindaddress.label", preferredLocale)); field.setVariable("httpbindaddress"); field.addValue(manager.getHttpBindUnsecureAddress()); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.httpbindstatus.form.field.httpbindsecureaddress.label", preferredLocale)); field.setVariable("httpbindsecureaddress"); field.addValue(manager.getHttpBindSecureAddress()); String jsUrl = manager.getJavaScriptUrl(); if (jsUrl != null) { field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.httpbindstatus.form.field.javascriptaddress.label", preferredLocale)); field.setVariable("javascriptaddress"); field.addValue(jsUrl); } field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.httpbindstatus.form.field.websocketaddress.label", preferredLocale)); field.setVariable("websocketaddress"); field.addValue(manager.getWebsocketUnsecureAddress()); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.httpbindstatus.form.field.websocketsecureaddress.label", preferredLocale)); field.setVariable("websocketsecureaddress"); field.addValue(manager.getWebsocketSecureAddress()); } command.add(form.getElement());
302
730
1,032
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/PacketsNotification.java
PacketsNotification
execute
class PacketsNotification extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.list_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.packet_type.label", preferredLocale)); field.setVariable("packet_type"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.packet_type.option.presence.label", preferredLocale), "presence"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.packet_type.option.iq.label", preferredLocale), "iq"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.packet_type.option.message.label", preferredLocale), "message"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.direction.label", preferredLocale)); field.setVariable("direction"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.direction.option.incoming.label", preferredLocale), "incoming"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.direction.option.outgoing.label", preferredLocale), "outgoing"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.processed.label", preferredLocale)); field.setVariable("processed"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.processed.option.false.label", preferredLocale), "false"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.packetsnotification.form.field.processed.option.true.label", preferredLocale), "true"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#packets_notification"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.packetsnotification.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } /** * Returns if the requester can access this command. Only components are allowed to * execute this command. * * @param requester the JID of the user requesting to execute this command. * @return true if the requester can access this command. */ @Override public boolean hasPermission(JID requester) { return InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); boolean presenceEnabled = false; boolean messageEnabled = false; boolean iqEnabled = false; for (String packet_type : data.getData().get("packet_type")) { if ("presence".equals(packet_type)) { presenceEnabled = true; } else if ("iq".equals(packet_type)) { iqEnabled = true; } else if ("message".equals(packet_type)) { messageEnabled = true; } } boolean incoming = "incoming".equals(data.getData().get("direction").get(0)); boolean processed = "true".equals(data.getData().get("processed").get(0)); JID componentJID = data.getOwner(); // Create or update subscription of the component to receive packet notifications PacketCopier.getInstance() .addSubscriber(componentJID, iqEnabled, messageEnabled, presenceEnabled, incoming, processed); // Inform that everything went fine Element note = command.addElement("note"); note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
1,136
331
1,467
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/SendAnnouncementToOnlineUsers.java
SendAnnouncementToOnlineUsers
execute
class SendAnnouncementToOnlineUsers extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#announce"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.sendannouncementtoonlineusers.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.sendannouncementtoonlineusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.sendannouncementtoonlineusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.sendannouncementtoonlineusers.form.field.announcement.label", preferredLocale)); field.setVariable("announcement"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); boolean requestError = false; final List<String> announcement = data.get("announcement"); if (announcement == null || announcement.isEmpty()) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.sendannouncementtoonlineusers.note.text-required", preferredLocale)); requestError = true; } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. XMPPServer.getInstance().getSessionManager().sendServerMessage(null, String.join(System.lineSeparator(), announcement)); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
546
288
834
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/group/AddGroup.java
AddGroup
execute
class AddGroup extends AdHocCommand { private static final Logger Log = LoggerFactory.getLogger(AddGroup.class); @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.group.label", preferredLocale)); field.setVariable("group"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.desc.label", preferredLocale)); field.setVariable("desc"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.members.label", preferredLocale)); field.setVariable("members"); field = form.addField(); field.setType(FormField.Type.list_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.showinroster.label", preferredLocale)); field.setVariable("showInRoster"); field.addValue("nobody"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.showinroster.option.nobody.label", preferredLocale), "nobody"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.showinroster.option.everybody.label", preferredLocale), "everybody"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.showinroster.option.onlygroup.label", preferredLocale), "onlyGroup"); field.addOption(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.showinroster.option.spefgroups.label", preferredLocale), "spefgroups"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.list_multi); field.setVariable("groupList"); for (Group group : GroupManager.getInstance().getGroups()) { field.addOption(group.getName(), group.getName()); } field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.form.field.displayname.label", preferredLocale)); field.setVariable("displayName"); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#add-group"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.group.addgroup.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Element note = command.addElement("note"); // Check if groups cannot be modified (backend is read-only) if (GroupManager.getInstance().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.note.groups-readonly", preferredLocale)); return; } // Get requested group Group group; try { group = GroupManager.getInstance().createGroup(data.getData().get("group").get(0)); } catch (GroupAlreadyExistsException e) { // Group not found note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.note.group-exists", preferredLocale)); return; } catch (GroupNameInvalidException e) { // Group name not valid note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.addgroup.note.group-name-invalid", preferredLocale)); return; } List<String> desc = data.getData().get("desc"); if (desc != null && !desc.isEmpty()) { group.setDescription(desc.get(0)); } List<String> members = data.getData().get("members"); boolean withErrors = false; if (members != null) { Collection<JID> users = group.getMembers(); for (String user : members) { try { users.add(new JID(user)); } catch (Exception e) { Log.warn("User not added to group", e); withErrors = true; } } } String showInRoster = data.getData().get("showInRoster").get(0); List<String> displayName = data.getData().get("displayName"); List<String> groupList = data.getData().get("groupList"); // New group is configured as a shared group switch (showInRoster) { case "nobody": // New group is not a shared group group.shareWithNobody(); break; case "everybody": if (displayName == null) { withErrors = true; } else { group.shareWithEverybody(displayName.get(0)); } break; case "spefgroups": if (displayName == null) { withErrors = true; } else { group.shareWithUsersInGroups(groupList, displayName.get(0)); } break; case "onlyGroup": if (displayName == null) { withErrors = true; } else { group.shareWithUsersInSameGroup(displayName.get(0)); } break; default: withErrors = true; } note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString((withErrors ? "commands.global.operation.finished.with-errors" : "commands.global.operation.finished.success"), preferredLocale));
1,152
835
1,987
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/group/AddGroupUsers.java
AddGroupUsers
execute
class AddGroupUsers extends AdHocCommand { private static final Logger Log = LoggerFactory.getLogger(AddGroupUsers.class); @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.form.field.group.label", preferredLocale)); field.setVariable("group"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.boolean_type); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.form.field.admin.label", preferredLocale)); field.setVariable("admin"); field.addValue(false); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.form.field.users.label", preferredLocale)); field.setVariable("users"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#add-group-members"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Element note = command.addElement("note"); // Check if groups cannot be modified (backend is read-only) if (GroupManager.getInstance().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.note.groups-readonly", preferredLocale)); return; } // Get requested group Group group; try { group = GroupManager.getInstance().getGroup(data.getData().get("group").get(0)); } catch (GroupNotFoundException e) { // Group not found note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.note.group-does-not-exist", preferredLocale)); return; } String admin = data.getData().get("admin").get(0); boolean isAdmin; try { isAdmin = DataForm.parseBoolean( admin ); } catch ( ParseException e ) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.addgroupusers.note.admin-invalid", preferredLocale)); return; } Collection<JID> users = (isAdmin ? group.getAdmins() : group.getMembers()); boolean withErrors = false; for (String user : data.getData().get("users")) { try { users.add(new JID(user)); } catch (Exception e) { Log.warn("User not added to group", e); withErrors = true; } } note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString((withErrors ? "commands.global.operation.finished.with-errors" : "commands.global.operation.finished.success"), preferredLocale));
741
518
1,259
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/group/DeleteGroup.java
DeleteGroup
execute
class DeleteGroup extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.group.deletegroup.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.group.deletegroup.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.deletegroup.form.field.group.label", preferredLocale)); field.setVariable("group"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#delete-group"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.group.deletegroup.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Element note = command.addElement("note"); // Check if groups cannot be modified (backend is read-only) if (GroupManager.getInstance().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.deletegroup.note.groups-readonly", preferredLocale)); return; } // Get requested group Group group; try { group = GroupManager.getInstance().getGroup(data.getData().get("group").get(0)); GroupManager.getInstance().deleteGroup(group); } catch (GroupNotFoundException e) { // Group not found note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.deletegroup.note.group-does-not-exist", preferredLocale)); return; } note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
533
297
830
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/group/DeleteGroupUsers.java
DeleteGroupUsers
execute
class DeleteGroupUsers extends AdHocCommand { private static final Logger Log = LoggerFactory.getLogger(DeleteGroupUsers.class); @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.group.deletegroupusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.group.deletegroupusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.deletegroupusers.form.field.group.label", preferredLocale)); field.setVariable("group"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.deletegroupusers.form.field.users.label", preferredLocale)); field.setVariable("users"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#delete-group-members"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.group.deletegroupusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Element note = command.addElement("note"); // Check if groups cannot be modified (backend is read-only) if (GroupManager.getInstance().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.deletegroupusers.note.groups-readonly", preferredLocale)); return; } // Get requested group Group group; try { group = GroupManager.getInstance().getGroup(data.getData().get("group").get(0)); } catch (GroupNotFoundException e) { // Group not found note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.deletegroupusers.note.group-does-not-exist", preferredLocale)); return; } boolean withErrors = false; for (String user : data.getData().get("users")) { try { group.getAdmins().remove(new JID(user)); group.getMembers().remove(new JID(user)); } catch (Exception e) { Log.warn("User not deleted from group", e); withErrors = true; } } note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString((withErrors ? "commands.global.operation.finished.with-errors" : "commands.global.operation.finished.success"), preferredLocale));
649
404
1,053
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/group/GetListGroupUsers.java
GetListGroupUsers
execute
class GetListGroupUsers extends AdHocCommand { @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.group.getlistgroupusers.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.group.getlistgroupusers.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.group.getlistgroupusers.form.field.group.label", preferredLocale)); field.setVariable("group"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override public String getCode() { return "http://jabber.org/protocol/admin#get-group-members"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.group.getlistgroupusers.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Group group; try { group = GroupManager.getInstance().getGroup(data.getData().get("group").get(0)); } catch (GroupNotFoundException e) { // Group not found Element note = command.addElement("note"); note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.group.getlistgroupusers.note.group-does-not-exist", preferredLocale)); return; } DataForm form = new DataForm(DataForm.Type.result); form.addReportedField("jid", LocaleUtils.getLocalizedString("commands.admin.group.getlistgroupusers.form.reportedfield.jid.label", preferredLocale), FormField.Type.jid_single); form.addReportedField("admin", LocaleUtils.getLocalizedString("commands.admin.group.getlistgroupusers.form.reportedfield.admin.label", preferredLocale), FormField.Type.boolean_type); // Add group members the result for (JID memberJID : group.getMembers()) { Map<String,Object> fields = new HashMap<>(); fields.put("jid", memberJID.toString()); fields.put("admin", false); form.addItemFields(fields); } // Add group admins the result for (JID memberJID : group.getAdmins()) { Map<String,Object> fields = new HashMap<>(); fields.put("jid", memberJID.toString()); fields.put("admin", true); form.addItemFields(fields); } command.add(form.getElement());
545
452
997
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/AddUser.java
AddUser
addStageInformation
class AddUser extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#add-user"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.adduser.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); // Check if groups cannot be modified (backend is read-only) if (UserManager.getUserProvider().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.adduser.note.users-readonly", preferredLocale)); return; } Map<String, List<String>> data = sessionData.getData(); // Let's create the jid and check that they are a local user JID account; try { account = new JID(get(data, "accountjid", 0)); } catch (IllegalArgumentException e) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.adduser.note.jid-invalid", preferredLocale)); return; } catch (NullPointerException npe) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.adduser.note.jid-required", preferredLocale)); return; } if (!XMPPServer.getInstance().isLocal(account)) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.adduser.note.jid-not-local", preferredLocale)); return; } String password = get(data, "password", 0); String passwordRetry = get(data, "password-verify", 0); if (password == null || password.isEmpty() || !password.equals(passwordRetry)) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.adduser.note.passwords-dont-match", preferredLocale)); return; } String email = get(data, "email", 0); String givenName = get(data, "given_name", 0); String surName = get(data, "surname", 0); String name = (givenName == null ? "" : givenName) + (surName == null ? "" : surName); name = (name.isEmpty() ? null : name); // If provider requires email, validate if (UserManager.getUserProvider().isEmailRequired() && !StringUtils.isValidEmailAddress(email)) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.adduser.note.email-required", preferredLocale)); return; } try { UserManager.getInstance().createUser(account.getNode(), password, name, email); } catch (UserAlreadyExistsException e) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.adduser.note.user-exists", preferredLocale)); return; } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale)); } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public boolean hasPermission(JID requester) { return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester)) && !UserManager.getUserProvider().isReadOnly(); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjid"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_private); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.field.password.label", preferredLocale)); field.setVariable("password"); field = form.addField(); field.setType(FormField.Type.text_private); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.field.password-verify.label", preferredLocale)); field.setVariable("password-verify"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.field.email.label", preferredLocale)); field.setVariable("email"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.field.given_name.label", preferredLocale)); field.setVariable("given_name"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.adduser.form.field.surname.label", preferredLocale)); field.setVariable("surname"); // Add the form to the command command.add(form.getElement());
1,176
658
1,834
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/AuthenticateUser.java
AuthenticateUser
execute
class AuthenticateUser extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#authenticate-user"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjid"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_private); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.form.field.password.label", preferredLocale)); field.setVariable("password"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Element note = command.addElement("note"); JID account; try { account = new JID(data.getData().get("accountjid").get(0)); } catch (IllegalArgumentException e) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.note.jid-invalid", preferredLocale)); return; } catch (NullPointerException ne) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.note.jid-required", preferredLocale)); return; } if (!XMPPServer.getInstance().isLocal(account)) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.note.jid-not-local", preferredLocale)); return; } String password = data.getData().get("password").get(0); // Get requested user User user; try { user = UserManager.getInstance().getUser(account.getNode()); } catch (UserNotFoundException e) { // User not found note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.note.user-does-not-exist", preferredLocale)); return; } try { AuthFactory.authenticate(user.getUsername(), password); } catch (UnauthorizedException | ConnectionException | InternalUnauthenticatedException e) { // Auth failed note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.authenticateuser.note.authentication-failed", preferredLocale)); return; } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
674
576
1,250
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/ChangeUserPassword.java
ChangeUserPassword
execute
class ChangeUserPassword extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#change-user-password"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_single); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjid"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_private); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.form.field.password.label", preferredLocale)); field.setVariable("password"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) && !UserManager.getUserProvider().isReadOnly(); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Element note = command.addElement("note"); // Check if groups cannot be modified (backend is read-only) if (UserManager.getUserProvider().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.note.users-readonly", preferredLocale)); return; } JID account; try { account = new JID(data.getData().get("accountjid").get(0)); } catch (IllegalArgumentException e) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.note.jid-invalid", preferredLocale)); return; } catch (NullPointerException ne) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.note.jid-required", preferredLocale)); return; } if (!XMPPServer.getInstance().isLocal(account)) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.note.jid-not-local", preferredLocale)); return; } String newPassword = data.getData().get("password").get(0); // Get requested group User user; try { user = UserManager.getInstance().getUser(account.getNode()); } catch (UserNotFoundException e) { // Group not found note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.changeuserpassword.note.user-does-not-exist", preferredLocale)); return; } // Set the new passowrd of the user user.setPassword(newPassword); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
674
573
1,247
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/DeleteUser.java
DeleteUser
execute
class DeleteUser extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#delete-user"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjids"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } @Override public boolean hasPermission(JID requester) { return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester)) && !UserManager.getUserProvider().isReadOnly(); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); // Check if users cannot be modified (backend is read-only) if (UserManager.getUserProvider().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.note.users-readonly", preferredLocale)); return; } Map<String, List<String>> data = sessionData.getData(); // Let's create the jids and check that they are a local user boolean requestError = false; final List<User> toDelete = new ArrayList<>(); for ( final String accountjid : data.get( "accountjids" )) { JID account; try { account = new JID( accountjid ); if ( !XMPPServer.getInstance().isLocal( account ) ) { note.addAttribute( "type", "error" ); note.setText( LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.note.jid-not-local", List.of(accountjid), preferredLocale)); requestError = true; } else { User user = UserManager.getInstance().getUser( account.getNode() ); toDelete.add( user ); } } catch (IllegalArgumentException e) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.note.jid-invalid", preferredLocale)); return; } catch ( NullPointerException npe ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.note.jid-required", preferredLocale)); requestError = true; } catch ( UserNotFoundException e ) { note.addAttribute( "type", "error" ); note.setText( LocaleUtils.getLocalizedString("commands.admin.user.deleteuser.note.user-does-not-exist", List.of(accountjid), preferredLocale)); requestError = true; } } if ( requestError ) { // We've collected all errors. Return without deleting anything. return; } // No errors. Delete all users. for ( final User user : toDelete ) { UserManager.getInstance().deleteUser(user); } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
599
717
1,316
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/DisableUser.java
DisableUser
execute
class DisableUser extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#disable-user"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.disableuser.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjids"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester)) && !LockOutManager.getLockOutProvider().isReadOnly(); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); // Check if locks can be set (backend is read-only) if (LockOutManager.getLockOutProvider().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.note.lockout-readonly", preferredLocale)); return; } Map<String, List<String>> data = sessionData.getData(); // Let's create the jids and check that they are a local user boolean requestError = false; final List<User> users = new ArrayList<>(); for ( final String accountjid : data.get( "accountjids" )) { JID account; try { account = new JID( accountjid ); if ( !XMPPServer.getInstance().isLocal( account ) ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.note.jid-not-local", List.of(accountjid), preferredLocale)); requestError = true; } else { User user = UserManager.getInstance().getUser( account.getNode() ); users.add( user ); } } catch ( NullPointerException npe ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.note.jid-required", preferredLocale)); requestError = true; } catch (IllegalArgumentException npe) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.note.jid-invalid", preferredLocale)); requestError = true; } catch ( UserNotFoundException e ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.disableuser.note.user-does-not-exist", List.of(accountjid), preferredLocale)); requestError = true; } } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. Disable all users. for (final User user : users) { LockOutManager.getInstance().disableAccount(user.getUsername(), null, null); // Close existing sessions for the disabled user. final StreamError error = new StreamError(StreamError.Condition.not_authorized); final Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(user.getUsername()); for (final ClientSession session : sessions) { session.deliverRawText(error.toXML()); session.close(); } } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
595
830
1,425
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/EndUserSession.java
EndUserSession
execute
class EndUserSession extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#end-user-session"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.endusersession.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.endusersession.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.endusersession.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.endusersession.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjids"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Let's create the jids and check that they are a local user boolean requestError = false; final List<JID> addresses = new ArrayList<>(); for ( final String accountjid : data.get( "accountjids" )) { JID address; try { address = new JID( accountjid ); if ( !XMPPServer.getInstance().isLocal( address ) ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.endusersession.note.jid-not-local", List.of(accountjid), preferredLocale)); requestError = true; } else { addresses.add(address); } } catch ( NullPointerException npe ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.endusersession.note.jid-required", preferredLocale)); requestError = true; } catch (IllegalArgumentException npe) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.endusersession.note.jid-invalid", preferredLocale)); requestError = true; } } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. Disable all users. for (final JID address : addresses) { // Note: If the JID is of the form <user@host>, the service MUST end all of the user's sessions; if the JID // is of the form <user@host/resource>, the service MUST end only the session associated with that resource. final Collection<ClientSession> sessions = new HashSet<>(); if (address.getResource() != null) { // Full JID: only close this session. sessions.add(SessionManager.getInstance().getSession(address)); } else { // Bare JID: close all sessions for the user. sessions.addAll(SessionManager.getInstance().getSessions(address.getNode())); } for (final ClientSession session : sessions) { session.close(); } } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
583
710
1,293
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/GetUserRoster.java
GetUserRoster
addStageInformation
class GetUserRoster extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#get-user-roster"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); // Check if rosters are enabled if (!RosterManager.isRosterServiceEnabled()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.note.rosterservice-disabled", preferredLocale)); return; } Map<String, List<String>> data = sessionData.getData(); boolean requestError = false; Map<JID, Roster> rosters = new HashMap<>(); final RosterManager rosterManager = XMPPServer.getInstance().getRosterManager(); for ( final String accountjid : data.get( "accountjids" )) { JID account; try { account = new JID( accountjid ); if ( !XMPPServer.getInstance().isLocal( account ) ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.note.jid-not-local", List.of(accountjid), preferredLocale)); requestError = true; } else { rosters.put(account, rosterManager.getRoster(account.getNode())); } } catch ( NullPointerException npe ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.note.jid-required", preferredLocale)); requestError = true; } catch (IllegalArgumentException npe) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.note.jid-invalid", preferredLocale)); requestError = true; } catch ( UserNotFoundException e ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.note.user-does-not-exist", List.of(accountjid), preferredLocale)); requestError = true; } } if (rosters.size() > 1) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.note.cannot-return-multiple", preferredLocale)); requestError = true; } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. for (final Map.Entry<JID, Roster> entry : rosters.entrySet()) { final JID owner = entry.getKey(); final Roster roster = entry.getValue(); DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setVariable("accountjids"); field.addValue(owner); final Element rosterElement = roster.getReset().getElement() .element(QName.get("query", "jabber:iq:roster")); if (rosterElement != null) { form.getElement().add(rosterElement.createCopy()); } command.add(form.getElement()); } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale)); } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester)) && RosterManager.isRosterServiceEnabled(); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.getuserroster.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjids"); field.setRequired(true); // Add the form to the command command.add(form.getElement());
1,349
285
1,634
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/ReEnableUser.java
ReEnableUser
execute
class ReEnableUser extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#reenable-user"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjids"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester)) && !LockOutManager.getLockOutProvider().isReadOnly(); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); // Check if locks can be set (backend is read-only) if (LockOutManager.getLockOutProvider().isReadOnly()) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.note.lockout-readonly", preferredLocale)); return; } Map<String, List<String>> data = sessionData.getData(); // Let's create the jids and check that they are a local user boolean requestError = false; final List<User> users = new ArrayList<>(); for ( final String accountjid : data.get( "accountjids" )) { JID account; try { account = new JID( accountjid ); if ( !XMPPServer.getInstance().isLocal( account ) ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.note.jid-not-local", List.of(accountjid), preferredLocale)); requestError = true; } else { User user = UserManager.getInstance().getUser( account.getNode() ); users.add( user ); } } catch ( NullPointerException npe ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.note.jid-required", preferredLocale)); requestError = true; } catch (IllegalArgumentException npe) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.note.jid-invalid", preferredLocale)); requestError = true; } catch ( UserNotFoundException e ) { note.addAttribute( "type", "error" ); note.setText(LocaleUtils.getLocalizedString("commands.admin.user.reenableuser.note.user-does-not-exist", List.of(accountjid), preferredLocale)); requestError = true; } } if ( requestError ) { // We've collected all errors. Return without applying changes. return; } // No errors. Re-Enable all users. for (final User user : users) { LockOutManager.getInstance().enableAccount(user.getUsername()); } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
600
739
1,339
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/admin/user/UserProperties.java
UserProperties
addStageInformation
class UserProperties extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/admin#get-user-properties"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.admin.user.userproperties.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull final SessionData data, Element command) { DataForm form = new DataForm(DataForm.Type.result); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); List<String> accounts = data.getData().get("accountjids"); if (accounts != null && !accounts.isEmpty()) { populateResponseFields(form, accounts); } command.add(form.getElement()); } private void populateResponseFields(DataForm form, List<String> accounts) { FormField jidField = form.addField(); jidField.setType(FormField.Type.jid_multi); jidField.setVariable("accountjids"); FormField emailField = form.addField(); emailField.setType(FormField.Type.text_multi); emailField.setVariable("email"); FormField nameField = form.addField(); nameField.setType(FormField.Type.text_multi); nameField.setVariable("name"); UserManager manager = UserManager.getInstance(); for(String account : accounts) { User user; try { JID jid = new JID(account); user = manager.getUser(jid.getNode()); } catch (Exception ex) { continue; } jidField.addValue(account); emailField.addValue(Objects.requireNonNullElse(user.getEmail(), "")); nameField.addValue(user.getName()); } } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected AdHocCommand.Action getExecuteAction(@Nonnull final SessionData data) { return AdHocCommand.Action.complete; } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.admin.user.userproperties.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.admin.user.userproperties.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_multi); field.setLabel(LocaleUtils.getLocalizedString("commands.admin.user.userproperties.form.field.accountjid.label", preferredLocale)); field.setVariable("accountjids"); field.setRequired(true); // Add the form to the command command.add(form.getElement());
676
279
955
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/GroupAdminAdded.java
GroupAdminAdded
addStageInformation
class GroupAdminAdded extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#group-admin-added"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.groupadminadded.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Input validation final Set<String> inputValidationErrors = new HashSet<>(); Group group = null; final String groupName = get(data, "groupName", 0); if (StringUtils.isBlank(groupName)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminadded.note.groupname-required", preferredLocale)); } else { try { group = GroupManager.getInstance().getGroup(groupName); } catch (GroupNotFoundException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminadded.note.group-does-not-exist", List.of(groupName), preferredLocale)); } } final String wasMemberValue = get(data, "wasMember", 0); if (StringUtils.isBlank(wasMemberValue)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminadded.note.wasmember-required", preferredLocale)); } final boolean wasMember = "1".equals(wasMemberValue) || Boolean.parseBoolean(wasMemberValue); JID admin; final String adminValue = get(data, "admin", 0); if (StringUtils.isBlank(adminValue)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminadded.note.admin-required", preferredLocale)); return; } else { try { admin = new JID(adminValue); } catch (IllegalArgumentException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminadded.note.admin-jid-invalid", List.of(adminValue), preferredLocale)); return; } } if (!inputValidationErrors.isEmpty()) { note.addAttribute("type", "error"); note.setText(StringUtils.join(inputValidationErrors, " ")); return; } // Perform post-processing (cache updates and event notifications). GroupManager.getInstance().adminAddedPostProcess(group, admin, wasMember); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale)); } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.groupadminadded.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.groupadminadded.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupadminadded.form.field.groupname.label", preferredLocale)); field.setVariable("groupName"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupadminadded.form.field.admin.label", preferredLocale)); field.setVariable("admin"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.boolean_type); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupadminadded.form.field.wasmember.label", preferredLocale)); field.setVariable("wasMember"); field.setRequired(true); // Add the form to the command command.add(form.getElement());
950
437
1,387
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/GroupAdminRemoved.java
GroupAdminRemoved
execute
class GroupAdminRemoved extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#group-admin-removed"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.groupadminremoved.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.form.field.groupname.label", preferredLocale)); field.setVariable("groupName"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.form.field.admin.label", preferredLocale)); field.setVariable("admin"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Input validation final Set<String> inputValidationErrors = new HashSet<>(); Group group = null; final String groupName = get(data, "groupName", 0); if (StringUtils.isBlank(groupName)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.note.groupname-required", preferredLocale)); } else { try { group = GroupManager.getInstance().getGroup(groupName); } catch (GroupNotFoundException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.note.group-does-not-exist", List.of(groupName), preferredLocale)); } } JID admin; final String adminValue = get(data, "admin", 0); if (StringUtils.isBlank(adminValue)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.note.admin-required", preferredLocale)); return; } else { try { admin = new JID(adminValue); } catch (IllegalArgumentException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupadminremoved.note.admin-jid-invalid", List.of(adminValue), preferredLocale)); return; } } if (!inputValidationErrors.isEmpty()) { note.addAttribute("type", "error"); note.setText(StringUtils.join(inputValidationErrors, " ")); return; } // Perform post-processing (cache updates and event notifications). GroupManager.getInstance().adminRemovedPostProcess(group, admin); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
657
554
1,211
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/GroupCreated.java
GroupCreated
execute
class GroupCreated extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#group-created"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.groupcreated.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.groupcreated.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.groupcreated.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupcreated.form.field.groupname.label", preferredLocale)); field.setVariable("groupName"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Input validation final Set<String> inputValidationErrors = new HashSet<>(); Group group = null; final String groupName = get(data, "groupName", 0); if (StringUtils.isBlank(groupName)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupcreated.note.groupname-required", preferredLocale)); } else { try { group = GroupManager.getInstance().getGroup(groupName); } catch (GroupNotFoundException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupcreated.note.group-does-not-exist", List.of(groupName), preferredLocale)); } } if (!inputValidationErrors.isEmpty()) { note.addAttribute("type", "error"); note.setText(StringUtils.join(inputValidationErrors, " ")); return; } // Perform post-processing (cache updates and event notifications). GroupManager.getInstance().createGroupPostProcess(group); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
562
379
941
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/GroupDeleting.java
GroupDeleting
execute
class GroupDeleting extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#group-created"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.groupdeleting.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.groupdeleting.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.groupdeleting.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupdeleting.form.field.groupname.label", preferredLocale)); field.setVariable("groupName"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Input validation final Set<String> inputValidationErrors = new HashSet<>(); Group group = null; final String groupName = get(data, "groupName", 0); if (StringUtils.isBlank(groupName)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupdeleting.note.groupname-required", preferredLocale)); } else { try { group = GroupManager.getInstance().getGroup(groupName); } catch (GroupNotFoundException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupdeleting.note.group-does-not-exist", List.of(groupName), preferredLocale)); } } if (!inputValidationErrors.isEmpty()) { note.addAttribute("type", "error"); note.setText(StringUtils.join(inputValidationErrors, " ")); return; } // Perform post-processing (cache updates and event notifications). GroupManager.getInstance().deleteGroupPreProcess(group); // Since the group is about to be deleted by the provided, mark it as removed in the caches. GroupManager.getInstance().deleteGroupPostProcess(group); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
572
421
993
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/GroupMemberAdded.java
GroupMemberAdded
addStageInformation
class GroupMemberAdded extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#group-member-added"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.groupmemberadded.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Input validation final Set<String> inputValidationErrors = new HashSet<>(); Group group = null; final String groupName = get(data, "groupName", 0); if (StringUtils.isBlank(groupName)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.note.groupname-required", preferredLocale)); } else { try { group = GroupManager.getInstance().getGroup(groupName); } catch (GroupNotFoundException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.note.group-does-not-exist", List.of(groupName), preferredLocale)); } } final String wasAdminValue = get(data, "wasAdmin", 0); if (StringUtils.isBlank(wasAdminValue)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.note.wasadmin-required", preferredLocale)); } final boolean wasAdmin = "1".equals(wasAdminValue) || Boolean.parseBoolean(wasAdminValue); JID member; final String memberValue = get(data, "member", 0); if (StringUtils.isBlank(memberValue)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.note.member-required", preferredLocale)); return; } else { try { member = new JID(memberValue); } catch (IllegalArgumentException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.note.member-jid-invalid", List.of(memberValue), preferredLocale)); return; } } if (!inputValidationErrors.isEmpty()) { note.addAttribute("type", "error"); note.setText(StringUtils.join(inputValidationErrors, " ")); return; } // Perform post-processing (cache updates and event notifications). GroupManager.getInstance().memberAddedPostProcess(group, member, wasAdmin); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale)); } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.form.field.groupname.label", preferredLocale)); field.setVariable("groupName"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.form.field.member.label", preferredLocale)); field.setVariable("member"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.boolean_type); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupmemberadded.form.field.wasadmin.label", preferredLocale)); field.setVariable("wasAdmin"); field.setRequired(true); // Add the form to the command command.add(form.getElement());
950
437
1,387
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/GroupMemberRemoved.java
GroupMemberRemoved
addStageInformation
class GroupMemberRemoved extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#group-member-removed"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Input validation final Set<String> inputValidationErrors = new HashSet<>(); Group group = null; final String groupName = get(data, "groupName", 0); if (StringUtils.isBlank(groupName)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.note.groupname-required", preferredLocale)); } else { try { group = GroupManager.getInstance().getGroup(groupName); } catch (GroupNotFoundException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.note.group-does-not-exist", List.of(groupName), preferredLocale)); } } JID member; final String memberValue = get(data, "member", 0); if (StringUtils.isBlank(memberValue)) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.note.member-required", preferredLocale)); return; } else { try { member = new JID(memberValue); } catch (IllegalArgumentException e) { inputValidationErrors.add(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.note.member-jid-invalid", List.of(memberValue), preferredLocale)); return; } } if (!inputValidationErrors.isEmpty()) { note.addAttribute("type", "error"); note.setText(StringUtils.join(inputValidationErrors, " ")); return; } // Perform post-processing (cache updates and event notifications). GroupManager.getInstance().memberRemovedPostProcess(group, member); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale)); } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) {<FILL_FUNCTION_BODY>} @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.form.field.groupname.label", preferredLocale)); field.setVariable("groupName"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.groupmemberremoved.form.field.member.label", preferredLocale)); field.setVariable("member"); field.setRequired(true); // Add the form to the command command.add(form.getElement());
853
358
1,211
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/UserCreated.java
UserCreated
execute
class UserCreated extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#user-created"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.usercreated.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.usercreated.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.usercreated.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.usercreated.form.field.username.label", preferredLocale)); field.setVariable("username"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Get the username String username; try { username = get(data, "username", 0); } catch (NullPointerException npe) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.usercreated.note.username-required", preferredLocale)); return; } // Sends the event User user; try { // Loads the new user user = UserManager.getUserProvider().loadUser(username); // Fire event. Map<String, Object> params = Collections.emptyMap(); UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_created, params); } catch (UserNotFoundException e) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.usercreated.note.user-does-not-exist", preferredLocale)); } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
560
365
925
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/UserDeleting.java
UserDeleting
execute
class UserDeleting extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#user-deleting"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.userdeleting.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.userdeleting.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.userdeleting.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.userdeleting.form.field.username.label", preferredLocale)); field.setVariable("username"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Gets the username String username; try { username = get(data, "username", 0); } catch (NullPointerException npe) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.userdeleting.note.username-required", preferredLocale)); return; } // Sends the event User user; try { // Gets current user user = UserManager.getInstance().getUser(username); Map<String, Object> params = Collections.emptyMap(); UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_deleting, params); } catch (UserNotFoundException e) { // It's ok, user doesn't exist, so deleting it is nothing } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
572
328
900
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/VCardCreated.java
VCardCreated
execute
class VCardCreated extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#vcard-created"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.vcardcreated.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.vcardcreated.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.vcardcreated.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.vcardcreated.form.field.username.label", preferredLocale)); field.setVariable("username"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Get the username String username; try { username = get(data, "username", 0); } catch (NullPointerException npe) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.vcardcreated.note.username-required", preferredLocale)); return; } // Loads the new vCard Element vCard = VCardManager.getProvider().loadVCard(username); if (vCard == null) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.vcardcreated.note.vcard-does-not-exist", preferredLocale)); return; } // Fire event. VCardEventDispatcher.dispatchVCardCreated(username, vCard); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
566
334
900
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/VCardDeleting.java
VCardDeleting
execute
class VCardDeleting extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#vcard-deleting"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.vcarddeleting.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.vcarddeleting.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.vcarddeleting.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.vcarddeleting.form.field.username.label", preferredLocale)); field.setVariable("username"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Gets the username String username; try { username = get(data, "username", 0); } catch (NullPointerException npe) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.vcarddeleting.note.username-required", preferredLocale)); return; } // Loads the vCard Element vCard = VCardManager.getInstance().getVCard(username); if (vCard == null) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.vcarddeleting.note.vcard-does-not-exist", preferredLocale)); return; } // Fire event. VCardEventDispatcher.dispatchVCardDeleted(username, vCard); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
578
337
915
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/commands/event/VCardModified.java
VCardModified
execute
class VCardModified extends AdHocCommand { @Override public String getCode() { return "http://jabber.org/protocol/event#vcard-modified"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("commands.event.vcardmodified.label"); } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public void execute(@Nonnull SessionData sessionData, Element command) {<FILL_FUNCTION_BODY>} @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("commands.event.vcardmodified.form.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("commands.event.vcardmodified.form.instruction", preferredLocale)); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel(LocaleUtils.getLocalizedString("commands.event.vcardmodified.form.field.username.label", preferredLocale)); field.setVariable("username"); field.setRequired(true); // Add the form to the command command.add(form.getElement()); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public boolean hasPermission(JID requester) { return super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester); } }
final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(sessionData.getOwner()); Element note = command.addElement("note"); Map<String, List<String>> data = sessionData.getData(); // Get the username String username; try { username = get(data, "username", 0); } catch (NullPointerException npe) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.vcardmodified.note.username-required", preferredLocale)); return; } // Loads the updated vCard Element vCard = VCardManager.getProvider().loadVCard(username); if (vCard == null) { note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("commands.event.vcardmodified.note.vcard-does-not-exist", preferredLocale)); return; } // Fire event. VCardEventDispatcher.dispatchVCardUpdated(username, vCard); // Answer that the operation was successful note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("commands.global.operation.finished.success", preferredLocale));
572
336
908
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/component/NotifyComponentInfo.java
NotifyComponentInfo
readExternal
class NotifyComponentInfo implements ClusterTask<Void> { private IQ iq; public NotifyComponentInfo() { } public NotifyComponentInfo(IQ iq) { this.iq = iq; } @Override public Void getResult() { return null; } @Override public void run() { final InternalComponentManager manager = InternalComponentManager.getInstance(); manager.addComponentInfo(iq); manager.notifyComponentInfo(iq); } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSerializable(out, (DefaultElement) iq.getElement()); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in); iq = new IQ(packetElement, true);
217
40
257
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/component/RequestComponentInfoNotification.java
RequestComponentInfoNotification
run
class RequestComponentInfoNotification implements ClusterTask<Void> { private JID component; private NodeID requestee; public RequestComponentInfoNotification() { } public RequestComponentInfoNotification(final JID component, NodeID requestee) { this.component = component; this.requestee = requestee; } @Override public Void getResult() { return null; } @Override public void run() {<FILL_FUNCTION_BODY>} @Override public void writeExternal( ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSerializable( out, component ); ExternalizableUtil.getInstance().writeSerializable( out, requestee ); } @Override public void readExternal( ObjectInput in) throws IOException, ClassNotFoundException { component = (JID) ExternalizableUtil.getInstance().readSerializable( in ); requestee = (NodeID) ExternalizableUtil.getInstance().readSerializable( in ); } }
final InternalComponentManager manager = InternalComponentManager.getInstance(); final IQ componentInfo = manager.getComponentInfo( component ); if ( componentInfo != null ) { CacheFactory.doClusterTask( new NotifyComponentInfo( componentInfo ), requestee.toByteArray() ); }
263
75
338
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/container/GetAdminConsoleInfoTask.java
GetAdminConsoleInfoTask
writeExternal
class GetAdminConsoleInfoTask implements ClusterTask<GetAdminConsoleInfoTask> { private String bindInterface; private int adminPort; private int adminSecurePort; private String adminSecret; @Override public GetAdminConsoleInfoTask getResult() { return this; } @Override public void run() { PluginManager pluginManager = XMPPServer.getInstance().getPluginManager(); AdminConsolePlugin adminConsolePlugin = ((AdminConsolePlugin) pluginManager.getPlugin("admin")); bindInterface = adminConsolePlugin.getBindInterface(); adminPort = adminConsolePlugin.getAdminUnsecurePort(); adminSecurePort = adminConsolePlugin.getAdminSecurePort(); adminSecret = AdminConsolePlugin.secret; if (bindInterface == null) { Enumeration<NetworkInterface> nets = null; try { nets = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { // We failed to discover a valid IP address where the admin console is running return; } for (NetworkInterface netInterface : Collections.list(nets)) { boolean found = false; Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); for (InetAddress address : Collections.list(addresses)) { if ("127.0.0.1".equals(address.getHostAddress()) || "0:0:0:0:0:0:0:1".equals(address.getHostAddress())) { continue; } Socket socket = new Socket(); InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort); try { socket.connect(remoteAddress); bindInterface = address.getHostAddress(); found = true; break; } catch (IOException e) { // Ignore this address. Let's hope there is more addresses to validate } } if (found) { break; } } } } public String getBindInterface() { return bindInterface; } public int getAdminPort() { return adminPort; } public int getAdminSecurePort() { return adminSecurePort; } public String getAdminSecret() { return adminSecret; } @Override public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { adminPort = ExternalizableUtil.getInstance().readInt(in); adminSecurePort = ExternalizableUtil.getInstance().readInt(in); if (ExternalizableUtil.getInstance().readBoolean(in)) { bindInterface = ExternalizableUtil.getInstance().readSafeUTF(in); } adminSecret = ExternalizableUtil.getInstance().readSafeUTF(in); } }
ExternalizableUtil.getInstance().writeInt(out, adminPort); ExternalizableUtil.getInstance().writeInt(out, adminSecurePort); ExternalizableUtil.getInstance().writeBoolean(out, bindInterface != null); if (bindInterface != null) { ExternalizableUtil.getInstance().writeSafeUTF(out, bindInterface); } ExternalizableUtil.getInstance().writeSafeUTF(out, adminSecret);
744
109
853
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/container/PluginCacheConfigurator.java
PluginCacheConfigurator
readInitParams
class PluginCacheConfigurator { private static final Logger Log = LoggerFactory.getLogger(PluginCacheConfigurator.class); private InputStream configDataStream; public void setInputStream(InputStream configDataStream) { this.configDataStream = configDataStream; } public void configure(String pluginName) { try { Document cacheXml = SAXReaderUtil.readDocument(configDataStream); List<Node> mappings = cacheXml.selectNodes("/cache-config/cache-mapping"); for (Node mapping: mappings) { registerCache(pluginName, mapping); } } catch (ExecutionException e) { Log.error(e.getMessage(), e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error(e.getMessage(), e); } } private void registerCache(String pluginName, Node configData) { String cacheName = configData.selectSingleNode("cache-name").getStringValue(); String schemeName = configData.selectSingleNode("scheme-name").getStringValue(); if (cacheName == null || schemeName == null) { throw new IllegalArgumentException("Both cache-name and scheme-name elements are required. Found cache-name: " + cacheName + " and scheme-name: " + schemeName); } Map<String, String> initParams = readInitParams(configData); CacheInfo info = new CacheInfo(cacheName, CacheInfo.Type.valueof(schemeName), initParams); PluginCacheRegistry.getInstance().registerCache(pluginName, info); } private Map<String, String> readInitParams(Node configData) {<FILL_FUNCTION_BODY>} }
Map<String, String> paramMap = new HashMap<>(); List<Node> params = configData.selectNodes("init-params/init-param"); for (Node param : params) { String paramName = param.selectSingleNode("param-name").getStringValue(); String paramValue = param.selectSingleNode("param-value").getStringValue(); paramMap.put(paramName, paramValue); } return paramMap;
431
112
543
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/container/PluginCacheRegistry.java
PluginCacheRegistry
getMaxLifetimeFromProperty
class PluginCacheRegistry { private static final Logger Log = LoggerFactory.getLogger(PluginCacheRegistry.class); private static final PluginCacheRegistry instance = new PluginCacheRegistry(); private Map<String, CacheInfo> extraCacheMappings = new HashMap<>(); private Map<String, List<CacheInfo>> pluginCaches = new HashMap<>(); public static PluginCacheRegistry getInstance() { return instance; } private PluginCacheRegistry() { } /** * Registers cache configuration data for a give cache and plugin. * * @param pluginName the name of the plugin which will use the cache. * @param info the cache configuration data. */ public void registerCache(String pluginName, CacheInfo info) { extraCacheMappings.put(info.getCacheName(), info); List<CacheInfo> caches = pluginCaches.get(pluginName); if (caches == null) { caches = new ArrayList<>(); pluginCaches.put(pluginName, caches); } caches.add(info); // Set system properties for this cache CacheFactory.setCacheTypeProperty(info.getCacheName(), info.getType().getName()); CacheFactory.setMaxSizeProperty(info.getCacheName(), getMaxSizeFromProperty(info)); CacheFactory.setMaxLifetimeProperty(info.getCacheName(), getMaxLifetimeFromProperty(info)); CacheFactory.setMinCacheSize(info.getCacheName(), getMinSizeFromProperty(info)); } /** * Unregisters all caches for the given plugin. * * @param pluginName the name of the plugin whose caches will be unregistered. */ public void unregisterCaches(String pluginName) { List<CacheInfo> caches = pluginCaches.remove(pluginName); if (caches != null) { for (CacheInfo info : caches) { extraCacheMappings.remove(info.getCacheName()); // Check if other cluster nodes have this plugin installed Collection<Boolean> answers = CacheFactory.doSynchronousClusterTask(new IsPluginInstalledTask(pluginName), false); for (Boolean installed : answers) { if (installed) { return; } } // Destroy cache if we are the last node hosting this plugin try { CacheFactory.destroyCache(info.getCacheName()); } catch (Exception e) { Log.warn(e.getMessage(), e); } } } } public CacheInfo getCacheInfo(String name) { return extraCacheMappings.get(name); } private long getMaxSizeFromProperty(CacheInfo cacheInfo) { String sizeProp = cacheInfo.getParams().get("back-size-high"); if (sizeProp != null) { if ("0".equals(sizeProp)) { return -1L; } try { return Integer.parseInt(sizeProp); } catch (NumberFormatException nfe) { Log.warn("Unable to parse back-size-high for cache: " + cacheInfo.getCacheName()); } } // Return default return CacheFactory.DEFAULT_MAX_CACHE_SIZE; } private static long getMaxLifetimeFromProperty(CacheInfo cacheInfo) {<FILL_FUNCTION_BODY>} private long getMinSizeFromProperty(CacheInfo cacheInfo) { String sizeProp = cacheInfo.getParams().get("back-size-low"); if (sizeProp != null) { if ("0".equals(sizeProp)) { return -1L; } try { return Integer.parseInt(sizeProp); } catch (NumberFormatException nfe) { Log.warn("Unable to parse back-size-low for cache: " + cacheInfo.getCacheName()); } } // Return default return CacheFactory.DEFAULT_MAX_CACHE_SIZE; } }
String lifetimeProp = cacheInfo.getParams().get("back-expiry"); if (lifetimeProp != null) { if ("0".equals(lifetimeProp)) { return -1L; } long factor = 1; if (lifetimeProp.endsWith("m")) { factor = Duration.ofMinutes(1).toMillis(); } else if (lifetimeProp.endsWith("h")) { factor = Duration.ofHours(1).toMillis(); } else if (lifetimeProp.endsWith("d")) { factor = Duration.ofDays(1).toMillis(); } try { return Long.parseLong(lifetimeProp.substring(0, lifetimeProp.length()-1)) * factor; } catch (NumberFormatException nfe) { Log.warn("Unable to parse back-expiry for cache: " + cacheInfo.getCacheName()); } } // Return default return CacheFactory.DEFAULT_MAX_CACHE_LIFETIME;
1,019
275
1,294
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/container/PluginClassLoader.java
PluginClassLoader
addDirectory
class PluginClassLoader extends URLClassLoader { private static final Logger Log = LoggerFactory.getLogger(PluginClassLoader.class); private List<JarURLConnection> cachedJarFiles = new ArrayList<JarURLConnection>(); public PluginClassLoader() { super(new URL[] {}, findParentClassLoader()); } /** * Adds a directory to the class loader. * * @param directory the directory. */ public void addDirectory(File directory) {<FILL_FUNCTION_BODY>} /** * Add the given URL to the classpath for this class loader, * caching the JAR file connection so it can be unloaded later * * @param file URL for the JAR file or directory to append to classpath */ public void addURLFile(URL file) { try { // open and cache JAR file connection URLConnection uc = file.openConnection(); if (uc instanceof JarURLConnection) { uc.setUseCaches(true); ((JarURLConnection) uc).getManifest(); cachedJarFiles.add((JarURLConnection)uc); } } catch (Exception e) { Log.warn("Failed to cache plugin JAR file: " + file.toExternalForm()); } addURL(file); } /** * Unload any JAR files that have been cached by this plugin */ public void unloadJarFiles() { for (JarURLConnection url : cachedJarFiles) { try { Log.info("Unloading plugin JAR file " + url.getJarFile().getName()); url.getJarFile().close(); } catch (Exception e) { Log.error("Failed to unload JAR file", e); } } } /** * Locates the best parent class loader based on context. * * @return the best parent classloader to use. */ private static ClassLoader findParentClassLoader() { ClassLoader parent = XMPPServer.class.getClassLoader(); if (parent == null) { parent = PluginClassLoader.class.getClassLoader(); } if (parent == null) { parent = ClassLoader.getSystemClassLoader(); } return parent; } }
try { // Add classes directory to classpath. File classesDir = new File(directory, "classes"); if (classesDir.exists()) { addURL(classesDir.toURI().toURL()); } // Add i18n directory to classpath. File databaseDir = new File(directory, "database"); if(databaseDir.exists()){ addURL(databaseDir.toURI().toURL()); } // Add i18n directory to classpath. File i18nDir = new File(directory, "i18n"); if(i18nDir.exists()){ addURL(i18nDir.toURI().toURL()); } // Add web directory to classpath. File webDir = new File(directory, "web"); if(webDir.exists()){ addURL(webDir.toURI().toURL()); } // Add lib directory to classpath. File libDir = new File(directory, "lib"); File[] jars = libDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar") || name.endsWith(".zip"); } }); if (jars != null) { for (int i = 0; i < jars.length; i++) { if (jars[i] != null && jars[i].isFile()) { String jarFileUri = jars[i].toURI().toString() + "!/"; addURLFile(new URL("jar", "", -1, jarFileUri)); } } } } catch (MalformedURLException mue) { Log.error(mue.getMessage(), mue); }
591
447
1,038
<methods>public void <init>(java.net.URL[]) ,public void <init>(java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void close() throws java.io.IOException,public java.net.URL findResource(java.lang.String) ,public Enumeration<java.net.URL> findResources(java.lang.String) throws java.io.IOException,public java.io.InputStream getResourceAsStream(java.lang.String) ,public java.net.URL[] getURLs() ,public static java.net.URLClassLoader newInstance(java.net.URL[]) ,public static java.net.URLClassLoader newInstance(java.net.URL[], java.lang.ClassLoader) <variables>private final java.security.AccessControlContext acc,private WeakHashMap<java.io.Closeable,java.lang.Void> closeables,private final jdk.internal.loader.URLClassPath ucp
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/container/PluginIconServlet.java
PluginIconServlet
doGet
class PluginIconServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { super.init(config); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {<FILL_FUNCTION_BODY>} }
String canonicalName = ParamUtils.getParameter(request, "plugin"); PluginManager pluginManager = XMPPServer.getInstance().getPluginManager(); PluginMetadata metadata = pluginManager.getMetadata( canonicalName ); if (metadata != null) { final URL icon = metadata.getIcon(); if ( icon != null ) { // Clear any empty lines added by the JSP declaration. This is required to show // the image in resin! response.reset(); if ( icon.toExternalForm().toLowerCase().endsWith( ".png" )) { response.setContentType("image/png"); } else if (icon.toExternalForm().toLowerCase().endsWith( ".png" )) { response.setContentType("image/gif"); } try (InputStream in = icon.openStream()) { try (OutputStream ost = response.getOutputStream()) { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) >= 0) { ost.write(buf, 0, len); } ost.flush(); } } catch (IOException ioe) { throw new ServletException(ioe); } } }
82
314
396
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/container/PluginMetadata.java
PluginMetadata
getInstance
class PluginMetadata { /** * Human readable name of the plugin. */ private final String name; /** * Canonical name of the plugin. */ private final String canonicalName; /** * Description of the plugin as specified in plugin.xml. */ private final String description; /** * The version of the plugin. */ private final Version version; /** * Author of the plugin as specified in plugin.xml. */ private final String author; /** * Icon's location of the plugin. */ private final URL icon; /** * Changelog location of the latest version of the plugin. */ private final URL changelog; /** * ReadMe location of the latest version of the plugin. */ private final URL readme; /** * Type of license of the plugin. */ private final String license; /** * Minimum server version (inclusive) required by this plugin as specified in plugin.xml. */ private final Version minServerVersion; /** * Maximum server version (exclusive) required by this plugin as specified in plugin.xml. */ private final Version priorToServerVersion; /** * Minimum Java (specification) version (inclusive) required by this plugin as specified in plugin.xml. */ private final JavaSpecVersion minJavaVersion; /** * Indicates if the plugin supports standard CSRF protection */ private final boolean csrfProtectionEnabled; /** * Constructs a metadata object based on a plugin. * * The plugin must be installed in Openfire. * * @param pluginDir the path of the plugin directory (cannot be null) * @return Metadata for the plugin (never null). */ public static PluginMetadata getInstance( Path pluginDir ) { return new PluginMetadata( PluginMetadataHelper.getName( pluginDir ), PluginMetadataHelper.getCanonicalName( pluginDir ), PluginMetadataHelper.getDescription( pluginDir ), PluginMetadataHelper.getVersion( pluginDir ), PluginMetadataHelper.getAuthor( pluginDir ), PluginMetadataHelper.getIcon( pluginDir ), PluginMetadataHelper.getChangelog( pluginDir ), PluginMetadataHelper.getReadme( pluginDir ), PluginMetadataHelper.getLicense( pluginDir ), PluginMetadataHelper.getMinServerVersion( pluginDir ), PluginMetadataHelper.getPriorToServerVersion( pluginDir ), PluginMetadataHelper.getMinJavaVersion( pluginDir ), PluginMetadataHelper.isCsrfProtectionEnabled( pluginDir ) ); } /** * Constructs a metadata object based on a plugin. * * The plugin must be installed in Openfire. * * @param plugin The plugin (cannot be null) * @return Metadata for the plugin (never null). */ public static PluginMetadata getInstance( Plugin plugin ) {<FILL_FUNCTION_BODY>} public PluginMetadata( String name, String canonicalName, String description, Version version, String author, URL icon, URL changelog, URL readme, String license, Version minServerVersion, Version priorToServerVersion, JavaSpecVersion minJavaVersion, boolean csrfProtectionEnabled) { this.name = name; this.canonicalName = canonicalName; this.description = description; this.version = version; this.author = author; this.icon = icon; this.changelog = changelog; this.readme = readme; this.license = license; this.minServerVersion = minServerVersion; this.priorToServerVersion = priorToServerVersion; this.minJavaVersion = minJavaVersion; this.csrfProtectionEnabled = csrfProtectionEnabled; } public String getName() { return name; } public String getCanonicalName() { return canonicalName; } public String getDescription() { return description; } public Version getVersion() { return version; } public String getAuthor() { return author; } public URL getIcon() { return icon; } public URL getChangelog() { return changelog; } public URL getReadme() { return readme; } public String getLicense() { return license; } public Version getMinServerVersion() { return minServerVersion; } public Version getPriorToServerVersion() { return priorToServerVersion; } public JavaSpecVersion getMinJavaVersion() { return minJavaVersion; } public String getHashCode() { return String.valueOf( hashCode() ); } public boolean isCsrfProtectionEnabled() { return csrfProtectionEnabled; } }
return new PluginMetadata( PluginMetadataHelper.getName( plugin ), PluginMetadataHelper.getCanonicalName( plugin ), PluginMetadataHelper.getDescription( plugin ), PluginMetadataHelper.getVersion( plugin ), PluginMetadataHelper.getAuthor( plugin ), PluginMetadataHelper.getIcon( plugin ), PluginMetadataHelper.getChangelog( plugin ), PluginMetadataHelper.getReadme( plugin ), PluginMetadataHelper.getLicense( plugin ), PluginMetadataHelper.getMinServerVersion( plugin ), PluginMetadataHelper.getPriorToServerVersion( plugin ), PluginMetadataHelper.getMinJavaVersion( plugin ), PluginMetadataHelper.isCsrfProtectionEnabled( plugin ) );
1,305
187
1,492
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/crowd/CrowdAdminProvider.java
CrowdAdminProvider
getAdmins
class CrowdAdminProvider implements AdminProvider { private static final Logger LOG = LoggerFactory.getLogger(CrowdAdminProvider.class); private static final String JIVE_AUTHORIZED_GROUPS = "admin.authorizedGroups"; @Override public List<JID> getAdmins() {<FILL_FUNCTION_BODY>} @Override public void setAdmins(List<JID> admins) { } @Override public boolean isReadOnly() { return true; } }
List<JID> results = new ArrayList<>(); GroupProvider provider = GroupManager.getInstance().getProvider(); String groups = JiveGlobals.getProperty(JIVE_AUTHORIZED_GROUPS); groups = (groups == null || groups.trim().length() == 0) ? "" : groups; JiveGlobals.setProperty(JIVE_AUTHORIZED_GROUPS, groups); // make sure the property is created StringTokenizer tokenizer = new StringTokenizer(groups, ","); while (tokenizer.hasMoreTokens()) { String groupName = tokenizer.nextToken().trim().toLowerCase(); if (groupName.length() > 0) { try { LOG.info("Adding admin users from group: " + groupName); Group group = provider.getGroup(groupName); if (group != null) { results.addAll(group.getMembers()); } } catch (GroupNotFoundException gnfe) { LOG.error("Error when trying to load the members of group:" + groupName, gnfe); } } } if (results.isEmpty()) { // Add default admin account when none was specified results.add(new JID("admin", XMPPServer.getInstance().getServerInfo().getXMPPDomain(), null, true)); } LOG.debug("admin users: {}", results); return results;
144
372
516
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/crowd/CrowdAuthProvider.java
CrowdAuthProvider
authenticate
class CrowdAuthProvider implements AuthProvider { private static final Logger LOG = LoggerFactory.getLogger(CrowdAuthProvider.class); private CrowdManager manager = null; public CrowdAuthProvider() { try { manager = CrowdManager.getInstance(); } catch (Exception e) { LOG.error("Failure to load the Crowd manager", e); } } /** * Returns if the username and password are valid; otherwise this * method throws an UnauthorizedException.<p> * * @param username the username or full JID. * @param password the password * @throws UnauthorizedException if the username and password do * not match any existing user. * @throws ConnectionException it there is a problem connecting to user and group sytem * @throws InternalUnauthenticatedException if there is a problem authentication Openfire itself into the user and group system */ @Override public void authenticate(String username, String password) throws UnauthorizedException, ConnectionException, InternalUnauthenticatedException {<FILL_FUNCTION_BODY>} @Override public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException { throw new UnsupportedOperationException("Retrieve password not supported by this version of authentication provider"); } @Override public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException { throw new UnsupportedOperationException("Setting password not implemented by this version of authentication provider"); } @Override public boolean supportsPasswordRetrieval() { return false; } @Override public boolean isScramSupported() { // TODO Auto-generated method stub return false; } @Override public String getSalt(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public int getIterations(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getServerKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getStoredKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } }
if (manager == null) { throw new ConnectionException("Unable to connect to Crowd"); } if (username == null || password == null || "".equals(password.trim())) { throw new 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 { manager.authenticate(username, password); } catch (RemoteException re) { throw new UnauthorizedException(); }
590
223
813
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/crowd/CrowdProperties.java
CrowdProperties
getCrowdServerUrl
class CrowdProperties { private static final String APPLICATION_NAME = "application.name"; private static final String APPLICATION_PASSWORD = "application.password"; private static final String CROWD_SERVER_URL = "crowd.server.url"; private static final String HTTP_PROXY_HOST = "http.proxy.host"; private static final String HTTP_PROXY_PORT = "http.proxy.port"; private static final String HTTP_PROXY_USERNAME = "http.proxy.username"; private static final String HTTP_PROXY_PASSWORD = "http.proxy.password"; private static final String HTTP_MAX_CONNECTIONS = "http.max.connections"; private static final String HTTP_TIMEOUT = "http.timeout"; private static final String HTTP_SOCKET_TIMEOUT = "http.socket.timeout"; private final Properties props; public CrowdProperties() throws IOException { props = new Properties(); File file = new File(JiveGlobals.getHomePath() + File.separator + "conf" + File.separator + "crowd.properties"); if (!file.exists()) { throw new IOException("The file crowd.properties is missing from Openfire conf folder"); } else { try (final FileInputStream fis = new FileInputStream(file)) { props.load(fis); } catch (IOException ioe) { throw new IOException("Unable to load crowd.properties file", ioe); } } // checking for required info in file if (StringUtils.isBlank(props.getProperty(APPLICATION_NAME)) || StringUtils.isBlank(props.getProperty(APPLICATION_PASSWORD)) || StringUtils.isBlank(props.getProperty(CROWD_SERVER_URL))) { throw new IOException("crowd.properties is missing required information (app name, app passwd, crowd url)"); } } public String getApplicationName() { return props.getProperty(APPLICATION_NAME); } public String getApplicationPassword() { return props.getProperty(APPLICATION_PASSWORD); } public String getCrowdServerUrl() {<FILL_FUNCTION_BODY>} public String getHttpProxyHost() { return props.getProperty(HTTP_PROXY_HOST); } public int getHttpProxyPort() { return getIntegerValue(HTTP_PROXY_PORT, 0); } public String getHttpProxyUsername() { return noNull(props.getProperty(HTTP_PROXY_USERNAME)); } public String getHttpProxyPassword() { return noNull(props.getProperty(HTTP_PROXY_PASSWORD)); } public int getHttpMaxConnections() { return getIntegerValue(HTTP_MAX_CONNECTIONS, 20); } public int getHttpConnectionTimeout() { return getIntegerValue(HTTP_TIMEOUT, 5000); } public int getHttpSocketTimeout() { return getIntegerValue(HTTP_SOCKET_TIMEOUT, 20000); } private int getIntegerValue(String propKey, int defaultValue) { int i; try { i = Integer.parseInt(props.getProperty(propKey)); } catch (NumberFormatException nfe) { i = defaultValue; } return i; } private String noNull(String str) { return (str != null) ? str : ""; } }
String url = props.getProperty(CROWD_SERVER_URL); if (!url.endsWith("/")) { url += "/"; } return url;
911
46
957
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/crowd/CrowdVCardProvider.java
CrowdVCardProvider
loadVCard
class CrowdVCardProvider extends DefaultVCardProvider { private static final Logger LOG = LoggerFactory.getLogger(CrowdVCardProvider.class); private static final String VCARD_TEMPLATE = "<vCard xmlns=\"vcard-temp\"><FN>@displayname@</FN><N><FAMILY>@lastname@</FAMILY><GIVEN>@firstname@</GIVEN></N><NICKNAME>@nickname@</NICKNAME><EMAIL><USERID>@email@</USERID></EMAIL></vCard>"; private static final ConcurrentHashMap<String, Object> MUTEX = new ConcurrentHashMap<>(); /** * @see org.jivesoftware.openfire.vcard.DefaultVCardProvider#loadVCard(java.lang.String) */ @Override public Element loadVCard(String username) {<FILL_FUNCTION_BODY>} /** * @see org.jivesoftware.openfire.vcard.DefaultVCardProvider#createVCard(java.lang.String, org.dom4j.Element) */ @Override public Element createVCard(String username, Element vCardElement) throws AlreadyExistsException { LOG.debug("createvcard: {}", vCardElement.asXML()); return super.createVCard(username, vCardElement); } /** * @see org.jivesoftware.openfire.vcard.DefaultVCardProvider#updateVCard(java.lang.String, org.dom4j.Element) */ @Override public Element updateVCard(String username, Element vCard) throws NotFoundException { // make sure some properties have not been overridden Element nickNameNode = vCard.element("NICKNAME"); Element displayNameNode = vCard.element("FN"); Element nameNode = vCard.element("N"); Element lastNameNode = nameNode.element("FAMILY"); Element firstnameNode = nameNode.element("GIVEN"); Element emailNode = vCard.element("EMAIL").element("USERID"); CrowdUserProvider userProvider = (CrowdUserProvider) UserManager.getUserProvider(); try { User user = userProvider.getCrowdUser(username); nickNameNode.setText(username); displayNameNode.setText(user.displayName); lastNameNode.setText(user.lastName); firstnameNode.setText(user.firstName); emailNode.setText(user.email); } catch (UserNotFoundException unfe) { LOG.error("Unable to find user:" + username + " for updating its vcard", unfe); } LOG.debug("updatevcard: {}", vCard.asXML()); return super.updateVCard(username, vCard); } }
LOG.debug("loadvcard {}", username); if (MUTEX.containsKey(username)) { // preventing looping return null; } try { MUTEX.put(username, username); Element vcard = super.loadVCard(username); if (vcard == null) { CrowdUserProvider userProvider = (CrowdUserProvider) UserManager.getUserProvider(); try { User user = userProvider.getCrowdUser(username); String str = VCARD_TEMPLATE.replace("@displayname@", user.displayName) .replace("@lastname@", user.lastName) .replace("@firstname@", user.firstName) .replace("@email@", user.email) .replace("@nickname@", username); vcard = SAXReaderUtil.readRootElement(str); } catch (UserNotFoundException unfe) { LOG.error("Unable to find user '{}' for loading its vcard", username, unfe); return null; } catch (ExecutionException e) { LOG.error("VCard parsing error", e); return null; } catch (InterruptedException e) { LOG.error("VCard parsing interrupted", e); Thread.currentThread().interrupt(); return null; } LOG.debug(vcard != null ? vcard.asXML() : "vcard is null"); // store this new vcard if (vcard != null) { try { createVCard(username, vcard); } catch (AlreadyExistsException aee) { LOG.error("Unable to create and store a new vcard for user:" + username + "; one already exists", aee); } } } return vcard; } catch (RuntimeException re) { LOG.error("Failure occured when loading a vcard for user:" + username, re); throw re; } finally { MUTEX.remove(username); }
732
524
1,256
<methods>public non-sealed void <init>() ,public Element createVCard(java.lang.String, Element) throws org.jivesoftware.util.AlreadyExistsException,public void deleteVCard(java.lang.String) ,public boolean isReadOnly() ,public Element loadVCard(java.lang.String) ,public Element updateVCard(java.lang.String, Element) throws org.jivesoftware.util.NotFoundException<variables>private static final java.lang.String DELETE_PROPERTIES,private static final java.lang.String INSERT_PROPERTY,private static final java.lang.String LOAD_PROPERTIES,private static final Logger Log,private static final java.lang.String UPDATE_PROPERTIES,private static final Interner<JID> userBaseMutex
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/crowd/jaxb/User.java
User
getOpenfireUser
class User { @XmlAttribute public String name; @XmlElement(name="display-name") public String displayName; @XmlElement(name="first-name") public String firstName; @XmlElement(name="last-name") public String lastName; public String email; private org.jivesoftware.openfire.user.User openfireUser; public synchronized org.jivesoftware.openfire.user.User getOpenfireUser() {<FILL_FUNCTION_BODY>} }
if (openfireUser == null) { openfireUser = new org.jivesoftware.openfire.user.User(name, displayName, email, new Date(), new Date()); } return openfireUser;
151
58
209
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/disco/DiscoItem.java
DiscoItem
getUID
class DiscoItem implements Result { private final JID jid; private final String name; private final String node; private final String action; private final Element element; private volatile String uid = null; public DiscoItem(Element element) { this.element = element; jid = new JID(element.attributeValue("jid")); action = element.attributeValue("action"); name = element.attributeValue("name"); node = element.attributeValue("node"); } /** * Creates a new DiscoItem instance. * * @param jid * specifies the Jabber ID of the item "owner" or location * (required). * @param name * specifies a natural-language name for the item (can be null). * @param node * specifies the particular node associated with the JID of the * item "owner" or location (can be null). * @param action * specifies the action to be taken for the item. * @throws IllegalArgumentException * If a required parameter was null, or if the supplied 'action' * parameter has another value than 'null', "update" or * "remove". */ public DiscoItem(JID jid, String name, String node, String action) { if (jid == null) { throw new IllegalArgumentException("Argument 'jid' cannot be null."); } if (action != null && !action.equals("update") && !action.equals("remove")) { throw new IllegalArgumentException( "Argument 'jid' cannot have any other value than null, \"update\" or \"remove\"."); } this.jid = jid; this.name = name; this.node = node; this.action = action; element = DocumentHelper.createElement("item"); element.addAttribute("jid", jid.toString()); if (action != null) { element.addAttribute("action", action); } if (name != null) { element.addAttribute("name", name); } if (node != null) { element.addAttribute("node", node); } } /** * <p> * Returns the entity's ID. * </p> * * @return the entity's ID. */ public JID getJID() { return jid; } /** * <p> * Returns the node attribute that supplements the 'jid' attribute. A node * is merely something that is associated with a JID and for which the JID * can provide information. * </p> * <p> * Node attributes SHOULD be used only when trying to provide or query * information which is not directly addressable. * </p> * * @return the node attribute that supplements the 'jid' attribute */ public String getNode() { return node; } /** * <p> * Returns the entity's name. The entity's name specifies in * natural-language the name for the item. * </p> * * @return the entity's name. */ public String getName() { return name; } /** * <p> * Returns the action (i.e. update or remove) that indicates what must be * done with this item or null if none. An "update" action requests the * server to create or update the item. Whilst a "remove" action requests to * remove the item. * </p> * * @return the action (i.e. update or remove) that indicates what must be * done with this item or null if none. */ public String getAction() { return action; } /** * Returns a dom4j element that represents this DiscoItem object. * * @return element representing this object. */ public Element getElement() { return element; } /* * (non-Javadoc) * * @see org.jivesoftware.util.resultsetmanager.Result#getUID() */ @Override public String getUID() {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return getUID().hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof DiscoItem && getUID().equals(((DiscoItem)obj).getUID()); } @Override public String toString() { return element.asXML(); } }
if (uid == null) { synchronized(this) { if (uid == null) { final StringBuilder sb = new StringBuilder(jid.toString()); if (name != null) { sb.append(name); } if (node != null) { sb.append(node); } if (action != null) { sb.append(action); } uid = sb.toString(); } } } return uid;
1,208
132
1,340
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/entitycaps/EntityCapabilities.java
EntityCapabilities
getCachedSize
class EntityCapabilities implements Cacheable, Externalizable { /** * Identities included in these entity capabilities. */ private Set<String> identities = new HashSet<>(); /** * Features included in these entity capabilities. */ private Set<String> features = new HashSet<>(); /** * Hash string that corresponds to the entity capabilities. To be * regenerated and used for discovering potential poisoning of entity * capabilities information. */ private String verAttribute; /** * The hash algorithm that was used to create the hash string. */ private String hashAttribute; /** * Adds an identity to the entity capabilities. * * @param identity the identity * @return true if the entity capabilities did not already include the * identity */ boolean addIdentity(String identity) { return identities.add(identity); } /** * Adds a feature to the entity capabilities. * * @param feature the feature * @return true if the entity capabilities did not already include the * feature */ boolean addFeature(String feature) { return features.add(feature); } /** * Returns the identities of the entity capabilities. * * @return all identities. */ public Set<String> getIdentities() { return identities; } /** * Determines whether or not a given identity is included in these entity * capabilities. * * @param category the category of the identity * @param type the type of the identity * @return true if identity is included, false if not */ public boolean containsIdentity(String category, String type) { return identities.contains(category + "/" + type); } /** * Returns the features of the entity capabilities. * * @return all features. */ public Set<String> getFeatures() { return features; } /** * Determines whether or not a given feature is included in these entity * capabilities. * * @param feature the feature * @return true if feature is included, false if not */ public boolean containsFeature(String feature) { return features.contains(feature); } void setVerAttribute(String verAttribute) { this.verAttribute = verAttribute; } String getVerAttribute() { return this.verAttribute; } void setHashAttribute(String hashAttribute) { this.hashAttribute = hashAttribute; } String getHashAttribute() { return this.hashAttribute; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { ExternalizableUtil.getInstance().readStrings(in, identities); ExternalizableUtil.getInstance().readStrings(in, features); verAttribute = ExternalizableUtil.getInstance().readSafeUTF(in); } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeStrings(out, identities); ExternalizableUtil.getInstance().writeStrings(out, features); ExternalizableUtil.getInstance().writeSafeUTF(out, verAttribute); } @Override public int getCachedSize() throws CannotCalculateSizeException {<FILL_FUNCTION_BODY>} }
int size = CacheSizes.sizeOfCollection(identities); size += CacheSizes.sizeOfCollection(features); size += CacheSizes.sizeOfString(verAttribute); return size;
868
53
921
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/event/GroupEventDispatcher.java
GroupEventDispatcher
dispatchEvent
class GroupEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(GroupEventDispatcher.class); private static List<GroupEventListener> listeners = new CopyOnWriteArrayList<>(); private GroupEventDispatcher() { // Not instantiable. } /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(GroupEventListener listener) { if (listener == null) { throw new NullPointerException(); } listeners.add(listener); } /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(GroupEventListener listener) { listeners.remove(listener); } /** * Dispatches an event to all listeners. * * @param group the group. * @param eventType the event type. * @param params event parameters. */ public static void dispatchEvent(Group group, EventType eventType, Map params) {<FILL_FUNCTION_BODY>} /** * Represents valid event types. */ public enum EventType { /** * A new group was created. */ group_created, /** * A group is about to be deleted. Note that this event is fired before * a group is actually deleted. This allows for referential cleanup * before the group is gone. */ group_deleting, /** * The name, description, or extended property of a group was changed. */ group_modified, /** * A member was added to a group. */ member_added, /** * A member was removed from a group. */ member_removed, /** * An administrator was added to a group. */ admin_added, /** * An administrator was removed from a group. */ admin_removed; } }
for (GroupEventListener listener : listeners) { try { switch (eventType) { case group_created: { listener.groupCreated(group, params); break; } case group_deleting: { listener.groupDeleting(group, params); break; } case member_added: { listener.memberAdded(group, params); break; } case member_removed: { listener.memberRemoved(group, params); break; } case admin_added: { listener.adminAdded(group, params); break; } case admin_removed: { listener.adminRemoved(group, params); break; } case group_modified: { listener.groupModified(group, params); break; } default: break; } } catch (Exception e) { Log.error(e.getMessage(), e); } }
525
258
783
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/event/ServerSessionEventDispatcher.java
ServerSessionEventDispatcher
addListener
class ServerSessionEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(ServerSessionEventDispatcher.class); private static List<ServerSessionEventListener> listeners = new CopyOnWriteArrayList<>(); private ServerSessionEventDispatcher() { // Not instantiable. } /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(ServerSessionEventListener listener) {<FILL_FUNCTION_BODY>} /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(ServerSessionEventListener listener) { listeners.remove(listener); } /** * Dispatches an event to all listeners. * * @param session the session. * @param eventType the event type. */ public static void dispatchEvent(Session session, EventType eventType) { for (ServerSessionEventListener listener : listeners) { try { switch (eventType) { case session_created: { listener.sessionCreated(session); break; } case session_destroyed: { listener.sessionDestroyed(session); break; } default: break; } } catch (Exception e) { Log.error(e.getMessage(), e); } } } /** * Represents valid event types. */ public enum EventType { /** * A session was created. */ session_created, /** * A session was destroyed */ session_destroyed, } }
if (listener == null) { throw new NullPointerException(); } listeners.add(listener);
436
33
469
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/event/SessionEventDispatcher.java
SessionEventDispatcher
dispatchEvent
class SessionEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(SessionEventDispatcher.class); private static List<SessionEventListener> listeners = new CopyOnWriteArrayList<>(); private SessionEventDispatcher() { // Not instantiable. } /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(SessionEventListener listener) { if (listener == null) { throw new NullPointerException(); } listeners.add(listener); } /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(SessionEventListener listener) { listeners.remove(listener); } /** * Dispatches an event to all listeners. * * @param session the session. * @param eventType the event type. */ public static void dispatchEvent(Session session, EventType eventType) {<FILL_FUNCTION_BODY>} /** * Represents valid event types. */ public enum EventType { /** * A session was created. */ session_created, /** * A session was destroyed */ session_destroyed, /** * An anonymous session was created. */ anonymous_session_created, /** * A anonymous session was destroyed */ anonymous_session_destroyed, /** * A resource was bound to the session. */ resource_bound } }
for (SessionEventListener listener : listeners) { try { switch (eventType) { case session_created: { listener.sessionCreated(session); break; } case session_destroyed: { listener.sessionDestroyed(session); break; } case anonymous_session_created: { listener.anonymousSessionCreated(session); break; } case anonymous_session_destroyed: { listener.anonymousSessionDestroyed(session); break; } case resource_bound: { listener.resourceBound(session); break; } default: break; } } catch (Exception e) { Log.error(e.getMessage(), e); } }
417
200
617
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/event/UserEventDispatcher.java
UserEventDispatcher
dispatchEvent
class UserEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(UserEventDispatcher.class); private static List<UserEventListener> listeners = new CopyOnWriteArrayList<>(); private UserEventDispatcher() { // Not instantiable. } /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(UserEventListener listener) { if (listener == null) { throw new NullPointerException(); } listeners.add(listener); } /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(UserEventListener listener) { listeners.remove(listener); } /** * Dispatches an event to all listeners. * * @param user the user. * @param eventType the event type. * @param params event parameters. */ public static void dispatchEvent(User user, EventType eventType, Map<String,Object> params) {<FILL_FUNCTION_BODY>} /** * Represents valid event types. */ public enum EventType { /** * A new user was created. */ user_created, /** * A user is about to be deleted. Note that this event is fired before * a user is actually deleted. This allows for referential cleanup * before the user is gone. */ user_deleting, /** * The name, email, password, or extended property of a user was changed. */ user_modified, } }
for (UserEventListener listener : listeners) { try { switch (eventType) { case user_created: { listener.userCreated(user, params); break; } case user_deleting: { listener.userDeleting(user, params); break; } case user_modified: { listener.userModified(user, params); break; } default: break; } } catch (Exception e) { Log.error(e.getMessage(), e); } }
434
150
584
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/filetransfer/DefaultFileTransferManager.java
DefaultFileTransferManager
createFileTransfer
class DefaultFileTransferManager extends BasicModule implements FileTransferManager { private static final Logger Log = LoggerFactory.getLogger( DefaultFileTransferManager.class ); private static final String CACHE_NAME = "File Transfer Cache"; private final Cache<String, FileTransfer> fileTransferMap; private final List<FileTransferEventListener> eventListeners = new ArrayList<>(); /** * Default constructor creates the cache. */ public DefaultFileTransferManager() { super("File Transfer Manager"); fileTransferMap = CacheFactory.createCache(CACHE_NAME); InterceptorManager.getInstance().addInterceptor(new MetaFileTransferInterceptor()); } /** * Returns true if the proxy transfer should be matched to an existing file transfer * in the system. * * @return Returns true if the proxy transfer should be matched to an existing file * transfer in the system. */ public boolean isMatchProxyTransfer() { return JiveGlobals.getBooleanProperty("xmpp.proxy.transfer.required", true); } protected void cacheFileTransfer(String key, FileTransfer transfer) { fileTransferMap.put(key, transfer); } protected FileTransfer retrieveFileTransfer(String key) { return fileTransferMap.get(key); } protected static Element getChildElement(Element element, String namespace) { //noinspection unchecked List<Element> elements = element.elements(); if (elements.isEmpty()) { return null; } for (Element childElement : elements) { String childNamespace = childElement.getNamespaceURI(); if (namespace.equals(childNamespace)) { return childElement; } } return null; } @Override public boolean acceptIncomingFileTransferRequest(FileTransfer transfer) throws FileTransferRejectedException { if(transfer != null) { fireFileTransferStart( transfer.getSessionID(), false ); String streamID = transfer.getSessionID(); JID from = new JID(transfer.getInitiator()); JID to = new JID(transfer.getTarget()); cacheFileTransfer(ProxyConnectionManager.createDigest(streamID, from, to), transfer); return true; } return false; } @Override public void registerProxyTransfer(String transferDigest, ProxyTransfer proxyTransfer) throws UnauthorizedException { FileTransfer transfer = retrieveFileTransfer(transferDigest); if (isMatchProxyTransfer() && transfer == null) { throw new UnauthorizedException("Unable to match proxy transfer with a file transfer"); } else if (transfer == null) { return; } transfer.setProgress(proxyTransfer); cacheFileTransfer(transferDigest, transfer); } private FileTransfer createFileTransfer(JID from, JID to, Element siElement) {<FILL_FUNCTION_BODY>} @Override public void addListener( FileTransferEventListener eventListener ) { eventListeners.add( eventListener ); } @Override public void removeListener( FileTransferEventListener eventListener ) { eventListeners.remove( eventListener ); } @Override public void fireFileTransferStart( String sid, boolean isReady ) throws FileTransferRejectedException { final FileTransfer transfer = fileTransferMap.get( sid ); for ( FileTransferEventListener listener : eventListeners ) { try { listener.fileTransferStart( transfer, isReady ); } catch ( FileTransferRejectedException ex ) { Log.debug( "Listener '{}' rejected file transfer '{}'.", listener, transfer ); throw ex; } catch ( Exception ex ) { Log.warn( "Listener '{}' threw exception when being informed of file transfer complete for transfer '{}'.", listener, transfer, ex ); } } } @Override public void fireFileTransferCompleted( String sid, boolean wasSuccessful ) { final FileTransfer transfer = fileTransferMap.get( sid ); for ( FileTransferEventListener listener : eventListeners ) { try { listener.fileTransferComplete( transfer, wasSuccessful ); } catch ( Exception ex ) { Log.warn( "Listener '{}' threw exception when being informed of file transfer complete for transfer '{}'.", listener, transfer, ex ); } } } /** * Interceptor to grab and validate file transfer meta information. */ private class MetaFileTransferInterceptor implements PacketInterceptor { @Override public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { // We only want packets received by the server if (!processed && incoming && packet instanceof IQ) { IQ iq = (IQ) packet; Element childElement = iq.getChildElement(); if(childElement == null) { return; } String namespace = childElement.getNamespaceURI(); String profile = childElement.attributeValue("profile"); // Check that the SI is about file transfer and try creating a file transfer if (NAMESPACE_SI.equals(namespace) && NAMESPACE_SI_FILETRANSFER.equals(profile)) { // If this is a set, check the feature offer if (iq.getType().equals(IQ.Type.set)) { JID from = iq.getFrom(); JID to = iq.getTo(); FileTransfer transfer = createFileTransfer(from, to, childElement); try { if (transfer == null || !acceptIncomingFileTransferRequest(transfer)) { throw new PacketRejectedException(); } } catch (FileTransferRejectedException e) { throw new PacketRejectedException(e); } } } } } } }
String streamID = siElement.attributeValue("id"); String mimeType = siElement.attributeValue("mime-type"); // Check profile, the only type we deal with currently is file transfer Element fileTransferElement = getChildElement(siElement, NAMESPACE_SI_FILETRANSFER); // Not valid form, reject if (fileTransferElement == null) { return null; } String fileName = fileTransferElement.attributeValue("name"); String sizeString = fileTransferElement.attributeValue("size"); if (fileName == null || sizeString == null) { return null; } long size; try { size = Long.parseLong(sizeString); } catch (Exception ex) { return null; } return new FileTransfer(from.toString(), to.toString(), streamID, fileName, size, mimeType);
1,565
231
1,796
<methods>public void <init>(java.lang.String) ,public void destroy() ,public java.lang.String getName() ,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public void start() throws java.lang.IllegalStateException,public void stop() <variables>private java.lang.String name
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/filetransfer/FileTransfer.java
FileTransfer
getCachedSize
class FileTransfer implements Cacheable, Serializable { private String sessionID; private String initiator; private String target; private String fileName; private long fileSize; private String mimeType; private FileTransferProgress progress; public FileTransfer(String initiator, String target, String sessionID, String fileName, long fileSize, String mimeType) { this.initiator = initiator; this.target = target; this.sessionID = sessionID; this.fileName = fileName; this.fileSize = fileSize; this.mimeType = mimeType; } public String getSessionID() { return sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public String getInitiator() { return initiator; } public void setInitiator(String initiator) { this.initiator = initiator; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public long getFileSize() { return fileSize; } public void setFileSize(long fileSize) { this.fileSize = fileSize; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public FileTransferProgress getProgress() { return progress; } public void setProgress(FileTransferProgress progress) { this.progress = progress; } @Override public int getCachedSize() {<FILL_FUNCTION_BODY>} }
// Approximate the size of the object in bytes by calculating the size // of each field. int size = 0; size += CacheSizes.sizeOfObject(); // overhead of object size += CacheSizes.sizeOfString(initiator); size += CacheSizes.sizeOfString(target); size += CacheSizes.sizeOfString(sessionID); size += CacheSizes.sizeOfString(fileName); size += CacheSizes.sizeOfString(mimeType); size += CacheSizes.sizeOfLong(); // File size size += CacheSizes.sizeOfObject(); // Progress return size;
522
162
684
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/filetransfer/proxy/DefaultProxyTransfer.java
DefaultProxyTransfer
doTransfer
class DefaultProxyTransfer implements ProxyTransfer { private static final Logger Log = LoggerFactory.getLogger(DefaultProxyTransfer.class); private String initiator; private InputStream inputStream; private OutputStream outputStream; private String target; private String transferDigest; private String streamID; private Future<?> future; private long amountWritten; private static final int BUFFER_SIZE = 8000; public DefaultProxyTransfer() { } @Override public String getInitiator() { return initiator; } @Override public void setInitiator(String initiator) { this.initiator = initiator; } @Override public InputStream getInputStream() { return inputStream; } @Override public void setInputStream(InputStream initiatorInputStream) { this.inputStream = initiatorInputStream; } @Override public OutputStream getOutputStream() { return outputStream; } @Override public void setOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } @Override public String getTarget() { return target; } @Override public void setTarget(String target) { this.target = target; } @Override public String getTransferDigest() { return transferDigest; } @Override public void setTransferDigest(String transferDigest) { this.transferDigest = transferDigest; } @Override public String getSessionID() { return streamID; } @Override public void setSessionID(String streamID) { this.streamID = streamID; } @Override public boolean isActivatable() { return ((inputStream != null) && (outputStream != null)); } @Override public synchronized void setTransferFuture(Future<?> future) { if(this.future != null) { throw new IllegalStateException("Transfer is already in progress, or has completed."); } this.future = future; } @Override public long getAmountTransferred() { return amountWritten; } @Override public void doTransfer() throws IOException {<FILL_FUNCTION_BODY>} @Override public int getCachedSize() { // Approximate the size of the object in bytes by calculating the size // of each field. int size = 0; size += CacheSizes.sizeOfObject(); // overhead of object size += CacheSizes.sizeOfString(initiator); size += CacheSizes.sizeOfString(target); size += CacheSizes.sizeOfString(transferDigest); size += CacheSizes.sizeOfString(streamID); size += CacheSizes.sizeOfLong(); // Amount written size += CacheSizes.sizeOfObject(); // Initiatior Socket size += CacheSizes.sizeOfObject(); // Target socket size += CacheSizes.sizeOfObject(); // Future return size; } }
if (!isActivatable()) { throw new IOException("Transfer missing party"); } try (InputStream in = getInputStream()) { try (OutputStream out = new ProxyOutputStream(getOutputStream())) { final byte[] b = new byte[BUFFER_SIZE]; int count = 0; amountWritten = 0; do { // write to the output stream out.write(b, 0, count); amountWritten += count; // read more bytes from the input stream count = in.read(b); } while (count >= 0); } }
822
156
978
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/group/ConcurrentGroupList.java
ConcurrentGroupList
syncGroups
class ConcurrentGroupList<T> extends CopyOnWriteArrayList<T> implements GroupAwareList<T> { private static final long serialVersionUID = 7735849143650412115L; // This set is used to optimize group operations within this list. // We only populate this set when it's needed to dereference the // groups in the base list, but once it exists we keep it in sync // via the various add/remove operations. // NOTE: added volatile keyword for double-check idiom (lazy instantiation) private volatile transient Set<String> knownGroupNamesInList; public ConcurrentGroupList() { super(); } public ConcurrentGroupList(Collection<? extends T> c) { super(c); } /** * Returns true if the list contains the given JID. If the JID * is not found in the list, search the list for groups and look * for the JID in each of the corresponding groups. * * @param value The target, presumably a JID * @return True if the target is in the list, or in any groups in the list */ @Override public boolean includes(Object value) { boolean found = false; if (contains(value)) { found = true; } else if (value instanceof JID) { JID target = (JID) value; Iterator<Group> iterator = getGroups().iterator(); while (!found && iterator.hasNext()) { found = iterator.next().isUser(target); } } return found; } /** * Returns the groups that are implied (resolvable) from the items in the list. * * @return A Set containing the groups in the list */ @Override public Set<Group> getGroups() { Set<Group> result = new HashSet<>(); for (String groupName : getKnownGroupNamesInList()) { result.add(Group.resolveFrom(groupName)); } return result; } /** * Accessor uses the "double-check idiom" (j2se 5.0+) for proper lazy instantiation. * Additionally, the set is not cached until there is at least one group in the list. * * @return the known group names among the items in the list */ private Set<String> getKnownGroupNamesInList() { Set<String> result = knownGroupNamesInList; if (result == null) { synchronized(this) { result = knownGroupNamesInList; if (result == null) { result = new HashSet<>(); // add all the groups into the group set for (T listItem : this) { Group group = Group.resolveFrom(listItem); if (group != null) { result.add(group.getName()); } } knownGroupNamesInList = result.isEmpty() ? null : result; } } } return result; } /** * This method is called from several of the mutators to keep * the group set in sync with the full list. * * @param item The item to be added or removed if it is in the group set * @param addOrRemove True to add, false to remove * @return true if the given item is a group */ private synchronized boolean syncGroups(Object item, boolean addOrRemove) {<FILL_FUNCTION_BODY>} // below are overrides for the various mutators @Override public T set(int index, T element) { T result = super.set(index, element); syncGroups(element, ADD); return result; } @Override public boolean add(T e) { boolean result = super.add(e); syncGroups(e, ADD); return result; } @Override public void add(int index, T element) { super.add(index, element); syncGroups(element, ADD); } @Override public T remove(int index) { T result = super.remove(index); syncGroups(result, REMOVE); return result; } @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { syncGroups(o, REMOVE); } return removed; } @Override public boolean addIfAbsent(T e) { boolean added = super.addIfAbsent(e); if (added) { syncGroups(e, ADD); } return added; } @Override public boolean removeAll(Collection<?> c) { boolean changed = super.removeAll(c); if (changed) { // drop the transient set, will be rebuilt when/if needed synchronized(this) { knownGroupNamesInList = null; } } return changed; } @Override public boolean retainAll(Collection<?> c) { boolean changed = super.retainAll(c); if (changed) { // drop the transient set, will be rebuilt when/if needed synchronized(this) { knownGroupNamesInList = null; } } return changed; } @Override public int addAllAbsent(Collection<? extends T> c) { int added = super.addAllAbsent(c); if (added > 0) { // drop the transient set, will be rebuilt when/if needed synchronized(this) { knownGroupNamesInList = null; } } return added; } @Override public void clear() { super.clear(); synchronized(this) { knownGroupNamesInList = null; } } @Override public boolean addAll(Collection<? extends T> c) { boolean changed = super.addAll(c); if (changed) { // drop the transient set, will be rebuilt when/if needed synchronized(this) { knownGroupNamesInList = null; } } return changed; } @Override public boolean addAll(int index, Collection<? extends T> c) { boolean changed = super.addAll(index, c); if (changed) { // drop the transient set, will be rebuilt when/if needed synchronized(this) { knownGroupNamesInList = null; } } return changed; } private static final boolean ADD = true; private static final boolean REMOVE = false; }
boolean result = false; // only sync if the group list has been instantiated if (knownGroupNamesInList != null) { Group group = Group.resolveFrom(item); if (group != null) { result = true; if (addOrRemove == ADD) { knownGroupNamesInList.add(group.getName()); } else if (addOrRemove == REMOVE) { knownGroupNamesInList.remove(group.getName()); if (knownGroupNamesInList.isEmpty()) { knownGroupNamesInList = null; } } } } return result;
1,712
159
1,871
<methods>public void <init>() ,public void <init>(Collection<? extends T>) ,public void <init>(T[]) ,public boolean add(T) ,public void add(int, T) ,public boolean addAll(Collection<? extends T>) ,public boolean addAll(int, Collection<? extends T>) ,public int addAllAbsent(Collection<? extends T>) ,public boolean addIfAbsent(T) ,public void clear() ,public java.lang.Object clone() ,public boolean contains(java.lang.Object) ,public boolean containsAll(Collection<?>) ,public boolean equals(java.lang.Object) ,public void forEach(Consumer<? super T>) ,public T get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public int indexOf(T, int) ,public boolean isEmpty() ,public Iterator<T> iterator() ,public int lastIndexOf(java.lang.Object) ,public int lastIndexOf(T, int) ,public ListIterator<T> listIterator() ,public ListIterator<T> listIterator(int) ,public T remove(int) ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super T>) ,public void replaceAll(UnaryOperator<T>) ,public boolean retainAll(Collection<?>) ,public T set(int, T) ,public int size() ,public void sort(Comparator<? super T>) ,public Spliterator<T> spliterator() ,public List<T> subList(int, int) ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>private volatile transient java.lang.Object[] array,final transient java.lang.Object lock,private static final long serialVersionUID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/group/DefaultGroupPropertyMap.java
EntryWrapper
updateProperty
class EntryWrapper<E> implements Entry<K,V> { private final Entry<K,V> delegate; /** * Sole constructor; requires a wrapped {@link Map.Entry} for delegation * @param delegate The corresponding entry from the map */ public EntryWrapper(Entry<K,V> delegate) { this.delegate = delegate; } /** * Delegated to corresponding method in the backing {@link Map.Entry} */ @Override public K getKey() { return delegate.getKey(); } /** * Delegated to corresponding method in the backing {@link Map.Entry} */ @Override public V getValue() { return delegate.getValue(); } /** * Set the value of the property corresponding to this entry. This * method also updates the database as needed depending on the new * property value. A null value will cause the property to be deleted * from the database. * * @param value The new property value * @return The old value of the corresponding property */ @Override public V setValue(V value) { V oldValue = delegate.setValue(value); K key = delegate.getKey(); if (key instanceof String) { if (value instanceof String) { if (oldValue == null) { insertProperty((String) key, (String) value); } else if (!value.equals(oldValue)) { updateProperty((String)key,(String)value, (String)oldValue); } } else { deleteProperty((String)key, (oldValue instanceof String) ? (String)oldValue : null); } } return oldValue; } } /** * Persist a new group property to the database for the current group * * @param key Property name * @param value Property value */ private synchronized void insertProperty(String key, String value) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(INSERT_PROPERTY); pstmt.setString(1, group.getName()); pstmt.setString(2, key); pstmt.setString(3, value); pstmt.executeUpdate(); } catch (SQLException e) { logger.error(e.getMessage(), e); } finally { DbConnectionManager.closeConnection(pstmt, con); } // Clean up caches. DefaultGroupProvider.sharedGroupMetaCache.clear(); GroupManager.getInstance().propertyAddedPostProcess(group, key); } /** * Update the value of an existing group property for the current group * * @param key Property name * @param value Property value * @param originalValue Original property value */ private synchronized void updateProperty(String key, String value, String originalValue) {<FILL_FUNCTION_BODY>
Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(UPDATE_PROPERTY); pstmt.setString(1, value); pstmt.setString(2, key); pstmt.setString(3, group.getName()); pstmt.executeUpdate(); } catch (SQLException e) { logger.error(e.getMessage(), e); } finally { DbConnectionManager.closeConnection(pstmt, con); } // Clean up caches. DefaultGroupProvider.sharedGroupMetaCache.clear(); GroupManager.getInstance().propertyModifiedPostProcess(group, key, originalValue);
766
189
955
<methods>public non-sealed void <init>() ,public abstract V put(K, V, boolean) <variables>private static final long serialVersionUID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/group/GroupCollection.java
GroupIterator
getNextElement
class GroupIterator implements Iterator<Group> { private int currentIndex = -1; private Group nextElement = null; @Override public boolean hasNext() { // If we are at the end of the list, there can't be any more elements // to iterate through. if (currentIndex + 1 >= elements.length && nextElement == null) { return false; } // Otherwise, see if nextElement is null. If so, try to load the next // element to make sure it exists. if (nextElement == null) { nextElement = getNextElement(); if (nextElement == null) { return false; } } return true; } @Override public Group next() throws java.util.NoSuchElementException { Group element; if (nextElement != null) { element = nextElement; nextElement = null; } else { element = getNextElement(); if (element == null) { throw new NoSuchElementException(); } } return element; } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Returns the next available element, or null if there are no more elements to return. * * @return the next available element. */ private Group getNextElement() {<FILL_FUNCTION_BODY>} }
while (currentIndex + 1 < elements.length) { currentIndex++; Group element = null; try { element = GroupManager.getInstance().getGroup(elements[currentIndex]); } catch (GroupNotFoundException unfe) { Log.debug("Group not for element '{}' not found.", elements[currentIndex], unfe); } if (element != null) { return element; } } return null;
369
118
487
<methods>public boolean add(org.jivesoftware.openfire.group.Group) ,public boolean addAll(Collection<? extends org.jivesoftware.openfire.group.Group>) ,public void clear() ,public boolean contains(java.lang.Object) ,public boolean containsAll(Collection<?>) ,public boolean isEmpty() ,public abstract Iterator<org.jivesoftware.openfire.group.Group> iterator() ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean retainAll(Collection<?>) ,public abstract int size() ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/group/GroupJID.java
GroupJID
isGroup
class GroupJID extends JID { private static final Logger Log = LoggerFactory.getLogger(GroupJID.class); private static final long serialVersionUID = 5681300465012974014L; private transient String groupName; /** * Construct a JID representing a Group. * * @param name A group name for the local domain */ public GroupJID(String name) { super(encodeNode(name), XMPPServer.getInstance().getServerInfo().getXMPPDomain(), StringUtils.hash(name), true); groupName = name; } /** * Construct a JID representing a Group from a regular JID. This constructor is * private because it is used only from within this class after the source JID * has been validated. * * @param source A full JID representing a group * @see GroupJID#fromString */ private GroupJID(JID source) { // skip stringprep for the new group JID, since it has already been parsed super(source.getNode(), source.getDomain(), source.getResource(), true); } /** * Returns the group name corresponding to this JID. * * @return The name for the corresponding group */ public String getGroupName() { // lazy instantiation if (groupName == null) { groupName = decodeNode(getNode()); } return groupName; } /** * Override the base class implementation to retain the resource * identifier for group JIDs. * * @return This JID, as a group JID */ @Override public JID asBareJID() { return this; } /** * Override the base class implementation to retain the resource * identifier for group JIDs. * * @return The full JID rendered as a string */ @Override public String toBareJID() { return this.toString(); } @Override public int compareTo(JID jid) { // Comparison order is domain, node, resource. int compare = getDomain().compareTo(jid.getDomain()); if (compare == 0) { String otherNode = jid.getNode(); compare = otherNode == null ? 1 : getGroupName().compareTo(otherNode); } if (compare == 0) { compare = jid.getResource() == null ? 0 : -1; } return compare; } /** * Encode the given group name in base32hex (UTF-8). This encoding * is valid according to the nodeprep profile of stringprep * (RFC6122, Appendix A) and needs no further escaping. * * @param name A group name * @return The encoded group name */ private static String encodeNode(String name) { return StringUtils.encodeBase32(name); } /** * Decode the given group name from base32hex (UTF-8). * * @param node A group name, encoded as base32hex * @return The group name */ private static String decodeNode(String node) { return new String(StringUtils.decodeBase32(node), StandardCharsets.UTF_8); } /** * Check a JID to determine whether it represents a group. If the given * JID is an instance of this class, it is a group JID. Otherwise, * calculate the hash to determine whether the JID can be resolved to * a group. * * @param jid A JID, possibly representing a group * @return true if the given jid represents a group in the local domain */ public static boolean isGroup(JID jid) { try { return isGroup(jid, false); } catch (GroupNotFoundException gnfe) { // should not happen because we do not validate the group exists Log.error("Unexpected group validation", gnfe); return false; } } /** * Check a JID to determine whether it represents a group. If the given * JID is an instance of this class, it is a group JID. Otherwise, * calculate the hash to determine whether the JID can be resolved to * a group. This method also optionally validates that the corresponding * group actually exists in the local domain. * * @param jid A JID, possibly representing a group * @param groupMustExist If true, validate that the corresponding group actually exists * @return true if the given jid represents a group in the local domain * @throws GroupNotFoundException The JID represents a group, but the group does not exist */ public static boolean isGroup(JID jid, boolean groupMustExist) throws GroupNotFoundException {<FILL_FUNCTION_BODY>} /** * Returns a JID from the given JID. If the JID represents a group, * returns an instance of this class, otherwise returns the given JID. * * @param jid A JID, possibly representing a group * @return A new GroupJID if the given JID represents a group, or the given JID */ public static JID fromJID(JID jid) { if (jid instanceof GroupJID || jid.getResource() == null || jid.getNode() == null) { return jid; } else { return (isGroup(jid)) ? new GroupJID(jid) : jid; } } /** * Creates a JID from the given string. If the string represents a group, * return an instance of this class, otherwise returns a regular JID. * * @param jid A JID, possibly representing a group * @return A JID with a type appropriate to its content * @throws IllegalArgumentException the given string is not a valid JID */ public static JID fromString(String jid) { Log.trace("Parsing JID from string: {}", jid); return fromJID(new JID(jid)); } }
boolean isGroup = false; String groupName = null, node = jid.getNode(); if (node != null) { isGroup = (jid instanceof GroupJID) ? true : jid.getResource() != null && StringUtils.isBase32(node) && StringUtils.hash(groupName = decodeNode(node)).equals(jid.getResource()); if (isGroup && groupMustExist) { Log.debug("Validating group: {}", jid); if (XMPPServer.getInstance().isLocal(jid)) { GroupManager.getInstance().getGroup(groupName); } else { isGroup = false; // not in the local domain } } } return isGroup;
1,584
199
1,783
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/DirectedPresence.java
DirectedPresence
readExternal
class DirectedPresence implements Externalizable { /** * ID of the node that received the request to send a directed presence. This is the * node ID that hosts the sender. */ private byte[] nodeID; /** * Full JID of the entity that received the directed presence. * E.g.: paul@js.com/Spark or conference.js.com */ private JID handler; /** * List of JIDs with the TO value of the directed presences. * E.g.: paul@js.com or room1@conference.js.com */ private Set<String> receivers = new HashSet<>(); public DirectedPresence() { } public DirectedPresence(JID handlerJID) { this.handler = handlerJID; this.nodeID = XMPPServer.getInstance().getNodeID().toByteArray(); } public byte[] getNodeID() { return nodeID; } public JID getHandler() { return handler; } public Set<String> getReceivers() { return receivers; } public void addReceiver(String receiver) { receivers.add(receiver); } public void removeReceiver(String receiver) { receivers.remove(receiver); } public boolean isEmpty() { return receivers.isEmpty(); } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeByteArray(out, nodeID); ExternalizableUtil.getInstance().writeSerializable(out, handler); ExternalizableUtil.getInstance().writeStrings(out, receivers); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
nodeID = ExternalizableUtil.getInstance().readByteArray(in); handler = (JID) ExternalizableUtil.getInstance().readSerializable(in); ExternalizableUtil.getInstance().readStrings(in, receivers);
476
60
536
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQBindHandler.java
IQBindHandler
handleIQ
class IQBindHandler extends IQHandler { private static final Logger Log = LoggerFactory.getLogger(IQBindHandler.class); private IQHandlerInfo info; private String serverName; private RoutingTable routingTable; public IQBindHandler() { super("Resource Binding handler"); info = new IQHandlerInfo("bind", "urn:ietf:params:xml:ns:xmpp-bind"); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override public void initialize(XMPPServer server) { super.initialize(server); routingTable = server.getRoutingTable(); serverName = server.getServerInfo().getXMPPDomain(); } @Override public IQHandlerInfo getInfo() { return info; } }
LocalClientSession session = (LocalClientSession) sessionManager.getSession(packet.getFrom()); // If no session was found then answer an error (if possible) if (session == null) { Log.error("Error during resource binding. Session not found in " + sessionManager.getPreAuthenticatedKeys() + " for key " + packet.getFrom()); // This error packet will probably won't make it through IQ reply = IQ.createResultIQ(packet); reply.setChildElement(packet.getChildElement().createCopy()); reply.setError(PacketError.Condition.internal_server_error); return reply; } IQ reply = IQ.createResultIQ(packet); reply.setFrom((String)null); // OF-2001: IQ bind requests are made from entities that have no resource yet. Responding with a 'from' value confuses many clients. Element child = reply.setChildElement("bind", "urn:ietf:params:xml:ns:xmpp-bind"); // Check if the client specified a desired resource String resource = packet.getChildElement().elementTextTrim("resource"); if (resource == null || resource.length() == 0) { // None was defined so use the random generated resource resource = session.getAddress().getResource(); } else { // Check that the desired resource is valid try { resource = JID.resourceprep(resource); } catch (IllegalArgumentException e) { reply.setChildElement(packet.getChildElement().createCopy()); reply.setError(PacketError.Condition.jid_malformed); // Send the error directly since a route does not exist at this point. session.process(reply); return null; } } // Get the token that was generated during the SASL authentication AuthToken authToken = session.getAuthToken(); if (authToken == null) { // User must be authenticated before binding a resource reply.setChildElement(packet.getChildElement().createCopy()); reply.setError(PacketError.Condition.not_authorized); // Send the error directly since a route does not exist at this point. session.process(reply); return reply; } if (authToken.isAnonymous()) { // User used ANONYMOUS SASL so initialize the session as an anonymous login session.setAnonymousAuth(); } else { String username = authToken.getUsername().toLowerCase(); // If a session already exists with the requested JID, then check to see // if we should kick it off or refuse the new connection ClientSession oldSession = routingTable.getClientRoute(new JID(username, serverName, resource, true)); if (oldSession != null) { try { int conflictLimit = sessionManager.getConflictKickLimit(); if (conflictLimit == SessionManager.NEVER_KICK) { reply.setChildElement(packet.getChildElement().createCopy()); reply.setError(PacketError.Condition.conflict); // Send the error directly since a route does not exist at this point. session.process(reply); return null; } int conflictCount = oldSession.incrementConflictCount(); if (conflictCount > conflictLimit) { Log.debug( "Kick out an old connection that is conflicting with a new one. Old session: {}", oldSession ); StreamError error = new StreamError(StreamError.Condition.conflict); oldSession.deliverRawText(error.toXML()); oldSession.close(); // When living on a remote cluster node, this will prevent that session from becoming 'resumable'. // OF-1923: As the session is now replaced, the old session will never be resumed. if ( oldSession instanceof LocalClientSession ) { // As the new session has already replaced the old session, we're not explicitly closing // the old session again, as that would cause the state of the new session to be affected. sessionManager.removeDetached((LocalClientSession) oldSession); } } else { reply.setChildElement(packet.getChildElement().createCopy()); reply.setError(PacketError.Condition.conflict); // Send the error directly since a route does not exist at this point. session.process(reply); return null; } } catch (Exception e) { Log.error("Error during login", e); } } // If the connection was not refused due to conflict, log the user in session.setAuthToken(authToken, resource); } child.addElement("jid").setText(session.getAddress().toString()); // Send the response directly since a route does not exist at this point. session.process(reply); // After the client has been informed, inform all listeners as well. SessionEventDispatcher.dispatchEvent(session, SessionEventDispatcher.EventType.resource_bound); return null;
234
1,264
1,498
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQEntityTimeHandler.java
IQEntityTimeHandler
handleIQ
class IQEntityTimeHandler extends IQHandler implements ServerFeaturesProvider { private final IQHandlerInfo info; public IQEntityTimeHandler() { super("XEP-0202: Entity Time"); info = new IQHandlerInfo("time", "urn:xmpp:time"); } @Override public IQ handleIQ(IQ packet) {<FILL_FUNCTION_BODY>} @Override public IQHandlerInfo getInfo() { return info; } @Override public Iterator<String> getFeatures() { return Collections.singleton(info.getNamespace()).iterator(); } /** * Formats a {@link TimeZone} as specified in XEP-0082: XMPP Date and Time Profiles. * * @param tz The time zone. * @return The formatted time zone. */ String formatsTimeZone(TimeZone tz) { // package-private for test. int seconds = Math.abs(tz.getOffset(System.currentTimeMillis())) / 1000; int hours = seconds / 3600; int minutes = (seconds % 3600) / 60; return (tz.getRawOffset() < 0 ? "-" : "+") + String.format("%02d:%02d", hours, minutes); } /** * Gets the ISO 8601 formatted date (UTC) as specified in XEP-0082: XMPP Date and Time Profiles. * * @param date The date. * @return The UTC formatted date. */ String getUtcDate(Date date) { // package-private for test. Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT")); calendar.setTime(date); // This makes sure the date is formatted as the xs:dateTime type. return DatatypeConverter.printDateTime(calendar); } }
IQ response = IQ.createResultIQ(packet); Element timeElement = DocumentHelper.createElement(QName.get(info.getName(), info.getNamespace())); timeElement.addElement("tzo").setText(formatsTimeZone(TimeZone.getDefault())); timeElement.addElement("utc").setText(getUtcDate(new Date())); response.setChildElement(timeElement); return response;
507
106
613
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQHandler.java
IQHandler
process
class IQHandler extends BasicModule implements ChannelHandler { private static final Logger Log = LoggerFactory.getLogger(IQHandler.class); protected PacketDeliverer deliverer; protected SessionManager sessionManager; /** * Create a basic module with the given name. * * @param moduleName The name for the module or null to use the default */ public IQHandler(String moduleName) { super(moduleName); } /** * RFC 6121 8.5.1. "No Such User" specifies how the server must respond to a request made against a non-existing user. * * The abstract IQ Handler plugin can act accordingly, but allows implementations to override this behavior. By * default, Openfire will perform a non-existing user check and act according to the RFC 6121. Subclasses can * disable this behavior by overriding this method, and returning 'false'. * * @return 'true' if the Abstract IQ Handler implementation should detect if the IQ request is made against a non-existing user and return an error. * @see <a href="http://xmpp.org/rfcs/rfc6121.html#rules-localpart-nosuchuser">RFC 6121 8.5.1. "No Such User"</a> * @see <a href="https://igniterealtime.atlassian.net/jira/software/c/projects/OF/issues/OF-880">OF-880</a> */ public boolean performNoSuchUserCheck() { return true; } @Override public void process(Packet packet) throws PacketException {<FILL_FUNCTION_BODY>} /** * Handles the received IQ packet. * * @param packet the IQ packet to handle. * @return the response to send back. * @throws UnauthorizedException if the user that sent the packet is not * authorized to request the given operation. */ public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; /** * Returns the handler information to help generically handle IQ packets. * IQHandlers that aren't local server iq handlers (e.g. chatbots, transports, etc) * return {@code null}. * * @return The IQHandlerInfo for this handler */ public abstract IQHandlerInfo getInfo(); @Override public void initialize(XMPPServer server) { super.initialize(server); deliverer = server.getPacketDeliverer(); sessionManager = server.getSessionManager(); } }
IQ iq = (IQ) packet; JID recipientJID = iq.getTo(); // RFC 6121 8.5.1. No Such User http://xmpp.org/rfcs/rfc6121.html#rules-localpart-nosuchuser // If the 'to' address specifies a bare JID <localpart@domainpart> or full JID <localpart@domainpart/resourcepart> where the domainpart of the JID matches a configured domain that is serviced by the server itself, the server MUST proceed as follows. // If the user account identified by the 'to' attribute does not exist, how the stanza is processed depends on the stanza type. // For an IQ stanza, the server MUST return a <service-unavailable/> stanza error to the sender. if (performNoSuchUserCheck() && iq.isRequest() && recipientJID != null && recipientJID.getNode() != null && !XMPPServer.getInstance().isRemote(recipientJID) && !UserManager.getInstance().isRegisteredUser(recipientJID, false) && !UserManager.isPotentialFutureLocalUser(recipientJID) && sessionManager.getSession(recipientJID) == null && !(recipientJID.asBareJID().equals(packet.getFrom().asBareJID()) && sessionManager.isPreAuthenticatedSession(packet.getFrom())) // A pre-authenticated session queries the server about itself. ) { Log.trace("Responding with 'service-unavailable' since the intended recipient isn't a local user ('no-such-user' check) to: {}", iq); // For an IQ stanza, the server MUST return a <service-unavailable/> stanza error to the sender. IQ response = IQ.createResultIQ(iq); response.setChildElement(iq.getChildElement().createCopy()); response.setError(PacketError.Condition.service_unavailable); sessionManager.getSession(iq.getFrom()).process(response); return; } try { IQ reply = handleIQ(iq); if (reply != null) { deliverer.deliver(reply); } } catch (org.jivesoftware.openfire.auth.UnauthorizedException e) { if (iq != null) { try { IQ response = IQ.createResultIQ(iq); response.setChildElement(iq.getChildElement().createCopy()); response.setError(PacketError.Condition.not_authorized); sessionManager.getSession(iq.getFrom()).process(response); } catch (Exception de) { Log.error(LocaleUtils.getLocalizedString("admin.error"), de); sessionManager.getSession(iq.getFrom()).close(); } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); try { IQ response = IQ.createResultIQ(iq); response.setChildElement(iq.getChildElement().createCopy()); response.setError(PacketError.Condition.internal_server_error); sessionManager.getSession(iq.getFrom()).process(response); } catch (Exception e1) { // Do nothing } }
690
874
1,564
<methods>public void <init>(java.lang.String) ,public void destroy() ,public java.lang.String getName() ,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public void start() throws java.lang.IllegalStateException,public void stop() <variables>private java.lang.String name
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQLastActivityHandler.java
IQLastActivityHandler
handleIQ
class IQLastActivityHandler extends IQHandler implements ServerFeaturesProvider { private static final String NAMESPACE = "jabber:iq:last"; private final IQHandlerInfo info; private PresenceManager presenceManager; public IQLastActivityHandler() { super("XMPP Last Activity Handler"); info = new IQHandlerInfo("query", NAMESPACE); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override public IQHandlerInfo getInfo() { return info; } @Override public Iterator<String> getFeatures() { return Collections.singleton(NAMESPACE).iterator(); } @Override public void initialize(XMPPServer server) { super.initialize(server); presenceManager = server.getPresenceManager(); } }
IQ reply = IQ.createResultIQ(packet); Element lastActivity = reply.setChildElement("query", NAMESPACE); String sender = packet.getFrom().getNode(); // Check if any of the usernames is null if (sender == null) { reply.setError(PacketError.Condition.forbidden); return reply; } if (packet.getTo() != null && packet.getTo().getNode() == null && XMPPServer.getInstance().isLocal(packet.getTo())) { // http://xmpp.org/extensions/xep-0012.html#server // When the last activity query is sent to a server or component (i.e., to a JID of the form <domain.tld>), // the information contained in the IQ reply reflects the uptime of the JID sending the reply. // The seconds attribute specifies how long the host has been running since it was last (re-)started. long uptime = XMPPServer.getInstance().getServerInfo().getLastStarted().getTime(); long lastActivityTime = (System.currentTimeMillis() - uptime) / 1000; lastActivity.addAttribute("seconds", String.valueOf(lastActivityTime)); return reply; } // If the 'to' attribute is null, treat the IQ on behalf of the account from which received the stanza // in accordance with RFC 6120 § 10.3.3. String username = packet.getTo() == null ? packet.getFrom().getNode() : packet.getTo().getNode(); try { if (username != null) { // Check that the user requesting this information is subscribed to the user's presence if (presenceManager.canProbePresence(packet.getFrom(), username)) { if (sessionManager.getSessions(username).isEmpty()) { User user = UserManager.getInstance().getUser(username); // The user is offline so answer the user's "last available time and the // status message of the last unavailable presence received from the user" long lastActivityTime = presenceManager.getLastActivity(user); if (lastActivityTime > -1) { // Convert it to seconds lastActivityTime = lastActivityTime / 1000; } lastActivity.addAttribute("seconds", String.valueOf(lastActivityTime)); String lastStatus = presenceManager.getLastPresenceStatus(user); if (lastStatus != null && lastStatus.length() > 0) { lastActivity.setText(lastStatus); } } else { // The user is online so answer seconds=0 lastActivity.addAttribute("seconds", "0"); } } else { reply.setError(PacketError.Condition.forbidden); } } } catch (UserNotFoundException e) { reply.setError(PacketError.Condition.forbidden); } return reply;
240
753
993
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQMessageCarbonsHandler.java
IQMessageCarbonsHandler
handleIQ
class IQMessageCarbonsHandler extends IQHandler implements ServerFeaturesProvider { private static final String NAMESPACE = "urn:xmpp:carbons:2"; private IQHandlerInfo info; public IQMessageCarbonsHandler() { super("XEP-0280: Message Carbons"); info = new IQHandlerInfo("", NAMESPACE); } @Override public IQ handleIQ(IQ packet) {<FILL_FUNCTION_BODY>} @Override public IQHandlerInfo getInfo() { return info; } @Override public Iterator<String> getFeatures() { return Collections.singleton(NAMESPACE).iterator(); } }
Element enable = packet.getChildElement(); if (XMPPServer.getInstance().isLocal(packet.getFrom())) { if (enable.getName().equals("enable")) { ClientSession clientSession = sessionManager.getSession(packet.getFrom()); clientSession.setMessageCarbonsEnabled(true); return IQ.createResultIQ(packet); } else if (enable.getName().equals("disable")) { ClientSession clientSession = sessionManager.getSession(packet.getFrom()); clientSession.setMessageCarbonsEnabled(false); return IQ.createResultIQ(packet); } else { IQ error = IQ.createResultIQ(packet); error.setError(PacketError.Condition.bad_request); return error; } } else { // if the request is from a client that is not hosted on this server. IQ error = IQ.createResultIQ(packet); error.setError(PacketError.Condition.not_allowed); return error; }
195
270
465
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQOfflineMessagesHandler.java
IQOfflineMessagesHandler
getExtendedInfos
class IQOfflineMessagesHandler extends IQHandler implements ServerFeaturesProvider, DiscoInfoProvider, DiscoItemsProvider { private static final Logger Log = LoggerFactory.getLogger(IQOfflineMessagesHandler.class); private static final String NAMESPACE = "http://jabber.org/protocol/offline"; final private XMPPDateTimeFormat xmppDateTime = new XMPPDateTimeFormat(); private IQHandlerInfo info; private IQDiscoInfoHandler infoHandler; private IQDiscoItemsHandler itemsHandler; private RoutingTable routingTable; private UserManager userManager; private OfflineMessageStore messageStore; public IQOfflineMessagesHandler() { super("Flexible Offline Message Retrieval Handler"); info = new IQHandlerInfo("offline", NAMESPACE); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException { IQ reply = IQ.createResultIQ(packet); Element offlineRequest = packet.getChildElement(); JID from = packet.getFrom(); if (offlineRequest.element("purge") != null) { // User requested to delete all offline messages messageStore.deleteMessages(from.getNode()); } else if (offlineRequest.element("fetch") != null) { // Mark that offline messages shouldn't be sent when the user becomes available stopOfflineFlooding(from); // User requested to receive all offline messages for (OfflineMessage offlineMessage : messageStore.getMessages(from.getNode(), false)) { sendOfflineMessage(from, offlineMessage); } } else { for (Iterator it = offlineRequest.elementIterator("item"); it.hasNext();) { Element item = (Element) it.next(); Date creationDate = null; try { creationDate = xmppDateTime.parseString(item.attributeValue("node")); } catch (ParseException e) { Log.error("Error parsing date", e); } if ("view".equals(item.attributeValue("action"))) { // User requested to receive specific message OfflineMessage offlineMsg = messageStore.getMessage(from.getNode(), creationDate); if (offlineMsg != null) { sendOfflineMessage(from, offlineMsg); } else { // If the requester is authorized but the node does not exist, the server MUST return a <item-not-found/> error. reply.setError(PacketError.Condition.item_not_found); } } else if ("remove".equals(item.attributeValue("action"))) { // User requested to delete specific message if (messageStore.getMessage(from.getNode(), creationDate) != null) { messageStore.deleteMessage(from.getNode(), creationDate); } else { // If the requester is authorized but the node does not exist, the server MUST return a <item-not-found/> error. reply.setError(PacketError.Condition.item_not_found); } } } } return reply; } private void sendOfflineMessage(JID receipient, OfflineMessage offlineMessage) { Element offlineInfo = offlineMessage.addChildElement("offline", NAMESPACE); offlineInfo.addElement("item").addAttribute("node", XMPPDateTimeFormat.format(offlineMessage.getCreationDate())); routingTable.routePacket(receipient, offlineMessage); } @Override public IQHandlerInfo getInfo() { return info; } @Override public Iterator<String> getFeatures() { return Collections.singleton(NAMESPACE).iterator(); } @Override public Iterator<Element> getIdentities(String name, String node, JID senderJID) { Element identity = DocumentHelper.createElement("identity"); identity.addAttribute("category", "automation"); identity.addAttribute("type", "message-list"); return Collections.singleton(identity).iterator(); } @Override public Iterator<String> getFeatures(String name, String node, JID senderJID) { return Collections.singleton(NAMESPACE).iterator(); } @Override public Set<DataForm> getExtendedInfos(String name, String node, JID senderJID) {<FILL_FUNCTION_BODY>} @Override public boolean hasInfo(String name, String node, JID senderJID) { return NAMESPACE.equals(node) && userManager.isRegisteredUser(senderJID, false); } @Override public Iterator<DiscoItem> getItems(String name, String node, JID senderJID) { // Mark that offline messages shouldn't be sent when the user becomes available stopOfflineFlooding(senderJID); List<DiscoItem> answer = new ArrayList<>(); for (OfflineMessage offlineMessage : messageStore.getMessages(senderJID.getNode(), false)) { answer.add(new DiscoItem(senderJID.asBareJID(), offlineMessage.getFrom().toString(), XMPPDateTimeFormat.format(offlineMessage.getCreationDate()), null)); } return answer.iterator(); } @Override public void initialize(XMPPServer server) { super.initialize(server); infoHandler = server.getIQDiscoInfoHandler(); itemsHandler = server.getIQDiscoItemsHandler(); messageStore = server.getOfflineMessageStore(); userManager = server.getUserManager(); routingTable = server.getRoutingTable(); } @Override public void start() throws IllegalStateException { super.start(); infoHandler.setServerNodeInfoProvider(NAMESPACE, this); itemsHandler.setServerNodeInfoProvider(NAMESPACE, this); } @Override public void stop() { super.stop(); infoHandler.removeServerNodeInfoProvider(NAMESPACE); itemsHandler.removeServerNodeInfoProvider(NAMESPACE); } private void stopOfflineFlooding(JID senderJID) { LocalClientSession session = (LocalClientSession) sessionManager.getSession(senderJID); if (session != null) { session.setOfflineFloodStopped(true); } } }
// Mark that offline messages shouldn't be sent when the user becomes available stopOfflineFlooding(senderJID); final DataForm dataForm = new DataForm(DataForm.Type.result); final FormField field1 = dataForm.addField(); field1.setVariable("FORM_TYPE"); field1.setType(FormField.Type.hidden); field1.addValue(NAMESPACE); final FormField field2 = dataForm.addField(); field2.setVariable("number_of_messages"); field2.addValue(String.valueOf(messageStore.getCount(senderJID.getNode()))); final Set<DataForm> dataForms = new HashSet<>(); dataForms.add(dataForm); return dataForms;
1,630
199
1,829
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager