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/session/ConnectionMultiplexerSessionTask.java
ConnectionMultiplexerSessionTask
toString
class ConnectionMultiplexerSessionTask extends RemoteSessionTask { private JID address; public ConnectionMultiplexerSessionTask() { } protected ConnectionMultiplexerSessionTask(JID address, Operation operation) { super(operation); this.address = address; } Session getSession() { return SessionManager.getInstance().getConnectionMultiplexerSession(address); } public String toString() {<FILL_FUNCTION_BODY>} }
return super.toString() + " operation: " + operation + " address: " + address;
127
25
152
<methods>public void <init>() ,public java.lang.Object getResult() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void run() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private static final Logger Log,protected org.jivesoftware.openfire.session.RemoteSessionTask.Operation operation,protected java.lang.Object result
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/DeliverRawTextTask.java
DeliverRawTextTask
writeExternal
class DeliverRawTextTask implements ClusterTask<Void> { private static final Logger Log = LoggerFactory.getLogger(DeliverRawTextTask.class); private SessionType sessionType; private JID address; private StreamID streamID; private String text; public DeliverRawTextTask() { super(); } DeliverRawTextTask(RemoteSession remoteSession, JID address, String text) { if (remoteSession instanceof RemoteClientSession) { this.sessionType = SessionType.client; } else if (remoteSession instanceof RemoteOutgoingServerSession) { Log.error("OutgoingServerSession used with DeliverRawTextTask; should be using DeliverRawTextServerTask: " + remoteSession); this.sessionType = SessionType.outgoingServer; } else if (remoteSession instanceof RemoteComponentSession) { this.sessionType = SessionType.component; } else if (remoteSession instanceof RemoteConnectionMultiplexerSession) { this.sessionType = SessionType.connectionManager; } else { Log.error("Invalid RemoteSession was used for task: " + remoteSession); } this.address = address; this.text = text; } DeliverRawTextTask(StreamID streamID, String text) { this.sessionType = SessionType.incomingServer; this.streamID = streamID; this.text = text; } public Void getResult() { return null; } public void run() { getSession().deliverRawText(text); } public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} public void readExternal(ObjectInput in) throws IOException { text = ExternalizableUtil.getInstance().readSafeUTF(in); sessionType = SessionType.values()[ExternalizableUtil.getInstance().readInt(in)]; if (ExternalizableUtil.getInstance().readBoolean(in)) { address = (JID) ExternalizableUtil.getInstance().readSerializable(in); } if (ExternalizableUtil.getInstance().readBoolean(in)) { streamID = BasicStreamIDFactory.createStreamID( ExternalizableUtil.getInstance().readSafeUTF(in) ); } } Session getSession() { if (sessionType == SessionType.client) { return XMPPServer.getInstance().getRoutingTable().getClientRoute(address); } else if (sessionType == SessionType.component) { return SessionManager.getInstance().getComponentSession(address.getDomain()); } else if (sessionType == SessionType.connectionManager) { return SessionManager.getInstance().getConnectionMultiplexerSession(address); } else if (sessionType == SessionType.outgoingServer) { Log.error("Trying to write raw data to a server session across the cluster: " + address.toString()); return null; } else if (sessionType == SessionType.incomingServer) { return SessionManager.getInstance().getIncomingServerSession(streamID); } Log.error("Found unknown session type: " + sessionType); return null; } public String toString() { return super.toString() + " sessionType: " + sessionType + " address: " + address; } private enum SessionType { client, outgoingServer, incomingServer, component, connectionManager } }
ExternalizableUtil.getInstance().writeSafeUTF(out, text); ExternalizableUtil.getInstance().writeInt(out, sessionType.ordinal()); ExternalizableUtil.getInstance().writeBoolean(out, address != null); if (address != null) { ExternalizableUtil.getInstance().writeSerializable(out, address); } ExternalizableUtil.getInstance().writeBoolean(out, streamID != null); if (streamID != null) { ExternalizableUtil.getInstance().writeSafeUTF( out, streamID.getID() ); }
871
145
1,016
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/DomainPair.java
DomainPair
equals
class DomainPair implements java.io.Serializable { private final String local; private final String remote; private static final long serialVersionUID = 1L; public DomainPair(String local, String remote) { this.local = local; this.remote = remote; } public String toString() { return "{" + local + " -> " + remote + "}"; } public String getLocal() { return local; } public String getRemote() { return remote; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = local.hashCode(); result = 31 * result + remote.hashCode(); return result; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DomainPair that = (DomainPair) o; if (!local.equals(that.local)) return false; return remote.equals(that.remote);
212
76
288
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/GetSessionsCountTask.java
GetSessionsCountTask
run
class GetSessionsCountTask implements ClusterTask<Integer> { private Boolean authenticated; private Integer count; public GetSessionsCountTask() { } public GetSessionsCountTask(Boolean authenticated) { this.authenticated = authenticated; } @Override public Integer getResult() { return count; } @Override public void run() {<FILL_FUNCTION_BODY>} @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeBoolean(out, authenticated); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { authenticated = ExternalizableUtil.getInstance().readBoolean(in); } }
if (authenticated) { // Get count of authenticated sessions count = SessionManager.getInstance().getUserSessionsCount(true); } else { // Get count of connected sessions (authenticated or not) count = SessionManager.getInstance().getConnectionsCount(true); }
200
79
279
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/IncomingServerSessionInfo.java
IncomingServerSessionInfo
toString
class IncomingServerSessionInfo implements Externalizable { private NodeID nodeID; private Set<String> validatedDomains; public IncomingServerSessionInfo() { } public NodeID getNodeID() { return nodeID; } public Set<String> getValidatedDomains() { return validatedDomains; } public IncomingServerSessionInfo(@Nonnull final LocalIncomingServerSession serverSession) { this.nodeID = XMPPServer.getInstance().getNodeID(); validatedDomains = new HashSet<>(serverSession.getValidatedDomains()); } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSerializable(out, nodeID); ExternalizableUtil.getInstance().writeSerializableCollection(out, validatedDomains); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { nodeID = (NodeID) ExternalizableUtil.getInstance().readSerializable(in); validatedDomains = new HashSet<>(); ExternalizableUtil.getInstance().readSerializableCollection(in, validatedDomains, this.getClass().getClassLoader()); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "IncomingServerSessionInfo{" + "nodeID=" + nodeID + ", validatedDomains=" + validatedDomains + '}';
335
45
380
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/IncomingServerSessionTask.java
IncomingServerSessionTask
run
class IncomingServerSessionTask extends RemoteSessionTask { private StreamID streamID; public IncomingServerSessionTask() { super(); } protected IncomingServerSessionTask(Operation operation, StreamID streamID) { super(operation); this.streamID = streamID; } Session getSession() { return SessionManager.getInstance().getIncomingServerSession(streamID); } public void run() {<FILL_FUNCTION_BODY>} public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); ExternalizableUtil.getInstance().writeSafeUTF(out, streamID.getID()); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); streamID = BasicStreamIDFactory.createStreamID( ExternalizableUtil.getInstance().readSafeUTF(in) ); } public String toString() { return super.toString() + " operation: " + operation + " streamID: " + streamID; } }
super.run(); switch (operation) { case getLocalDomain: result = ((IncomingServerSession) getSession()).getLocalDomain(); break; case getAddress: result = getSession().getAddress(); break; case getAuthenticationMethod: result = ((IncomingServerSession) getSession()).getAuthenticationMethod(); break; case getValidatedDomains: result = ((IncomingServerSession) getSession()).getValidatedDomains(); break; }
269
131
400
<methods>public void <init>() ,public java.lang.Object getResult() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void run() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private static final Logger Log,protected org.jivesoftware.openfire.session.RemoteSessionTask.Operation operation,protected java.lang.Object result
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalComponentSession.java
LocalExternalComponent
processPacket
class LocalExternalComponent implements ComponentSession.ExternalComponent { /** * Keeps track of the IQ (get/set) packets that were sent from a given component's connection. This * information will be used to ensure that the IQ reply will be sent to the same component's connection. */ private static final Map<String, LocalExternalComponent> iqs = new HashMap<>(); private LocalComponentSession session; private Connection connection; private String name = ""; private String type = ""; private String category = ""; /** * List of subdomains that were binded for this component. The list will include * the initial subdomain. */ private List<String> subdomains = new ArrayList<>(); public LocalExternalComponent(LocalComponentSession session, Connection connection) { this.session = session; this.connection = connection; } @Override public void processPacket(Packet packet) {<FILL_FUNCTION_BODY>} /** * Delivers the packet to the external component. * * @param packet the packet to deliver. */ void deliver(Packet packet) { if (connection != null && !connection.isClosed()) { try { connection.deliver(packet); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); connection.close(new StreamError(StreamError.Condition.internal_server_error)); } } } @Override public String getName() { return name; } @Override public String getDescription() { return category + " - " + type; } @Override public void setName(String name) { this.name = name; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getInitialSubdomain() { if (subdomains.isEmpty()) { return null; } return subdomains.get(0); } private void addSubdomain(String subdomain) { subdomains.add(subdomain); } @Override public Collection<String> getSubdomains() { return subdomains; } @Override public void initialize(JID jid, ComponentManager componentManager) { addSubdomain(jid.toString()); } @Override public void start() { } @Override public void shutdown() { // Remove tracking of IQ packets sent from this component synchronized (iqs) { List<String> toRemove = new ArrayList<>(); for (Map.Entry<String,LocalExternalComponent> entry : iqs.entrySet()) { if (entry.getValue() == this) { toRemove.add(entry.getKey()); } } // Remove keys pointing to component being removed for (String key : toRemove) { iqs.remove(key); } } } @Override public String toString() { return super.toString() + " - subdomains: " + subdomains; } public void track(IQ iq) { synchronized (iqs) { iqs.put(iq.getID(), this); } } /** * @return the session */ public LocalComponentSession getSession() { return session; } }
if (packet instanceof IQ) { IQ iq = (IQ) packet; if (iq.getType() == IQ.Type.result || iq.getType() == IQ.Type.error) { // Check if this IQ reply belongs to a specific component and route // reply to that specific component (if it exists) LocalExternalComponent targetComponent; synchronized (iqs) { targetComponent = iqs.remove(packet.getID()); } if (targetComponent != null) { targetComponent.processPacket(packet); return; } } } // Ask the session to process the outgoing packet. This will // give us the chance to apply PacketInterceptors session.process(packet);
961
199
1,160
<methods>public void <init>(java.lang.String, org.jivesoftware.openfire.Connection, org.jivesoftware.openfire.StreamID, java.util.Locale) ,public void close() ,public void deliverRawText(java.lang.String) ,public JID getAddress() ,public abstract List<Element> getAvailableStreamFeatures() ,public java.lang.String getCipherSuiteName() ,public org.jivesoftware.openfire.Connection getConnection() ,public java.util.Date getCreationDate() ,public java.lang.String getHostAddress() throws java.net.UnknownHostException,public java.lang.String getHostName() throws java.net.UnknownHostException,public final java.util.Locale getLanguage() ,public java.util.Date getLastActiveDate() ,public long getNumClientPackets() ,public long getNumServerPackets() ,public java.security.cert.Certificate[] getPeerCertificates() ,public java.lang.String getServerName() ,public java.lang.Object getSessionData(java.lang.String) ,public Map<java.lang.String,java.lang.String> getSoftwareVersion() ,public org.jivesoftware.openfire.session.Session.Status getStatus() ,public org.jivesoftware.openfire.StreamID getStreamID() ,public org.jivesoftware.openfire.streammanagement.StreamManager getStreamManager() ,public java.lang.String getTLSProtocolName() ,public void incrementClientPacketCount() ,public void incrementServerPacketCount() ,public boolean isClosed() ,public boolean isDetached() ,public boolean isEncrypted() ,public boolean isSecure() ,public boolean isUsingSelfSignedCertificate() ,public void process(Packet) ,public void reattach(org.jivesoftware.openfire.session.LocalSession, long) ,public java.lang.Object removeSessionData(java.lang.String) ,public void setAddress(JID) ,public void setDetached() ,public java.lang.Object setSessionData(java.lang.String, java.lang.Object) ,public void setSoftwareVersionData(java.lang.String, java.lang.String) ,public void setStatus(org.jivesoftware.openfire.session.Session.Status) ,public java.lang.String toString() ,public boolean validate() <variables>private static final Logger Log,protected JID address,private java.util.concurrent.atomic.AtomicLong clientPacketCount,protected org.jivesoftware.openfire.Connection conn,private final non-sealed java.util.Locale language,private long lastActiveDate,private final java.util.concurrent.locks.Lock lock,protected final non-sealed java.lang.String serverName,private java.util.concurrent.atomic.AtomicLong serverPacketCount,private final Map<java.lang.String,java.lang.Object> sessionData,protected org.jivesoftware.openfire.SessionManager sessionManager,private Map<java.lang.String,java.lang.String> softwareVersionData,protected final long startDate,protected org.jivesoftware.openfire.session.Session.Status status,protected final non-sealed org.jivesoftware.openfire.StreamID streamID,protected final non-sealed org.jivesoftware.openfire.streammanagement.StreamManager streamManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalServerSession.java
LocalServerSession
getConnection
class LocalServerSession extends LocalSession implements ServerSession { /** * The method that was used to authenticate this session. Null when the session is not authenticated. */ protected AuthenticationMethod authenticationMethod = null; public LocalServerSession(String serverName, Connection connection, StreamID streamID) { super(serverName, connection, streamID, Locale.getDefault()); } @Override public void setDetached() { // TODO Implement stream management for s2s (OF-2425). Remove this override when it is. throw new UnsupportedOperationException("Stream management is not supported for server-to-server connections"); } @Override public void reattach(LocalSession connectionProvider, long h) { // TODO Implement stream management for s2s (OF-2425). Remove this override when it is. throw new UnsupportedOperationException("Stream management is not supported for server-to-server connections"); } /** * Returns the connection associated with this Session. * * @return The connection for this session */ @Nonnull @Override public Connection getConnection() {<FILL_FUNCTION_BODY>} @Override public void setStatus(Status status) { super.setStatus(status); if (status != Status.AUTHENTICATED) { authenticationMethod = null; } } /** * Obtain method that was used to authenticate this session. Null when the session is not authenticated. * * @return the method used for authentication (possibly null). */ @Override public AuthenticationMethod getAuthenticationMethod() { return authenticationMethod; } /** * Set the method that was used to authenticate this session. Setting a value will cause the status of this session * to be updated to 'Authenticated'. * * @param authenticationMethod The new authentication method for this session */ public void setAuthenticationMethod(@Nonnull final AuthenticationMethod authenticationMethod) { this.authenticationMethod = authenticationMethod; setStatus(Status.AUTHENTICATED); } @Override public String toString() { return this.getClass().getSimpleName() +"{" + "address=" + address + ", streamID=" + streamID + ", status=" + status + ", isEncrypted=" + isEncrypted() + ", isDetached=" + isDetached() + ", authenticationMethod=" + authenticationMethod + '}'; } }
final Connection connection = super.getConnection(); // valid only as long as stream management for s2s is not implemented (OF-2425). Remove this override when it is. assert connection != null; // Openfire does not implement stream management for s2s (OF-2425). Therefor, the connection cannot be null. return connection;
639
89
728
<methods>public void <init>(java.lang.String, org.jivesoftware.openfire.Connection, org.jivesoftware.openfire.StreamID, java.util.Locale) ,public void close() ,public void deliverRawText(java.lang.String) ,public JID getAddress() ,public abstract List<Element> getAvailableStreamFeatures() ,public java.lang.String getCipherSuiteName() ,public org.jivesoftware.openfire.Connection getConnection() ,public java.util.Date getCreationDate() ,public java.lang.String getHostAddress() throws java.net.UnknownHostException,public java.lang.String getHostName() throws java.net.UnknownHostException,public final java.util.Locale getLanguage() ,public java.util.Date getLastActiveDate() ,public long getNumClientPackets() ,public long getNumServerPackets() ,public java.security.cert.Certificate[] getPeerCertificates() ,public java.lang.String getServerName() ,public java.lang.Object getSessionData(java.lang.String) ,public Map<java.lang.String,java.lang.String> getSoftwareVersion() ,public org.jivesoftware.openfire.session.Session.Status getStatus() ,public org.jivesoftware.openfire.StreamID getStreamID() ,public org.jivesoftware.openfire.streammanagement.StreamManager getStreamManager() ,public java.lang.String getTLSProtocolName() ,public void incrementClientPacketCount() ,public void incrementServerPacketCount() ,public boolean isClosed() ,public boolean isDetached() ,public boolean isEncrypted() ,public boolean isSecure() ,public boolean isUsingSelfSignedCertificate() ,public void process(Packet) ,public void reattach(org.jivesoftware.openfire.session.LocalSession, long) ,public java.lang.Object removeSessionData(java.lang.String) ,public void setAddress(JID) ,public void setDetached() ,public java.lang.Object setSessionData(java.lang.String, java.lang.Object) ,public void setSoftwareVersionData(java.lang.String, java.lang.String) ,public void setStatus(org.jivesoftware.openfire.session.Session.Status) ,public java.lang.String toString() ,public boolean validate() <variables>private static final Logger Log,protected JID address,private java.util.concurrent.atomic.AtomicLong clientPacketCount,protected org.jivesoftware.openfire.Connection conn,private final non-sealed java.util.Locale language,private long lastActiveDate,private final java.util.concurrent.locks.Lock lock,protected final non-sealed java.lang.String serverName,private java.util.concurrent.atomic.AtomicLong serverPacketCount,private final Map<java.lang.String,java.lang.Object> sessionData,protected org.jivesoftware.openfire.SessionManager sessionManager,private Map<java.lang.String,java.lang.String> softwareVersionData,protected final long startDate,protected org.jivesoftware.openfire.session.Session.Status status,protected final non-sealed org.jivesoftware.openfire.StreamID streamID,protected final non-sealed org.jivesoftware.openfire.streammanagement.StreamManager streamManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/OutgoingServerSessionTask.java
OutgoingServerSessionTask
toString
class OutgoingServerSessionTask extends RemoteSessionTask { protected DomainPair domainPair; public OutgoingServerSessionTask() { } protected OutgoingServerSessionTask(DomainPair domainPair, Operation operation) { super(operation); this.domainPair = domainPair; } Session getSession() { return SessionManager.getInstance().getOutgoingServerSession(domainPair); } public void run() { super.run(); if (operation == Operation.getOutgoingDomainPairs) { result = ((OutgoingServerSession) getSession()).getOutgoingDomainPairs(); } else if (operation == Operation.getAuthenticationMethod) { result = ((OutgoingServerSession) getSession()).getAuthenticationMethod(); } } public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); ExternalizableUtil.getInstance().writeSerializable(out, domainPair); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); domainPair = (DomainPair) ExternalizableUtil.getInstance().readSerializable(in); } public String toString() {<FILL_FUNCTION_BODY>} }
return super.toString() + " operation: " + operation + " domain pair: " + domainPair;
312
27
339
<methods>public void <init>() ,public java.lang.Object getResult() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void run() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private static final Logger Log,protected org.jivesoftware.openfire.session.RemoteSessionTask.Operation operation,protected java.lang.Object result
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/ProcessPacketTask.java
ProcessPacketTask
getSession
class ProcessPacketTask implements ClusterTask<Void> { private static final Logger Log = LoggerFactory.getLogger(ProcessPacketTask.class); private SessionType sessionType; private JID address; private StreamID streamID; private Packet packet; public ProcessPacketTask() { super(); } ProcessPacketTask(RemoteSession remoteSession, JID address, Packet packet) { if (remoteSession instanceof RemoteClientSession) { this.sessionType = SessionType.client; } else if (remoteSession instanceof RemoteOutgoingServerSession) { this.sessionType = SessionType.outgoingServer; } else if (remoteSession instanceof RemoteComponentSession) { this.sessionType = SessionType.component; } else if (remoteSession instanceof RemoteConnectionMultiplexerSession) { this.sessionType = SessionType.connectionManager; } else { Log.error("Invalid RemoteSession was used for task: " + remoteSession); } this.address = address; this.packet = packet; } ProcessPacketTask(StreamID streamID, Packet packet) { this.sessionType = SessionType.incomingServer; this.streamID = streamID; this.packet = packet; } public Void getResult() { return null; } public void run() { getSession().process(packet); } public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeBoolean(out, address != null); if (address != null) { ExternalizableUtil.getInstance().writeSerializable(out, address); } ExternalizableUtil.getInstance().writeBoolean(out, streamID != null); if (streamID != null) { ExternalizableUtil.getInstance().writeSafeUTF( out, streamID.getID() ); } ExternalizableUtil.getInstance().writeInt(out, sessionType.ordinal()); 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()); } public void readExternal(ObjectInput in) throws IOException { if (ExternalizableUtil.getInstance().readBoolean(in)) { address = (JID) ExternalizableUtil.getInstance().readSerializable(in); } if (ExternalizableUtil.getInstance().readBoolean(in)) { streamID = BasicStreamIDFactory.createStreamID( ExternalizableUtil.getInstance().readSafeUTF(in) ); } sessionType = SessionType.values()[ExternalizableUtil.getInstance().readInt(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; } } Session getSession() {<FILL_FUNCTION_BODY>} public String toString() { return super.toString() + " sessionType: " + sessionType + " address: " + address; } private enum SessionType { client, outgoingServer, incomingServer, component, connectionManager } }
if (sessionType == SessionType.client) { return XMPPServer.getInstance().getRoutingTable().getClientRoute(address); } else if (sessionType == SessionType.component) { return SessionManager.getInstance().getComponentSession(address.getDomain()); } else if (sessionType == SessionType.connectionManager) { return SessionManager.getInstance().getConnectionMultiplexerSession(address); } else if (sessionType == SessionType.outgoingServer) { final DomainPair pair = new DomainPair(packet.getFrom().getDomain(), address.getDomain()); return SessionManager.getInstance().getOutgoingServerSession(pair); } else if (sessionType == SessionType.incomingServer) { return SessionManager.getInstance().getIncomingServerSession(streamID); } Log.error("Found unknown session type: " + sessionType); return null;
966
229
1,195
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/RemoteIncomingServerSession.java
RemoteIncomingServerSession
getAuthenticationMethod
class RemoteIncomingServerSession extends RemoteSession implements IncomingServerSession { private String localDomain; private AuthenticationMethod authenticationMethod; private Collection<String> validatedDomains; public RemoteIncomingServerSession(byte[] nodeID, StreamID streamID) { super(nodeID, null); this.streamID = streamID; } @Override public AuthenticationMethod getAuthenticationMethod() {<FILL_FUNCTION_BODY>} public JID getAddress() { if (address == null) { RemoteSessionTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getAddress); address = (JID) doSynchronousClusterTask(task); } return address; } public Collection<String> getValidatedDomains() { if (validatedDomains == null) { RemoteSessionTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getValidatedDomains); validatedDomains = (Collection<String>) doSynchronousClusterTask(task); } return validatedDomains; } public String getLocalDomain() { if (localDomain == null) { RemoteSessionTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getLocalDomain); localDomain = (String) doSynchronousClusterTask(task); } return localDomain; } RemoteSessionTask getRemoteSessionTask(RemoteSessionTask.Operation operation) { return new IncomingServerSessionTask(operation, streamID); } ClusterTask getDeliverRawTextTask(String text) { return new DeliverRawTextTask(streamID, text); } ClusterTask getProcessPacketTask(Packet packet) { return new ProcessPacketTask(streamID, packet); } }
if (authenticationMethod == null) { ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getAuthenticationMethod); authenticationMethod = (AuthenticationMethod) doSynchronousClusterTask(task); } return authenticationMethod;
447
62
509
<methods>public void <init>(byte[], JID) ,public void close() ,public void deliverRawText(java.lang.String) ,public JID getAddress() ,public java.lang.String getCipherSuiteName() ,public java.util.Date getCreationDate() ,public java.lang.String getHostAddress() throws java.net.UnknownHostException,public java.lang.String getHostName() throws java.net.UnknownHostException,public final java.util.Locale getLanguage() ,public java.util.Date getLastActiveDate() ,public long getNumClientPackets() ,public long getNumServerPackets() ,public java.security.cert.Certificate[] getPeerCertificates() ,public java.lang.String getServerName() ,public Map<java.lang.String,java.lang.String> getSoftwareVersion() ,public org.jivesoftware.openfire.session.Session.Status getStatus() ,public org.jivesoftware.openfire.StreamID getStreamID() ,public java.lang.String getTLSProtocolName() ,public boolean isClosed() ,public boolean isEncrypted() ,public boolean isSecure() ,public void process(Packet) ,public boolean validate() <variables>protected JID address,private java.util.Date creationDate,private java.lang.String hostAddress,private java.lang.String hostName,protected byte[] nodeID,private java.lang.String serverName,protected org.jivesoftware.openfire.StreamID streamID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/RemoteOutgoingServerSession.java
RemoteOutgoingServerSession
getAuthenticationMethod
class RemoteOutgoingServerSession extends RemoteSession implements OutgoingServerSession { private AuthenticationMethod authenticationMethod; private final DomainPair pair; public RemoteOutgoingServerSession(byte[] nodeID, DomainPair address) { super(nodeID, new JID(null, address.getRemote(), null, true)); this.pair = address; } @Override public Collection<DomainPair> getOutgoingDomainPairs() { ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getOutgoingDomainPairs); return (Collection<DomainPair>) doSynchronousClusterTask(task); } @Override public void addOutgoingDomainPair(@Nonnull final DomainPair domainPair) { doClusterTask(new AddOutgoingDomainPair(domainPair)); } @Override public boolean authenticateSubdomain(@Nonnull final DomainPair domainPair) { ClusterTask task = new AuthenticateSubdomainTask(domainPair); return (Boolean) doSynchronousClusterTask(task); } @Override public AuthenticationMethod getAuthenticationMethod() {<FILL_FUNCTION_BODY>} @Override public boolean checkOutgoingDomainPair(@Nonnull final DomainPair domainPair) { ClusterTask task = new CheckOutgoingDomainPairTask(domainPair); return (Boolean)doSynchronousClusterTask(task); } @Override RemoteSessionTask getRemoteSessionTask(RemoteSessionTask.Operation operation) { return new OutgoingServerSessionTask(pair, operation); } @Override ClusterTask getDeliverRawTextTask(String text) { return new DeliverRawTextServerTask(pair, text); } @Override ClusterTask getProcessPacketTask(Packet packet) { return new ProcessPacketTask(this, address, packet); } private static class DeliverRawTextServerTask extends OutgoingServerSessionTask { private String text; public DeliverRawTextServerTask() { super(); } protected DeliverRawTextServerTask(DomainPair address, String text) { super(address, null); this.text = text; } @Override public void run() { getSession().deliverRawText(text); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); ExternalizableUtil.getInstance().writeSafeUTF(out, text); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); text = ExternalizableUtil.getInstance().readSafeUTF(in); } } private static class AddOutgoingDomainPair extends OutgoingServerSessionTask { public AddOutgoingDomainPair() { super(); } protected AddOutgoingDomainPair(DomainPair address) { super(address, null); } @Override public void run() { ((OutgoingServerSession) getSession()).addOutgoingDomainPair(domainPair); } } private static class AuthenticateSubdomainTask extends OutgoingServerSessionTask { public AuthenticateSubdomainTask() { super(); } protected AuthenticateSubdomainTask(DomainPair address) { super(address, null); } @Override public void run() { result = ((OutgoingServerSession) getSession()).authenticateSubdomain(domainPair); } } private static class CheckOutgoingDomainPairTask extends OutgoingServerSessionTask { public CheckOutgoingDomainPairTask() { super(); } protected CheckOutgoingDomainPairTask(DomainPair address) { super(address, null); } @Override public void run() { result = ((OutgoingServerSession) getSession()).checkOutgoingDomainPair(this.domainPair); } } }
if (authenticationMethod == null) { ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getAuthenticationMethod); authenticationMethod = (AuthenticationMethod) doSynchronousClusterTask(task); } return authenticationMethod;
995
62
1,057
<methods>public void <init>(byte[], JID) ,public void close() ,public void deliverRawText(java.lang.String) ,public JID getAddress() ,public java.lang.String getCipherSuiteName() ,public java.util.Date getCreationDate() ,public java.lang.String getHostAddress() throws java.net.UnknownHostException,public java.lang.String getHostName() throws java.net.UnknownHostException,public final java.util.Locale getLanguage() ,public java.util.Date getLastActiveDate() ,public long getNumClientPackets() ,public long getNumServerPackets() ,public java.security.cert.Certificate[] getPeerCertificates() ,public java.lang.String getServerName() ,public Map<java.lang.String,java.lang.String> getSoftwareVersion() ,public org.jivesoftware.openfire.session.Session.Status getStatus() ,public org.jivesoftware.openfire.StreamID getStreamID() ,public java.lang.String getTLSProtocolName() ,public boolean isClosed() ,public boolean isEncrypted() ,public boolean isSecure() ,public void process(Packet) ,public boolean validate() <variables>protected JID address,private java.util.Date creationDate,private java.lang.String hostAddress,private java.lang.String hostName,protected byte[] nodeID,private java.lang.String serverName,protected org.jivesoftware.openfire.StreamID streamID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/RemoteSession.java
RemoteSession
doClusterTask
class RemoteSession implements Session { protected byte[] nodeID; protected JID address; // Cache content that never changes protected StreamID streamID; private Date creationDate; private String serverName; private String hostAddress; private String hostName; public RemoteSession(byte[] nodeID, JID address) { this.nodeID = nodeID; this.address = address; } public JID getAddress() { return address; } /** * Remote sessions are always authenticated. Otherwise, they won't be visibile to other * cluster nodes. When the session is closed it will no longer be visible to other nodes * so CLOSED is never returned. * * @return the authenticated status. */ @Override public Status getStatus() { return Session.Status.AUTHENTICATED; } public StreamID getStreamID() { // Get it once and cache it since it never changes if (streamID == null) { ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getStreamID); streamID = (StreamID) doSynchronousClusterTask(task); } return streamID; } public String getServerName() { if (serverName == null) { ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getServerName); serverName = (String) doSynchronousClusterTask(task); } return serverName; } public Date getCreationDate() { // Get it once and cache it since it never changes if (creationDate == null) { ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.getCreationDate); creationDate = (Date) doSynchronousClusterTask(task); } return creationDate; } public Date getLastActiveDate() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getLastActiveDate); return (Date) doSynchronousClusterTask(task); } public long getNumClientPackets() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getNumClientPackets); final Object clusterTaskResult = doSynchronousClusterTask(task); return clusterTaskResult == null ? -1 : (Long) clusterTaskResult; } public long getNumServerPackets() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getNumServerPackets); final Object clusterTaskResult = doSynchronousClusterTask(task); return clusterTaskResult == null ? -1 : (Long) clusterTaskResult; } public String getTLSProtocolName() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getTLSProtocolName); return (String) doSynchronousClusterTask(task); } public String getCipherSuiteName() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getCipherSuiteName); return (String) doSynchronousClusterTask(task); } public Certificate[] getPeerCertificates() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getPeerCertificates); return (Certificate[]) doSynchronousClusterTask(task); } public Map<String,String> getSoftwareVersion() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getSoftwareVersion); return (Map<String,String>) doSynchronousClusterTask(task); } public void process(Packet packet) { doClusterTask(getProcessPacketTask(packet)); } public void close() { doSynchronousClusterTask(getRemoteSessionTask(RemoteSessionTask.Operation.close)); } public boolean isClosed() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.isClosed); final Object clusterTaskResult = doSynchronousClusterTask(task); return clusterTaskResult == null ? false : (Boolean) clusterTaskResult; } @Deprecated // Remove in Openfire 4.9 or later. public boolean isSecure() { return isEncrypted(); } public boolean isEncrypted() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.isEncrypted); final Object clusterTaskResult = doSynchronousClusterTask(task); return clusterTaskResult == null ? false : (Boolean) clusterTaskResult; } public String getHostAddress() throws UnknownHostException { if (hostAddress == null) { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getHostAddress); hostAddress = (String) doSynchronousClusterTask(task); } return hostAddress; } public String getHostName() throws UnknownHostException { if (hostName == null) { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.getHostName); hostName = (String) doSynchronousClusterTask(task); } return hostName; } public void deliverRawText(String text) { doClusterTask(getDeliverRawTextTask(text)); } public boolean validate() { ClusterTask<Object> task = getRemoteSessionTask(RemoteSessionTask.Operation.validate); final Object clusterTaskResult = doSynchronousClusterTask(task); return clusterTaskResult == null ? false : (Boolean) clusterTaskResult; } abstract RemoteSessionTask getRemoteSessionTask(RemoteSessionTask.Operation operation); abstract ClusterTask getDeliverRawTextTask(String text); abstract ClusterTask getProcessPacketTask(Packet packet); /** * Invokes a task on the remote cluster member synchronously and returns the result of * the remote operation. * * @param task the ClusterTask object to be invoked on a given cluster member. * @return result of remote operation. */ protected Object doSynchronousClusterTask(ClusterTask<Object> task) { ClusterNodeInfo info = CacheFactory.getClusterNodeInfo(nodeID); Object result = null; if (info == null && task instanceof RemoteSessionTask) { // clean up invalid session Session remoteSession = ((RemoteSessionTask)task).getSession(); if (remoteSession instanceof ClientSession) { SessionManager.getInstance().removeSession(null, remoteSession.getAddress(), false, false); } } else { result = (info == null) ? null : CacheFactory.doSynchronousClusterTask(task, nodeID); } return result; } /** * Invokes a task on the remote cluster member in an asynchronous fashion. * * @param task the task to be invoked on the specified cluster member. */ protected void doClusterTask(ClusterTask task) {<FILL_FUNCTION_BODY>} @Override public final Locale getLanguage() { return Locale.getDefault(); } }
ClusterNodeInfo info = CacheFactory.getClusterNodeInfo(nodeID); if (info == null && task instanceof RemoteSessionTask) { // clean up invalid session Session remoteSession = ((RemoteSessionTask)task).getSession(); if (remoteSession instanceof ClientSession) { SessionManager.getInstance().removeSession(null, remoteSession.getAddress(), false, false); } } else { CacheFactory.doClusterTask(task, nodeID); }
1,785
116
1,901
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/RemoteSessionTask.java
RemoteSessionTask
writeExternal
class RemoteSessionTask implements ClusterTask<Object> { private static final Logger Log = LoggerFactory.getLogger(RemoteSessionTask.class); protected Object result; protected Operation operation; public RemoteSessionTask() { } protected RemoteSessionTask(Operation operation) { this.operation = operation; } abstract Session getSession(); public Object getResult() { return result; } public void run() { if (operation == Operation.getStreamID) { result = getSession().getStreamID(); } else if (operation == Operation.getServerName) { result = getSession().getServerName(); } else if (operation == Operation.getCreationDate) { result = getSession().getCreationDate(); } else if (operation == Operation.getLastActiveDate) { result = getSession().getLastActiveDate(); } else if (operation == Operation.getNumClientPackets) { result = getSession().getNumClientPackets(); } else if (operation == Operation.getNumServerPackets) { result = getSession().getNumServerPackets(); } else if (operation == Operation.getTLSProtocolName) { result = getSession().getTLSProtocolName(); } else if (operation == Operation.getCipherSuiteName) { result = getSession().getCipherSuiteName(); } else if (operation == Operation.getPeerCertificates) { result = getSession().getPeerCertificates(); } else if (operation == Operation.getSoftwareVersion) { result = getSession().getSoftwareVersion(); } else if (operation == Operation.close) { // Run in another thread so we avoid blocking calls (in hazelcast) final Session session = getSession(); if (session != null) { final Future<?> future = TaskEngine.getInstance().submit( () -> { try { if (session instanceof LocalSession) { // OF-2311: If closed by another cluster node, chances are that the session needs to be closed forcibly. // Chances of the session being resumed are neglectable, while retaining the session in a detached state // causes problems (eg: IQBindHandler could have re-issued the resource to a replacement session). ((LocalSession) session).getStreamManager().formalClose(); } session.close(); } catch (Exception e) { Log.info("An exception was logged while closing session: {}", session, e); } }); // Wait until the close operation is done or timeout is met try { future.get(15, TimeUnit.SECONDS); } catch (Exception e) { Log.info("An exception was logged while executing RemoteSessionTask to close session: {}", session, e); } } } else if (operation == Operation.isClosed) { result = getSession().isClosed(); } else if (operation == Operation.isEncrypted) { result = getSession().isEncrypted(); } else if (operation == Operation.getHostAddress) { try { result = getSession().getHostAddress(); } catch (UnknownHostException e) { Log.error("Error getting address of session: " + getSession(), e); } } else if (operation == Operation.getHostName) { try { result = getSession().getHostName(); } catch (UnknownHostException e) { Log.error("Error getting address of session: " + getSession(), e); } } else if (operation == Operation.validate) { result = getSession().validate(); } else if (operation == Operation.removeDetached) { final Session session = getSession(); if (session instanceof LocalSession) { Log.debug("Terminating local session as instructed by another cluster node: {}", session); final Future<?> future = TaskEngine.getInstance().submit( () -> { try { SessionManager.getInstance().terminateDetached((LocalSession) session); } catch (Exception e) { Log.info("An exception was logged while closing session: {}", session, e); } }); // Wait until the close operation is done or timeout is met try { future.get(15, TimeUnit.SECONDS); } catch (Exception e) { Log.info("An exception was logged while executing RemoteSessionTask to close session: {}", session, e); } } } } public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { if (ExternalizableUtil.getInstance().readBoolean(in)) { operation = Operation.values()[ExternalizableUtil.getInstance().readInt(in)]; } } public enum Operation { /** * Basic session operations */ getStreamID, getServerName, getCreationDate, getLastActiveDate, getNumClientPackets, getNumServerPackets, getTLSProtocolName, getCipherSuiteName, getPeerCertificates, getSoftwareVersion, close, isClosed, @Deprecated isSecure, // Replaced with 'isEncrypted', replace in Openfire 4.9 or later. isEncrypted, getHostAddress, getHostName, validate, removeDetached, /** * Operations of c2s sessions */ isInitialized, incrementConflictCount, hasRequestedBlocklist, /** * Operations of outgoing server sessions */ getOutgoingDomainPairs, getAuthenticationMethod, /** * Operations of external component sessions */ getType, getCategory, getInitialSubdomain, getSubdomains, getName, getDescription, start, shutdown, /** * Operations of incoming server sessions */ getLocalDomain, getAddress, getValidatedDomains } }
ExternalizableUtil.getInstance().writeBoolean(out, operation != null); if (operation != null) { ExternalizableUtil.getInstance().writeInt(out, operation.ordinal()); }
1,567
54
1,621
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/SoftwareServerVersionManager.java
SoftwareServerVersionManager
sessionCreated
class SoftwareServerVersionManager extends BasicModule implements ServerSessionEventListener { private static final Logger Log = LoggerFactory.getLogger(SoftwareServerVersionManager.class); public SoftwareServerVersionManager() { super("Software Server Version Manager"); } @Override public void start() throws IllegalStateException { super.start(); ServerSessionEventDispatcher.addListener(this); } @Override public void stop() { super.stop(); ServerSessionEventDispatcher.removeListener(this); } @Override public void sessionCreated(Session session) {<FILL_FUNCTION_BODY>} @Override public void sessionDestroyed(Session session) { } }
try { IQ versionRequest = new IQ(IQ.Type.get); versionRequest.setTo(session.getAddress()); versionRequest.setFrom(session.getServerName()); versionRequest.setChildElement("query", "jabber:iq:version"); session.process(versionRequest); } catch (Exception e) { Log.error("Exception while trying to query a server for its software version.", e);; }
189
116
305
<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/session/SoftwareVersionManager.java
SoftwareVersionManager
resourceBound
class SoftwareVersionManager extends BasicModule implements SessionEventListener { private static final Logger Log = LoggerFactory.getLogger(SoftwareVersionManager.class); public static final SystemProperty<Boolean> VERSION_QUERY_ENABLED = SystemProperty.Builder.ofType( Boolean.class ) .setKey("xmpp.client.version-query.enabled") .setDefaultValue(true) .setDynamic(true) .build(); public static final SystemProperty<Duration> VERSION_QUERY_DELAY = SystemProperty.Builder.ofType( Duration.class ) .setKey("xmpp.client.version-query.delay") .setChronoUnit(ChronoUnit.MILLIS) .setDefaultValue(Duration.ofSeconds(5)) .setDynamic(true) .build(); public SoftwareVersionManager() { super("Software Version Manager"); } @Override public void start() throws IllegalStateException { super.start(); SessionEventDispatcher.addListener(this); } @Override public void stop() { super.stop(); SessionEventDispatcher.removeListener(this); } @Override public void sessionCreated(Session session) { } @Override public void sessionDestroyed(Session session) { } @Override public void anonymousSessionCreated(Session session) { } @Override public void anonymousSessionDestroyed(Session session) { } @Override public void resourceBound(final Session session) {<FILL_FUNCTION_BODY>} }
if (!VERSION_QUERY_ENABLED.getValue()) { return; } // Prevent retaining a reference to the session object, while waiting for the right time to execute the query. // There's (unproven) concern that this is a factor in issue OF-2367. Better safe than sorry. final JID address = session.getAddress(); // The server should not send requests to the client before the client session // has been established (see IQSessionEstablishmentHandler). Sadly, Openfire // does not provide a hook for this. For now, the resource bound event is // used instead (which should be immediately followed by session establishment). TaskEngine.getInstance().schedule( new TimerTask() { @Override public void run() { try { final Session session = SessionManager.getInstance().getSession(address); if (session == null || session.isClosed() || !VERSION_QUERY_ENABLED.getValue()){ return; } IQ versionRequest = new IQ(IQ.Type.get); versionRequest.setTo(session.getAddress()); versionRequest.setFrom(session.getServerName()); versionRequest.setChildElement("query", "jabber:iq:version"); session.process(versionRequest); } catch (Exception e) { Log.error("Exception while trying to query a client ({}) for its software version.", session.getAddress(), e); }} }, VERSION_QUERY_DELAY.getValue()); // Let time pass for the session establishment to have occurred.
414
388
802
<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/spi/BasicStreamIDFactory.java
BasicStreamID
getCachedSize
class BasicStreamID implements StreamID, Cacheable { String id; public BasicStreamID(String id) { if ( id == null || id.isEmpty() ) { throw new IllegalArgumentException( "Argument 'id' cannot be null." ); } this.id = StringEscapeUtils.escapeXml10( id ); } @Override public String getID() { return id; } @Override public String toString() { return id; } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals( Object o ) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; return id.equals( ((BasicStreamID) o).id ); } @Override public int getCachedSize() throws CannotCalculateSizeException {<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(id); // id return size;
257
69
326
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/spi/ClientRoute.java
ClientRoute
readExternal
class ClientRoute implements Cacheable, Externalizable { private NodeID nodeID; private boolean available; public ClientRoute() { } public NodeID getNodeID() { return nodeID; } public void setNodeID( final NodeID nodeID ) { this.nodeID = nodeID; } public boolean isAvailable() { return available; } public ClientRoute(NodeID nodeID, boolean available) { this.nodeID = nodeID; this.available = available; } @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 += nodeID.toByteArray().length; // Node ID size += CacheSizes.sizeOfBoolean(); // available return size; } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeByteArray(out, nodeID.toByteArray()); ExternalizableUtil.getInstance().writeBoolean(out, available); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} @Override public String toString() { return "ClientRoute{" + "nodeID=" + nodeID + ", available=" + available + '}'; } }
byte[] bytes = ExternalizableUtil.getInstance().readByteArray(in); // Retrieve the NodeID but try to use the singleton instance if (XMPPServer.getInstance().getNodeID().equals(bytes)) { nodeID = XMPPServer.getInstance().getNodeID(); } else { nodeID = NodeID.getInstance(bytes); } available = ExternalizableUtil.getInstance().readBoolean(in);
395
112
507
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/spi/LocalRoutingTable.java
LocalRoutingTable
addRoute
class LocalRoutingTable { private static final Logger Log = LoggerFactory.getLogger(LocalRoutingTable.class); Map<DomainPair, RoutableChannelHandler> routes = new ConcurrentHashMap<>(); /** * Adds a route of a local {@link RoutableChannelHandler} * * @param pair DomainPair associated to the route. * @param route the route hosted by this node. * @return true if the element was added or false if was already present. */ boolean addRoute(DomainPair pair, RoutableChannelHandler route) {<FILL_FUNCTION_BODY>} /** * Returns the route hosted by this node that is associated to the specified address. * * @param pair DomainPair associated to the route. * @return the route hosted by this node that is associated to the specified address. */ RoutableChannelHandler getRoute(DomainPair pair) { return routes.get(pair); } RoutableChannelHandler getRoute(JID jid) { return routes.get(new DomainPair("", jid.toString())); } /** * Returns the client sessions that are connected to this JVM. * * @return the client sessions that are connected to this JVM. */ Collection<LocalClientSession> getClientRoutes() { List<LocalClientSession> sessions = new ArrayList<>(); for (RoutableChannelHandler route : routes.values()) { if (route instanceof LocalClientSession) { sessions.add((LocalClientSession) route); } } return sessions; } /** * Returns the outgoing server sessions that are connected to this JVM. * * @return the outgoing server sessions that are connected to this JVM. */ Collection<LocalOutgoingServerSession> getServerRoutes() { List<LocalOutgoingServerSession> sessions = new ArrayList<>(); for (RoutableChannelHandler route : routes.values()) { if (route instanceof LocalOutgoingServerSession) { sessions.add((LocalOutgoingServerSession) route); } } return sessions; } /** * Returns the external component sessions that are connected to this JVM. * * @return the external component sessions that are connected to this JVM. */ Collection<RoutableChannelHandler> getComponentRoute() { List<RoutableChannelHandler> sessions = new ArrayList<>(); for (RoutableChannelHandler route : routes.values()) { if (!(route instanceof LocalOutgoingServerSession || route instanceof LocalClientSession)) { sessions.add(route); } } return sessions; } /** * Removes a route of a local {@link RoutableChannelHandler} * * @param pair DomainPair associated to the route. */ void removeRoute(DomainPair pair) { final RoutableChannelHandler removed = routes.remove(pair); Log.trace( "Remove local route '{}' (for pair: '{}') {}", removed == null ? "(null)" : removed.getAddress(), pair, removed != null ? "removed" : "not removed (was not present)."); } public void start() { // Run through the server sessions every 3 minutes after a 3 minutes server startup delay (default values) Duration period = Duration.ofMinutes(3); TaskEngine.getInstance().scheduleAtFixedRate(new ServerCleanupTask(), period, period); } public void stop() { try { // Send the close stream header to all connected connections for (RoutableChannelHandler route : routes.values()) { if (route instanceof LocalSession) { LocalSession session = (LocalSession) route; try { // Notify connected client that the server is being shut down if (session.getConnection() != null) { // Can occur if a session is 'detached'. session.getConnection().systemShutdown(); } } catch (Throwable t) { Log.debug("A throwable was thrown while trying to send the close stream header to a session.", t); } } } } catch (Exception e) { Log.debug("An exception was thrown while trying to send the close stream header to a session.", e); } } public boolean isLocalRoute(DomainPair pair) { return routes.containsKey(pair); } public boolean isLocalRoute(JID jid) { return routes.containsKey(new DomainPair("", jid.toString())); } /** * Task that closes idle server sessions. */ private class ServerCleanupTask extends TimerTask { /** * Close outgoing server sessions that have been idle for a long time. */ @Override public void run() { // Do nothing if this feature is disabled int idleTime = SessionManager.getInstance().getServerSessionIdleTime(); if (idleTime == -1) { return; } final long deadline = System.currentTimeMillis() - idleTime; for (RoutableChannelHandler route : routes.values()) { // Check outgoing server sessions if (route instanceof OutgoingServerSession) { Session session = (Session) route; try { if (session.getLastActiveDate().getTime() < deadline) { Log.debug( "ServerCleanupTask is closing an outgoing server session that has been idle for a long time. Last active: {}. Session to be closed: {}", session.getLastActiveDate(), session ); session.close(); } } catch (Throwable e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } } }
final boolean result = routes.put(pair, route) != route; Log.trace( "Route '{}' (for pair: '{}') {}", route.getAddress(), pair, result ? "added" : "not added (was already present)." ); return result;
1,448
69
1,517
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/spi/NettyServerInitializer.java
NettyServerInitializer
initChannel
class NettyServerInitializer extends ChannelInitializer<SocketChannel> { private static final Logger Log = LoggerFactory.getLogger(NettyServerInitializer.class); /** * Controls the write timeout time in seconds to handle stalled sessions and prevent DoS */ public static final SystemProperty<Duration> WRITE_TIMEOUT_SECONDS = SystemProperty.Builder.ofType(Duration.class) .setKey("xmpp.socket.write-timeout-seconds") .setDefaultValue(Duration.ofSeconds(30)) .setChronoUnit(ChronoUnit.SECONDS) .setDynamic(true) .build(); public static final String TRAFFIC_HANDLER_NAME = "trafficShapingHandler"; private final ChannelGroup allChannels; // This is a collection that is managed by the invoking entity. private final ConnectionConfiguration configuration; private final Set<NettyChannelHandlerFactory> channelHandlerFactories; // This is a collection that is managed by the invoking entity. public NettyServerInitializer(ConnectionConfiguration configuration, ChannelGroup allChannels, Set<NettyChannelHandlerFactory> channelHandlerFactories) { this.allChannels = allChannels; this.configuration = configuration; this.channelHandlerFactories = channelHandlerFactories; } @Override public void initChannel(SocketChannel ch) throws Exception {<FILL_FUNCTION_BODY>} private boolean isDirectTLSConfigured() { return this.configuration.getTlsPolicy() == Connection.TLSPolicy.directTLS; } }
boolean isClientConnection = configuration.getType() == ConnectionType.SOCKET_C2S; NettyConnectionHandler businessLogicHandler = NettyConnectionHandlerFactory.createConnectionHandler(configuration); Duration maxIdleTimeBeforeClosing = businessLogicHandler.getMaxIdleTime().isNegative() ? Duration.ZERO : businessLogicHandler.getMaxIdleTime(); ch.pipeline() .addLast(TRAFFIC_HANDLER_NAME, new ChannelTrafficShapingHandler(0)) .addLast("idleStateHandler", new IdleStateHandler(maxIdleTimeBeforeClosing.dividedBy(2).toMillis(), 0, 0, TimeUnit.MILLISECONDS)) .addLast("keepAliveHandler", new NettyIdleStateKeepAliveHandler(isClientConnection)) .addLast(new NettyXMPPDecoder()) .addLast(new StringEncoder(StandardCharsets.UTF_8)) .addLast("stalledSessionHandler", new WriteTimeoutHandler(Math.toIntExact(WRITE_TIMEOUT_SECONDS.getValue().getSeconds()))) .addLast(businessLogicHandler); // Add ChannelHandler providers implemented by plugins, if any. channelHandlerFactories.forEach(factory -> { try { factory.addNewHandlerTo(ch.pipeline()); } catch (Throwable t) { Log.warn("Unable to add ChannelHandler from '{}' to pipeline of new channel: {}", factory, ch, t); } }); if (isDirectTLSConfigured()) { ch.attr(CONNECTION).get().startTLS(false, true); } allChannels.add(ch);
399
435
834
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/spi/PacketDelivererImpl.java
PacketDelivererImpl
deliver
class PacketDelivererImpl extends BasicModule implements PacketDeliverer { /** * The handler that does the actual delivery (could be a channel instead) */ protected SocketPacketWriteHandler deliverHandler; public PacketDelivererImpl() { super("Packet Delivery"); } @Override public void deliver(Packet packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} @Override public void start() throws IllegalStateException { super.start(); deliverHandler = new SocketPacketWriteHandler(XMPPServer.getInstance().getRoutingTable()); } @Override public void stop() { super.stop(); deliverHandler = null; } }
if (packet == null) { throw new PacketException("Packet was null"); } if (deliverHandler == null) { throw new PacketException("Could not send packet - no route" + packet.toString()); } // Let the SocketPacketWriteHandler process the packet. SocketPacketWriteHandler may send // it over the socket or store it when user is offline or drop it. deliverHandler.process(packet);
195
115
310
<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/spi/PacketRouterImpl.java
PacketRouterImpl
route
class PacketRouterImpl extends BasicModule implements PacketRouter { private IQRouter iqRouter; private PresenceRouter presenceRouter; private MessageRouter messageRouter; /** * Constructs a packet router. */ public PacketRouterImpl() { super("XMPP Packet Router"); } /** * Routes the given packet based on packet recipient and sender. The * router defers actual routing decisions to other classes. * <h2>Warning</h2> * Be careful to enforce concurrency DbC of concurrent by synchronizing * any accesses to class resources. * * @param packet The packet to route */ @Override public void route(Packet packet) {<FILL_FUNCTION_BODY>} @Override public void route(IQ packet) { iqRouter.route(packet); } @Override public void route(Message packet) { messageRouter.route(packet); } @Override public void route(Presence packet) { presenceRouter.route(packet); } @Override public void initialize(XMPPServer server) { super.initialize(server); iqRouter = server.getIQRouter(); messageRouter = server.getMessageRouter(); presenceRouter = server.getPresenceRouter(); } }
if (packet instanceof Message) { route((Message)packet); } else if (packet instanceof Presence) { route((Presence)packet); } else if (packet instanceof IQ) { route((IQ)packet); } else { throw new IllegalArgumentException(); }
372
89
461
<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/spi/PacketTransporterImpl.java
PacketTransporterImpl
deliver
class PacketTransporterImpl extends BasicModule { private static final Logger Log = LoggerFactory.getLogger(PacketTransporterImpl.class); /** * The handler that does the actual delivery (could be a channel instead) */ private TransportHandler transportHandler; /** * deliverer for xmpp server */ private PacketDeliverer deliverer; /** * xmpp server */ private XMPPServer xmppServer; /** * This is a singleton, you can't create one. Be very careful not to do anything * that refers back to the factory's create method. Do initialization in the init() * method if at all possible. */ public PacketTransporterImpl() { super("XMPP Packet Transporter"); } /** * Obtain the transport handler that this transporter uses for delivering * transport packets. * * @return The transport handler instance used by this transporter */ public TransportHandler getTransportHandler() { return transportHandler; } /** * Delivers the given packet based on packet recipient and sender. The * deliverer defers actual routing decisions to other classes. * <h2>Warning</h2> * Be careful to enforce concurrency DbC of concurrent by synchronizing * any accesses to class resources. * * @param packet The packet to route * @throws NullPointerException If the packet is null or the * packet could not be routed * @throws UnauthorizedException if the user is not authorised */ public void deliver(Packet packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} @Override public void initialize(XMPPServer server) { super.initialize(server); xmppServer = server; deliverer = server.getPacketDeliverer(); transportHandler = server.getTransportHandler(); } }
if (packet == null) { throw new NullPointerException(); } if (xmppServer != null && xmppServer.isLocal(packet.getTo())) { deliverer.deliver(packet); } else if (transportHandler != null) { transportHandler.process(packet); } else { Log.warn("Could not deliver message: no deliverer available " + packet.toString()); }
505
123
628
<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/spi/XMPPServerInfoImpl.java
XMPPServerInfoImpl
getHostname
class XMPPServerInfoImpl implements XMPPServerInfo { private static final Logger Log = LoggerFactory.getLogger( XMPPServerInfoImpl.class ); private final Date startDate; public static final Version VERSION = new Version(4, 9, 0, Version.ReleaseStatus.Alpha, -1 ); /** * Simple constructor * * @param startDate the server's last start time (can be null indicating * it hasn't been started). */ public XMPPServerInfoImpl(Date startDate) { this.startDate = startDate; } @Override public Version getVersion() { return VERSION; } @Override public String getHostname() {<FILL_FUNCTION_BODY>} @Override public void setHostname( String fqdn ) { if ( fqdn == null || fqdn.isEmpty() ) { JiveGlobals.deleteXMLProperty( "fqdn" ); } else { JiveGlobals.setXMLProperty( "fqdn", fqdn.toLowerCase() ); } } @Override public String getXMPPDomain() { return Optional.ofNullable(XMPP_DOMAIN.getValue()).orElse(getHostname()).toLowerCase(); } @Override public Date getLastStarted() { return startDate; } }
final String fqdn = JiveGlobals.getXMLProperty( "fqdn" ); if ( fqdn != null && !fqdn.trim().isEmpty() ) { return fqdn.trim().toLowerCase(); } try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(); } catch (UnknownHostException ex) { Log.warn( "Unable to determine local hostname.", ex ); return "localhost"; }
383
136
519
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/stanzaid/StanzaIDUtil.java
StanzaIDUtil
ensureUniqueAndStableStanzaID
class StanzaIDUtil { private static final Logger Log = LoggerFactory.getLogger( StanzaIDUtil.class ); /** * Modifies the stanza that's passed as a packet by adding a Stanza ID on behalf of what is assumed to be a local * entity. * * @param packet The inbound packet (cannot be null). * @param self The ID of the 'local' entity that will generate the stanza ID (cannot be null). * @return the updated packet * @see <a href="https://xmpp.org/extensions/xep-0359.html">XEP-0359</a> */ public static Packet ensureUniqueAndStableStanzaID( final Packet packet, final JID self ) {<FILL_FUNCTION_BODY>} /** * Returns the first stable and unique stanza-id value from the packet, that is defined * for a particular 'by' value. * * This method does not evaluate 'origin-id' elements in the packet. * * @param packet The stanza (cannot be null). * @param by The 'by' value for which to return the ID (cannot be null or an empty string). * @return The unique and stable ID, or null if no such ID is found. */ public static String findFirstUniqueAndStableStanzaID( final Packet packet, final String by ) { if ( packet == null ) { throw new IllegalArgumentException( "Argument 'packet' cannot be null." ); } if ( by == null || by.isEmpty() ) { throw new IllegalArgumentException( "Argument 'by' cannot be null or an empty string." ); } final List<Element> sids = packet.getElement().elements( QName.get( "stanza-id", "urn:xmpp:sid:0" ) ); if ( sids == null ) { return null; } for ( final Element sid : sids ) { if ( by.equals( sid.attributeValue( "by" ) ) ) { final String result = sid.attributeValue( "id" ); if ( result != null && !result.isEmpty() ) { return result; } } } return null; } }
if ( !JiveGlobals.getBooleanProperty( "xmpp.sid.enabled", true ) ) { return packet; } if ( packet instanceof IQ && !JiveGlobals.getBooleanProperty( "xmpp.sid.iq.enabled", false ) ) { return packet; } if ( packet instanceof Message && !JiveGlobals.getBooleanProperty( "xmpp.sid.message.enabled", true ) ) { return packet; } if ( packet instanceof Presence && !JiveGlobals.getBooleanProperty( "xmpp.sid.presence.enabled", false ) ) { return packet; } final Element parentElement; if ( packet instanceof IQ ) { parentElement = ((IQ) packet).getChildElement(); } else { parentElement = packet.getElement(); } // The packet likely is an IQ result or error, which can, but are not required to have a child element. // To have a consistent behavior for these, we'll not add a stanza-ID here. if ( parentElement == null ) { Log.debug( "Unable to find appropriate element. Not adding stanza-id to packet: {}", packet ); return packet; } // Stanza ID generating entities, which encounter a <stanza-id/> element where the 'by' attribute matches the 'by' // attribute they would otherwise set, MUST delete that element even if they are not adding their own stanza ID. final Iterator<Element> existingElementIterator = parentElement.elementIterator( QName.get( "stanza-id", "urn:xmpp:sid:0" ) ); while (existingElementIterator.hasNext()) { final Element element = existingElementIterator.next(); if (self.toString().equals( element.attributeValue( "by" ) ) ) { Log.warn( "Removing a 'stanza-id' element from an inbound stanza, as its 'by' attribute value matches the value that we would set. Offending stanza: {}", packet ); existingElementIterator.remove(); } } final String id = UUID.randomUUID().toString(); Log.debug( "Using newly generated value '{}' for stanza that has id '{}'.", id, packet.getID() ); final Element stanzaIdElement = parentElement.addElement( QName.get( "stanza-id", "urn:xmpp:sid:0" ) ); stanzaIdElement.addAttribute( "id", id ); stanzaIdElement.addAttribute( "by", self.toString() ); return packet;
598
677
1,275
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/stats/StatisticsManager.java
StatisticsManager
addMultiStatistic
class StatisticsManager { private static StatisticsManager instance = new StatisticsManager(); public static StatisticsManager getInstance() { return instance; } private final Map<String, Statistic> statistics = new ConcurrentHashMap<>(); private final Map<String, List<String>> multiStatGroups = new ConcurrentHashMap<>(); private final Map<String, String> keyToGroupMap = new ConcurrentHashMap<>(); private StatisticsManager() { } /** * Adds a stat to be tracked to the StatManager. * * @param statKey the statistic key. * @param definition the statistic to be tracked. */ public void addStatistic(String statKey, Statistic definition) { statistics.put(statKey, definition); } /** * Returns a statistic being tracked by the StatManager. * * @param statKey The key of the definition. * @return Returns the related stat. */ public Statistic getStatistic(String statKey) { return statistics.get(statKey); } public void addMultiStatistic(String statKey, String groupName, Statistic statistic) {<FILL_FUNCTION_BODY>} public List<String> getStatGroup(String statGroup) { return multiStatGroups.get(statGroup); } public String getMultistatGroup(String statKey) { return keyToGroupMap.get(statKey); } /** * Returns all statistics that the StatManager is tracking. * @return Returns all statistics that the StatManager is tracking. */ public Set<Map.Entry<String, Statistic>> getAllStatistics() { return statistics.entrySet(); } /** * Removes a statistic from the server. * * @param statKey The key of the stat to be removed. */ public void removeStatistic(String statKey) { statistics.remove(statKey); } }
addStatistic(statKey, statistic); List<String> group = multiStatGroups.get(groupName); if(group == null) { group = new ArrayList<>(); multiStatGroups.put(groupName, group); } group.add(statKey); keyToGroupMap.put(statKey, groupName);
511
89
600
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/stats/i18nStatistic.java
i18nStatistic
retrieveValue
class i18nStatistic implements Statistic { private String resourceKey; private String pluginName; private Type statisticType; public i18nStatistic(String resourceKey, Statistic.Type statisticType) { this(resourceKey, null, statisticType); } public i18nStatistic(String resourceKey, String pluginName, Statistic.Type statisticType) { this.resourceKey = resourceKey; this.pluginName = pluginName; this.statisticType = statisticType; } @Override public final String getName() { return retrieveValue("name"); } @Override public final Type getStatType() { return statisticType; } @Override public final String getDescription() { return retrieveValue("desc"); } @Override public final String getUnits() { return retrieveValue("units"); } private String retrieveValue(String key) {<FILL_FUNCTION_BODY>} }
String wholeKey = "stat." + resourceKey + "." + key; if (pluginName != null) { return LocaleUtils.getLocalizedString(wholeKey, pluginName); } else { return LocaleUtils.getLocalizedString(wholeKey); }
266
75
341
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/transport/TransportHandler.java
TransportHandler
process
class TransportHandler extends BasicModule implements ChannelHandler { private static final Logger Log = LoggerFactory.getLogger(TransportHandler.class); private Map<String, Channel<Packet>> transports = new ConcurrentHashMap<>(); private PacketDeliverer deliverer; public TransportHandler() { super("Transport handler"); } public void addTransport(Channel<Packet> transport) { transports.put(transport.getName(), transport); } @Override public void process(Packet packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} @Override public void initialize(XMPPServer server) { super.initialize(server); deliverer = server.getPacketDeliverer(); } }
boolean handled = false; String host = packet.getTo().getDomain(); for (Channel<Packet> channel : transports.values()) { if (channel.getName().equalsIgnoreCase(host)) { channel.add(packet); handled = true; } } if (!handled) { JID recipient = packet.getTo(); JID sender = packet.getFrom(); packet.setError(PacketError.Condition.remote_server_timeout); packet.setFrom(recipient); packet.setTo(sender); try { deliverer.deliver(packet); } catch (PacketException e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } }
203
202
405
<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/update/AvailablePlugin.java
AvailablePlugin
getInstance
class AvailablePlugin extends PluginMetadata { private static final Logger Log = LoggerFactory.getLogger( AvailablePlugin.class ); private static final DateFormat RELEASE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private static final DateFormat RELEASE_DATE_DISPLAY_FORMAT = DateFormat.getDateInstance(DateFormat.MEDIUM); /** * URL from where the latest version of the plugin can be downloaded. */ private final URL downloadURL; /** * Size in bytes of the plugin jar file. */ private final long fileSize; private final String releaseDate; public static AvailablePlugin getInstance( Element plugin ) {<FILL_FUNCTION_BODY>} public AvailablePlugin(String name, String canonicalName, String description, Version latestVersion, String author, URL icon, URL changelog, URL readme, String license, Version minServerVersion, Version priorToServerVersion, JavaSpecVersion minJavaVersion, URL downloadUrl, long fileSize, final String releaseDate) { super( name, canonicalName, description, latestVersion, author, icon, changelog, readme, license, minServerVersion, priorToServerVersion, minJavaVersion, false ); this.downloadURL = downloadUrl; this.fileSize = fileSize; this.releaseDate = releaseDate; } /** * URL from where the latest version of the plugin can be downloaded. * * @return download URL. */ public URL getDownloadURL() { return downloadURL; } /** * Returns the size in bytes of the plugin jar file. * * @return the size in bytes of the plugin jar file. */ public long getFileSize() { return fileSize; } /** * @return the date the plugin was released */ public String getReleaseDate() { return releaseDate; } }
String pluginName = plugin.attributeValue("name"); Version latestVersion = null; String latestVersionValue = plugin.attributeValue("latest"); if ( latestVersionValue != null && !latestVersionValue.isEmpty() ) { latestVersion = new Version( latestVersionValue ); } URL icon = null; String iconValue = plugin.attributeValue("icon"); if ( iconValue != null && !iconValue.isEmpty() ) { try { icon = new URL( iconValue ); } catch ( MalformedURLException e ) { Log.warn( "Unable to create icon URL from value '{}' for plugin {}.", iconValue, pluginName, e ); } } URL readme = null; String readmeValue = plugin.attributeValue("readme"); if ( readmeValue != null && !readmeValue.isEmpty() ) { try { readme = new URL( readmeValue ); } catch ( MalformedURLException e ) { Log.warn( "Unable to create readme URL from value '{}' for plugin {}.", readmeValue, pluginName, e ); } } URL changelog = null; String changelogValue = plugin.attributeValue("changelog"); if ( changelogValue != null && !changelogValue.isEmpty() ) { try { changelog = new URL( changelogValue ); } catch ( MalformedURLException e ) { Log.warn( "Unable to create changelog URL from value '{}' for plugin {}.", changelogValue, pluginName, e ); } } URL downloadUrl = null; String downloadUrlValue = plugin.attributeValue("url"); if ( downloadUrlValue != null && !downloadUrlValue.isEmpty() ) { try { downloadUrl = new URL( downloadUrlValue ); } catch ( MalformedURLException e ) { Log.warn( "Unable to create download URL from value '{}' for plugin {}.", downloadUrlValue, pluginName, e ); } } String license = plugin.attributeValue("licenseType"); String description = plugin.attributeValue("description"); String author = plugin.attributeValue("author"); Version minServerVersion = null; String minServerVersionValue = plugin.attributeValue("minServerVersion"); if ( minServerVersionValue != null && !minServerVersionValue.isEmpty() ) { minServerVersion = new Version( minServerVersionValue ); } Version priorToServerVersion = null; String priorToServerVersionValue = plugin.attributeValue("priorToServerVersion"); if ( priorToServerVersionValue != null && !priorToServerVersionValue.isEmpty() ) { priorToServerVersion = new Version( priorToServerVersionValue ); } JavaSpecVersion minJavaVersion = null; String minJavaVersionValue = plugin.attributeValue( "minJavaVersion" ); if ( minJavaVersionValue != null && !minJavaVersionValue.isEmpty() ) { minJavaVersion = new JavaSpecVersion( minJavaVersionValue ); } String releaseDate = null; final String releaseDateString = plugin.attributeValue("releaseDate"); if( releaseDateString!= null) { try { releaseDate = RELEASE_DATE_DISPLAY_FORMAT.format(RELEASE_DATE_FORMAT.parse(releaseDateString)); } catch (final ParseException e) { Log.warn("Unexpected exception parsing release date: " + releaseDateString, e); } } long fileSize = -1; String fileSizeValue = plugin.attributeValue("fileSize"); if ( fileSizeValue != null && !fileSizeValue.isEmpty() ) { fileSize = Long.parseLong( fileSizeValue ); } String canonical = downloadUrlValue != null ? downloadUrlValue.substring( downloadUrlValue.lastIndexOf( '/' ) + 1, downloadUrlValue.lastIndexOf( '.' ) ) : null; return new AvailablePlugin( pluginName, canonical, description, latestVersion, author, icon, changelog, readme, license, minServerVersion, priorToServerVersion, minJavaVersion, downloadUrl, fileSize, releaseDate );
509
1,111
1,620
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, org.jivesoftware.util.Version, java.lang.String, java.net.URL, java.net.URL, java.net.URL, java.lang.String, org.jivesoftware.util.Version, org.jivesoftware.util.Version, org.jivesoftware.util.JavaSpecVersion, boolean) ,public java.lang.String getAuthor() ,public java.lang.String getCanonicalName() ,public java.net.URL getChangelog() ,public java.lang.String getDescription() ,public java.lang.String getHashCode() ,public java.net.URL getIcon() ,public static org.jivesoftware.openfire.container.PluginMetadata getInstance(java.nio.file.Path) ,public static org.jivesoftware.openfire.container.PluginMetadata getInstance(org.jivesoftware.openfire.container.Plugin) ,public java.lang.String getLicense() ,public org.jivesoftware.util.JavaSpecVersion getMinJavaVersion() ,public org.jivesoftware.util.Version getMinServerVersion() ,public java.lang.String getName() ,public org.jivesoftware.util.Version getPriorToServerVersion() ,public java.net.URL getReadme() ,public org.jivesoftware.util.Version getVersion() ,public boolean isCsrfProtectionEnabled() <variables>private final non-sealed java.lang.String author,private final non-sealed java.lang.String canonicalName,private final non-sealed java.net.URL changelog,private final non-sealed boolean csrfProtectionEnabled,private final non-sealed java.lang.String description,private final non-sealed java.net.URL icon,private final non-sealed java.lang.String license,private final non-sealed org.jivesoftware.util.JavaSpecVersion minJavaVersion,private final non-sealed org.jivesoftware.util.Version minServerVersion,private final non-sealed java.lang.String name,private final non-sealed org.jivesoftware.util.Version priorToServerVersion,private final non-sealed java.net.URL readme,private final non-sealed org.jivesoftware.util.Version version
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/update/PluginDownloadManager.java
PluginDownloadManager
installPlugin
class PluginDownloadManager { private static final Logger Log = LoggerFactory.getLogger(PluginDownloadManager.class); /** * Starts the download process of a given plugin with it's URL. * * @param url the url of the plugin to download. * @return the Update. */ public Update downloadPlugin(String url) { UpdateManager updateManager = XMPPServer.getInstance().getUpdateManager(); updateManager.downloadPlugin(url); Update returnUpdate = null; for (Update update : updateManager.getPluginUpdates()) { if (update.getURL().equals(url)) { returnUpdate = update; break; } } return returnUpdate; } /** * Installs a new plugin into Openfire. * * @param url the url of the plugin to install. * @param version the version of the new plugin * @param hashCode the matching hashcode of the <code>AvailablePlugin</code>. * @return the hashCode. */ public DownloadStatus installPlugin(String url, String version, int hashCode) {<FILL_FUNCTION_BODY>} /** * Updates the PluginList from the server. Please note, this method is used with javascript calls and will not * be found with a find usages. * * @return true if the plugin list was updated. */ public boolean updatePluginsList() { UpdateManager updateManager = XMPPServer.getInstance().getUpdateManager(); try { // Todo: Unify update checking into one xml file. Have the update check set the last check property. updateManager.checkForServerUpdate(true); updateManager.checkForPluginsUpdates(true); // Keep track of the last time we checked for updates UpdateManager.LAST_UPDATE_CHECK.setValue(Instant.now()); return true; } catch (Exception e) { Log.error(e.getMessage(), e); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } return false; } }
UpdateManager updateManager = XMPPServer.getInstance().getUpdateManager(); boolean worked = updateManager.downloadPlugin(url); final DownloadStatus status = new DownloadStatus(); status.setHashCode(hashCode); status.setVersion(version); status.setSuccessfull(worked); status.setUrl(url); return status;
543
93
636
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/AuthorizationBasedUserProviderMapper.java
AuthorizationBasedUserProviderMapper
getUserProvider
class AuthorizationBasedUserProviderMapper implements UserProviderMapper { /** * Name of the property of which the value is expected to be the classname of the UserProvider which will serve the * administrative users. */ public static final String PROPERTY_ADMINPROVIDER_CLASSNAME = "authorizationBasedUserMapper.adminProvider.className"; /** * Name of the property of which the value is expected to be the classname of the UserProvider which will serve the * regular, non-administrative users. */ public static final String PROPERTY_USERPROVIDER_CLASSNAME = "authorizationBasedUserMapper.userProvider.className"; /** * Serves the administrative users. */ protected final UserProvider adminProvider; /** * Serves the regular, non-administrative users. */ protected final UserProvider userProvider; public AuthorizationBasedUserProviderMapper() { // Migrate properties. JiveGlobals.migrateProperty( PROPERTY_ADMINPROVIDER_CLASSNAME ); JiveGlobals.migrateProperty( PROPERTY_USERPROVIDER_CLASSNAME ); // Instantiate providers. adminProvider = UserMultiProvider.instantiate( PROPERTY_ADMINPROVIDER_CLASSNAME ); if ( adminProvider == null ) { throw new IllegalStateException( "A class name for the admin provider must be specified via openfire.xml or the system properties using property: " + PROPERTY_ADMINPROVIDER_CLASSNAME ); } userProvider = UserMultiProvider.instantiate( PROPERTY_USERPROVIDER_CLASSNAME ); if ( userProvider == null ) { throw new IllegalStateException( "A class name for the user provider must be specified via openfire.xml or the system properties using property: " + PROPERTY_USERPROVIDER_CLASSNAME ); } } @Override public UserProvider getUserProvider( String username ) {<FILL_FUNCTION_BODY>} @Override public Set<UserProvider> getUserProviders() { final Set<UserProvider> result = new LinkedHashSet<>(); result.add( adminProvider ); result.add( userProvider ); return result; } }
// 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; }
577
105
682
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/HybridUserProvider.java
HybridUserProvider
deleteUser
class HybridUserProvider extends UserMultiProvider { private static final Logger Log = LoggerFactory.getLogger( HybridUserProvider.class ); private final List<UserProvider> userProviders = new ArrayList<>(); public HybridUserProvider() { // Migrate user provider properties JiveGlobals.migrateProperty( "hybridUserProvider.primaryProvider.className" ); JiveGlobals.migrateProperty( "hybridUserProvider.secondaryProvider.className" ); JiveGlobals.migrateProperty( "hybridUserProvider.tertiaryProvider.className" ); // Load primary, secondary, and tertiary user providers. final UserProvider primary = instantiate( "hybridUserProvider.primaryProvider.className" ); if ( primary != null ) { userProviders.add( primary ); } final UserProvider secondary = instantiate( "hybridUserProvider.secondaryProvider.className" ); if ( secondary != null ) { userProviders.add( secondary ); } final UserProvider tertiary = instantiate( "hybridUserProvider.tertiaryProvider.className" ); if ( tertiary != null ) { userProviders.add( tertiary ); } // Verify that there's at least one provider available. if ( userProviders.isEmpty() ) { Log.error( "At least one UserProvider must be specified via openfire.xml or the system properties!" ); } } @Override protected List<UserProvider> getUserProviders() { return userProviders; } /** * Creates a new user in the first non-read-only provider. * * @param username the username. * @param password the plain-text password. * @param name the user's name, which can be {@code null}, unless isNameRequired is set to true. * @param email the user's email address, which can be {@code null}, unless isEmailRequired is set to true. * @return The user that was created. * @throws UserAlreadyExistsException if the user already exists */ @Override public User createUser( String username, String password, String name, String email ) throws UserAlreadyExistsException { // create the user (first writable provider wins) for ( final UserProvider provider : getUserProviders() ) { if ( provider.isReadOnly() ) { continue; } return provider.createUser( username, password, name, email ); } // all providers are read-only throw new UnsupportedOperationException(); } /** * Removes a user from all non-read-only providers. * * @param username the username to delete. */ @Override public void deleteUser( String username ) {<FILL_FUNCTION_BODY>} /** * Returns the first provider that contains the user, or the first provider that is not read-only when the user * does not exist in any provider. * * @param username the username (cannot be null or empty). * @return The user provider (never null) */ public UserProvider getUserProvider( String username ) { UserProvider nonReadOnly = null; for ( final UserProvider provider : getUserProviders() ) { try { provider.loadUser( username ); return provider; } catch ( UserNotFoundException unfe ) { if ( Log.isDebugEnabled() ) { Log.debug( "User {} not found by UserProvider {}", username, provider.getClass().getName() ); } if ( nonReadOnly == null && !provider.isReadOnly() ) { nonReadOnly = provider; } } } // User does not exist. Return a provider suitable for creating users. if ( nonReadOnly == null ) { throw new UnsupportedOperationException(); } return nonReadOnly; } /** * Loads a user from the first provider that contains the user. * * @param username the username (cannot be null or empty). * @return The user (never null). * @throws UserNotFoundException When none of the providers contains the user. */ @Override public User loadUser( String username ) throws UserNotFoundException { for ( UserProvider provider : userProviders ) { try { return provider.loadUser( username ); } catch ( UserNotFoundException unfe ) { if ( Log.isDebugEnabled() ) { Log.debug( "User {} not found by UserProvider {}", username, provider.getClass().getName() ); } } } //if we get this far, no provider was able to load the user throw new UserNotFoundException(); } /** * Changes the creation date of a user in the first provider that contains the user. * * @param username the username. * @param creationDate the date the user was created. * @throws UserNotFoundException when the user was not found in any provider. * @throws UnsupportedOperationException when the provider is read-only. */ @Override public void setCreationDate( String username, Date creationDate ) throws UserNotFoundException { getUserProvider( username ).setCreationDate( username, creationDate ); } /** * Changes the modification date of a user in the first provider that contains the user. * * @param username the username. * @param modificationDate the date the user was (last) modified. * @throws UserNotFoundException when the user was not found in any provider. * @throws UnsupportedOperationException when the provider is read-only. */ @Override public void setModificationDate( String username, Date modificationDate ) throws UserNotFoundException { getUserProvider( username ).setCreationDate( username, modificationDate ); } /** * Changes the full name of a user in the first provider that contains the user. * * @param username the username. * @param name the new full name a user. * @throws UserNotFoundException when the user was not found in any provider. * @throws UnsupportedOperationException when the provider is read-only. */ @Override public void setName( String username, String name ) throws UserNotFoundException { getUserProvider( username ).setEmail( username, name ); } /** * Changes the email address of a user in the first provider that contains the user. * * @param username the username. * @param email the new email address of a user. * @throws UserNotFoundException when the user was not found in any provider. * @throws UnsupportedOperationException when the provider is read-only. */ @Override public void setEmail( String username, String email ) throws UserNotFoundException { getUserProvider( username ).setEmail( username, email ); } }
// all providers are read-only if ( isReadOnly() ) { throw new UnsupportedOperationException(); } for ( final UserProvider provider : getUserProviders() ) { if ( provider.isReadOnly() ) { continue; } provider.deleteUser( username ); }
1,782
88
1,870
<methods>public non-sealed void <init>() ,public Collection<org.jivesoftware.openfire.user.User> findUsers(Set<java.lang.String>, java.lang.String) throws java.lang.UnsupportedOperationException,public Collection<org.jivesoftware.openfire.user.User> findUsers(Set<java.lang.String>, java.lang.String, int, int) throws java.lang.UnsupportedOperationException,public Set<java.lang.String> getSearchFields() throws java.lang.UnsupportedOperationException,public int getUserCount() ,public Collection<java.lang.String> getUsernames() ,public Collection<org.jivesoftware.openfire.user.User> getUsers() ,public Collection<org.jivesoftware.openfire.user.User> getUsers(int, int) ,public static org.jivesoftware.openfire.user.UserProvider instantiate(java.lang.String) ,public boolean isEmailRequired() ,public boolean isNameRequired() ,public boolean isReadOnly() <variables>private static final Logger Log
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/MappedUserProvider.java
MappedUserProvider
loadUser
class MappedUserProvider extends UserMultiProvider { /** * Name of the property of which the value is expected to be the classname of the UserProviderMapper instance to be * used by instances of this class. */ public static final String PROPERTY_MAPPER_CLASSNAME = "mappedUserProvider.mapper.className"; /** * Used to determine what provider is to be used to operate on a particular user. */ protected final UserProviderMapper mapper; public MappedUserProvider() { // 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 = (UserProviderMapper) c.newInstance(); } catch ( Exception e ) { throw new IllegalStateException( "Unable to create new instance of UserProviderMapper class: " + mapperClass, e ); } } @Override public Collection<UserProvider> getUserProviders() { return mapper.getUserProviders(); } @Override public UserProvider getUserProvider( String username ) { return mapper.getUserProvider( username ); } @Override public User loadUser( String username ) throws UserNotFoundException {<FILL_FUNCTION_BODY>} @Override public User createUser( String username, String password, String name, String email ) throws UserAlreadyExistsException { return getUserProvider( username ).createUser( username, password, name, email ); } @Override public void deleteUser( String username ) { getUserProvider( username ).deleteUser( username ); } @Override public void setName( String username, String name ) throws UserNotFoundException { getUserProvider( username ).setName( username, name ); } @Override public void setEmail( String username, String email ) throws UserNotFoundException { getUserProvider( username ).setEmail( username, email ); } @Override public void setCreationDate( String username, Date creationDate ) throws UserNotFoundException { getUserProvider( username ).setCreationDate( username, creationDate ); } @Override public void setModificationDate( String username, Date modificationDate ) throws UserNotFoundException { getUserProvider( username ).setModificationDate( username, modificationDate ); } }
final UserProvider userProvider; try{ userProvider = getUserProvider( username ); } catch (RuntimeException e){ throw new UserNotFoundException("Unable to identify user provider for username "+username, e); } return userProvider.loadUser( username );
709
71
780
<methods>public non-sealed void <init>() ,public Collection<org.jivesoftware.openfire.user.User> findUsers(Set<java.lang.String>, java.lang.String) throws java.lang.UnsupportedOperationException,public Collection<org.jivesoftware.openfire.user.User> findUsers(Set<java.lang.String>, java.lang.String, int, int) throws java.lang.UnsupportedOperationException,public Set<java.lang.String> getSearchFields() throws java.lang.UnsupportedOperationException,public int getUserCount() ,public Collection<java.lang.String> getUsernames() ,public Collection<org.jivesoftware.openfire.user.User> getUsers() ,public Collection<org.jivesoftware.openfire.user.User> getUsers(int, int) ,public static org.jivesoftware.openfire.user.UserProvider instantiate(java.lang.String) ,public boolean isEmailRequired() ,public boolean isNameRequired() ,public boolean isReadOnly() <variables>private static final Logger Log
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/PresenceEventDispatcher.java
PresenceEventDispatcher
addListener
class PresenceEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(PresenceEventDispatcher.class); private static List<PresenceEventListener> listeners = new CopyOnWriteArrayList<>(); /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(PresenceEventListener listener) {<FILL_FUNCTION_BODY>} /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(PresenceEventListener listener) { listeners.remove(listener); } /** * Notification message indicating that a session that was not available is now * available. A session becomes available when an available presence is received. * Sessions that are available will have a route in the routing table thus becoming * eligible for receiving messages (in particular messages sent to the user bare JID). * * @param session the session that is now available. * @param presence the received available presence. */ public static void availableSession(ClientSession session, Presence presence) { if (!listeners.isEmpty()) { for (PresenceEventListener listener : listeners) { try { listener.availableSession(session, presence); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'availableSession' event!", e); } } } } /** * Notification message indicating that a session that was available is no longer * available. A session becomes unavailable when an unavailable presence is received. * The entity may still be connected to the server and may send an available presence * later to indicate that communication can proceed. * * @param session the session that is no longer available. * @param presence the received unavailable presence. */ public static void unavailableSession(ClientSession session, Presence presence) { if (!listeners.isEmpty()) { for (PresenceEventListener listener : listeners) { try { listener.unavailableSession(session, presence); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'unavailableSession' event!", e); } } } } /** * Notification message indicating that an available session has changed its * presence. This is the case when the user presence changed the show value * (e.g. away, dnd, etc.) or the presence status message. * * @param session the affected session. * @param presence the received available presence with the new information. */ public static void presenceChanged(ClientSession session, Presence presence) { if (!listeners.isEmpty()) { for (PresenceEventListener listener : listeners) { try { listener.presenceChanged(session, presence); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'presenceChanged' event!", e); } } } } /** * Notification message indicating that a user has successfully subscribed * to the presence of another user. * * @param subscriberJID the user that initiated the subscription. * @param authorizerJID the user that authorized the subscription. */ public static void subscribedToPresence(JID subscriberJID, JID authorizerJID) { if (!listeners.isEmpty()) { for (PresenceEventListener listener : listeners) { try { listener.subscribedToPresence(subscriberJID, authorizerJID); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'subscribedToPresence' event!", e); } } } } /** * Notification message indicating that a user has unsubscribed * to the presence of another user. * * @param unsubscriberJID the user that initiated the unsubscribe request. * @param recipientJID the recipient user of the unsubscribe request. */ public static void unsubscribedToPresence(JID unsubscriberJID, JID recipientJID) { if (!listeners.isEmpty()) { for (PresenceEventListener listener : listeners) { try { listener.unsubscribedToPresence(unsubscriberJID, recipientJID); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'unsubscribedToPresence' event!", e); } } } } }
if (listener == null) { throw new NullPointerException(); } listeners.add(listener);
1,149
33
1,182
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/PropertyBasedUserProviderMapper.java
PropertyBasedUserProviderMapper
getUserProvider
class PropertyBasedUserProviderMapper implements UserProviderMapper { protected final Map<String, UserProvider> providersByPrefix = new HashMap<>(); protected UserProvider fallbackProvider; public PropertyBasedUserProviderMapper() { // Migrate properties. JiveGlobals.migratePropertyTree( "propertyBasedUserMapper" ); // Instantiate the fallback provider fallbackProvider = UserMultiProvider.instantiate( "propertyBasedUserMapper.fallbackProvider.className" ); if ( fallbackProvider == null ) { throw new IllegalStateException( "Expected a UserProvider class name in property 'propertyBasedUserMapper.fallbackProvider.className'" ); } // Instantiate all sets final List<String> setProperties = JiveGlobals.getPropertyNames( "propertyBasedUserMapper.set" ); for ( final String setProperty : setProperties ) { final UserProvider provider = UserMultiProvider.instantiate( setProperty + ".provider.className" ); if ( provider == null ) { throw new IllegalStateException( "Expected a UserProvider class name in property '" + setProperty + ".provider.className'" ); } providersByPrefix.put( setProperty, provider ); } } @Override public UserProvider getUserProvider( String username ) {<FILL_FUNCTION_BODY>} @Override public Set<UserProvider> getUserProviders() { final Set<UserProvider> result = new LinkedHashSet<>(); result.addAll( providersByPrefix.values() ); result.add( fallbackProvider ); return result; } }
for ( final Map.Entry<String, UserProvider> 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;
411
146
557
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/UserCollection.java
UserIterator
next
class UserIterator implements Iterator<User> { private int currentIndex = -1; private User 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 User next() throws java.util.NoSuchElementException {<FILL_FUNCTION_BODY>} @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 User getNextElement() { while (currentIndex + 1 < elements.length) { currentIndex++; User element = null; try { element = UserManager.getInstance().getUser(elements[currentIndex]); } catch (UserNotFoundException unfe) { // Ignore. } if (element != null) { return element; } } return null; } }
User element; if (nextElement != null) { element = nextElement; nextElement = null; } else { element = getNextElement(); if (element == null) { throw new NoSuchElementException(); } } return element;
392
77
469
<methods>public boolean add(org.jivesoftware.openfire.user.User) ,public boolean addAll(Collection<? extends org.jivesoftware.openfire.user.User>) ,public void clear() ,public boolean contains(java.lang.Object) ,public boolean containsAll(Collection<?>) ,public boolean isEmpty() ,public abstract Iterator<org.jivesoftware.openfire.user.User> 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/user/UserNameManager.java
UserNameManager
getUserName
class UserNameManager { private static XMPPServer server = XMPPServer.getInstance(); /** * Map that keeps the UserNameProvider to use for each specific domain. */ private static Map<String, UserNameProvider> providersByDomain = new ConcurrentHashMap<>(); private UserNameManager() { } /** * Adds the specified {@link UserNameProvider} as the provider of users of the specified domain. * * @param domain the domain hosted by the UserNameProvider. * @param provider the provider that will provide the name of users in the specified domain. */ public static void addUserNameProvider(String domain, UserNameProvider provider) { providersByDomain.put(domain, provider); } /** * Removes any {@link UserNameProvider} that was associated with the specified domain. * * @param domain the domain hosted by a UserNameProvider. */ public static void removeUserNameProvider(String domain) { providersByDomain.remove(domain); } /** * Returns the name of the XMPP entity. If the entity is a local user then the User's name * will be returned. However, if the user is not a local user then check if there exists a * UserNameProvider that provides name for the specified domain. If none was found then * the vCard of the entity might be requested and if none was found then a string * representation of the entity's JID will be returned. * * @param entity the JID of the entity to get its name. * @return the name of the XMPP entity. * @throws UserNotFoundException if the jid belongs to the local server but no user was * found for that jid. */ public static String getUserName(JID entity) throws UserNotFoundException { return getUserName(entity, entity.toString()); } /** * Returns the name of the XMPP entity. If the entity is a local user then the User's name * will be returned. However, if the user is not a local user then check if there exists a * UserNameProvider that provides name for the specified domain. If none was found then * the vCard of the entity might be requested and if none was found then a string * representation of the entity's JID will be returned. * * @param entity the JID of the entity to get its name. * @param defaultName default name to return when no name was found. * @return the name of the XMPP entity. * @throws UserNotFoundException if the jid belongs to the local server but no user was * found for that jid. */ public static String getUserName(JID entity, String defaultName) throws UserNotFoundException {<FILL_FUNCTION_BODY>} }
if (server.isLocal(entity)) { // Contact is a local entity so search for his user name User localUser = UserManager.getInstance().getUser(entity.getNode()); return !localUser.isNameVisible() || "".equals(localUser.getName()) ? entity.getNode() : localUser.getName(); } else { UserNameProvider provider = providersByDomain.get(entity.getDomain()); if (provider != null) { return provider.getUserName(entity); } // TODO Request vCard to the remote server/component and return the name as // TODO defined in the vCard. We might need to cache this information to avoid // TODO high traffic. // Return the jid itself as the username return defaultName; }
697
193
890
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/property/DefaultUserPropertyProvider.java
DefaultUserPropertyProvider
insertProperty
class DefaultUserPropertyProvider implements UserPropertyProvider { private static final Logger Log = LoggerFactory.getLogger( DefaultUserPropertyProvider.class ); private static final String LOAD_PROPERTIES = "SELECT name, propValue FROM ofUserProp WHERE username=?"; private static final String LOAD_PROPERTY = "SELECT propValue FROM ofUserProp WHERE username=? AND name=?"; private static final String DELETE_PROPERTY = "DELETE FROM ofUserProp WHERE username=? AND name=?"; private static final String UPDATE_PROPERTY = "UPDATE ofUserProp SET propValue=? WHERE name=? AND username=?"; private static final String INSERT_PROPERTY = "INSERT INTO ofUserProp (username, name, propValue) VALUES (?, ?, ?)"; @Override public Map<String, String> loadProperties( String username ) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; final Map<String, String> properties = new ConcurrentHashMap<>(); try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement( LOAD_PROPERTIES ); pstmt.setString( 1, username ); rs = pstmt.executeQuery(); while ( rs.next() ) { properties.put( rs.getString( 1 ), rs.getString( 2 ) ); } } catch ( SQLException sqle ) { Log.error( sqle.getMessage(), sqle ); } finally { DbConnectionManager.closeConnection( rs, pstmt, con ); } return properties; } @Override public String loadProperty( String username, String propertyName ) { String propertyValue = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement( LOAD_PROPERTY ); pstmt.setString( 1, username ); pstmt.setString( 2, propertyName ); rs = pstmt.executeQuery(); while ( rs.next() ) { propertyValue = rs.getString( 1 ); } } catch ( SQLException sqle ) { Log.error( sqle.getMessage(), sqle ); } finally { DbConnectionManager.closeConnection( rs, pstmt, con ); } return propertyValue; } @Override public void insertProperty( String username, String propName, String propValue ) {<FILL_FUNCTION_BODY>} @Override public void updateProperty( String username, String propName, String propValue ) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement( UPDATE_PROPERTY ); pstmt.setString( 1, propValue ); pstmt.setString( 2, propName ); pstmt.setString( 3, username ); pstmt.executeUpdate(); } catch ( SQLException e ) { Log.error( e.getMessage(), e ); } finally { DbConnectionManager.closeConnection( pstmt, con ); } } @Override public void deleteProperty( String username, String propName ) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement( DELETE_PROPERTY ); pstmt.setString( 1, username ); pstmt.setString( 2, propName ); pstmt.executeUpdate(); } catch ( SQLException e ) { Log.error( e.getMessage(), e ); } finally { DbConnectionManager.closeConnection( pstmt, con ); } } @Override public boolean isReadOnly() { return false; } }
Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement( INSERT_PROPERTY ); pstmt.setString( 1, username ); pstmt.setString( 2, propName ); pstmt.setString( 3, propValue ); pstmt.executeUpdate(); } catch ( SQLException e ) { Log.error( e.getMessage(), e ); } finally { DbConnectionManager.closeConnection( pstmt, con ); }
1,057
156
1,213
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/property/HybridUserPropertyProvider.java
HybridUserPropertyProvider
updateProperty
class HybridUserPropertyProvider implements UserPropertyProvider { private static final Logger Log = LoggerFactory.getLogger( HybridUserPropertyProvider.class ); private final List<UserPropertyProvider> providers = new ArrayList<>(); public HybridUserPropertyProvider() { // Migrate user provider properties JiveGlobals.migrateProperty( "hybridUserPropertyProvider.primaryProvider.className" ); JiveGlobals.migrateProperty( "hybridUserPropertyProvider.secondaryProvider.className" ); JiveGlobals.migrateProperty( "hybridUserPropertyProvider.tertiaryProvider.className" ); // Load primary, secondary, and tertiary user providers. final UserPropertyProvider primary = MappedUserPropertyProvider.instantiate( "hybridUserPropertyProvider.primaryProvider.className" ); if ( primary != null ) { providers.add( primary ); } final UserPropertyProvider secondary = MappedUserPropertyProvider.instantiate( "hybridUserPropertyProvider.secondaryProvider.className" ); if ( secondary != null ) { providers.add( secondary ); } final UserPropertyProvider tertiary = MappedUserPropertyProvider.instantiate( "hybridUserPropertyProvider.tertiaryProvider.className" ); if ( tertiary != null ) { providers.add( tertiary ); } // Verify that there's at least one provider available. if ( providers.isEmpty() ) { Log.error( "At least one UserPropertyProvider must be specified via openfire.xml or the system properties!" ); } } /** * Returns the properties from the first provider that returns a non-empty collection. * * When none of the providers provide properties an empty collection is returned. * * @param username The identifier of the user (cannot be null or empty). * @return A collection, possibly empty, never null. */ @Override public Map<String, String> loadProperties( String username ) { for ( final UserPropertyProvider provider : providers ) { try { final Map<String, String> properties = provider.loadProperties( username ); if ( !properties.isEmpty() ) { return properties; } } catch ( UserNotFoundException e ) { // User not in this provider. Try other providers; } } return Collections.emptyMap(); } /** * Returns a property from the first provider that returns a non-null value. * * This method will return null when the desired property was not defined in any provider. * * @param username The identifier of the user (cannot be null or empty). * @param propName The property name (cannot be null or empty). * @return The property value (possibly null). */ @Override public String loadProperty( String username, String propName ) { for ( final UserPropertyProvider provider : providers ) { try { final String property = provider.loadProperty( username, propName ); if ( property != null ) { return property; } } catch ( UserNotFoundException e ) { // User not in this provider. Try other providers; } } return null; } /** * Adds a new property, updating a previous property value if one already exists. * * Note that the implementation of this method is equal to that of {@link #updateProperty(String, String, String)}. * * First, tries to find a provider that has the property for the provided user. If that provider is read-only, an * UnsupportedOperationException is thrown. If the provider is not read-only, the existing property value will be * updated. * * When the property is not defined in any provider, it will be added in the first non-read-only provider. * * When all providers are read-only, an UnsupportedOperationException is thrown. * * @param username The identifier of the user (cannot be null or empty). * @param propName The property name (cannot be null or empty). * @param propValue The property value (cannot be null). */ @Override public void insertProperty( String username, String propName, String propValue ) throws UnsupportedOperationException { updateProperty( username, propName, propValue ); } /** * Updates a property (or adds a new property when the property does not exist). * * Note that the implementation of this method is equal to that of {@link #insertProperty(String, String, String)}. * * First, tries to find a provider that has the property for the provided user. If that provider is read-only, an * UnsupportedOperationException is thrown. If the provider is not read-only, the existing property value will be * updated. * * When the property is not defined in any provider, it will be added in the first non-read-only provider. * * When all providers are read-only, an UnsupportedOperationException is thrown. * * @param username The identifier of the user (cannot be null or empty). * @param propName The property name (cannot be null or empty). * @param propValue The property value (cannot be null). */ @Override public void updateProperty( String username, String propName, String propValue ) throws UnsupportedOperationException {<FILL_FUNCTION_BODY>} /** * Removes a property from all non-read-only providers. * * @param username The identifier of the user (cannot be null or empty). * @param propName The property name (cannot be null or empty). */ @Override public void deleteProperty( String username, String propName ) throws UnsupportedOperationException { // all providers are read-only if ( isReadOnly() ) { throw new UnsupportedOperationException(); } for ( final UserPropertyProvider provider : providers ) { if ( provider.isReadOnly() ) { continue; } try { provider.deleteProperty( username, propName ); } catch ( UserNotFoundException e ) { // User not in this provider. Try other providers; } } } /** * Returns whether <em>all</em> backing providers are read-only. When read-only, properties can not be created, * deleted, or modified. If at least one provider is not read-only, this method returns false. * * @return true when all backing providers are read-only, otherwise false. */ @Override public boolean isReadOnly() { // TODO Make calls concurrent for improved throughput. for ( final UserPropertyProvider provider : providers ) { // If at least one provider is not readonly, neither is this proxy. if ( !provider.isReadOnly() ) { return false; } } return true; } }
for ( final UserPropertyProvider provider : providers ) { try { if ( provider.loadProperty( username, propName ) != null ) { provider.updateProperty( username, propName, propValue ); return; } } catch ( UserNotFoundException e ) { // User not in this provider. Try other providers; } } for ( final UserPropertyProvider provider : providers ) { try { if ( !provider.isReadOnly() ) { provider.insertProperty( username, propName, propValue ); return; } } catch ( UserNotFoundException e ) { // User not in this provider. Try other providers; } } throw new UnsupportedOperationException();
1,762
203
1,965
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/property/JDBCUserPropertyProvider.java
JDBCUserPropertyProvider
loadProperty
class JDBCUserPropertyProvider implements UserPropertyProvider { private static final Logger Log = LoggerFactory.getLogger( JDBCUserPropertyProvider.class ); private String loadPropertySQL; private String loadPropertiesSQL; private String connectionString; private boolean useConnectionProvider; /** * Constructs a new JDBC user property provider. */ public JDBCUserPropertyProvider() { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty( "jdbcUserPropertyProvider.driver" ); JiveGlobals.migrateProperty( "jdbcUserPropertyProvider.connectionString" ); JiveGlobals.migrateProperty( "jdbcUserPropertyProvider.loadPropertySQL" ); JiveGlobals.migrateProperty( "jdbcUserPropertyProvider.loadPropertiesSQL" ); useConnectionProvider = JiveGlobals.getBooleanProperty( "jdbcUserProvider.useConnectionProvider" ); // Load the JDBC driver and connection string. if ( !useConnectionProvider ) { String jdbcDriver = JiveGlobals.getProperty( "jdbcUserPropertyProvider.driver" ); try { Class.forName( jdbcDriver ).newInstance(); } catch ( Exception e ) { Log.error( "Unable to load JDBC driver: " + jdbcDriver, e ); return; } connectionString = JiveGlobals.getProperty( "jdbcProvider.connectionString" ); } // Load database statements for user data. loadPropertySQL = JiveGlobals.getProperty( "jdbcUserPropertyProvider.loadPropertySQL" ); loadPropertiesSQL = JiveGlobals.getProperty( "jdbcUserPropertyProvider.loadPropertiesSQL" ); } /** * 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 'jdbcUserPropertyProvider.isEscaped' * property to 'false'. * * @return 'false' if this implementation needs to escape database content before processing. */ protected boolean assumePersistedDataIsEscaped() { return JiveGlobals.getBooleanProperty( "jdbcUserPropertyProvider.isEscaped", true ); } private Connection getConnection() throws SQLException { if ( useConnectionProvider ) { return DbConnectionManager.getConnection(); } else { return DriverManager.getConnection( connectionString ); } } @Override public Map<String, String> loadProperties( String username ) throws UnsupportedOperationException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause. final String queryValue = assumePersistedDataIsEscaped() ? username : JID.unescapeNode( username ); try { con = getConnection(); pstmt = con.prepareStatement( loadPropertiesSQL ); pstmt.setString( 1, queryValue ); rs = pstmt.executeQuery(); final Map<String, String> result = new HashMap<>(); while ( rs.next() ) { final String propName = rs.getString( 1 ); final String propValue = rs.getString( 2 ); result.put( propName, propValue ); } return result; } catch ( Exception e ) { throw new UnsupportedOperationException( e ); } finally { DbConnectionManager.closeConnection( rs, pstmt, con ); } } @Override public String loadProperty( String username, String propName ) {<FILL_FUNCTION_BODY>} @Override public void insertProperty( String username, String propName, String propValue ) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void updateProperty( String username, String propName, String propValue ) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void deleteProperty( String username, String propName ) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public boolean isReadOnly() { return true; } }
Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause. final String queryValue = assumePersistedDataIsEscaped() ? username : JID.unescapeNode( username ); try { con = getConnection(); pstmt = con.prepareStatement( loadPropertySQL ); pstmt.setString( 1, queryValue ); pstmt.setString( 2, propName ); rs = pstmt.executeQuery(); if ( rs.next() ) { return rs.getString( 1 ); } return null; } catch ( Exception e ) { throw new UnsupportedOperationException( e ); } finally { DbConnectionManager.closeConnection( rs, pstmt, con ); }
1,151
246
1,397
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/user/property/MappedUserPropertyProvider.java
MappedUserPropertyProvider
instantiate
class MappedUserPropertyProvider implements UserPropertyProvider { /** * Name of the property of which the value is expected to be the classname of the UserPropertyProviderMapper * instance to be used by instances of this class. */ public static final String PROPERTY_MAPPER_CLASSNAME = "mappedUserPropertyProvider.mapper.className"; private static final Logger Log = LoggerFactory.getLogger( MappedUserPropertyProvider.class ); /** * Used to determine what provider is to be used to operate on a particular user. */ protected final UserPropertyProviderMapper mapper; public MappedUserPropertyProvider() { // 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 = (UserPropertyProviderMapper) c.newInstance(); } catch ( Exception e ) { throw new IllegalStateException( "Unable to create new instance of UserPropertyProviderMapper class: " + mapperClass, e ); } } /** * Instantiates a UserPropertyProvider based on a property value (that is expected to be a class name). When the * property is not set, this method returns null. When the property is set, but an exception occurs while * instantiating the class, this method logs the error and returns null. * * UserProvider classes are required to have a public, no-argument constructor. * * @param propertyName A property name (cannot ben ull). * @return A user provider (can be null). */ public static UserPropertyProvider instantiate( String propertyName ) {<FILL_FUNCTION_BODY>} @Override public Map<String, String> loadProperties( String username ) throws UserNotFoundException { return mapper.getUserPropertyProvider( username ).loadProperties( username ); } @Override public String loadProperty( String username, String propName ) throws UserNotFoundException { return mapper.getUserPropertyProvider( username ).loadProperty( username, propName ); } @Override public void insertProperty( String username, String propName, String propValue ) throws UserNotFoundException { mapper.getUserPropertyProvider( username ).insertProperty( username, propName, propValue ); } @Override public void updateProperty( String username, String propName, String propValue ) throws UserNotFoundException { mapper.getUserPropertyProvider( username ).updateProperty( username, propName, propValue ); } @Override public void deleteProperty( String username, String propName ) throws UserNotFoundException { mapper.getUserPropertyProvider( username ).deleteProperty( username, propName ); } /** * Returns whether <em>all</em> backing providers are read-only. When read-only, properties can not be created, * deleted, or modified. If at least one provider is not read-only, this method returns false. * * @return true when all backing providers are read-only, otherwise false. */ @Override public boolean isReadOnly() { // TODO Make calls concurrent for improved throughput. for ( final UserPropertyProvider provider : mapper.getUserPropertyProviders() ) { // If at least one provider is not readonly, neither is this proxy. if ( !provider.isReadOnly() ) { return false; } } return true; } }
final String className = JiveGlobals.getProperty( propertyName ); if ( className == null ) { Log.debug( "Property '{}' is undefined. Skipping.", propertyName ); return null; } Log.debug( "About to to instantiate an UserPropertyProvider '{}' based on the value of property '{}'.", className, propertyName ); try { final Class c = ClassUtils.forName( className ); final UserPropertyProvider provider = (UserPropertyProvider) c.newInstance(); Log.debug( "Instantiated UserPropertyProvider '{}'", className ); return provider; } catch ( Exception e ) { Log.error( "Unable to load UserPropertyProvider '{}'. Users in this provider will be disabled.", className, e ); return null; }
962
206
1,168
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/vcard/DefaultVCardProvider.java
DefaultVCardProvider
createVCard
class DefaultVCardProvider implements VCardProvider { private static final Logger Log = LoggerFactory.getLogger(DefaultVCardProvider.class); private static final Interner<JID> userBaseMutex = Interners.newWeakInterner(); private static final String LOAD_PROPERTIES = "SELECT vcard FROM ofVCard WHERE username=?"; private static final String DELETE_PROPERTIES = "DELETE FROM ofVCard WHERE username=?"; private static final String UPDATE_PROPERTIES = "UPDATE ofVCard SET vcard=? WHERE username=?"; private static final String INSERT_PROPERTY = "INSERT INTO ofVCard (username, vcard) VALUES (?, ?)"; @Override public Element loadVCard(String username) { final JID mutex; if (username.contains("@")) { // OF-2320: VCards are used for MUC rooms, to store their avatar. For this usecase, the 'username' is actually a (bare) JID value representing the room. mutex = new JID(username); } else { mutex = XMPPServer.getInstance().createJID(username, null); } synchronized (userBaseMutex.intern(mutex)) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; Element vCardElement = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_PROPERTIES); pstmt.setString(1, username); rs = pstmt.executeQuery(); while (rs.next()) { vCardElement = SAXReaderUtil.readRootElement(rs.getString(1)); } } catch (Exception e) { Log.error("Error loading vCard of username: " + username, e); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } finally { DbConnectionManager.closeConnection(rs, pstmt, con); } if ( JiveGlobals.getBooleanProperty( PhotoResizer.PROPERTY_RESIZE_ON_LOAD, PhotoResizer.PROPERTY_RESIZE_ON_LOAD_DEFAULT ) ) { PhotoResizer.resizeAvatar( vCardElement ); } return vCardElement; } } @Override public Element createVCard(String username, Element vCardElement) throws AlreadyExistsException {<FILL_FUNCTION_BODY>} @Override public Element updateVCard(String username, Element vCardElement) throws NotFoundException { if (loadVCard(username) == null) { // The user does not have a vCard throw new NotFoundException("Username " + username + " does not have a vCard"); } if ( JiveGlobals.getBooleanProperty( PhotoResizer.PROPERTY_RESIZE_ON_CREATE, PhotoResizer.PROPERTY_RESIZE_ON_CREATE_DEFAULT ) ) { PhotoResizer.resizeAvatar( vCardElement ); } Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(UPDATE_PROPERTIES); pstmt.setString(1, vCardElement.asXML()); pstmt.setString(2, username); pstmt.executeUpdate(); } catch (SQLException e) { Log.error("Error updating vCard of username: " + username, e); } finally { DbConnectionManager.closeConnection(pstmt, con); } return vCardElement; } @Override public void deleteVCard(String username) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(DELETE_PROPERTIES); pstmt.setString(1, username); pstmt.executeUpdate(); } catch (SQLException e) { Log.error("Error deleting vCard of username: " + username, e); } finally { DbConnectionManager.closeConnection(pstmt, con); } } @Override public boolean isReadOnly() { return false; } }
if (loadVCard(username) != null) { // The user already has a vCard throw new AlreadyExistsException("Username " + username + " already has a vCard"); } if ( JiveGlobals.getBooleanProperty( PhotoResizer.PROPERTY_RESIZE_ON_CREATE, PhotoResizer.PROPERTY_RESIZE_ON_CREATE_DEFAULT ) ) { PhotoResizer.resizeAvatar( vCardElement ); } Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(INSERT_PROPERTY); pstmt.setString(1, username); pstmt.setString(2, vCardElement.asXML()); pstmt.executeUpdate(); } catch (SQLException e) { Log.error("Error creating vCard for username: " + username, e); } finally { DbConnectionManager.closeConnection(pstmt, con); } return vCardElement;
1,112
271
1,383
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/vcard/PhotoResizer.java
PhotoResizer
cropAndShrink
class PhotoResizer { private static final Logger Log = LoggerFactory.getLogger( PhotoResizer.class ); // Property that, when 'true' causes avatars that are being loaded from backend storage to be resized, prior to be // processed and send to entities. public static final String PROPERTY_RESIZE_ON_LOAD = "avatar.resize.enable-on-load"; public static final boolean PROPERTY_RESIZE_ON_LOAD_DEFAULT = true; // Property that, when 'true' causes avatars that are being stored in backend storage to be resized. public static final String PROPERTY_RESIZE_ON_CREATE = "avatar.resize.enable-on-create"; public static final boolean PROPERTY_RESIZE_ON_CREATE_DEFAULT = false; // Property that controls the target dimension, in pixels. public static final String PROPERTY_TARGETDIMENSION = "avatar.resize.targetdimension"; public static final int PROPERTY_TARGETDIMENSION_DEFAULT = 96; public static void resizeAvatar( final Element vCardElement ) { if ( vCardElement == null ) { return; } // XPath didn't work? if ( vCardElement.element( "PHOTO" ) == null ) { return; } if ( vCardElement.element( "PHOTO" ).element( "BINVAL" ) == null || vCardElement.element( "PHOTO" ).element( "TYPE" ) == null ) { return; } final Element element = vCardElement.element( "PHOTO" ).element( "BINVAL" ); if ( element.getTextTrim() == null || element.getTextTrim().isEmpty() ) { return; } // Get a writer (check if we can generate a new image for the type of the original). final String type = vCardElement.element( "PHOTO" ).element( "TYPE" ).getTextTrim(); final Iterator it = ImageIO.getImageWritersByMIMEType( type ); if ( !it.hasNext() ) { Log.debug( "Cannot resize avatar. No writers available for MIME type {}.", type ); return; } final ImageWriter iw = (ImageWriter) it.next(); // Extract the original avatar from the VCard. final byte[] original = Base64.decode( element.getTextTrim() ); // Crop and shrink, if needed. final int targetDimension = JiveGlobals.getIntProperty( PROPERTY_TARGETDIMENSION, PROPERTY_TARGETDIMENSION_DEFAULT ); final byte[] resized = cropAndShrink( original, targetDimension, iw ); // If a resized image was created, replace to original avatar in the VCard. if ( resized != null ) { Log.debug( "Replacing original avatar in vcard with a resized variant." ); vCardElement.element( "PHOTO" ).element( "BINVAL" ).setText( Base64.encodeBytes( resized ) ); } } public static byte[] cropAndShrink( final byte[] bytes, final int targetDimension, final ImageWriter iw ) {<FILL_FUNCTION_BODY>} }
Log.debug( "Original image size: {} bytes.", bytes.length ); BufferedImage avatar; try ( final ByteArrayInputStream stream = new ByteArrayInputStream( bytes ) ) { avatar = ImageIO.read( stream ); if ( avatar.getWidth() <= targetDimension && avatar.getHeight() <= targetDimension ) { Log.debug( "Original image dimension ({}x{}) is within acceptable bounds ({}x{}). No need to resize.", new Object[] { avatar.getWidth(), avatar.getHeight(), targetDimension, targetDimension }); return null; } } catch ( IOException | RuntimeException ex ) { Log.warn( "Failed to resize avatar. An unexpected exception occurred while reading the original image.", ex ); return null; } /* We're going to be resizing, let's crop the image so that it's square and figure out the new starting size. */ Log.debug( "Original image is " + avatar.getWidth() + "x" + avatar.getHeight() + " pixels" ); final int targetWidth, targetHeight; if ( avatar.getHeight() == avatar.getWidth() ) { Log.debug( "Original image is already square ({}x{})", avatar.getWidth(), avatar.getHeight() ); targetWidth = targetHeight = avatar.getWidth(); } else { final int x, y; if ( avatar.getHeight() > avatar.getWidth() ) { Log.debug( "Original image is taller ({}) than wide ({}).", avatar.getHeight(), avatar.getWidth() ); x = 0; y = ( avatar.getHeight() - avatar.getWidth() ) / 2; targetWidth = targetHeight = avatar.getWidth(); } else { Log.debug( "Original image is wider ({}) than tall ({}).", avatar.getWidth(), avatar.getHeight() ); x = ( avatar.getWidth() - avatar.getHeight() ) / 2; y = 0; targetWidth = targetHeight = avatar.getHeight(); } // pull out a square image, centered. avatar = avatar.getSubimage( x, y, targetWidth, targetHeight ); } /* Let's crop/scale the image as necessary out the new dimensions. */ final BufferedImage resizedAvatar = new BufferedImage( targetDimension, targetDimension, avatar.getType() ); final AffineTransform scale = AffineTransform.getScaleInstance( (double) targetDimension / (double) targetWidth, (double) targetDimension / (double) targetHeight ); final Graphics2D g = resizedAvatar.createGraphics(); g.drawRenderedImage( avatar, scale ); Log.debug( "Resized image is {}x{}.", resizedAvatar.getWidth(), resizedAvatar.getHeight() ); /* Now we have to dump the new jpeg, png, etc. to a byte array */ try ( final ByteArrayOutputStream bostream = new ByteArrayOutputStream(); final ImageOutputStream iostream = new MemoryCacheImageOutputStream( bostream ) ) { iw.setOutput( iostream ); iw.write( resizedAvatar ); final byte[] data = bostream.toByteArray(); Log.debug( "Resized image size: {} bytes.", data.length ); return data; } catch ( IOException | RuntimeException ex ) { Log.warn( "Failed to resize avatar. An unexpected exception occurred while writing the resized image.", ex ); return null; }
858
922
1,780
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/vcard/VCardEventDispatcher.java
VCardEventDispatcher
dispatchVCardCreated
class VCardEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(VCardEventDispatcher.class); /** * List of listeners that will be notified when vCards are created, updated or deleted. */ private static List<VCardListener> listeners = new CopyOnWriteArrayList<>(); /** * Registers a listener to receive events when a vCard is created, updated or deleted. * * @param listener the listener. */ public static void addListener(VCardListener listener) { if (listener == null) { throw new NullPointerException(); } listeners.add(listener); } /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(VCardListener listener) { listeners.remove(listener); } /** * Dispatches that a vCard was updated to all listeners. * * @param user the user for which the vCard was set. * @param vCard the vcard updated. */ public static void dispatchVCardUpdated(String user, Element vCard) { for (VCardListener listener : listeners) { try { listener.vCardUpdated(user, vCard); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'vCardUpdated' event!", e); } } } /** * Dispatches that a vCard was created to all listeners. * * @param user the user for which the vCard was created. * @param vCard the vcard created. */ public static void dispatchVCardCreated(String user, Element vCard) {<FILL_FUNCTION_BODY>} /** * Dispatches that a vCard was deleted to all listeners. * * @param user the user for which the vCard was deleted. * @param vCard the vcard deleted. */ public static void dispatchVCardDeleted(String user, Element vCard) { for (VCardListener listener : listeners) { try { listener.vCardDeleted(user, vCard); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'vCardDeleted' event!", e); } } } }
for (VCardListener listener : listeners) { try { listener.vCardCreated(user, vCard); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'vCardCreated' event!", e); } }
598
70
668
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/websocket/OpenfireWebSocketServlet.java
OpenfireWebSocketServlet
configure
class OpenfireWebSocketServlet extends JettyWebSocketServlet { private static final long serialVersionUID = 1074354600476010708L; private static final Logger Log = LoggerFactory.getLogger(OpenfireWebSocketServlet.class); @Override public void destroy() { // terminate any active websocket sessions SessionManager sm = XMPPServer.getInstance().getSessionManager(); for (ClientSession session : sm.getSessions()) { if (session instanceof LocalSession) { Object ws = ((LocalSession) session).getSessionData("ws"); if (ws != null && (Boolean) ws) { Log.debug( "Closing session as websocket servlet is being destroyed: {}", session ); session.close(); } } } super.destroy(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // add CORS headers for all HTTP responses (errors, etc.) if (HttpBindManager.HTTP_BIND_CORS_ENABLED.getValue()) { final HttpBindManager boshManager = HttpBindManager.getInstance(); if (boshManager.isAllOriginsAllowed()) { // Set the Access-Control-Allow-Origin header to * to allow all Origin to do the CORS response.setHeader("Access-Control-Allow-Origin", HttpBindManager.HTTP_BIND_CORS_ALLOW_ORIGIN_ALL); } else { // Get the Origin header from the request and check if it is in the allowed Origin Map. // If it is allowed write it back to the Access-Control-Allow-Origin header of the respond. final String origin = request.getHeader("Origin"); if (boshManager.isThisOriginAllowed(origin)) { response.setHeader("Access-Control-Allow-Origin", origin); } } response.setHeader("Access-Control-Allow-Methods", String.join(",", HttpBindManager.HTTP_BIND_CORS_ALLOW_METHODS.getValue())); response.setHeader("Access-Control-Allow-Headers", String.join(",", HttpBindManager.HTTP_BIND_CORS_ALLOW_HEADERS.getValue())); response.setHeader("Access-Control-Max-Age", String.valueOf(HttpBindManager.HTTP_BIND_CORS_MAX_AGE.getValue().toSeconds())); } super.service(request, response); } @Override public void configure(JettyWebSocketServletFactory factory) {<FILL_FUNCTION_BODY>} }
if (!WebSocketClientConnectionHandler.isCompressionEnabled()) { factory.getAvailableExtensionNames().remove("permessage-deflate"); } final int messageSize = JiveGlobals.getIntProperty("xmpp.parser.buffer.size", 1048576); factory.setMaxTextMessageSize(messageSize); // Jetty's idle policy cannot be modified - it will bluntly kill the connection. Ensure that it's longer than // the maximum amount of idle-time that Openfire allows for its client connections! final Duration propValue = ConnectionSettings.Client.IDLE_TIMEOUT_PROPERTY.getValue(); final long maxJettyIdleMs; if (propValue.isNegative() || propValue.isZero()) { maxJettyIdleMs = Long.MAX_VALUE; } else { maxJettyIdleMs = propValue.plus(Duration.of(30, ChronoUnit.SECONDS)).toMillis(); } factory.setIdleTimeout(Duration.ofMillis(maxJettyIdleMs)); factory.setCreator((req, resp) -> { try { for (String subprotocol : req.getSubProtocols()) { if ("xmpp".equals(subprotocol)) { resp.setAcceptedSubProtocol(subprotocol); return new WebSocketClientConnectionHandler(); } } } catch (Exception e) { Log.warn("Unable to load websocket factory", e); } Log.warn("Failed to create websocket for {}:{} make a request at {}", req.getHttpServletRequest().getRemoteAddr(), req.getHttpServletRequest().getRemotePort(), req.getRequestPath() ); return null; });
665
446
1,111
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/websocket/StreamManagementPacketRouter.java
StreamManagementPacketRouter
route
class StreamManagementPacketRouter extends SessionPacketRouter { public static final String SM_UNSOLICITED_ACK_FREQUENCY = "stream.management.unsolicitedAckFrequency"; static { JiveGlobals.migrateProperty(SM_UNSOLICITED_ACK_FREQUENCY); } private int unsolicitedAckFrequency = JiveGlobals.getIntProperty(SM_UNSOLICITED_ACK_FREQUENCY, 0); public StreamManagementPacketRouter(LocalClientSession session) { super(session); } @Override public void route(Element wrappedElement) throws UnknownStanzaException {<FILL_FUNCTION_BODY>} private boolean isUnsolicitedAckExpected() { if (!session.getStreamManager().isEnabled()) { return false; } return unsolicitedAckFrequency > 0 && session.getNumClientPackets() % unsolicitedAckFrequency == 0; } }
if (StreamManager.NAMESPACE_V3.equals(wrappedElement.getNamespace().getStringValue())) { session.getStreamManager().process(wrappedElement); } else if (CsiManager.isStreamManagementNonza(wrappedElement)) { session.getCsiManager().process(wrappedElement); } else { super.route(wrappedElement); if (isUnsolicitedAckExpected()) { session.getStreamManager().sendServerAcknowledgement(); } }
267
130
397
<methods>public void <init>(org.jivesoftware.openfire.session.LocalClientSession) ,public static boolean isInvalidStanzaSentPriorToResourceBinding(Packet, org.jivesoftware.openfire.session.ClientSession) ,public void route(Element) throws org.jivesoftware.openfire.multiplex.UnknownStanzaException,public void route(Packet) ,public void route(IQ) ,public void route(Message) ,public void route(Presence) ,public void setSkipJIDValidation(boolean) <variables>private org.jivesoftware.openfire.PacketRouter router,protected org.jivesoftware.openfire.session.LocalClientSession session,private boolean skipJIDValidation
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/websocket/WebSocketClientConnectionHandler.java
XmppSessionIdleTask
run
class XmppSessionIdleTask extends TimerTask { private Instant pendingPingSentAt = null; @Override public void run() {<FILL_FUNCTION_BODY>} private void sendPing() { // Ping the connection to see if it is alive. final JID entity = wsConnection.getStanzaHandler().getAddress(); final IQ pingRequest = new IQ(IQ.Type.get); pingRequest.setChildElement("ping", IQPingHandler.NAMESPACE); pingRequest.setFrom(XMPPServer.getInstance().getServerInfo().getXMPPDomain()); pingRequest.setTo(entity); Log.debug("Pinging websocket connection (XMPP address: '{}') that has been idle: {}", entity, wsConnection); // OF-1497: Ensure that data sent to the client is processed through LocalClientSession, to avoid // synchronisation issues with stanza counts related to Stream Management (XEP-0198)! final LocalClientSession ofSession = (LocalClientSession) SessionManager.getInstance().getSession(entity); if (ofSession == null) { Log.warn( "Trying to ping a websocket connection (XMPP address: '{}') that's idle, but has no corresponding Openfire session. Websocket connection: {}", entity, wsConnection ); } else { try { ofSession.deliver( pingRequest ); pendingPingSentAt = Instant.now(); } catch (UnauthorizedException e) { Log.warn("An unexpected exception occurred while trying to ping a websocket connection (XMPP address: '{}') that's idle. Websocket connection: {}", entity, wsConnection, e); } } } }
if (!isWebSocketOpen() || getMaxIdleTime().isNegative() || getMaxIdleTime().isZero()) { TaskEngine.getInstance().cancelScheduledTask(websocketFramePingTask); TaskEngine.getInstance().cancelScheduledTask(xmppSessionIdleTask); return; } // Was there activity since we've pinged, then reset the 'ping' status. if (pendingPingSentAt != null && lastReceived.isAfter(pendingPingSentAt)) { pendingPingSentAt = null; } final Duration inactive = Duration.between(lastReceived, Instant.now()); if (inactive.compareTo(getMaxIdleTime()) > 0) { // Inactive session, that didn't respond to a ping that should've been sent earlier. Kill. Log.debug("Closing connection that has been idle: {}", wsConnection); wsConnection.close(new StreamError(StreamError.Condition.connection_timeout, "Closing connection due to inactivity.")); return; } final boolean doPing = ConnectionSettings.Client.KEEP_ALIVE_PING_PROPERTY.getValue(); if (doPing) { // Probe the peer once, when it's inactive for 50% of the maximum idle time (this mimics the behavior for TCP connections). final boolean alreadyPinged = pendingPingSentAt != null; if (!alreadyPinged) { if (inactive.compareTo(getMaxIdleTime().dividedBy(2)) > 0) { // Client has been inactive for more than 50% of the max idle time, and has not been pinged yet. sendPing(); } } }
445
432
877
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/websocket/WebSocketClientStanzaHandler.java
WebSocketClientStanzaHandler
createSession
class WebSocketClientStanzaHandler extends ClientStanzaHandler { private static final Logger Log = LoggerFactory.getLogger(WebSocketClientStanzaHandler.class); public static final String STREAM_HEADER = "open"; public static final String STREAM_FOOTER = "close"; public static final String FRAMING_NAMESPACE = "urn:ietf:params:xml:ns:xmpp-framing"; public WebSocketClientStanzaHandler(final PacketRouter router, final WebSocketConnection connection) { super(router, connection); } @Override protected void initiateSession(String stanza, XMPPPacketReader reader) throws Exception { // Found a stream:stream tag... if (!sessionCreated) { sessionCreated = true; MXParser parser = reader.getXPPParser(); parser.setInput(new StringReader(stanza)); createSession(parser); } else if (startedSASL && saslStatus == SASLAuthentication.Status.authenticated) { startedSASL = false; saslSuccessful(); } } @Override protected void createSession(XmlPullParser xpp) throws XmlPullParserException, IOException {<FILL_FUNCTION_BODY>} @Override protected void createSession(String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException { // This largely copies LocalClientSession#createSession, with modifications that are specific to websockets. if (!LocalClientSession.isAllowed(connection)) { // Client cannot connect from this IP address so end the stream and TCP connection. String hostAddress = "Unknown"; try { hostAddress = connection.getHostAddress(); } catch (UnknownHostException e) { // Do nothing } Log.debug("Closed connection to client attempting to connect from: {}", hostAddress); // Include the not-authorized error in the response and close the underlying connection. connection.close(new StreamError(StreamError.Condition.not_authorized)); return; } // Retrieve list of namespaces declared in current element (OF-2556) connection.setAdditionalNamespaces(XMPPPacketReader.getPrefixedNamespacesOnCurrentElement(xpp)); final Locale language = Session.detectLanguage(xpp); connection.setXMPPVersion(1, 0); // Create a ClientSession for this user. session = SessionManager.getInstance().createClientSession(connection, language); session.setSessionData("ws", Boolean.TRUE); openStream(); sendStreamFeatures(); } private void openStream() { session.incrementClientPacketCount(); connection.deliverRawText(withoutDeclaration(getStreamHeader())); } private void sendStreamFeatures() { final Element features = DocumentHelper.createElement(QName.get("features", "stream", "http://etherx.jabber.org/streams")); if (saslStatus != SASLAuthentication.Status.authenticated) { // Include available SASL Mechanisms final Element saslMechanisms = SASLAuthentication.getSASLMechanisms(session); if (saslMechanisms != null) { features.add(saslMechanisms); } } // Include Stream features final List<Element> specificFeatures = session.getAvailableStreamFeatures(); if (specificFeatures != null) { for (final Element feature : specificFeatures) { features.add(feature); } } connection.deliverRawText(features.asXML()); } @Override protected Document getStreamHeader() { final Element open = DocumentHelper.createElement(QName.get("open", FRAMING_NAMESPACE)); final Document document = DocumentHelper.createDocument(open); document.setXMLEncoding(StandardCharsets.UTF_8.toString()); open.addAttribute("from", XMPPServer.getInstance().getServerInfo().getXMPPDomain()); open.addAttribute("id", session.getStreamID().toString()); open.addAttribute(QName.get("lang", Namespace.XML_NAMESPACE), session.getLanguage().toLanguageTag()); open.addAttribute("version", "1.0"); return document; } /** * After SASL authentication was successful we should open a new stream and offer * new stream features such as resource binding and session establishment. Notice that * resource binding and session establishment should only be offered to clients (i.e. not * to servers or external components) */ @Override protected void saslSuccessful() { // When using websockets, send the stream header in a separate websocket frame! connection.deliverRawText(withoutDeclaration(getStreamHeader())); sendStreamFeatures(); } protected boolean isStartOfStream(final String xml) { return xml.startsWith("<" + STREAM_HEADER); } protected boolean isEndOfStream(final String xml) { return xml.startsWith("<" + STREAM_FOOTER); } public static String withoutDeclaration(final Document document) { try { StringWriter out = new StringWriter(); OutputFormat format = new OutputFormat(); format.setSuppressDeclaration(true); format.setExpandEmptyElements(false); XMLWriter writer = new XMLWriter(out, format); writer.write(document); writer.flush(); return out.toString(); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } }
for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) { eventType = xpp.next(); } final String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); String host = xpp.getAttributeValue("", "to"); try { // Check that the TO attribute of the stream header matches the server name or a valid // subdomain. If the value of the 'to' attribute is not valid then return a host-unknown // error and close the underlying connection. if (validateHost() && isHostUnknown(host)) { throw new StreamErrorException(StreamError.Condition.host_unknown, "Incorrect hostname in stream header: " + host); } if (!STREAM_HEADER.equals(xpp.getName())) { throw new StreamErrorException(StreamError.Condition.unsupported_stanza_type, "Incorrect stream header: " + xpp.getName()); } // Validate the stream namespace (https://tools.ietf.org/html/rfc7395#section-3.3.2) if (!FRAMING_NAMESPACE.equals(xpp.getNamespace())) { throw new StreamErrorException(StreamError.Condition.invalid_namespace, "Invalid namespace in stream header: " + xpp.getNamespace()); } // Create the correct session based on the sent namespace. At this point the server // may offer the client to encrypt the connection. If the client decides to encrypt // the connection then a <starttls> stanza should be received createSession(serverName, xpp, connection); } catch (final StreamErrorException ex) { Log.warn("Failed to create a session. Closing connection: {}", connection, ex); connection.deliverRawText(ex.getStreamError().toXML()); connection.deliverRawText("<close xmlns='" + FRAMING_NAMESPACE + "'/>"); connection.close(); }
1,463
505
1,968
<methods>public void <init>(org.jivesoftware.openfire.PacketRouter, org.jivesoftware.openfire.Connection) <variables>private static final Logger Log
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/websocket/WebSocketConnection.java
WebSocketConnection
getConfiguration
class WebSocketConnection extends VirtualConnection { private static final Logger Log = LoggerFactory.getLogger(WebSocketConnection.class); private InetSocketAddress remotePeer; private WebSocketClientConnectionHandler socket; private PacketDeliverer backupDeliverer; private ConnectionConfiguration configuration; private ConnectionType connectionType; private WebSocketClientStanzaHandler stanzaHandler; public WebSocketConnection(WebSocketClientConnectionHandler socket, PacketDeliverer backupDeliverer, InetSocketAddress remotePeer) { this.socket = socket; this.backupDeliverer = backupDeliverer; this.remotePeer = remotePeer; this.connectionType = ConnectionType.SOCKET_C2S; } @Override public void closeVirtualConnection(@Nullable final StreamError error) { try { if (error != null) { deliverRawText0(error.toXML()); } final String closeElement; if (STREAM_SUBSTITUTION_ENABLED.getValue()) { closeElement = "</stream:stream>"; } else { closeElement = "<" + WebSocketClientStanzaHandler.STREAM_FOOTER + " xmlns='"+WebSocketClientStanzaHandler.FRAMING_NAMESPACE+"'/>"; } deliverRawText0(closeElement); } finally { socket.getWsSession().close(); } } @Override public byte[] getAddress() { return remotePeer.getAddress().getAddress(); } @Override public String getHostAddress() { return remotePeer.getAddress().getHostAddress(); } @Override public String getHostName() { return remotePeer.getHostName(); } @Override public void systemShutdown() { close(new StreamError(StreamError.Condition.system_shutdown)); } @Override public void deliver(Packet packet) throws UnauthorizedException { if (isClosed()) { if (backupDeliverer != null) { backupDeliverer.deliver(packet); } else { Log.trace("Discarding packet that was due to be delivered on closed connection {}, for which no backup deliverer was configured.", this); } } else { boolean errorDelivering = false; try { final String xml; if (Namespace.NO_NAMESPACE.equals(packet.getElement().getNamespace())) { // use string-based operation here to avoid cascading xmlns wonkery StringBuilder packetXml = new StringBuilder(packet.toXML()); packetXml.insert(packetXml.indexOf(" "), " xmlns=\"jabber:client\""); xml = packetXml.toString(); } else { xml = packet.toXML(); } socket.getWsSession().getRemote().sendString(xml); } catch (Exception e) { Log.debug("Error delivering packet:\n" + packet, e); errorDelivering = true; } if (errorDelivering) { close(); // Retry sending the packet again. Most probably if the packet is a // Message it will be stored offline if (backupDeliverer != null) { backupDeliverer.deliver(packet); } else { Log.trace("Discarding packet that failed to be delivered to connection {}, for which no backup deliverer was configured.", this); } } else { session.incrementServerPacketCount(); } } } @Override public void deliverRawText(String text) { if (!isClosed()) { deliverRawText0(text); } } private void deliverRawText0(String text) { boolean errorDelivering = false; try { socket.getWsSession().getRemote().sendString(text); } catch (Exception e) { Log.debug("Error delivering raw text:\n" + text, e); errorDelivering = true; } // Attempt to close the connection if delivering text fails. if (errorDelivering) { close(); } } @Override public boolean validate() { return socket.isWebSocketOpen(); } @Override @Deprecated // Remove in Openfire 4.9 or later. public boolean isSecure() { return isEncrypted(); } @Override public boolean isEncrypted() { return socket.isWebSocketEncrypted(); } @Override @Nullable public PacketDeliverer getPacketDeliverer() { return backupDeliverer; } @Override public ConnectionConfiguration getConfiguration() {<FILL_FUNCTION_BODY>} @Override public boolean isCompressed() { return WebSocketClientConnectionHandler.isCompressionEnabled(); } @Override public Optional<String> getTLSProtocolName() { return Optional.ofNullable(this.socket.getTLSProtocolName()); } @Override public Optional<String> getCipherSuiteName() { return Optional.ofNullable(this.socket.getCipherSuiteName()); } void setStanzaHandler(final WebSocketClientStanzaHandler stanzaHandler) { this.stanzaHandler = stanzaHandler; } WebSocketClientStanzaHandler getStanzaHandler() { return stanzaHandler; } @Override public void reinit(LocalSession session) { super.reinit(session); stanzaHandler.setSession(session); } @Override public String toString() { return "WebSocketConnection{" + "jid=" + (getStanzaHandler() == null ? "(null)" : getStanzaHandler().getAddress()) + ", remotePeer=" + remotePeer + ", socket=" + socket + ", connectionType=" + connectionType + '}'; } }
if (configuration == null) { final ConnectionManager connectionManager = XMPPServer.getInstance().getConnectionManager(); configuration = connectionManager.getListener( connectionType, true ).generateConnectionConfiguration(); } return configuration;
1,555
58
1,613
<methods>public non-sealed void <init>() ,public void addCompression() ,public void close(StreamError, boolean) ,public abstract void closeVirtualConnection(StreamError) ,public java.security.cert.Certificate[] getLocalCertificates() ,public org.jivesoftware.openfire.PacketDeliverer getPacketDeliverer() ,public java.security.cert.Certificate[] getPeerCertificates() ,public boolean isClosed() ,public boolean isCompressed() ,public boolean isEncrypted() ,public boolean isInitialized() ,public boolean isSecure() ,public boolean isUsingSelfSignedCertificate() ,public void setUsingSelfSignedCertificate(boolean) ,public void startCompression() ,public void startTLS(boolean, boolean) throws java.lang.Exception,public boolean validate() <variables>private static final Logger Log,private final AtomicReference<org.jivesoftware.openfire.Connection.State> state
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/websocket/XMPPPPacketReaderFactory.java
XMPPPPacketReaderFactory
create
class XMPPPPacketReaderFactory extends BasePooledObjectFactory<XMPPPacketReader> { private static Logger Log = LoggerFactory.getLogger( XMPPPPacketReaderFactory.class ); private static XmlPullParserFactory xppFactory = null; static { try { xppFactory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null); xppFactory.setNamespaceAware(true); } catch (XmlPullParserException e) { Log.error("Error creating a parser factory", e); } } //-- BasePooledObjectFactory implementation @Override public XMPPPacketReader create() throws Exception {<FILL_FUNCTION_BODY>} @Override public PooledObject<XMPPPacketReader> wrap(XMPPPacketReader reader) { return new DefaultPooledObject<XMPPPacketReader>(reader); } @Override public boolean validateObject(PooledObject<XMPPPacketReader> po) { // reset the input for the pooled parser try { po.getObject().getXPPParser().resetInput(); return true; } catch (XmlPullParserException xppe) { Log.error("Failed to reset pooled parser; evicting from pool", xppe); return false; } } }
XMPPPacketReader parser = new XMPPPacketReader(); parser.setXPPFactory( xppFactory ); return parser;
359
39
398
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/AesEncryptor.java
AesEncryptor
editKey
class AesEncryptor implements Encryptor { private static final Logger log = LoggerFactory.getLogger(AesEncryptor.class); private static final String ALGORITHM = "AES/CBC/PKCS7Padding"; private static final byte[] INIT_PARM = { (byte)0xcd, (byte)0x91, (byte)0xa7, (byte)0xc5, (byte)0x27, (byte)0x8b, (byte)0x39, (byte)0xe0, (byte)0xfa, (byte)0x72, (byte)0xd0, (byte)0x29, (byte)0x83, (byte)0x65, (byte)0x9d, (byte)0x74 }; private static final byte[] DEFAULT_KEY = { (byte)0xf2, (byte)0x46, (byte)0x5d, (byte)0x2a, (byte)0xd1, (byte)0x73, (byte)0x0b, (byte)0x18, (byte)0xcb, (byte)0x86, (byte)0x95, (byte)0xa3, (byte)0xb1, (byte)0xe5, (byte)0x89, (byte)0x27 }; private static boolean isInitialized = false; private byte[] cipherKey = null; /** Default constructor */ public AesEncryptor() { initialize(); } /** * Custom key constructor * * @param key the custom key */ public AesEncryptor(String key) { initialize(); setKey(key); } /* (non-Javadoc) * @see org.jivesoftware.util.Encryptor#encrypt(java.lang.String) */ @Override public String encrypt(String value) { return encrypt(value, null); } @Override public String encrypt(String value, byte[] iv) { if (value == null) { return null; } byte [] bytes = value.getBytes(StandardCharsets.UTF_8); return Base64.encodeBytes(cipher(bytes, getKey(), iv == null ? INIT_PARM : iv, Cipher.ENCRYPT_MODE)); } /* (non-Javadoc) * @see org.jivesoftware.util.Encryptor#decrypt(java.lang.String) */ @Override public String decrypt(String value) { return decrypt(value, null); } @Override public String decrypt(String value, byte[] iv) { if (value == null) { return null; } byte [] bytes = cipher(Base64.decode(value), getKey(), iv == null ? INIT_PARM : iv, Cipher.DECRYPT_MODE); if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } /** * Symmetric encrypt/decrypt routine. * * @param attribute The value to be converted * @param key The encryption key * @param mode The cipher mode (encrypt or decrypt) * @return The converted attribute, or null if conversion fails */ private byte [] cipher(byte [] attribute, byte [] key, byte[] iv, int mode) { byte [] result = null; try { // Create AES encryption key Key aesKey = new SecretKeySpec(key, "AES"); // Create AES Cipher Cipher aesCipher = Cipher.getInstance(ALGORITHM); // Initialize AES Cipher and convert aesCipher.init(mode, aesKey, new IvParameterSpec(iv)); result = aesCipher.doFinal(attribute); } catch (Exception e) { log.error("AES cipher failed", e); } return result; } /** * Return the encryption key. This will return the user-defined * key (if available) or a default encryption key. * * @return The encryption key */ private byte [] getKey() { return cipherKey == null ? DEFAULT_KEY : cipherKey; } /** * Set the encryption key. This will apply the user-defined key, * truncated or filled (via the default key) as needed to meet * the key length specifications. * * @param key The encryption key */ private void setKey(byte [] key) { cipherKey = editKey(key); } /* (non-Javadoc) * @see org.jivesoftware.util.Encryptor#setKey(java.lang.String) */ @Override public void setKey(String key) { if (key == null) { cipherKey = null; return; } byte [] bytes = key.getBytes(StandardCharsets.UTF_8); setKey(editKey(bytes)); } /** * Validates an optional user-defined encryption key. Only the * first sixteen bytes of the input array will be used for the key. * It will be filled (if necessary) to a minimum length of sixteen. * * @param key The user-defined encryption key * @return A valid encryption key, or null */ private byte [] editKey(byte [] key) {<FILL_FUNCTION_BODY>} /** Installs the required security provider(s) */ private synchronized void initialize() { if (!isInitialized) { try { Security.addProvider(new BouncyCastleProvider()); isInitialized = true; } catch (Throwable t) { log.warn("JCE provider failure; unable to load BC", t); } } } /* */ }
if (key == null) { return null; } byte [] result = new byte [DEFAULT_KEY.length]; for (int x=0; x<DEFAULT_KEY.length; x++) { result[x] = x < key.length ? key[x] : DEFAULT_KEY[x]; } return result;
1,562
86
1,648
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/AutoCloseableReentrantLock.java
AutoCloseableReentrantLock
close
class AutoCloseableReentrantLock { // This is a WeakHashMap - when there are no references to the key, the entry will be removed private static final Map<String, ReentrantLock> LOCK_MAP = Collections.synchronizedMap(new WeakHashMap<>()); private final ReentrantLock lock; private final AutoCloseableLock autoCloseable; private String key; /** * Create a class and resource specific lock. If another thread has not closed another AutoCloseableReentrantLock * with the same class and resource then this will block until it is closed. * * @param clazz The class for which the lock should be created. * @param resource The resource for which the lock should be created. */ public AutoCloseableReentrantLock(final Class clazz, final String resource) { key = (clazz.getName() + '#' + resource).intern(); lock = LOCK_MAP.computeIfAbsent(key, missingKey -> new ReentrantLock()); autoCloseable = new AutoCloseableLock(this); } private synchronized void close() throws IllegalMonitorStateException {<FILL_FUNCTION_BODY>} private synchronized void checkNotReleased() throws IllegalStateException { if (key == null) { throw new IllegalStateException("Lock has already been released"); } } /** * Acquires the lock, blocking indefinitely. * * @return An AutoCloseableLock * @throws IllegalStateException if this lock has already been released by the last thread to hold it */ @SuppressWarnings( "LockAcquiredButNotSafelyReleased" ) public AutoCloseableLock lock() throws IllegalStateException { checkNotReleased(); lock.lock(); return autoCloseable; } /** * Tries to acquire the lock, returning immediately. * * @return An AutoCloseableLock if the lock was required, otherwise empty. * @throws IllegalStateException if this lock has already been released by the last thread to hold it */ public Optional<AutoCloseableLock> tryLock() { checkNotReleased(); if (lock.tryLock()) { return Optional.of(autoCloseable); } else { return Optional.empty(); } } /** * Acquires the lock, blocking until the lock is acquired or the thread is interrupted. * * @return An AutoCloseableLock * @throws InterruptedException if the thread was interrupted before the lock could be acquired * @throws IllegalStateException if this lock has already been released by the last thread to hold it */ @SuppressWarnings( "LockAcquiredButNotSafelyReleased" ) public AutoCloseableLock lockInterruptibly() throws InterruptedException, IllegalStateException { checkNotReleased(); lock.lockInterruptibly(); return autoCloseable; } /** * Queries if this lock is held by the current thread. * * @return {@code true} if current thread holds this lock and {@code false} otherwise * @see ReentrantLock#isHeldByCurrentThread() */ public boolean isHeldByCurrentThread() { return lock.isHeldByCurrentThread(); } /** * Queries if this lock is held by any thread. This method is * designed for use in monitoring of the system state, * not for synchronization control. * * @return {@code true} if any thread holds this lock and {@code false} otherwise * @see ReentrantLock#isLocked() */ public boolean isLocked() { return lock.isLocked(); } public static final class AutoCloseableLock implements AutoCloseable { private final AutoCloseableReentrantLock lock; private AutoCloseableLock(final AutoCloseableReentrantLock lock) { this.lock = lock; } /** * Releases the lock. * * @throws IllegalMonitorStateException if the current thread does not hold the lock. */ @Override public void close() throws IllegalMonitorStateException { lock.close(); } } }
lock.unlock(); // Clear the reference to the key so the GC can remove the entry from the WeakHashMap if no-one else has it if (!lock.isHeldByCurrentThread()) { key = null; }
1,064
61
1,125
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/ByteFormat.java
ByteFormat
format
class ByteFormat extends Format { /** * Formats a long which represent a number of bytes. * @param bytes the number of bytes to format * @return the formatted string */ public String format(long bytes) { return super.format(bytes); } /** * Formats a long which represent a number of kilobytes. * @param kilobytes the number of kilobytes to format * @return the formatted string */ public String formatKB(long kilobytes) { return format(kilobytes * 1024); } /** * Format the given object (must be a Long). * * @param obj assumed to be the number of bytes as a Long. * @param buf the StringBuffer to append to. * @param pos the field position * @return A formatted string representing the given bytes in more human-readable form. */ @Override public StringBuffer format(Object obj, StringBuffer buf, FieldPosition pos) {<FILL_FUNCTION_BODY>} /** * In this implementation, returns null always. * * @param source unused parameter * @param pos unused parameter * @return returns null in this implementation. */ @Override public Object parseObject(String source, ParsePosition pos) { return null; } }
if (obj instanceof Long) { long numBytes = (Long) obj; if (numBytes < 1024 * 1024) { DecimalFormat formatter = new DecimalFormat("#,##0.0"); buf.append(formatter.format((double)numBytes / 1024.0)).append(" K"); } else { DecimalFormat formatter = new DecimalFormat("#,##0.0"); buf.append(formatter.format((double)numBytes / (1024.0 * 1024.0))).append(" MB"); } } return buf;
349
163
512
<methods>public java.lang.Object clone() ,public final java.lang.String format(java.lang.Object) ,public abstract java.lang.StringBuffer format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition) ,public java.text.AttributedCharacterIterator formatToCharacterIterator(java.lang.Object) ,public java.lang.Object parseObject(java.lang.String) throws java.text.ParseException,public abstract java.lang.Object parseObject(java.lang.String, java.text.ParsePosition) <variables>private static final long serialVersionUID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/CacheableOptional.java
CacheableOptional
getCachedSize
class CacheableOptional<T extends Serializable> implements Cacheable { private final T value; private CacheableOptional(T value) { this.value = value; } public static <T extends Serializable> CacheableOptional<T> of(final T value) { return new CacheableOptional<>(value); } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static <T extends Serializable> CacheableOptional<T> from(final Optional<T> value) { return new CacheableOptional<>(value.orElse(null)); } public T get() { return value; } public boolean isPresent() { return value != null; } public boolean isAbsent() { return value == null; } public Optional<T> toOptional() { return Optional.ofNullable(this.value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final CacheableOptional<?> that = (CacheableOptional<?>) o; return Objects.equals(this.value, that.value); } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return "CacheableOptional{" + (value == null ? "absent value" : "value=" + value) + '}'; } @Override public int getCachedSize() throws CannotCalculateSizeException {<FILL_FUNCTION_BODY>} }
final int sizeOfValue = CacheSizes.sizeOfAnything(value); if (value == null) { // 94 bytes seems to be the overhead of a CacheableOptional representing absent value return 94 + sizeOfValue; } else { // 72 bytes seems to be the overhead of a CacheableOptional<String> representing present value return 72 + CacheSizes.sizeOfString(value.getClass().getName()) + sizeOfValue; }
442
120
562
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/ClassUtils.java
ClassUtils
loadClass
class ClassUtils { private static ClassUtils instance = new ClassUtils(); /** * Loads the class with the specified name. * * @param className the name of the class * @return the resulting <code>Class</code> object * @throws ClassNotFoundException if the class was not found */ public static Class forName(String className) throws ClassNotFoundException { return instance.loadClass(className); } /** * Loads the given resource as a stream. * * @param name the name of the resource that exists in the classpath. * @return the resource as an input stream or {@code null} if the resource was not found. */ public static InputStream getResourceAsStream(String name) { return instance.loadResource(name); } /** * Not instantiatable. */ private ClassUtils() {} public Class loadClass(String className) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} private InputStream loadResource(String name) { InputStream in = getClass().getResourceAsStream(name); if (in == null) { in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); if (in == null) { in = getClass().getClassLoader().getResourceAsStream(name); } } return in; } }
Class theClass = null; try { theClass = Class.forName(className); } catch (ClassNotFoundException e1) { try { theClass = Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e2) { theClass = getClass().getClassLoader().loadClass(className); } } return theClass;
353
108
461
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/CollectionUtils.java
CollectionUtils
distinctByKey
class CollectionUtils { /** * Returns a stateful stream filter that, once applied to a stream, returns a stream consisting * of the distinct elements (according to the specified key). * <p> * The implementation of {@link Stream#distinct()} can be used to return a stream that has distinct * elements, based on the implementation of {@link Object#equals(Object)}. That implementation does * not allow to filter a stream based on one property of each object. The implementation of provided * by this method does. * * @param keyExtractor A function to extract the desired key from the stream objects (cannot be null). * @param <T> Stream element type. * @return A filter * @see <a href="https://stackoverflow.com/questions/27870136/java-lambda-stream-distinct-on-arbitrary-key">Stack Overflow: Java Lambda Stream Distinct() on arbitrary key?</a> */ public static <T> Predicate<T> distinctByKey( Function<? super T, Object> keyExtractor ) {<FILL_FUNCTION_BODY>} /** * Returns all elements that occur more than exactly once in the combination of all elements from all provided * collections. * * @param collections The collection for which to return duplicates * @param <V> The type of the entities in the collections. * @return The duplicates */ @Nonnull public static <V> Set<V> findDuplicates(@Nonnull final Collection<V>... collections) { final Set<V> merged = new HashSet<>(); final Set<V> duplicates = new HashSet<>(); for (Collection<V> collection : collections) { for (V o : collection) { if (!merged.add(o)) { duplicates.add(o); } } } return duplicates; } }
final Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent( keyExtractor.apply( t ), Boolean.TRUE ) == null;
484
49
533
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/CookieUtils.java
CookieUtils
setCookie
class CookieUtils { /** * Returns the specified cookie, or {@code null} if the cookie * does not exist. Note: because of the way that cookies are implemented * it's possible for multiple cookies with the same name to exist (but with * different domain values). This method will return the first cookie that * has a name match. * * @param request the servlet request. * @param name the name of the cookie. * @return the Cookie object if it exists, otherwise {@code null}. */ public static Cookie getCookie(HttpServletRequest request, String name) { Cookie cookies[] = request.getCookies(); // Return null if there are no cookies or the name is invalid. if (cookies == null || name == null || name.length() == 0) { return null; } // Otherwise, we do a linear scan for the cookie. Cookie cookie = null; for (int i = 0; i < cookies.length; i++) { // If the current cookie name matches the one we're looking for, we've // found a matching cookie. if (cookies[i].getName().equals(name)) { cookie = cookies[i]; // The best matching cookie will be the one that has the correct // domain name. If we've found the cookie with the correct domain name, // return it. Otherwise, we'll keep looking for a better match. if (request.getServerName().equals(cookie.getDomain())) { break; } } } return cookie; } /** * Deletes the specified cookie. * * @param request the servlet request. * @param response the servlet response. * @param cookie the cookie object to be deleted. */ @SuppressWarnings("lgtm[java/insecure-cookie]") // We're explicitly setting an empty cookie to remove things. public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, Cookie cookie) { if (cookie != null) { // Invalidate the cookie String path = request.getContextPath() == null ? "/" : request.getContextPath(); if ("".equals(path)) { path = "/"; } cookie.setPath(path); cookie.setValue(""); cookie.setMaxAge(0); response.addCookie(cookie); } } /** * Stores a value in a cookie. By default this cookie will persist for 30 days. * * @see #setCookie(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,String,String,int) * @param request the servlet request. * @param response the servlet response. * @param name a name to identify the cookie. * @param value the value to store in the cookie. */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) { // Save the cookie value for 1 month setCookie(request, response, name, value, 60*60*24*30); } /** * Stores a value in a cookie. This cookie will persist for the amount * specified in the {@code saveTime} parameter. * * @see #setCookie(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,String,String) * @param request the servlet request. * @param response the servlet response. * @param name a name to identify the cookie. * @param value the value to store in the cookie. * @param maxAge the time (in seconds) this cookie should live. */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge) {<FILL_FUNCTION_BODY>} }
// Check to make sure the new value is not null (appservers like Tomcat // 4 blow up if the value is null). if (value == null) { value = ""; } String path = request.getContextPath() == null ? "/" : request.getContextPath(); if ("".equals(path)) { path = "/"; } Cookie cookie = new Cookie(name, value); cookie.setMaxAge(maxAge); cookie.setPath(path); cookie.setHttpOnly(true); response.addCookie(cookie);
1,006
152
1,158
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/FastDateFormat.java
Pair
compareTo
class Pair implements Comparable, java.io.Serializable { private final Object mObj1; private final Object mObj2; public Pair(Object obj1, Object obj2) { mObj1 = obj1; mObj2 = obj2; } @Override public int compareTo(Object obj) {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Pair)) { return false; } Pair key = (Pair)obj; return (mObj1 == null ? key.mObj1 == null : mObj1.equals(key.mObj1)) && (mObj2 == null ? key.mObj2 == null : mObj2.equals(key.mObj2)); } @Override public int hashCode() { return (mObj1 == null ? 0 : mObj1.hashCode()) + (mObj2 == null ? 0 : mObj2.hashCode()); } @Override public String toString() { return "[" + mObj1 + ':' + mObj2 + ']'; } }
if (this == obj) { return 0; } Pair other = (Pair)obj; Object a = mObj1; Object b = other.mObj1; firstTest: { if (a == null) { if (b != null) { return 1; } // Both a and b are null. break firstTest; } else { if (b == null) { return -1; } } int result = ((Comparable)a).compareTo(b); if (result != 0) { return result; } } a = mObj2; b = other.mObj2; if (a == null) { if (b != null) { return 1; } // Both a and b are null. return 0; } else { if (b == null) { return -1; } } return ((Comparable)a).compareTo(b);
330
281
611
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/FaviconServlet.java
FaviconServlet
getImage
class FaviconServlet extends HttpServlet { private static final Logger LOGGER = LoggerFactory.getLogger(FaviconServlet.class); /** * The content-type of the images to return. */ private static final String CONTENT_TYPE = "image/x-icon"; /** * Bytes of the default favicon to return when one was not found on a host. */ private byte[] defaultBytes; /** * Pool of HTTP connections to use to get the favicons */ private CloseableHttpClient client; /** * Cache the domains that a favicon was not found. */ private Cache<String, Integer> missesCache; /** * Cache the favicons that we've found. */ private Cache<String, byte[]> hitsCache; @Override public void init(ServletConfig config) throws ServletException { super.init(config); // Create a pool of HTTP connections to use to get the favicons client = HttpClientBuilder.create() .setConnectionManager(new PoolingHttpClientConnectionManager()) .setRedirectStrategy(new LaxRedirectStrategy()) .build(); // Load the default favicon to use when no favicon was found of a remote host try { defaultBytes = Files.readAllBytes(JiveGlobals.getHomePath().resolve("plugins").resolve("admin").resolve("webapp").resolve("images").resolve("server_16x16.gif")); } catch (final IOException e) { LOGGER.warn("Unable to retrieve default favicon", e); } // Initialize caches. missesCache = CacheFactory.createCache("Favicon Misses"); hitsCache = CacheFactory.createCache("Favicon Hits"); } @Override public void destroy() { try { client.close(); } catch (IOException e) { LOGGER.warn("Unable to close HTTP client", e); } } /** * Retrieve the image based on it's name. * * @param request the httpservletrequest. * @param response the httpservletresponse. */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { final String host = request.getParameter("host"); // OF-1885: Ensure that the provided value is a valid hostname. if (!InetAddresses.isInetAddress(host) && !InternetDomainName.isValid(host)) { LOGGER.info("Request for favicon of hostname that can't be parsed as a valid hostname '{}' is ignored.", host); writeBytesToStream(defaultBytes, response); return; } // Validate that we're connected to the host final SessionManager sessionManager = SessionManager.getInstance(); final Optional<String> optionalHost = Stream .concat(sessionManager.getIncomingServers().stream(), sessionManager.getOutgoingServers().stream()) .filter(remoteServerHost -> remoteServerHost.equalsIgnoreCase(host)) .findAny(); if (!optionalHost.isPresent()) { LOGGER.info("Request to unconnected host {} ignored - using default response", host); writeBytesToStream(defaultBytes, response); return; } // Check special cases where we need to change host to get a favicon final String hostToUse = "gmail.com".equals(host) ? "google.com" : host; byte[] bytes = getImage(hostToUse, defaultBytes); if (bytes != null) { writeBytesToStream(bytes, response); } } /** * Writes out a <code>byte</code> to the ServletOuputStream. * * @param bytes the bytes to write to the <code>ServletOutputStream</code>. */ private void writeBytesToStream(byte[] bytes, HttpServletResponse response) { response.setContentType(CONTENT_TYPE); // Send image try (ServletOutputStream sos = response.getOutputStream()) { sos.write(bytes); sos.flush(); } catch (IOException e) { // Do nothing } } /** * Returns the favicon image bytes of the specified host. * * @param host the name of the host to get its favicon. * @return the image bytes found, otherwise null. */ private byte[] getImage(String host, byte[] defaultImage) { // If we've already attempted to get the favicon twice and failed, // return the default image. if (missesCache.get(host) != null && missesCache.get(host) > 1) { // Domain does not have a favicon so return default icon return defaultImage; } // See if we've cached the favicon. if (hitsCache.containsKey(host)) { return hitsCache.get(host); } byte[] bytes = getImage(host); if (bytes == null) { // Cache that the requested domain does not have a favicon. Check if this // is the first cache miss or the second. if (missesCache.get(host) != null) { missesCache.put(host, 2); } else { missesCache.put(host, 1); } // Return byte of default icon bytes = defaultImage; } // Cache the favicon. else { hitsCache.put(host, bytes); } return bytes; } private byte[] getImage(@Nonnull final String host) {<FILL_FUNCTION_BODY>} }
final Set<URI> urls = new HashSet<>(); try { // Using a builder to reduce the impact of using user-provided values to generate a URL request. urls.add(new URIBuilder().setScheme("https").setHost(host).setPath("favicon.ico").build()); urls.add(new URIBuilder().setScheme("http").setHost(host).setPath("favicon.ico").build()); } catch (URISyntaxException e) { LOGGER.debug("An exception occurred while trying to obtain an image from: {}", host, e); return null; } // Try to get the favicon from the url using an HTTP connection from the pool // that also allows configuring timeout values (e.g. connect and get data) final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); for (final URI url : urls) { final HttpUriRequest getRequest = RequestBuilder.get(url) .setConfig(requestConfig) .build(); try (final CloseableHttpResponse response = client.execute(getRequest)) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final byte[] result = EntityUtils.toByteArray(response.getEntity()); // Prevent SSRF by checking result (OF-1885) if (!GraphicsUtils.isImage(result)) { LOGGER.info("Ignoring response to an HTTP request that should have returned an image (but returned something else): {}", url); continue; } return result; } } catch (final IOException ex) { LOGGER.debug("An exception occurred while trying to obtain an image from: {}", url, ex); } } return null;
1,434
466
1,900
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/GraphicsUtils.java
GraphicsUtils
isImage
class GraphicsUtils { private static final Logger Log = LoggerFactory.getLogger( GraphicsUtils.class ); /** * Checks if the provided input stream represents an image. * * @param stream The data to be parsed. Cannot be null. * @return true if the provided data is successfully identified as an image, otherwise false. */ public static boolean isImage( final InputStream stream ) {<FILL_FUNCTION_BODY>} /** * Checks if the provided byte array represents an image. * * @param bytes The data to be parsed. Cannot be null. * @return true if the provided data is successfully identified as an image, otherwise false. */ public static boolean isImage( final byte[] bytes ) { if ( bytes == null ) { throw new IllegalArgumentException( "Argument 'bytes' cannot be null." ); } return isImage( new ByteArrayInputStream( bytes ) ); } }
try { // This attempts to read the bytes as an image, returning null if it cannot parse the bytes as an image. return null != ImageIO.read( stream ); } catch ( IOException e ) { Log.debug( "An exception occurred while determining if data represents an image.", e ); return false; }
241
88
329
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/HTTPConnectionException.java
HTTPConnectionException
getMessage
class HTTPConnectionException extends Exception { private int errorCode; public HTTPConnectionException(int errorCode) { super(); this.errorCode = errorCode; } public int getErrorCode() { return errorCode; } @Override public String getMessage() {<FILL_FUNCTION_BODY>} }
if (errorCode == 400) { return "400 Bad Request"; } else if (errorCode == 401) { return "401 Unauthorized"; } else if (errorCode == 402) { return "402 Payment Required"; } else if (errorCode == 403) { return "403 Forbidden"; } else if (errorCode == 404) { return "404 Not Found"; } else if (errorCode == 405) { return "405 Method Not Allowed"; } else if (errorCode == 406) { return "406 Not Acceptable"; } else if (errorCode == 407) { return "407 Proxy Authentication Required"; } else if (errorCode == 408) { return "408 Request Timeout"; } else if (errorCode == 409) { return "409 Conflict"; } else if (errorCode == 410) { return "410 Gone"; } else if (errorCode == 411) { return "411 Length Required"; } else if (errorCode == 412) { return "412 Precondition Failed"; } else if (errorCode == 413) { return "413 Request Entity Too Large"; } else if (errorCode == 414) { return "414 Request-URI Too Long"; } else if (errorCode == 415) { return "415 Unsupported Media Type"; } else if (errorCode == 416) { return "416 Requested Range Not Satisfiable"; } else if (errorCode == 418) { return "417 Expectation Failed"; } return "Unknown HTTP error code: " + errorCode;
92
516
608
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/JavaSpecVersion.java
JavaSpecVersion
getVersionString
class JavaSpecVersion implements Comparable<JavaSpecVersion> { private static final Pattern PATTERN_SINGLE = Pattern.compile( "(\\d+)"); private static final Pattern PATTERN_DOUBLE = Pattern.compile( "(\\d+)\\.(\\d+)"); /** * The major number (ie 1.x). */ private final int major; /** * The minor version number (ie x.8). */ private final int minor; /** * Create a new version information object. * * @param major the major release number. * @param minor the minor release number. */ public JavaSpecVersion( int major, int minor ) { this.major = major; this.minor = minor; } /** * Create a new version from a simple version string (e.g. "1.8") * * @param source the version string */ public JavaSpecVersion( CharSequence source ) { if (source != null) { Matcher matcherSingle = PATTERN_SINGLE.matcher( source); Matcher matcherDouble = PATTERN_DOUBLE.matcher( source); if (matcherDouble.matches()) { major = Integer.parseInt(matcherDouble.group(1)); minor = Integer.parseInt(matcherDouble.group(2)); } else if (matcherSingle.matches()) { major = 0; minor = Integer.parseInt(matcherSingle.group(1)); } else { this.major = this.minor = 0; } } else { this.major = this.minor = 0; } } /** * Returns the version number of this instance of Openfire as a * String (ie major.minor.revision). * * @return The version as a string */ public String getVersionString() {<FILL_FUNCTION_BODY>} /** * Convenience method for comparing versions * * @param otherVersion a version to compare against * @return {@code true} if this version is newer, otherwise {@code false} */ public boolean isNewerThan(JavaSpecVersion otherVersion) { return this.compareTo(otherVersion) > 0; } @Override public int compareTo(JavaSpecVersion that) { if (that == null) { return 1; } return Integer.compare(minor, that.minor); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof JavaSpecVersion )) { return false; } JavaSpecVersion other = (JavaSpecVersion) o; return Objects.equals(minor, other.minor); } @Override public int hashCode() { return minor; } @Override public String toString() { return getVersionString(); } }
if ( major > 0 ) { return major + "." + minor; } else { return String.valueOf( minor ); }
783
40
823
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/JiveBeanInfo.java
JiveBeanInfo
getBeanDescriptor
class JiveBeanInfo implements BeanInfo { private static final Logger Log = LoggerFactory.getLogger(JiveBeanInfo.class); private ResourceBundle bundle; public JiveBeanInfo() { //Get the locale that should be used, then load the resource bundle. Locale currentLocale = JiveGlobals.getLocale(); try { bundle = ResourceBundle.getBundle("bean_" + getName(), currentLocale); } catch (Exception e) { // Ignore any exception when trying to load bundle. } } /** * Returns the names of the properties of the bean that should be exposed. * * @return the names of the properties that should be exposed. */ public abstract String[] getPropertyNames(); /** * Returns the bean Class. * * @return the Class of the JavaBean that the BeanInfo is for. */ public abstract Class getBeanClass(); /** * Returns the name of the class that the bean info applies to (which * corresponds to the resource bundle that will be loaded). For example, * for the class {@code com.foo.ExampleClass}, the name would be * {@code ExampleClass}. * * @return the name of the JavaBean that the BeanInfo is for. */ public abstract String getName(); // BeanInfo Interface @Override public BeanDescriptor getBeanDescriptor() {<FILL_FUNCTION_BODY>} @Override public PropertyDescriptor[] getPropertyDescriptors() { Class beanClass = getBeanClass(); String[] properties = getPropertyNames(); PropertyDescriptor[] descriptors = new PropertyDescriptor[properties.length]; try { // For each property, create a property descriptor and set the // name and description using the localized data. for (int i = 0; i < descriptors.length; i++) { PropertyDescriptor newDescriptor = new PropertyDescriptor(properties[i], beanClass); if (bundle != null) { newDescriptor.setDisplayName(bundle.getString(properties[i] + ".displayName")); newDescriptor.setShortDescription(bundle.getString(properties[i] + ".shortDescription")); } descriptors[i] = newDescriptor; } return descriptors; } catch (IntrospectionException ie) { Log.error(ie.getMessage(), ie); throw new Error(ie.toString()); } } @Override public int getDefaultPropertyIndex() { return -1; } @Override public EventSetDescriptor[] getEventSetDescriptors() { return null; } @Override public int getDefaultEventIndex() { return -1; } @Override public MethodDescriptor[] getMethodDescriptors() { return null; } @Override public BeanInfo[] getAdditionalBeanInfo() { return null; } @Override public java.awt.Image getIcon(int iconKind) { return null; } }
BeanDescriptor descriptor = new BeanDescriptor(getBeanClass()); try { // Attempt to load the displayName and shortDescription explicitly. String displayName = bundle.getString("displayName"); if (displayName != null) { descriptor.setDisplayName(displayName); } String shortDescription = bundle.getString("shortDescription"); if (shortDescription != null) { descriptor.setShortDescription(shortDescription); } // Add any other properties that are specified. Enumeration enumeration = bundle.getKeys(); while (enumeration.hasMoreElements()) { String key = (String)enumeration.nextElement(); String value = bundle.getString(key); if (value != null) { descriptor.setValue(key, value); } } } catch (Exception e) { // Ignore any exceptions. We may get some if we try to load a // a property that doesn't appear in the resource bundle. } return descriptor;
779
256
1,035
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/LinkedList.java
LinkedList
toString
class LinkedList<E> { /** * The root of the list keeps a reference to both the first and last * elements of the list. */ private LinkedListNode<E> head; /** * Creates a new linked list. */ public LinkedList() { head = new LinkedListNode<>(); } /** * Returns the first linked list node in the list. * * @return the first element of the list. */ public LinkedListNode<E> getFirst() { LinkedListNode<E> node = head.next; if (node == head) { return null; } return node; } /** * Returns the last linked list node in the list. * * @return the last element of the list. */ public LinkedListNode<E> getLast() { LinkedListNode<E> node = head.previous; if (node == head) { return null; } return node; } /** * Adds a node to the beginning of the list. * * @param node the node to add to the beginning of the list. * @return the node created to wrap the object. */ public LinkedListNode<E> addFirst(LinkedListNode<E> node) { return node.insert(head.next, head); } /** * Adds an object to the beginning of the list by automatically creating a * a new node and adding it to the beginning of the list. * * @param object the object to add to the beginning of the list. * @return the node created to wrap the object. */ public LinkedListNode<E> addFirst(E object) { return new LinkedListNode<>(object, head.next, head); } /** * Adds a node to the end of the list. * * @param node the node to add to the beginning of the list. * @return the node created to wrap the object. */ public LinkedListNode<E> addLast(LinkedListNode<E> node) { return node.insert(head, head.previous); } /** * Adds an object to the end of the list by automatically creating a * a new node and adding it to the end of the list. * * @param object the object to add to the end of the list. * @return the node created to wrap the object. */ public LinkedListNode<E> addLast(E object) { return new LinkedListNode<>(object, head, head.previous); } /** * Erases all elements in the list and re-initializes it. */ public void clear() { //Remove all references in the list. LinkedListNode<E> node = getLast(); while (node != null) { node.remove(); node = getLast(); } //Re-initialize. head.next = head.previous = head; } /** * Returns a String representation of the linked list with a comma * delimited list of all the elements in the list. * * @return a String representation of the LinkedList. */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
LinkedListNode<E> node = head.next; StringBuilder buf = new StringBuilder(); while (node != head) { buf.append(node.toString()).append(", "); node = node.next; } return buf.toString();
846
69
915
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/LinkedListNode.java
LinkedListNode
remove
class LinkedListNode<E> { public LinkedListNode<E> previous; public LinkedListNode<E> next; public E object; /** * This class is further customized for the CoolServlets cache system. It * maintains a timestamp of when a Cacheable object was first added to * cache. Timestamps are stored as long values and represent the number * of milleseconds passed since January 1, 1970 00:00:00.000 GMT. * <p> * The creation timestamp is used in the case that the cache has a * maximum lifetime set. In that case, when * [current time] - [creation time] &gt; [max lifetime], the object will be * deleted from cache.</p> */ public long timestamp; /** * Constructs an self-referencing node. This node acts as a start/end * sentinel when traversing nodes in a LinkedList. */ public LinkedListNode() { previous = next = this; } /** * Constructs a new linked list node. * * @param object the Object that the node represents. * @param next a reference to the next LinkedListNode in the list. * @param previous a reference to the previous LinkedListNode in the list. */ public LinkedListNode(E object, LinkedListNode<E> next, LinkedListNode<E> previous) { if (next != null && previous != null) { this.insert(next, previous); } this.object = object; } /** * Removes this node from the linked list that it was a part of. * @return This node; next and previous references dropped */ public LinkedListNode<E> remove() {<FILL_FUNCTION_BODY>} /** * Inserts this node into the linked list that it will be a part of. * @param next a reference to the next LinkedListNode in the list. * @param previous a reference to the previous LinkedListNode in the list. * @return This node, updated to reflect previous/next changes */ public LinkedListNode<E> insert(LinkedListNode<E> next, LinkedListNode<E> previous) { this.next = next; this.previous = previous; this.previous.next = this.next.previous = this; return this; } /** * Returns a String representation of the linked list node by calling the * toString method of the node's object. * * @return a String representation of the LinkedListNode. */ @Override public String toString() { return object == null ? "null" : object.toString(); } }
previous.next = next; next.previous = previous; previous = next = null; return this;
700
32
732
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/LocaleFilter.java
LocaleFilter
doFilter
class LocaleFilter implements Filter { private ServletContext context; @Override public void init(FilterConfig config) throws ServletException { this.context = config.getServletContext(); } /** * Ssets the locale context-wide based on a call to {@link JiveGlobals#getLocale()}. */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} /** * Does nothing */ @Override public void destroy() { } }
final String pathInfo = ((HttpServletRequest)request).getPathInfo(); if (pathInfo == null) { // Note, putting the locale in the application at this point is a little overkill // (ie, every user who hits this filter will do this). Eventually, it might make // sense to just set the locale in the user's session and if that's done we might // want to honor a preference to get the user's locale based on request headers. // For now, this is just a convenient place to set the locale globally. Config.set(context, Config.FMT_LOCALE, JiveGlobals.getLocale()); } else { try { String[] parts = pathInfo.split("/"); String pluginName = parts[1]; ResourceBundle bundle = LocaleUtils.getPluginResourceBundle(pluginName); LocalizationContext ctx = new LocalizationContext(bundle, JiveGlobals.getLocale()); Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, ctx); } catch (Exception e) { // Note, putting the locale in the application at this point is a little overkill // (ie, every user who hits this filter will do this). Eventually, it might make // sense to just set the locale in the user's session and if that's done we might // want to honor a preference to get the user's locale based on request headers. // For now, this is just a convenient place to set the locale globally. Config.set(context, Config.FMT_LOCALE, JiveGlobals.getLocale()); } } // Move along: chain.doFilter(request, response);
160
422
582
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/Log.java
Log
setDebugEnabled
class Log { private static final org.slf4j.Logger Logger = org.slf4j.LoggerFactory.getLogger(Log.class); public static final SystemProperty<Boolean> DEBUG_ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("log.debug.enabled") .setDefaultValue(false) .setDynamic(true) .addListener(Log::setDebugEnabled) .build(); public static final SystemProperty<Boolean> TRACE_ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("log.trace.enabled") .setDefaultValue(false) .setDynamic(true) .addListener(Log::setTraceEnabled) .build(); private static Level lastLogLevel = getRootLogLevel(); public static void setDebugEnabled(final boolean enabled) {<FILL_FUNCTION_BODY>} public static void setTraceEnabled(final boolean enabled) { if (enabled && getRootLogLevel().isMoreSpecificThan(Level.TRACE)) { lastLogLevel = getRootLogLevel(); setLogLevel(Level.TRACE); } else if (!enabled && getRootLogLevel().isLessSpecificThan(Level.TRACE)) { setLogLevel(lastLogLevel != Level.TRACE ? lastLogLevel : Level.INFO); lastLogLevel = Level.TRACE; } } public static Level getRootLogLevel() { // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j. final LoggerContext ctx = (LoggerContext) LogManager.getContext( false ); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getRootLogger(); return loggerConfig.getLevel(); } private static void setLogLevel(Level newLevel) { // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j. final LoggerContext ctx = (LoggerContext) LogManager.getContext( false ); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getRootLogger(); loggerConfig.setLevel( newLevel ); ctx.updateLoggers(); // This causes all Loggers to refetch information from their LoggerConfig. } public static void rotateOpenfireLogFile() { // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j. File logFile = new File(Log.getLogDirectory(), "openfire.log"); emptyFile(logFile); } public static void markOpenfireLogFile(String username) { String message = getMarkMessage(username); File logFile = new File(Log.getLogDirectory(), "openfire.log"); try(FileWriter fw = new FileWriter(logFile, true); PrintWriter out = new PrintWriter(fw)) { out.println(message); } catch (IOException e) { e.printStackTrace(); // Writing it to the logfile feels wrong, as we're processing the logfile here. } } /** * Returns the directory that log files exist in. The directory name will * have a File.separator as the last character in the string. * * @return the directory that log files exist in. */ public static String getLogDirectory() { // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j. final StringBuilder sb = new StringBuilder(); sb.append(JiveGlobals.getHomePath()); if (!sb.substring(sb.length()-1).startsWith(File.separator)) { sb.append(File.separator); } sb.append("logs"); sb.append(File.separator); return sb.toString(); } private static String getMarkMessage(String username) { final List<String> args = new ArrayList<>(); args.add(username); args.add(JiveGlobals.formatDateTime(new java.util.Date())); return LocaleUtils.getLocalizedString("log.marker_inserted_by", args); } private static void printToStdErr(String s, Throwable throwable) { if (s != null) { System.err.println(s); } if (throwable != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); System.err.print(sw.toString()); System.err.print("\n"); } } private static void emptyFile(File logFile) { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(logFile)); out.write(""); } catch (IOException ex) { Logger.warn("Could not empty file " + logFile.getName(), ex); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { Logger.warn("Could not close file.", ex); } } } } }
if (enabled && getRootLogLevel().isMoreSpecificThan(Level.DEBUG)) { lastLogLevel = getRootLogLevel(); setLogLevel(Level.DEBUG); } else if (!enabled && getRootLogLevel().isLessSpecificThan(Level.DEBUG)) { setLogLevel(lastLogLevel != Level.DEBUG ? lastLogLevel : Level.INFO); lastLogLevel = Level.DEBUG; }
1,354
109
1,463
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/NamedThreadFactory.java
NamedThreadFactory
newThread
class NamedThreadFactory implements ThreadFactory { private final AtomicInteger threadNumber = new AtomicInteger(1); private final String threadNamePrefix; private final ThreadFactory delegate; private final Boolean daemon; private final Integer priority; private final Long stackSize; private final ThreadGroup threadGroup; /** * Constructs an instance that delegates thread creation to the thread factory passed as an argument. When the * delegate argument is null, the instance will instantiate threads itself (similar to the functionality of the * other constructor of this class). * * When null is provided for the optional arguments of this method, the values as defined by the delegate factory * are used. * * @param threadNamePrefix The prefix of the name for new threads (cannot be null or an empty string). * @param delegate The factory to which this implementation delegates to (null when no override is desired). * @param daemon override for the isDaemon value for new threads (null when no override is desired). * @param priority override for the priority value for new threads (null when no override is desired). */ public NamedThreadFactory( String threadNamePrefix, ThreadFactory delegate, Boolean daemon, Integer priority ) { if ( threadNamePrefix == null || threadNamePrefix.isEmpty() ) { throw new IllegalArgumentException( "Argument 'threadNamePrefix' cannot be null or an empty string." ); } this.threadNamePrefix = threadNamePrefix; this.delegate = delegate; this.daemon = daemon; this.priority = priority; this.threadGroup = null; this.stackSize = null; } /** * Constructs a thread factory that will create new Thread instances (as opposed to using a delegate thread * factory). * * When null is provided for the optional arguments of this method, default values as provided by the Thread class * implementation will be used. * * @param threadNamePrefix The prefix of the name for new threads (cannot be null or an empty string). * @param daemon the isDaemon value for new threads (null to use default value). * @param priority override for the priority value for new threads (null to use default value). * @param threadGroup override for the thread group (null to use default value). * @param stackSize override for the stackSize value for new threads (null to use default value). */ public NamedThreadFactory( String threadNamePrefix, Boolean daemon, Integer priority, ThreadGroup threadGroup, Long stackSize ) { if ( threadNamePrefix == null || threadNamePrefix.isEmpty() ) { throw new IllegalArgumentException( "Argument 'threadNamePrefix' cannot be null or an empty string." ); } this.delegate = null; this.threadNamePrefix = threadNamePrefix; this.daemon = daemon; this.priority = priority; this.threadGroup = threadGroup; this.stackSize = stackSize; } @Override public Thread newThread( Runnable runnable ) {<FILL_FUNCTION_BODY>} }
final String name = threadNamePrefix + threadNumber.incrementAndGet(); final Thread thread; if ( delegate != null ) { thread = delegate.newThread( runnable ); thread.setName( name ); } else { if ( stackSize != null ) { thread = new Thread( threadGroup, runnable, name, stackSize ); } else { thread = new Thread( threadGroup, runnable, name ); } } if ( daemon != null && thread.isDaemon() != daemon ) { thread.setDaemon( daemon ); } if ( priority != null && thread.getPriority() != priority ) { thread.setPriority( priority ); } return thread;
762
213
975
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/PropertyClusterEventTask.java
PropertyClusterEventTask
writeExternal
class PropertyClusterEventTask implements ClusterTask<Void> { private Type event; private String key; private String value; private boolean isEncrypted; public static PropertyClusterEventTask createPutTask(String key, String value, boolean isEncrypted) { PropertyClusterEventTask task = new PropertyClusterEventTask(); task.event = Type.put; task.key = key; task.value = value; task.isEncrypted = isEncrypted; return task; } public static PropertyClusterEventTask createDeleteTask(String key) { PropertyClusterEventTask task = new PropertyClusterEventTask(); task.event = Type.deleted; task.key = key; return task; } @Override public Void getResult() { return null; } @Override public void run() { if (Type.put == event) { JiveProperties.getInstance().localPut(key, value, isEncrypted); } else if (Type.deleted == event) { JiveProperties.getInstance().localRemove(key); } } @Override public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { event = Type.values()[ExternalizableUtil.getInstance().readInt(in)]; key = ExternalizableUtil.getInstance().readSafeUTF(in); if (ExternalizableUtil.getInstance().readBoolean(in)) { value = ExternalizableUtil.getInstance().readSafeUTF(in); isEncrypted = ExternalizableUtil.getInstance().readBoolean(in); } } private static enum Type { /** * Event triggered when a system property was added or updated in the system. */ put, /** * Event triggered when a system property was deleted from the system. */ deleted } }
ExternalizableUtil.getInstance().writeInt(out, event.ordinal()); ExternalizableUtil.getInstance().writeSafeUTF(out, key); ExternalizableUtil.getInstance().writeBoolean(out, value != null); if (value != null) { ExternalizableUtil.getInstance().writeSafeUTF(out, value); ExternalizableUtil.getInstance().writeBoolean(out, isEncrypted); }
496
106
602
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/PropertyEventDispatcher.java
PropertyEventDispatcher
addListener
class PropertyEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(PropertyEventDispatcher.class); private static Set<PropertyEventListener> listeners = new CopyOnWriteArraySet<>(); private PropertyEventDispatcher() { // Not instantiable. } /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(PropertyEventListener listener) {<FILL_FUNCTION_BODY>} /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(PropertyEventListener listener) { listeners.remove(listener); } /** * Dispatches an event to all listeners. * * @param property the property. * @param eventType the event type. * @param params event parameters. */ public static void dispatchEvent(String property, EventType eventType, Map<String, Object> params) { for (PropertyEventListener listener : listeners) { try { switch (eventType) { case property_set: { listener.propertySet(property, params); break; } case property_deleted: { listener.propertyDeleted(property, params); break; } case xml_property_set: { listener.xmlPropertySet(property, params); break; } case xml_property_deleted: { listener.xmlPropertyDeleted(property, params); break; } default: break; } } catch (Exception e) { Log.error(e.getMessage(), e); } } } /** * Represents valid event types. */ public enum EventType { /** * A property was set. */ property_set, /** * A property was deleted. */ property_deleted, /** * An XML property was set. */ xml_property_set, /** * An XML property was deleted. */ xml_property_deleted; } }
if (listener == null) { throw new NullPointerException(); } listeners.add(listener);
560
33
593
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/S2STestService.java
S2SInterceptor
interceptPacket
class S2SInterceptor implements PacketInterceptor { private final StringBuilder xml = new StringBuilder(); private final IQ ping; /** * @param ping The IQ ping request that was used to initiate the test. */ public S2SInterceptor( IQ ping ) { this.ping = ping; } /** * Keeps a log of the XMPP traffic, releasing the wait lock on response received. */ @Override public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException {<FILL_FUNCTION_BODY>} /** * Returns the received stanzas as a String. */ public String toString() { return xml.toString(); } }
if (ping.getTo() == null || packet.getFrom() == null || packet.getTo() == null) { return; } if (!processed && (ping.getTo().getDomain().equals(packet.getFrom().getDomain()) || ping.getTo().getDomain().equals(packet.getTo().getDomain()))) { // Log all traffic to and from the domain. xml.append(packet.toXML()); xml.append('\n'); // If we've received our IQ response, stop the test. if ( packet instanceof IQ ) { final IQ iq = (IQ) packet; if ( iq.isResponse() && ping.getID().equals( iq.getID() ) && ping.getTo().equals( iq.getFrom() ) ) { Log.info("{} server to server response received.", iq.getType() == Type.result ? "Successful" : "Erroneous"); waitUntil.release(); } } }
209
262
471
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/SAXReaderUtil.java
ParserTask
call
class ParserTask implements Callable<Document> { private static final ThreadLocal<SAXReader> localSAXReader = ThreadLocal.withInitial(()-> { try { return constructNewReader(); } catch (SAXException e) { Log.error("Unable to construct a new XML parser.", e); return null; } }); @Nullable private final InputStream stream; @Nullable private final Reader reader; @Nullable private final File file; public ParserTask(@Nonnull final InputStream stream) { this.stream = stream; this.reader = null; this.file = null; } public ParserTask(@Nonnull final Reader reader) { this.stream = null; this.reader = reader; this.file = null; } public ParserTask(@Nonnull final File file) { this.stream = null; this.reader = null; this.file = file; } @Override public Document call() throws Exception {<FILL_FUNCTION_BODY>} }
if (stream != null) { return localSAXReader.get().read(stream); } else if (reader != null) { return localSAXReader.get().read(reader); } else if (file != null) { return localSAXReader.get().read(file); } else { // Did you forget to add an 'else' block for the new type that you added? throw new IllegalStateException("Unable to parse data. Data is either null, or of an unrecognized type."); }
283
135
418
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/SimpleSSLSocketFactory.java
DummyTrustManager
isServerTrusted
class DummyTrustManager implements X509TrustManager { public boolean isClientTrusted(X509Certificate[] cert) { return true; } public boolean isServerTrusted(X509Certificate[] cert) {<FILL_FUNCTION_BODY>} @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
try { cert[0].checkValidity(); return true; } catch (CertificateExpiredException e) { return false; } catch (CertificateNotYetValidException e) { return false; }
216
66
282
<methods>public void <init>() ,public java.net.Socket createSocket(java.net.Socket, java.io.InputStream, boolean) throws java.io.IOException,public abstract java.net.Socket createSocket(java.net.Socket, java.lang.String, int, boolean) throws java.io.IOException,public static javax.net.SocketFactory getDefault() ,public abstract java.lang.String[] getDefaultCipherSuites() ,public abstract java.lang.String[] getSupportedCipherSuites() <variables>static final boolean DEBUG
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/SmsService.java
SmsTask
run
class SmsTask implements Runnable { private final ObjectPool<SMPPSession> sessionPool; // Settings that apply to source of an SMS message. private final TypeOfNumber sourceTon = JiveGlobals.getEnumProperty( "sms.smpp.source.ton", TypeOfNumber.class, TypeOfNumber.UNKNOWN ); private final NumberingPlanIndicator sourceNpi = JiveGlobals.getEnumProperty( "sms.smpp.source.npi", NumberingPlanIndicator.class, NumberingPlanIndicator.UNKNOWN ); private final String sourceAddress = JiveGlobals.getProperty( "sms.smpp.source.address" ); // Settings that apply to destination of an SMS message. private final TypeOfNumber destinationTon = JiveGlobals.getEnumProperty( "sms.smpp.destination.ton", TypeOfNumber.class, TypeOfNumber.UNKNOWN ); private final NumberingPlanIndicator destinationNpi = JiveGlobals.getEnumProperty( "sms.smpp.destination.npi", NumberingPlanIndicator.class, NumberingPlanIndicator.UNKNOWN ); private final String destinationAddress; private final byte[] message; // Non-configurable defaults (for now - TODO?) private final ESMClass esm = new ESMClass(); private final byte protocolId = 0; private final byte priorityFlag = 1; private final String serviceType = "CMT"; private final String scheduleDeliveryTime = timeFormatter.format( new Date() ); private final String validityPeriod = null; private final RegisteredDelivery registeredDelivery = new RegisteredDelivery( SMSCDeliveryReceipt.DEFAULT ); private final byte replaceIfPresentFlag = 0; private final DataCoding dataCoding = new GeneralDataCoding( Alphabet.ALPHA_DEFAULT, MessageClass.CLASS1, false ); private final byte smDefaultMsgId = 0; SmsTask( ObjectPool<SMPPSession> sessionPool, String message, String destinationAddress ) { this.sessionPool = sessionPool; this.message = message.getBytes(); this.destinationAddress = destinationAddress; } @Override public void run() {<FILL_FUNCTION_BODY>} public void sendMessage() throws Exception { final SMPPSession session = sessionPool.borrowObject(); try { final String messageId = session.submitShortMessage( serviceType, sourceTon, sourceNpi, sourceAddress, destinationTon, destinationNpi, destinationAddress, esm, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, message ); Log.debug( "Message submitted, message_id is '{}'.", messageId ); } finally { sessionPool.returnObject( session ); } } }
try { sendMessage(); } catch ( Exception e ) { Log.error( "An exception occurred while sending a SMS message (to '{}')", destinationAddress, e ); }
758
57
815
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/WebBean.java
WebBean
init
class WebBean { public HttpSession session; public HttpServletRequest request; public HttpServletResponse response; public ServletContext application; public JspWriter out; public void init(HttpServletRequest request, HttpServletResponse response, HttpSession session, ServletContext app, JspWriter out) { this.request = request; this.response = response; this.session = session; this.application = app; this.out = out; } public void init(HttpServletRequest request, HttpServletResponse response, HttpSession session, ServletContext app) { this.request = request; this.response = response; this.session = session; this.application = app; } public void init(PageContext pageContext){<FILL_FUNCTION_BODY>} }
this.request = (HttpServletRequest)pageContext.getRequest(); this.response = (HttpServletResponse)pageContext.getResponse(); this.session = pageContext.getSession(); this.application = pageContext.getServletContext(); this.out = pageContext.getOut();
215
74
289
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/XMPPDateTimeFormat.java
XMPPDateTimeFormat
parseString
class XMPPDateTimeFormat { /** * Date/time format for use by SimpleDateFormat. The format conforms to * <a href="http://www.xmpp.org/extensions/xep-0082.html">XEP-0082</a>, which defines * a unified date/time format for XMPP. */ public static final String XMPP_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; public static final String XMPP_DATETIME_FORMAT_WO_TIMEZONE = "yyyy-MM-dd'T'HH:mm:ss.SSS"; public static final String XMPP_DATETIME_FORMAT_WO_MILLIS_WO_TIMEZONE = "yyyy-MM-dd'T'HH:mm:ss"; public static final String XMPP_DATE_FORMAT = "yyyy-MM-dd"; public static final String XMPP_TIME_FORMAT = "HH:mm:ss.SSS"; public static final String XMPP_TIME_FORMAT_WO_MILLIS = "HH:mm:ss"; /** * Date/time format for use by SimpleDateFormat. The format conforms to the format * defined in <a href="http://www.xmpp.org/extensions/xep-0091.html">XEP-0091</a>, * a specialized date format for historical XMPP usage. */ public static final String XMPP_DELAY_DATETIME_FORMAT = "yyyyMMdd'T'HH:mm:ss"; // matches CCYY-MM-DDThh:mm:ss.SSS(Z|(+|-)hh:mm)) private static final Pattern xep80DateTimePattern = Pattern.compile("^\\d+(-\\d+){2}+T(\\d+:){2}\\d+.\\d+(Z|([+-](\\d+:\\d+)))?$"); // matches CCYY-MM-DDThh:mm:ss(Z|(+|-)hh:mm)) private static final Pattern xep80DateTimeWoMillisPattern = Pattern.compile("^\\d+(-\\d+){2}+T(\\d+:){2}\\d+(Z|([+-](\\d+:\\d+)))?$"); // matches CCYYMMDDThh:mm:ss @SuppressWarnings("unused") private static final Pattern xep91Pattern = Pattern.compile("^\\d+T\\d+:\\d+:\\d+$"); private static final FastDateFormat FAST_FORMAT = FastDateFormat.getInstance( XMPP_DATETIME_FORMAT, TimeZone.getTimeZone("UTC")); private final DateFormat dateTimeFormat = new SimpleDateFormat(XMPP_DATETIME_FORMAT_WO_TIMEZONE + 'Z'); private final DateFormat dateTimeFormatWoMillies = new SimpleDateFormat(XMPP_DATETIME_FORMAT_WO_MILLIS_WO_TIMEZONE + 'Z'); /** * Create a new thread-safe instance of this utility class */ public XMPPDateTimeFormat() { TimeZone utc = TimeZone.getTimeZone("UTC"); dateTimeFormat.setTimeZone(utc); dateTimeFormatWoMillies.setTimeZone(utc); } /** * Tries to convert a given string to a Date object. * This method supports the format types defined by XEP-0082 and the format defined in legacy protocols * XEP-0082: CCYY-MM-DDThh:mm:ss[.sss]TZD * legacy: CCYYMMDDThh:mm:ss * * This method either returns a Date instance as result or it will return null or throw a ParseException * in case the String couldn't be parsed. * * @param dateString the String that should be parsed * @return the parsed date or null if the String could not be parsed * @throws ParseException if the date could not be parsed */ public Date parseString(String dateString) throws ParseException {<FILL_FUNCTION_BODY>} /** * Formats a Date object to String as defined in XEP-0082. * * The resulting String will have the timezone set to UTC ('Z') and includes milliseconds: * CCYY-MM-DDThh:mm:ss.sssZ * * @param date the date to format * @return the formatted date */ public static String format(Date date) { return FAST_FORMAT.format(date); } }
Matcher xep82WoMillisMatcher = xep80DateTimeWoMillisPattern.matcher(dateString); Matcher xep82Matcher = xep80DateTimePattern.matcher(dateString); if (xep82WoMillisMatcher.matches() || xep82Matcher.matches()) { String rfc822Date; // Convert the ISO 8601 time zone string to a RFC822 compatible format // since SimpleDateFormat supports ISO8601 only with Java7 or higher if (dateString.charAt(dateString.length() - 1) == 'Z') { rfc822Date = dateString.replace("Z", "+0000"); } else { // If the time zone wasn't specified with 'Z', then it's in // ISO8601 format (i.e. '(+|-)HH:mm') // RFC822 needs a similar format just without the colon (i.e. // '(+|-)HHmm)'), so remove it int lastColon = dateString.lastIndexOf(':'); rfc822Date = dateString.substring(0, lastColon) + dateString.substring(lastColon + 1); } if (xep82WoMillisMatcher.matches()) { synchronized (dateTimeFormatWoMillies) { return dateTimeFormatWoMillies.parse(rfc822Date); } } else { // OF-898: Replace any number of millisecond-characters with at most three of them. rfc822Date = rfc822Date.replaceAll("(\\.[0-9]{3})[0-9]*", "$1"); synchronized (dateTimeFormat) { return dateTimeFormat.parse(rfc822Date); } } } throw new ParseException("Date String could not be parsed", 0);
1,199
505
1,704
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/cache/CacheSizes.java
CacheSizes
sizeOfAnything
class CacheSizes { /** * Returns the size in bytes of a basic Object. This method should only * be used for actual Object objects and not classes that extend Object. * * @return the size of an Object. */ public static int sizeOfObject() { return 4; } /** * Returns the size in bytes of a String. * * @param string the String to determine the size of. * @return the size of a String. */ public static int sizeOfString(String string) { if (string == null) { return 0; } return 4 + string.getBytes().length; } /** * Returns the size in bytes of a primitive int. * * @return the size of a primitive int. */ public static int sizeOfInt() { return 4; } /** * Returns the size in bytes of a primitive char. * * @return the size of a primitive char. */ public static int sizeOfChar() { return 2; } /** * Returns the size in bytes of a primitive boolean. * * @return the size of a primitive boolean. */ public static int sizeOfBoolean() { return 1; } /** * Returns the size in bytes of a primitive long. * * @return the size of a primitive long. */ public static int sizeOfLong() { return 8; } /** * Returns the size in bytes of a primitive double. * * @return the size of a primitive double. */ public static int sizeOfDouble() { return 8; } /** * Returns the size in bytes of a Date. * * @return the size of a Date. */ public static int sizeOfDate() { return 12; } /** * Returns the size in bytes of a Map object. * * @param map the Map object to determine the size of. * @return the size of the Map object. * @throws CannotCalculateSizeException if the size cannot be calculated */ public static int sizeOfMap(Map<?,?> map) throws CannotCalculateSizeException { if (map == null) { return 0; } // Base map object -- should be something around this size. int size = 36; Set<? extends Map.Entry> set = map.entrySet(); // Add in size of each value for (Map.Entry<Object, Object> entry : set) { size += sizeOfAnything(entry.getKey()); size += sizeOfAnything(entry.getValue()); } return size; } /** * Returns the size in bytes of a Collection object. Elements are assumed to be * {@code String}s, {@code Long}s or {@code Cacheable} objects. * * @param list the Collection object to determine the size of. * @return the size of the Collection object. * @throws CannotCalculateSizeException if the size cannot be calculated */ public static int sizeOfCollection(Collection list) throws CannotCalculateSizeException { if (list == null) { return 0; } // Base list object (approximate) int size = 36; // Add in size of each value Object[] values = list.toArray(); for (int i = 0; i < values.length; i++) { size += sizeOfAnything(values[i]); } return size; } /** * Returns the size of an object in bytes. Determining size by serialization * is only used as a last resort. * * @param object the object to calculate the size of * @return the size of an object in bytes. * @throws CannotCalculateSizeException if the size cannot be calculated */ public static int sizeOfAnything(Object object) throws CannotCalculateSizeException {<FILL_FUNCTION_BODY>} private static class NullOutputStream extends OutputStream { int size = 0; @Override public void write(int b) throws IOException { size++; } @Override public void write(byte[] b) throws IOException { size += b.length; } @Override public void write(byte[] b, int off, int len) { size += len; } /** * Returns the number of bytes written out through the stream. * * @return the number of bytes written to the stream. */ public int size() { return size; } } }
// If the object is Cacheable, ask it its size. if (object == null) { return 0; } if (object instanceof Cacheable) { return ((Cacheable)object).getCachedSize(); } // Check for other common types of objects put into cache. else if (object instanceof String) { return sizeOfString((String)object); } else if (object instanceof Long) { return sizeOfLong(); } else if (object instanceof Integer) { return sizeOfObject() + sizeOfInt(); } else if (object instanceof Double) { return sizeOfObject() + sizeOfDouble(); } else if (object instanceof Boolean) { return sizeOfObject() + sizeOfBoolean(); } else if (object instanceof Map) { return sizeOfMap((Map)object); } else if (object instanceof long[]) { long[] array = (long[])object; return sizeOfObject() + array.length * sizeOfLong(); } else if (object instanceof Collection) { return sizeOfCollection((Collection)object); } else if (object instanceof byte[]) { byte [] array = (byte[])object; return sizeOfObject() + array.length; } // Default behavior -- serialize the object to determine its size. else { int size = 1; try { // Default to serializing the object out to determine size. CacheSizes.NullOutputStream out = new NullOutputStream(); ObjectOutputStream outObj = new ObjectOutputStream(out); outObj.writeObject(object); size = out.size(); } catch (IOException ioe) { throw new CannotCalculateSizeException(object); } return size; }
1,205
448
1,653
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/cache/ComponentCacheWrapper.java
ComponentCacheWrapper
clear
class ComponentCacheWrapper<K extends Serializable, V extends Serializable> extends CacheWrapper<K, V> { public ComponentCacheWrapper(Cache<K, V> cache) { super(cache); } @Override public void clear() {<FILL_FUNCTION_BODY>} }
// no-op; we don't want to clear the components cache
77
20
97
<methods>public java.lang.String addClusteredCacheEntryListener(ClusteredCacheEntryListener<K,V>, boolean, boolean) ,public void clear() ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<K,V>> entrySet() ,public V get(java.lang.Object) ,public long getCacheHits() ,public long getCacheMisses() ,public java.lang.String getCacheSizeRemark() ,public org.jivesoftware.util.cache.Cache.CapacityUnit getCapacityUnit() ,public long getLongCacheSize() ,public long getMaxCacheSize() ,public java.lang.String getMaxCacheSizeRemark() ,public long getMaxLifetime() ,public java.lang.String getName() ,public Cache<K,V> getWrappedCache() ,public boolean isEmpty() ,public Set<K> keySet() ,public V put(K, V) ,public void putAll(Map<? extends K,? extends V>) ,public V remove(java.lang.Object) ,public void removeClusteredCacheEntryListener(java.lang.String) ,public void setMaxCacheSize(long) ,public void setMaxLifetime(long) ,public void setName(java.lang.String) ,public int size() ,public Collection<V> values() <variables>private Cache<K,V> cache
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/cache/ConsistencyMonitor.java
Task
run
class Task extends TimerTask { @Override public void run() {<FILL_FUNCTION_BODY>} }
final Instant start = Instant.now(); Log.debug("Starting new cache consistency check."); final RoutingTableImpl routingTable = (RoutingTableImpl) XMPPServer.getInstance().getRoutingTable(); final SessionManager sessionManager = XMPPServer.getInstance().getSessionManager(); final MultiUserChatManager multiUserChatManager = XMPPServer.getInstance().getMultiUserChatManager(); final Set<String> offenders = new HashSet<>(); final Collection<String> serverRoutesFailures = routingTable.clusteringStateConsistencyReportForServerRoutes().get("fail"); if (serverRoutesFailures != null && !serverRoutesFailures.isEmpty()) { offenders.add(RoutingTableImpl.S2S_CACHE_NAME); } final Collection<String> componentRoutesFailures = routingTable.clusteringStateConsistencyReportForComponentRoutes().get("fail"); if (componentRoutesFailures != null && !componentRoutesFailures.isEmpty()) { offenders.add(RoutingTableImpl.COMPONENT_CACHE_NAME); } final Collection<String> clientRoutesFailures = routingTable.clusteringStateConsistencyReportForClientRoutes().get("fail"); if (clientRoutesFailures != null && !clientRoutesFailures.isEmpty()) { // This check operates on multiple caches. offenders.add(RoutingTableImpl.C2S_CACHE_NAME); offenders.add(RoutingTableImpl.ANONYMOUS_C2S_CACHE_NAME); } final Collection<String> usersSessionsFailures = routingTable.clusteringStateConsistencyReportForUsersSessions().get("fail"); if (usersSessionsFailures != null && !usersSessionsFailures.isEmpty()) { offenders.add(RoutingTableImpl.C2S_SESSION_NAME); } final Collection<String> incomingServerSessionsFailures = sessionManager.clusteringStateConsistencyReportForIncomingServerSessionInfos().get("fail"); if (incomingServerSessionsFailures != null && !incomingServerSessionsFailures.isEmpty()) { offenders.add(SessionManager.ISS_CACHE_NAME); } final Collection<String> sessionInfosFailures = sessionManager.clusteringStateConsistencyReportForSessionInfos().get("fail"); if (sessionInfosFailures != null && !sessionInfosFailures.isEmpty()) { offenders.add(SessionManager.C2S_INFO_CACHE_NAME); } final List<Multimap<String, String>> mucReportsList = multiUserChatManager.clusteringStateConsistencyReportForMucRoomsAndOccupant(); final Collection<String> mucOccupantFailures = new ArrayList<>(); for (Multimap<String, String> mucReport : mucReportsList) { mucReport.get("fail").addAll(mucOccupantFailures); } if (!mucOccupantFailures.isEmpty()) { offenders.add("MUC Service"); } if (offenders.isEmpty()) { Log.info("Cache consistency check completed in {}. No issues found.", Duration.between(start, Instant.now())); } else { Log.warn("Cache consistency check completed in {}. Detected issues in: {}", Duration.between(start, Instant.now()), String.join(", ", offenders)); XMPPServer.getInstance().sendMessageToAdmins("Cache inconsistencies were detected. This can cause bugs, especially when running in a cluster. " + "If this problem persists, all Openfire instances in the cluster need to be restarted at the same time. Affected cache(s): " + String.join(", ", offenders)); }
38
971
1,009
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/cache/DefaultLocalCacheStrategy.java
DefaultLocalCacheStrategy
createCache
class DefaultLocalCacheStrategy implements CacheFactoryStrategy { /** * Keep track of the locks that are currently being used. */ private Map<CacheKey, LockAndCount> locks = new ConcurrentHashMap<>(); private Interner<CacheKey> interner = Interners.newWeakInterner(); public DefaultLocalCacheStrategy() { } @Override public boolean startCluster() { return false; } @Override public void stopCluster() { } @Override public Cache createCache(String name) {<FILL_FUNCTION_BODY>} @Override public void destroyCache(Cache cache) { cache.clear(); } @Override public boolean isSeniorClusterMember() { return true; } @Override public Collection<ClusterNodeInfo> getClusterNodesInfo() { return Collections.emptyList(); } @Override public int getMaxClusterNodes() { return 0; } @Override public byte[] getSeniorClusterMemberID() { return null; } @Override public byte[] getClusterMemberID() { return XMPPServer.getInstance().getNodeID().toByteArray(); } @Override public long getClusterTime() { return System.currentTimeMillis(); } @Override public void doClusterTask(final ClusterTask task) { } @Override public void doClusterTask(ClusterTask task, byte[] nodeID) { throw new IllegalStateException("Cluster service is not available"); } @Override public Collection<Object> doSynchronousClusterTask(ClusterTask task, boolean includeLocalMember) { return Collections.emptyList(); } @Override public Object doSynchronousClusterTask(ClusterTask task, byte[] nodeID) { throw new IllegalStateException("Cluster service is not available"); } @Override public void updateCacheStats(Map<String, Cache> caches) { } @Override public String getPluginName() { return "local"; } @Override public Lock getLock(Object key, Cache cache) { return new LocalLock(new CacheKey(cache, key)); } @SuppressWarnings( "LockAcquiredButNotSafelyReleased" ) private void acquireLock(CacheKey key) { ReentrantLock lock = lookupLockForAcquire(key); lock.lock(); } private void releaseLock(CacheKey key) { ReentrantLock lock = lookupLockForRelease(key); lock.unlock(); } private ReentrantLock lookupLockForAcquire(CacheKey cacheKey) { CacheKey mutex = interner.intern(cacheKey); // Ensure that the mutex used in the next line is the same for objects that are equal. synchronized(mutex) { LockAndCount lac = locks.get(mutex); if (lac == null) { lac = new LockAndCount(new ReentrantLock()); lac.count = 1; locks.put(mutex, lac); } else { lac.count++; } return lac.lock; } } private ReentrantLock lookupLockForRelease(CacheKey cacheKey) { CacheKey mutex = interner.intern(cacheKey); // Ensure that the mutex used in the next line is the same for objects that are equal. synchronized(mutex) { LockAndCount lac = locks.get(mutex); if (lac == null) { throw new IllegalStateException("No lock found for object " + mutex); } if (lac.count <= 1) { locks.remove(mutex); } else { lac.count--; } return lac.lock; } } private class LocalLock implements Lock { private final CacheKey key; LocalLock(CacheKey key) { this.key = key; } @Override public void lock(){ acquireLock(key); } @Override public void unlock() { releaseLock(key); } @Override public void lockInterruptibly() throws InterruptedException { ReentrantLock lock = lookupLockForAcquire(key); lock.lockInterruptibly(); } @Nonnull @Override public Condition newCondition(){ ReentrantLock lock = lookupLockForAcquire(key); return lock.newCondition(); } @Override public boolean tryLock() { ReentrantLock lock = lookupLockForAcquire(key); return lock.tryLock(); } @Override public boolean tryLock(long time, @Nonnull TimeUnit unit) throws InterruptedException { ReentrantLock lock = lookupLockForAcquire(key); return lock.tryLock(time, unit); } } private static class LockAndCount { final ReentrantLock lock; int count; LockAndCount(ReentrantLock lock) { this.lock = lock; } } @Override public ClusterNodeInfo getClusterNodeInfo(byte[] nodeID) { // not clustered return null; } /** * A key of a cache, namespaced by the cache that it belongs to. */ private static class CacheKey { final String cacheName; final Object key; private CacheKey(Cache cache, Object key) { this.cacheName = cache.getName(); this.key = key; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheKey cacheKey = (CacheKey) o; return cacheName.equals(cacheKey.cacheName) && key.equals(cacheKey.key); } @Override public int hashCode() { return Objects.hash(cacheName, key); } } }
// Get cache configuration from system properties or default (hardcoded) values long maxSize = CacheFactory.getMaxCacheSize(name); long lifetime = CacheFactory.getMaxCacheLifetime(name); // Create cache with located properties return new DefaultCache(name, maxSize, lifetime);
1,574
75
1,649
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/cache/ReverseLookupComputingCacheEntryListener.java
ReverseLookupComputingCacheEntryListener
entryRemoved
class ReverseLookupComputingCacheEntryListener<K, V> implements ClusteredCacheEntryListener<K, V> { private final Map<NodeID, Set<K>> reverseCacheRepresentation; private final Function<V, Set<NodeID>> ownageDeducer; public ReverseLookupComputingCacheEntryListener(@Nonnull final Map<NodeID, Set<K>> reverseCacheRepresentation, @Nonnull final Function<V, Set<NodeID>> ownageDeducer) { this.reverseCacheRepresentation = reverseCacheRepresentation; this.ownageDeducer = ownageDeducer; } @Override public void entryAdded(@Nonnull final K key, @Nullable final V value, @Nonnull final NodeID initiator) { final Set<NodeID> newNodesWithThisKey = ownageDeducer.apply(value); add(key, newNodesWithThisKey); } private void add(K key, Set<NodeID> newNodesWithThisKey) { // Step 1 : update existing entries to the updated situation final Iterator<Map.Entry<NodeID, Set<K>>> iter = reverseCacheRepresentation.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<NodeID, Set<K>> existingEntry = iter.next(); final NodeID existingEntryNodeID = existingEntry.getKey(); if (newNodesWithThisKey.contains(existingEntryNodeID)) { existingEntry.getValue().add(key); } } // Step 2 : add entries for node ids that were not in the reverse lookup before for (final NodeID nodeIdForWhichTheValueExists : newNodesWithThisKey) { if (!reverseCacheRepresentation.containsKey(nodeIdForWhichTheValueExists)) { reverseCacheRepresentation.computeIfAbsent(nodeIdForWhichTheValueExists, k -> new HashSet<>()).add(key); } } } @Override public void entryRemoved(@Nonnull final K key, @Nullable final V oldValue, @Nonnull final NodeID initiator) {<FILL_FUNCTION_BODY>} @Override public void entryUpdated(@Nonnull final K key, @Nullable final V oldValue, @Nullable final V newValue, @Nonnull final NodeID nodeID) { final Set<NodeID> nodesToAdd = ownageDeducer.apply(newValue); // Remove all entries for the key. final Iterator<Map.Entry<NodeID, Set<K>>> iter = reverseCacheRepresentation.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<NodeID, Set<K>> existingEntry = iter.next(); final NodeID existingEntryNodeID = existingEntry.getKey(); if (!nodesToAdd.contains(existingEntryNodeID)) { existingEntry.getValue().remove(key); if (existingEntry.getValue().isEmpty()) { iter.remove(); } } } // Add entries for only the latest state of the value. add(key, nodesToAdd); } @Override public void entryEvicted(@Nonnull final K key, @Nullable final V oldValue, @Nonnull final NodeID nodeID) { entryRemoved(key, oldValue, nodeID); } @Override public void mapCleared(@Nonnull final NodeID nodeID) { // This is not necessarily correct, as the node owners aren't recalculated using the function. It probably is // sufficient though to work with cluster nodes dropping out of the cluster. reverseCacheRepresentation.remove(nodeID); } @Override public void mapEvicted(@Nonnull final NodeID nodeID) { mapCleared(nodeID); } }
final Iterator<Map.Entry<NodeID, Set<K>>> iter = reverseCacheRepresentation.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<NodeID, Set<K>> existingEntry = iter.next(); existingEntry.getValue().remove(key); if (existingEntry.getValue().isEmpty()) { iter.remove(); } }
947
100
1,047
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/cache/ReverseLookupUpdatingCacheEntryListener.java
ReverseLookupUpdatingCacheEntryListener
entryRemoved
class ReverseLookupUpdatingCacheEntryListener<K, V> implements ClusteredCacheEntryListener<K, V> { private final ConcurrentMap<NodeID, Set<K>> reverseCacheRepresentation; public ReverseLookupUpdatingCacheEntryListener(@Nonnull final ConcurrentMap<NodeID, Set<K>> reverseCacheRepresentation) { this.reverseCacheRepresentation = reverseCacheRepresentation; } @Override public void entryAdded(@Nonnull final K key, @Nullable final V value, @Nonnull final NodeID nodeID) { reverseCacheRepresentation.computeIfAbsent(nodeID, k -> new HashSet<>()).add(key); } @Override public void entryRemoved(@Nonnull final K key, @Nullable final V oldValue, @Nonnull final NodeID nodeID) {<FILL_FUNCTION_BODY>} @Override public void entryUpdated(@Nonnull final K key, @Nullable final V oldValue, @Nullable final V newValue, @Nonnull final NodeID nodeID) { // Possibly out-of-order event. The update itself signals that it's expected that the entry exists, so lets add it. entryAdded(key, newValue, nodeID); } @Override public void entryEvicted(@Nonnull final K key, @Nullable final V oldValue, @Nonnull final NodeID nodeID) { entryRemoved(key, oldValue, nodeID); } @Override public void mapCleared(@Nonnull final NodeID nodeID) { reverseCacheRepresentation.remove(nodeID); } @Override public void mapEvicted(@Nonnull final NodeID nodeID) { reverseCacheRepresentation.remove(nodeID); } }
reverseCacheRepresentation.computeIfPresent(nodeID, (k, v) -> { v.remove(key); return v; });
443
42
485
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/util/cert/CNCertificateIdentityMapping.java
CNCertificateIdentityMapping
mapIdentity
class CNCertificateIdentityMapping implements CertificateIdentityMapping { private static Pattern cnPattern = Pattern.compile("(?i)(cn=)([^,]*)"); /** * Maps certificate CommonName as identity credentials * * @param certificate the certificates to map * @return A List of names. */ @Override public List<String> mapIdentity(X509Certificate certificate) {<FILL_FUNCTION_BODY>} /** * Returns the short name of mapping * * @return The short name of the mapping */ @Override public String name() { return "Common Name Mapping"; } }
String name = certificate.getSubjectDN().getName(); Matcher matcher = cnPattern.matcher(name); // Create an array with the detected identities List<String> names = new ArrayList<>(); while (matcher.find()) { names.add(matcher.group(2)); } return names;
179
89
268
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/ArraySwap.java
ArraySwap
swap
class ArraySwap { private OperateData[] operateDataArray; private int start; public int length; public void swap(OperateData[] operateDataArray, int start, int length) {<FILL_FUNCTION_BODY>} public OperateData get(int i) { return this.operateDataArray[i + start]; } }
this.operateDataArray = operateDataArray; this.start = start; this.length = length;
95
32
127
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/DefaultExpressResourceLoader.java
DefaultExpressResourceLoader
loadExpress
class DefaultExpressResourceLoader implements IExpressResourceLoader { @Override public String loadExpress(String expressName) throws Exception {<FILL_FUNCTION_BODY>} }
expressName = expressName.replace('.', '/') + ".ql"; InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(expressName); if (inputStream == null) { throw new QLException("不能找到表达式文件:" + expressName); } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String tmpStr; while ((tmpStr = bufferedReader.readLine()) != null) { stringBuilder.append(tmpStr).append("\n"); } bufferedReader.close(); inputStream.close(); return stringBuilder.toString();
47
176
223
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/DynamicParamsUtil.java
DynamicParamsUtil
maybeDynamicParams
class DynamicParamsUtil { public static boolean supportDynamicParams = false; private DynamicParamsUtil() { throw new IllegalStateException("Utility class"); } public static Object[] transferDynamicParams(InstructionSetContext context, ArraySwap list, Class<?>[] declaredParamsClasses, boolean maybeDynamicParams) throws Exception { Object[] params; // 参数定义不符合动态参数形式 || 用户自定义不支持 || 用户传入的参数不符合 if (!maybeDynamicParams || !supportDynamicParams || !maybeDynamicParams(context, list, declaredParamsClasses)) { if (declaredParamsClasses.length != list.length) { throw new QLException("定义的参数长度与运行期传入的参数长度不一致"); } params = new Object[list.length]; for (int i = 0; i < list.length; i++) { params[i] = list.get(i).getObject(context); } return params; } //支持不定参数的使用 function(arg1,arg2,arg3...) //list -> parameters[] // arg1,arg2 -> arg1,arg2,[] // arg1,arg2,arg3,arg4,arg5 -> arg1,arg2,[arg3,arg4,arg5] int paramLength = declaredParamsClasses.length; int beforeCount = paramLength - 1; int paramsCount = list.length - beforeCount; if (beforeCount >= 0 && declaredParamsClasses[beforeCount].isArray() && paramsCount >= 0) { Class<?> componentType = declaredParamsClasses[beforeCount].getComponentType(); params = new Object[beforeCount + 1]; Object[] lastParameters = (Object[])Array.newInstance(componentType, paramsCount); params[beforeCount] = lastParameters; for (int i = 0; i < list.length; i++) { if (i < beforeCount) { params[i] = list.get(i).getObject(context); } else { lastParameters[i - beforeCount] = list.get(i).getObject(context); } } } else { throw new QLException("定义的参数长度与运行期传入的参数长度不一致"); } return params; } public static boolean maybeDynamicParams(Class<?>[] declaredParamsClasses) { int length = declaredParamsClasses.length; return length > 0 && declaredParamsClasses[length - 1].isArray(); } private static boolean maybeDynamicParams(InstructionSetContext context, ArraySwap list, Class<?>[] declaredParamsClasses) throws Exception {<FILL_FUNCTION_BODY>} }
//长度不一致,有可能 if (declaredParamsClasses.length != list.length) { return true; } //长度一致的不定参数:不定参数的数组,只输入了一个参数并且为array,有可能 int length = list.length; Object lastParam = list.get(length - 1).getObject(context); return lastParam != null && !lastParam.getClass().isArray();
687
112
799
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/ExportItem.java
ExportItem
toString
class ExportItem { public static final String TYPE_ALIAS = "alias"; public static final String TYPE_DEF = "def"; public static final String TYPE_FUNCTION = "function"; public static final String TYPE_MACRO = "macro"; private String globeName; String name; /** * def, alias */ private String type; /** * 类名或者别名 */ private String desc; public ExportItem(String name, String type, String desc) { this.globeName = name; this.name = name; this.type = type; this.desc = desc; } public ExportItem(String globeName, String name, String type, String desc) { this.globeName = globeName; this.name = name; this.type = type; this.desc = desc; } @Override public String toString() {<FILL_FUNCTION_BODY>} public String getGlobeName() { return globeName; } public void setGlobeName(String globeName) { this.globeName = globeName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
return this.globeName + "[" + this.type + ":" + this.name + " " + this.desc + "]";
387
36
423
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/ExpressLoader.java
ExpressLoader
getExportInfo
class ExpressLoader { private final ConcurrentHashMap<String, InstructionSet> expressInstructionSetCache = new ConcurrentHashMap<>(); final ExpressRunner expressRunner; public ExpressLoader(ExpressRunner expressRunner) { this.expressRunner = expressRunner; } public InstructionSet loadExpress(String expressName) throws Exception { return parseInstructionSet(expressName, this.expressRunner.getExpressResourceLoader().loadExpress(expressName)); } public void addInstructionSet(String expressName, InstructionSet set) throws Exception { synchronized (expressInstructionSetCache) { if (expressInstructionSetCache.containsKey(expressName)) { throw new QLException("表达式定义重复:" + expressName); } expressInstructionSetCache.put(expressName, set); } } public InstructionSet parseInstructionSet(String expressName, String expressString) throws Exception { InstructionSet parseResult; if (expressInstructionSetCache.containsKey(expressName)) { throw new QLException("表达式定义重复:" + expressName); } synchronized (expressInstructionSetCache) { parseResult = this.expressRunner.parseInstructionSet(expressString); parseResult.setName(expressName); parseResult.setGlobeName(expressName); // 需要将函数和宏定义都提取出来 for (FunctionInstructionSet item : parseResult .getFunctionInstructionSets()) { this.addInstructionSet(item.name, item.instructionSet); item.instructionSet.setName(item.name); item.instructionSet.setGlobeName(expressName + "." + item.name); } if (parseResult.hasMain()) { this.addInstructionSet(expressName, parseResult); } } return parseResult; } public void clear() { this.expressInstructionSetCache.clear(); } public InstructionSet getInstructionSet(String expressName) { return expressInstructionSetCache.get(expressName); } public ExportItem[] getExportInfo() {<FILL_FUNCTION_BODY>} }
Map<String, ExportItem> result = new TreeMap<>(); for (InstructionSet instructionSet : expressInstructionSetCache.values()) { String globeName = instructionSet.getGlobeName(); for (ExportItem exportItem : instructionSet.getExportDef()) { exportItem.setGlobeName(globeName + "." + exportItem.getName()); result.put(exportItem.getGlobeName(), exportItem); } String name = instructionSet.getName(); String type = instructionSet.getType(); result.put(globeName, new ExportItem(globeName, name, type, instructionSet.toString())); } return result.values().toArray(new ExportItem[0]);
565
181
746
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/ExpressRemoteCacheRunner.java
ExpressRemoteCacheRunner
execute
class ExpressRemoteCacheRunner { public void loadCache(String expressName, String text) { InstructionSet instructionSet; try { instructionSet = getExpressRunner().parseInstructionSet(text); CacheObject cache = new CacheObject(); cache.setExpressName(expressName); cache.setText(text); cache.setInstructionSet(instructionSet); this.putCache(expressName, cache); } catch (Exception e) { throw new RuntimeException("解析指令并缓存过程出现错误.", e); } } public Object execute(String name, IExpressContext<String, Object> context, List<String> errorList, boolean isTrace, boolean isCatchException) {<FILL_FUNCTION_BODY>} /** * 获取执行器ExpressRunner * * @return */ public abstract ExpressRunner getExpressRunner(); /** * 获取缓存对象 * * @param key * @return */ public abstract Object getCache(String key); /** * 放置缓存的对象 * * @param key * @param object */ public abstract void putCache(String key, Object object); }
try { CacheObject cache = (CacheObject)this.getCache(name); if (cache == null) { throw new RuntimeException("未获取到缓存对象."); } ExpressRunner expressRunner = getExpressRunner(); return expressRunner.execute(cache.getInstructionSet(), context, errorList, isTrace, isCatchException); } catch (Exception e) { throw new RuntimeException("获取缓存信息,并且执行指令集出现错误.", e); }
318
124
442
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/InstructionSetContext.java
InstructionSetContext
clear
class InstructionSetContext implements IExpressContext<String, Object> { /** * 没有知道数据类型的变量定义是否传递到最外层的Context */ private boolean isExpandToParent = true; private IExpressContext<String, Object> parent = null; private Map<String, Object> content; /** * 符号表 */ private final Map<String, Object> symbolTable = new HashMap<>(); private ExpressLoader expressLoader; private boolean isSupportDynamicFieldName = false; private ExpressRunner runner; public ExpressRunner getRunner() { return runner; } public InstructionSetContext(boolean isExpandToParent, ExpressRunner expressRunner, IExpressContext<String, Object> parent, ExpressLoader expressLoader, boolean isSupportDynamicFieldName) { this.initial(isExpandToParent, expressRunner, parent, expressLoader, isSupportDynamicFieldName); } public void initial(boolean isExpandToParent, ExpressRunner expressRunner, IExpressContext<String, Object> parent, ExpressLoader expressLoader, boolean isSupportDynamicFieldName) { this.isExpandToParent = isExpandToParent; this.runner = expressRunner; this.parent = parent; this.expressLoader = expressLoader; this.isSupportDynamicFieldName = isSupportDynamicFieldName; } public void clear() {<FILL_FUNCTION_BODY>} public void exportSymbol(String varName, Object aliasNameObject) throws Exception { if (this.parent instanceof InstructionSetContext) { ((InstructionSetContext)this.parent).exportSymbol(varName, aliasNameObject); } else { this.addSymbol(varName, aliasNameObject); } } public void addSymbol(String varName, Object aliasNameObject) throws Exception { if (this.symbolTable.containsKey(varName)) { throw new QLException("变量" + varName + "已经存在,不能重复定义,也不能再从函数内部 export"); } this.symbolTable.put(varName, aliasNameObject); } public void addSymbol(Map<String, Object> aliasNameObjects) { this.symbolTable.putAll(aliasNameObjects); } public void setSupportDynamicFieldName(boolean isSupportDynamicFieldName) { this.isSupportDynamicFieldName = isSupportDynamicFieldName; } public boolean isSupportDynamicFieldName() { return this.isSupportDynamicFieldName; } public ExpressRunner getExpressRunner() { return this.runner; } public Object findAliasOrDefSymbol(String varName) { Object result = this.symbolTable.get(varName); if (result == null && this.parent instanceof InstructionSetContext) { result = ((InstructionSetContext)this.parent).findAliasOrDefSymbol(varName); } return result; } public Object getSymbol(String varName) throws Exception { Object result = this.symbolTable.get(varName); if (result == null && this.expressLoader != null) { result = this.expressLoader.getInstructionSet(varName); } if (result == null) { if (this.isExpandToParent && this.parent != null && this.parent instanceof InstructionSetContext) { result = ((InstructionSetContext)this.parent).getSymbol(varName); } else { result = OperateDataCacheManager.fetchOperateDataAttr(varName, null); this.addSymbol(varName, result); } } return result; } public ExpressLoader getExpressLoader() { return expressLoader; } public IExpressContext<String, Object> getParent() { return this.parent; } @Override public Object get(Object key) { if (this.content != null && this.content.containsKey(key)) { return this.content.get(key); } else if (this.isExpandToParent && this.parent != null) { return this.parent.get(key); } return null; } @Override public Object put(String key, Object value) { if (this.content != null && this.content.containsKey(key)) { return this.content.put(key, value); } else if (!this.isExpandToParent) { if (this.content == null) { this.content = new HashMap<>(); } return this.content.put(key, value); } else if (this.parent != null) { return this.parent.put(key, value); } else { throw new RuntimeException("没有定义局部变量:" + key + ",而且没有全局上下文"); } } }
isExpandToParent = true; parent = null; content = null; expressLoader = null; isSupportDynamicFieldName = false; runner = null; symbolTable.clear();
1,240
55
1,295
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/InstructionSetRunner.java
InstructionSetRunner
executeOuter
class InstructionSetRunner { private InstructionSetRunner() { throw new IllegalStateException("Utility class"); } public static Object executeOuter(ExpressRunner runner, InstructionSet instructionSet, ExpressLoader loader, IExpressContext<String, Object> iExpressContext, List<String> errorList, boolean isTrace, boolean isCatchException, boolean isSupportDynamicFieldName, long timeoutMills) throws Exception {<FILL_FUNCTION_BODY>} /** * 批量执行指令集合,指令集间可以共享 变量和函数 * * @param runner 解释器 * @param instructionSet 指令集 * @param loader 加载器 * @param iExpressContext 上下文 * @param errorList 错误列表 * @param isTrace 打印跟踪日志 * @param isCatchException 捕获异常 * @param isReturnLastData 返回最后一个数据 * @param isSupportDynamicFieldName 日支持动态字段名 * @param executeTimeOut 脚本运行的结束时限, -1 表示没有限制 * @return * @throws Exception */ public static Object execute(ExpressRunner runner, InstructionSet instructionSet, ExpressLoader loader, IExpressContext<String, Object> iExpressContext, List<String> errorList, boolean isTrace, boolean isCatchException, boolean isReturnLastData, boolean isSupportDynamicFieldName, ExecuteTimeout executeTimeOut) throws Exception { InstructionSetContext context = OperateDataCacheManager.fetchInstructionSetContext(true, runner, iExpressContext, loader, isSupportDynamicFieldName); return execute(instructionSet, context, errorList, isTrace, isCatchException, isReturnLastData, executeTimeOut); } public static Object execute(InstructionSet set, InstructionSetContext context, List<String> errorList, boolean isTrace, boolean isCatchException, boolean isReturnLastData, ExecuteTimeout executeTimeOut) throws Exception { RunEnvironment environment; Object result = null; environment = OperateDataCacheManager.fetRunEnvironment(set, context, isTrace, executeTimeOut); try { CallResult tempResult = set.execute(environment, context, errorList, isReturnLastData); if (tempResult.isExit()) { result = tempResult.getReturnValue(); } } catch (Exception e) { if (!isCatchException) { throw e; } } return result; } }
try { OperateDataCacheManager.push(runner); return execute(runner, instructionSet, loader, iExpressContext, errorList, isTrace, isCatchException, true, isSupportDynamicFieldName, timeoutMills != -1? // 优先使用参数传入 new ExecuteTimeout(timeoutMills): // 如果参数未传入, 则看一下是否有全局设置 QLExpressTimer.getTimeout() != -1? new ExecuteTimeout(QLExpressTimer.getTimeout()): ExecuteTimeout.NO_TIMEOUT); } finally { OperateDataCacheManager.resetCache(); }
642
168
810
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/OperateData.java
OperateData
toJavaCode
class OperateData { protected Object dataObject; protected Class<?> type; public OperateData(Object obj, Class<?> type) { this.type = type; this.dataObject = obj; } /** * 给对象缓存接口使用 * * @param obj * @param type */ public void initial(Object obj, Class<?> type) { this.type = type; this.dataObject = obj; } public void clear() { this.dataObject = null; this.type = null; } public Class<?> getDefineType() { throw new RuntimeException(this.getClass().getName() + "必须实现方法:getDefineType"); } public Class<?> getOriginalType() { return this.type; } public Class<?> getType(InstructionSetContext parent) throws Exception { if (type != null) { return type; } Object obj = this.getObject(parent); if (obj == null) { return null; } else { return obj.getClass(); } } public final Object getObject(InstructionSetContext context) throws Exception { if (this.type != null && this.type.equals(void.class)) { throw new QLException("void 不能参与任何操作运算,请检查使用在表达式中使用了没有返回值的函数,或者分支不完整的if语句"); } return getObjectInner(context); } public Object getObjectInner(InstructionSetContext context) throws Exception { return this.dataObject; } public void setObject(InstructionSetContext parent, Object object) throws Exception { throw new RuntimeException("必须在子类中实现此方法"); } public String toJavaCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { if (this.dataObject == null) { return this.type + ":null"; } else { if (this.dataObject instanceof Class) { return ExpressUtil.getClassName((Class<?>)this.dataObject); } else { return this.dataObject.toString(); } } } public void toResource(StringBuilder builder, int level) { if (this.dataObject != null) { builder.append(this.dataObject); } else { builder.append("null"); } } }
if (!this.getClass().equals(OperateData.class)) { throw new RuntimeException(this.getClass().getName() + "没有实现:toJavaCode()"); } String result = "new " + OperateData.class.getName() + "("; if (String.class.equals(this.type)) { result = result + "\"" + this.dataObject + "\""; } else if (this.type.isPrimitive()) { result = result + this.dataObject.getClass().getName() + ".valueOf(\"" + this.dataObject + "\")"; } else { result = result + "new " + this.dataObject.getClass().getName() + "(\"" + this.dataObject + "\")"; } result = result + "," + type.getName() + ".class"; result = result + ")"; return result;
655
221
876
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/Operator.java
Operator
compareData
class Operator extends OperatorBase { @Override public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception { Object[] parameters = new Object[list.length]; for (int i = 0; i < list.length; i++) { if (list.get(i) == null && QLExpressRunStrategy.isAvoidNullPointer()) { parameters[i] = null; } else { parameters[i] = list.get(i).getObject(parent); } } Object result = this.executeInner(parameters); if (result != null && result.getClass().equals(OperateData.class)) { throw new QLException("操作符号定义的返回类型错误:" + this.getAliasName()); } if (result == null) { //return new OperateData(null,null); return OperateDataCacheManager.fetchOperateData(null, null); } else { //return new OperateData(result,ExpressUtil.getSimpleDataType(result.getClass())); return OperateDataCacheManager.fetchOperateData(result, ExpressUtil.getSimpleDataType(result.getClass())); } } public abstract Object executeInner(Object[] list) throws Exception; /** * 进行对象是否相等的比较 * * @param op1 * @param op2 * @return */ public static boolean objectEquals(Object op1, Object op2) { if (op1 == null && op2 == null) { return true; } if (op1 == null || op2 == null) { return false; } //Character的值比较 if (op1 instanceof Character || op2 instanceof Character) { int compareResult; if (op1 instanceof Character && op2 instanceof Character) { return op1.equals(op2); } else if (op1 instanceof Number) { compareResult = OperatorOfNumber.compareNumber((Number)op1, (int)(Character)op2); return compareResult == 0; } else if (op2 instanceof Number) { compareResult = OperatorOfNumber.compareNumber((int)(Character)op1, (Number)op2); return compareResult == 0; } } //数值的值比较 if (op1 instanceof Number && op2 instanceof Number) { //数字比较 int compareResult = OperatorOfNumber.compareNumber((Number)op1, (Number)op2); return compareResult == 0; } //调用原始Object的比较 return op1.equals(op2); } /** * 进行对象比较 * * @param op1 * @param op2 * @return 0 等于 ,负数 小于 , 正数 大于 * @throws Exception */ public static int compareData(Object op1, Object op2) throws Exception {<FILL_FUNCTION_BODY>} }
if (op1 == op2) { return 0; } int compareResult; if (op1 instanceof String) { compareResult = ((String)op1).compareTo(op2.toString()); } else if (op2 instanceof String) { compareResult = op1.toString().compareTo((String)op2); } else if (op1 instanceof Character || op2 instanceof Character) { if (op1 instanceof Character && op2 instanceof Character) { compareResult = ((Character)op1).compareTo((Character)op2); } else if (op1 instanceof Number) { compareResult = OperatorOfNumber.compareNumber((Number)op1, (int)(Character)op2); } else if (op2 instanceof Number) { compareResult = OperatorOfNumber.compareNumber((int)(Character)op1, (Number)op2); } else { throw new QLException(op1 + "和" + op2 + "不能执行compare 操作"); } } else if (op1 instanceof Number && op2 instanceof Number) { //数字比较 compareResult = OperatorOfNumber.compareNumber((Number)op1, (Number)op2); } else if ((op1 instanceof Boolean) && (op2 instanceof Boolean)) { if (((Boolean)op1).booleanValue() == ((Boolean)op2).booleanValue()) { compareResult = 0; } else { compareResult = -1; } } else if ((op1 instanceof Date) && (op2 instanceof Date)) { compareResult = ((Date)op1).compareTo((Date)op2); } else { throw new QLException(op1 + "和" + op2 + "不能执行compare 操作"); } return compareResult;
759
439
1,198
<methods>public non-sealed void <init>() ,public com.ql.util.express.OperateData execute(com.ql.util.express.InstructionSetContext, com.ql.util.express.ArraySwap, List<java.lang.String>) throws java.lang.Exception,public abstract com.ql.util.express.OperateData executeInner(com.ql.util.express.InstructionSetContext, com.ql.util.express.ArraySwap) throws java.lang.Exception,public java.lang.String getAliasName() ,public java.lang.String getErrorInfo() ,public java.lang.String getName() ,public java.lang.String[] getOperateDataAnnotation() ,public java.lang.String[] getOperateDataDesc() ,public boolean isPrecise() ,public void setAliasName(java.lang.String) ,public void setErrorInfo(java.lang.String) ,public void setName(java.lang.String) ,public void setPrecise(boolean) ,public java.lang.Object[] toObjectList(com.ql.util.express.InstructionSetContext, com.ql.util.express.ArraySwap) throws java.lang.Exception,public java.lang.String toString() <variables>protected java.lang.String aliasName,protected java.lang.String errorInfo,protected boolean isPrecise,protected java.lang.String name,protected java.lang.String[] operateDataAnnotation,protected java.lang.String[] operateDataDesc
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/QLambda.java
QLambda
call
class QLambda { private final InstructionSet functionSet; private final RunEnvironment environment; private final List<String> errorList; public QLambda(InstructionSet functionSet, RunEnvironment environment, List<String> errorList) { this.functionSet = functionSet; this.environment = environment; this.errorList = errorList; } public Object call(Object... params) throws Exception {<FILL_FUNCTION_BODY>} /** * 为了用起来更像 java 的 lambda 表达式而增加额外的一些方法 */ public void run() throws Exception { call(); } /** * Consumer * BiConsumer */ public void accept(Object... params) throws Exception { call(params); } /** * Function * BiFunction */ public Object apply(Object... params) throws Exception { return call(params); } /** * Supplier */ public Object get() throws Exception { return call(); } }
InstructionSetContext context = OperateDataCacheManager.fetchInstructionSetContext( true, environment.getContext().getExpressRunner(), environment.getContext(), environment.getContext().getExpressLoader(), environment.getContext().isSupportDynamicFieldName()); OperateDataLocalVar[] vars = functionSet.getParameters(); for (int i = 0; i < vars.length; i++) { OperateDataLocalVar operateDataLocalVar = OperateDataCacheManager.fetchOperateDataLocalVar( vars[i].getName(), params.length <= i ? Object.class : params[i] == null ? Object.class : params[i].getClass()); context.addSymbol(operateDataLocalVar.getName(), operateDataLocalVar); operateDataLocalVar.setObject(context, params.length > i ? params[i] : null); } return InstructionSetRunner.execute(functionSet, context, errorList, environment.isTrace(), false, true, environment.getExecuteTimeOut());
274
251
525
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/QLambdaInvocationHandler.java
QLambdaInvocationHandler
invoke
class QLambdaInvocationHandler implements InvocationHandler { private final QLambda qLambda; public QLambdaInvocationHandler(QLambda qLambda) { this.qLambda = qLambda; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>} }
return Modifier.isAbstract(method.getModifiers()) ? qLambda.call(args) : // 为了应对 toString 方法 method.getReturnType() == String.class ? "QLambdaProxy" : null;
90
58
148
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/RunEnvironment.java
RunEnvironment
ensureCapacity
class RunEnvironment { private static final int INIT_DATA_LENGTH = 15; private boolean isTrace; private int point = -1; int programPoint = 0; private OperateData[] dataContainer; private final ArraySwap arraySwap = new ArraySwap(); private boolean isExit = false; private Object returnValue = null; private InstructionSet instructionSet; private InstructionSetContext context; /** * 脚本运行时间限制 */ private ExecuteTimeout executeTimeOut; public RunEnvironment(InstructionSet instructionSet, InstructionSetContext instructionSetContext, boolean isTrace, ExecuteTimeout executeTimeOut) { dataContainer = new OperateData[INIT_DATA_LENGTH]; this.instructionSet = instructionSet; this.context = instructionSetContext; this.isTrace = isTrace; this.executeTimeOut = executeTimeOut; } public void initial(InstructionSet instructionSet, InstructionSetContext instructionSetContext, boolean isTrace, ExecuteTimeout executeTimeOut) { this.instructionSet = instructionSet; this.context = instructionSetContext; this.isTrace = isTrace; this.executeTimeOut = executeTimeOut; } public void clear() { isTrace = false; point = -1; programPoint = 0; isExit = false; returnValue = null; instructionSet = null; context = null; executeTimeOut = null; } public InstructionSet getInstructionSet() { return instructionSet; } public InstructionSetContext getContext() { return this.context; } public void setContext(InstructionSetContext instructionSetContext) { this.context = instructionSetContext; } public boolean isExit() { return isExit; } public Object getReturnValue() { return returnValue; } public void setReturnValue(Object value) { this.returnValue = value; } public void quitExpress(Object returnValue) { this.isExit = true; this.returnValue = returnValue; } public void quitExpress() { this.isExit = true; this.returnValue = null; } public boolean isTrace() { return this.isTrace; } public int getProgramPoint() { return programPoint; } public void programPointAddOne() { programPoint++; } public void gotoLastWhenReturn() { programPoint = this.instructionSet.getInstructionLength(); } public int getDataStackSize() { return this.point + 1; } public void push(OperateData data) { this.point++; if (this.point >= this.dataContainer.length) { ensureCapacity(this.point + 1); } this.dataContainer[point] = data; } public OperateData peek() { if (point < 0) { throw new RuntimeException("系统异常,堆栈指针错误"); } return this.dataContainer[point]; } public OperateData pop() { if (point < 0) { throw new RuntimeException("系统异常,堆栈指针错误"); } OperateData result = this.dataContainer[point]; this.point--; return result; } public void clearDataStack() { this.point = -1; } public void gotoWithOffset(int offset) { this.programPoint = this.programPoint + offset; } /** * 此方法是调用最频繁的,因此尽量精简代码,提高效率 * * @param len * @return */ public ArraySwap popArray(int len) { int start = point - len + 1; this.arraySwap.swap(this.dataContainer, start, len); point = point - len; return this.arraySwap; } public void ensureCapacity(int minCapacity) {<FILL_FUNCTION_BODY>} public boolean isExecuteTimeout() { return executeTimeOut != null && executeTimeOut.isExpired(); } public ExecuteTimeout getExecuteTimeOut() { return executeTimeOut; } }
int oldCapacity = this.dataContainer.length; if (minCapacity > oldCapacity) { int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) { newCapacity = minCapacity; } OperateData[] tempList = new OperateData[newCapacity]; System.arraycopy(this.dataContainer, 0, tempList, 0, oldCapacity); this.dataContainer = tempList; }
1,132
133
1,265
<no_super_class>
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/instruction/BlockInstructionFactory.java
BlockInstructionFactory
createInstruction
class BlockInstructionFactory extends InstructionFactory { @Override public boolean createInstruction(ExpressRunner expressRunner, InstructionSet result, Stack<ForRelBreakContinue> forStack, ExpressNode node, boolean isRoot) throws Exception {<FILL_FUNCTION_BODY>} }
if (node.isTypeEqualsOrChild("STAT_SEMICOLON") && result.getCurrentPoint() >= 0 && !(result.getInstruction( result.getCurrentPoint()) instanceof InstructionClearDataStack)) { result.addInstruction(new InstructionClearDataStack().setLine(node.getLine())); } boolean needOpenNewArea = !isRoot && "STAT_BLOCK".equals(node.getNodeType().getName()); if (needOpenNewArea) { result.addInstruction(new InstructionOpenNewArea().setLine(node.getLine())); } boolean returnVal; boolean hasDef = false; for (ExpressNode tmpNode : node.getChildrenArray()) { boolean tmpHas = expressRunner.createInstructionSetPrivate(result, forStack, tmpNode, false); hasDef = hasDef || tmpHas; } if (needOpenNewArea) { result.addInstruction(new InstructionCloseNewArea().setLine(node.getLine())); returnVal = false; } else { returnVal = hasDef; } return returnVal;
72
280
352
<methods>public non-sealed void <init>() ,public abstract boolean createInstruction(com.ql.util.express.ExpressRunner, com.ql.util.express.InstructionSet, Stack<com.ql.util.express.instruction.ForRelBreakContinue>, com.ql.util.express.parse.ExpressNode, boolean) throws java.lang.Exception,public static com.ql.util.express.instruction.InstructionFactory getInstructionFactory(java.lang.String) <variables>private static final Map<java.lang.String,com.ql.util.express.instruction.InstructionFactory> INSTRUCTION_FACTORY_MAP
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/instruction/BreakInstructionFactory.java
BreakInstructionFactory
createInstruction
class BreakInstructionFactory extends InstructionFactory { @Override public boolean createInstruction(ExpressRunner expressRunner, InstructionSet result, Stack<ForRelBreakContinue> forStack, ExpressNode node, boolean isRoot) {<FILL_FUNCTION_BODY>} }
InstructionGoTo breakInstruction = new InstructionGoTo(result.getCurrentPoint() + 1); breakInstruction.setName("break"); forStack.peek().breakList.add(breakInstruction); result.addInstruction(breakInstruction.setLine(node.getLine())); return false;
70
81
151
<methods>public non-sealed void <init>() ,public abstract boolean createInstruction(com.ql.util.express.ExpressRunner, com.ql.util.express.InstructionSet, Stack<com.ql.util.express.instruction.ForRelBreakContinue>, com.ql.util.express.parse.ExpressNode, boolean) throws java.lang.Exception,public static com.ql.util.express.instruction.InstructionFactory getInstructionFactory(java.lang.String) <variables>private static final Map<java.lang.String,com.ql.util.express.instruction.InstructionFactory> INSTRUCTION_FACTORY_MAP
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/instruction/CallFunctionInstructionFactory.java
CallFunctionInstructionFactory
createInstruction
class CallFunctionInstructionFactory extends InstructionFactory { @Override public boolean createInstruction(ExpressRunner expressRunner, InstructionSet result, Stack<ForRelBreakContinue> forStack, ExpressNode node, boolean isRoot) throws Exception {<FILL_FUNCTION_BODY>} }
ExpressNode[] children = node.getChildrenArray(); String functionName = children[0].getValue(); boolean returnVal = false; children = node.getChildrenArray(); for (int i = 1; i < children.length; i++) { boolean tmpHas = expressRunner.createInstructionSetPrivate(result, forStack, children[i], false); returnVal = returnVal || tmpHas; } OperatorBase op = expressRunner.getOperatorFactory().getOperator(functionName); int opNum = children.length - 1; if (op != null) { result.addInstruction(new InstructionOperator(op, opNum).setLine(node.getLine())); } else { result.addInstruction( new InstructionCallSelfDefineFunction(functionName, opNum).setLine(children[0].getLine())); } return returnVal;
73
224
297
<methods>public non-sealed void <init>() ,public abstract boolean createInstruction(com.ql.util.express.ExpressRunner, com.ql.util.express.InstructionSet, Stack<com.ql.util.express.instruction.ForRelBreakContinue>, com.ql.util.express.parse.ExpressNode, boolean) throws java.lang.Exception,public static com.ql.util.express.instruction.InstructionFactory getInstructionFactory(java.lang.String) <variables>private static final Map<java.lang.String,com.ql.util.express.instruction.InstructionFactory> INSTRUCTION_FACTORY_MAP
alibaba_QLExpress
QLExpress/src/main/java/com/ql/util/express/instruction/CastInstructionFactory.java
CastInstructionFactory
createInstruction
class CastInstructionFactory extends InstructionFactory { @Override public boolean createInstruction(ExpressRunner expressRunner, InstructionSet result, Stack<ForRelBreakContinue> forStack, ExpressNode node, boolean isRoot) throws Exception {<FILL_FUNCTION_BODY>} }
boolean returnVal = false; OperatorBase op = expressRunner.getOperatorFactory().newInstance(node); ExpressNode[] children = node.getChildrenArray(); if (children.length == 0) { throw new QLException("扩展类型不存在"); } else if (children.length > 2) { throw new QLException("扩展操作只能有一个类型为Class的操作数"); } else if (!children[0].getNodeType().isEqualsOrChild("CONST_CLASS")) { throw new QLException("扩展操作只能有一个类型为Class的操作数,当前的数据类型是:" + children[0].getNodeType().getName()); } for (ExpressNode child : children) { boolean tmpHas = expressRunner.createInstructionSetPrivate(result, forStack, child, false); returnVal = returnVal || tmpHas; } result.addInstruction(new InstructionOperator(op, children.length).setLine(node.getLine())); return returnVal;
72
252
324
<methods>public non-sealed void <init>() ,public abstract boolean createInstruction(com.ql.util.express.ExpressRunner, com.ql.util.express.InstructionSet, Stack<com.ql.util.express.instruction.ForRelBreakContinue>, com.ql.util.express.parse.ExpressNode, boolean) throws java.lang.Exception,public static com.ql.util.express.instruction.InstructionFactory getInstructionFactory(java.lang.String) <variables>private static final Map<java.lang.String,com.ql.util.express.instruction.InstructionFactory> INSTRUCTION_FACTORY_MAP