repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/ProtocolCommandSupport.java | client/src/main/java/org/apache/commons/net/ProtocolCommandSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.io.Serializable;
import java.util.EventListener;
import org.apache.commons.net.util.ListenerList;
/***
* ProtocolCommandSupport is a convenience class for managing a list of
* ProtocolCommandListeners and firing ProtocolCommandEvents. You can
* simply delegate ProtocolCommandEvent firing and listener
* registering/unregistering tasks to this class.
*
*
* @see ProtocolCommandEvent
* @see ProtocolCommandListener
***/
public class ProtocolCommandSupport implements Serializable
{
private static final long serialVersionUID = -8017692739988399978L;
private final Object __source;
private final ListenerList __listeners;
/***
* Creates a ProtocolCommandSupport instance using the indicated source
* as the source of ProtocolCommandEvents.
*
* @param source The source to use for all generated ProtocolCommandEvents.
***/
public ProtocolCommandSupport(Object source)
{
__listeners = new ListenerList();
__source = source;
}
/***
* Fires a ProtocolCommandEvent signalling the sending of a command to all
* registered listeners, invoking their
* {@link org.apache.commons.net.ProtocolCommandListener#protocolCommandSent protocolCommandSent() }
* methods.
*
* @param command The string representation of the command type sent, not
* including the arguments (e.g., "STAT" or "GET").
* @param message The entire command string verbatim as sent to the server,
* including all arguments.
***/
public void fireCommandSent(String command, String message)
{
ProtocolCommandEvent event;
event = new ProtocolCommandEvent(__source, command, message);
for (EventListener listener : __listeners)
{
((ProtocolCommandListener)listener).protocolCommandSent(event);
}
}
/***
* Fires a ProtocolCommandEvent signalling the reception of a command reply
* to all registered listeners, invoking their
* {@link org.apache.commons.net.ProtocolCommandListener#protocolReplyReceived protocolReplyReceived() }
* methods.
*
* @param replyCode The integer code indicating the natureof the reply.
* This will be the protocol integer value for protocols
* that use integer reply codes, or the reply class constant
* corresponding to the reply for protocols like POP3 that use
* strings like OK rather than integer codes (i.e., POP3Repy.OK).
* @param message The entire reply as received from the server.
***/
public void fireReplyReceived(int replyCode, String message)
{
ProtocolCommandEvent event;
event = new ProtocolCommandEvent(__source, replyCode, message);
for (EventListener listener : __listeners)
{
((ProtocolCommandListener)listener).protocolReplyReceived(event);
}
}
/***
* Adds a ProtocolCommandListener.
*
* @param listener The ProtocolCommandListener to add.
***/
public void addProtocolCommandListener(ProtocolCommandListener listener)
{
__listeners.addListener(listener);
}
/***
* Removes a ProtocolCommandListener.
*
* @param listener The ProtocolCommandListener to remove.
***/
public void removeProtocolCommandListener(ProtocolCommandListener listener)
{
__listeners.removeListener(listener);
}
/***
* Returns the number of ProtocolCommandListeners currently registered.
*
* @return The number of ProtocolCommandListeners currently registered.
***/
public int getListenerCount()
{
return __listeners.getListenerCount();
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/ProtocolCommandEvent.java | client/src/main/java/org/apache/commons/net/ProtocolCommandEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.util.EventObject;
/***
* There exists a large class of IETF protocols that work by sending an
* ASCII text command and arguments to a server, and then receiving an
* ASCII text reply. For debugging and other purposes, it is extremely
* useful to log or keep track of the contents of the protocol messages.
* The ProtocolCommandEvent class coupled with the
* {@link org.apache.commons.net.ProtocolCommandListener}
* interface facilitate this process.
*
*
* @see ProtocolCommandListener
* @see ProtocolCommandSupport
***/
public class ProtocolCommandEvent extends EventObject
{
private static final long serialVersionUID = 403743538418947240L;
private final int __replyCode;
private final boolean __isCommand;
private final String __message, __command;
/***
* Creates a ProtocolCommandEvent signalling a command was sent to
* the server. ProtocolCommandEvents created with this constructor
* should only be sent after a command has been sent, but before the
* reply has been received.
*
* @param source The source of the event.
* @param command The string representation of the command type sent, not
* including the arguments (e.g., "STAT" or "GET").
* @param message The entire command string verbatim as sent to the server,
* including all arguments.
***/
public ProtocolCommandEvent(Object source, String command, String message)
{
super(source);
__replyCode = 0;
__message = message;
__isCommand = true;
__command = command;
}
/***
* Creates a ProtocolCommandEvent signalling a reply to a command was
* received. ProtocolCommandEvents created with this constructor
* should only be sent after a complete command reply has been received
* fromt a server.
*
* @param source The source of the event.
* @param replyCode The integer code indicating the natureof the reply.
* This will be the protocol integer value for protocols
* that use integer reply codes, or the reply class constant
* corresponding to the reply for protocols like POP3 that use
* strings like OK rather than integer codes (i.e., POP3Repy.OK).
* @param message The entire reply as received from the server.
***/
public ProtocolCommandEvent(Object source, int replyCode, String message)
{
super(source);
__replyCode = replyCode;
__message = message;
__isCommand = false;
__command = null;
}
/***
* Returns the string representation of the command type sent (e.g., "STAT"
* or "GET"). If the ProtocolCommandEvent is a reply event, then null
* is returned.
*
* @return The string representation of the command type sent, or null
* if this is a reply event.
***/
public String getCommand()
{
return __command;
}
/***
* Returns the reply code of the received server reply. Undefined if
* this is not a reply event.
*
* @return The reply code of the received server reply. Undefined if
* not a reply event.
***/
public int getReplyCode()
{
return __replyCode;
}
/***
* Returns true if the ProtocolCommandEvent was generated as a result
* of sending a command.
*
* @return true If the ProtocolCommandEvent was generated as a result
* of sending a command. False otherwise.
***/
public boolean isCommand()
{
return __isCommand;
}
/***
* Returns true if the ProtocolCommandEvent was generated as a result
* of receiving a reply.
*
* @return true If the ProtocolCommandEvent was generated as a result
* of receiving a reply. False otherwise.
***/
public boolean isReply()
{
return !isCommand();
}
/***
* Returns the entire message sent to or received from the server.
* Includes the line terminator.
*
* @return The entire message sent to or received from the server.
***/
public String getMessage()
{
return __message;
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/DatagramSocketClient.java | client/src/main/java/org/apache/commons/net/DatagramSocketClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.Charset;
/***
* The DatagramSocketClient provides the basic operations that are required
* of client objects accessing datagram sockets. It is meant to be
* subclassed to avoid having to rewrite the same code over and over again
* to open a socket, close a socket, set timeouts, etc. Of special note
* is the {@link #setDatagramSocketFactory setDatagramSocketFactory }
* method, which allows you to control the type of DatagramSocket the
* DatagramSocketClient creates for network communications. This is
* especially useful for adding things like proxy support as well as better
* support for applets. For
* example, you could create a
* {@link org.apache.commons.net.DatagramSocketFactory}
* that
* requests browser security capabilities before creating a socket.
* All classes derived from DatagramSocketClient should use the
* {@link #_socketFactory_ _socketFactory_ } member variable to
* create DatagramSocket instances rather than instantiating
* them by directly invoking a constructor. By honoring this contract
* you guarantee that a user will always be able to provide his own
* Socket implementations by substituting his own SocketFactory.
*
*
* @see DatagramSocketFactory
***/
public abstract class DatagramSocketClient
{
/***
* The default DatagramSocketFactory shared by all DatagramSocketClient
* instances.
***/
private static final DatagramSocketFactory __DEFAULT_SOCKET_FACTORY =
new DefaultDatagramSocketFactory();
/**
* Charset to use for byte IO.
*/
private Charset charset = Charset.defaultCharset();
/*** The timeout to use after opening a socket. ***/
protected int _timeout_;
/*** The datagram socket used for the connection. ***/
protected DatagramSocket _socket_;
/***
* A status variable indicating if the client's socket is currently open.
***/
protected boolean _isOpen_;
/*** The datagram socket's DatagramSocketFactory. ***/
protected DatagramSocketFactory _socketFactory_;
/***
* Default constructor for DatagramSocketClient. Initializes
* _socket_ to null, _timeout_ to 0, and _isOpen_ to false.
***/
public DatagramSocketClient()
{
_socket_ = null;
_timeout_ = 0;
_isOpen_ = false;
_socketFactory_ = __DEFAULT_SOCKET_FACTORY;
}
/***
* Opens a DatagramSocket on the local host at the first available port.
* Also sets the timeout on the socket to the default timeout set
* by {@link #setDefaultTimeout setDefaultTimeout() }.
* <p>
* _isOpen_ is set to true after calling this method and _socket_
* is set to the newly opened socket.
*
* @exception SocketException If the socket could not be opened or the
* timeout could not be set.
***/
public void open() throws SocketException
{
_socket_ = _socketFactory_.createDatagramSocket();
_socket_.setSoTimeout(_timeout_);
_isOpen_ = true;
}
/***
* Opens a DatagramSocket on the local host at a specified port.
* Also sets the timeout on the socket to the default timeout set
* by {@link #setDefaultTimeout setDefaultTimeout() }.
* <p>
* _isOpen_ is set to true after calling this method and _socket_
* is set to the newly opened socket.
*
* @param port The port to use for the socket.
* @exception SocketException If the socket could not be opened or the
* timeout could not be set.
***/
public void open(int port) throws SocketException
{
_socket_ = _socketFactory_.createDatagramSocket(port);
_socket_.setSoTimeout(_timeout_);
_isOpen_ = true;
}
/***
* Opens a DatagramSocket at the specified address on the local host
* at a specified port.
* Also sets the timeout on the socket to the default timeout set
* by {@link #setDefaultTimeout setDefaultTimeout() }.
* <p>
* _isOpen_ is set to true after calling this method and _socket_
* is set to the newly opened socket.
*
* @param port The port to use for the socket.
* @param laddr The local address to use.
* @exception SocketException If the socket could not be opened or the
* timeout could not be set.
***/
public void open(int port, InetAddress laddr) throws SocketException
{
_socket_ = _socketFactory_.createDatagramSocket(port, laddr);
_socket_.setSoTimeout(_timeout_);
_isOpen_ = true;
}
/***
* Closes the DatagramSocket used for the connection.
* You should call this method after you've finished using the class
* instance and also before you call {@link #open open() }
* again. _isOpen_ is set to false and _socket_ is set to null.
* If you call this method when the client socket is not open,
* a NullPointerException is thrown.
***/
public void close()
{
if (_socket_ != null) {
_socket_.close();
}
_socket_ = null;
_isOpen_ = false;
}
/***
* Returns true if the client has a currently open socket.
*
* @return True if the client has a curerntly open socket, false otherwise.
***/
public boolean isOpen()
{
return _isOpen_;
}
/***
* Set the default timeout in milliseconds to use when opening a socket.
* After a call to open, the timeout for the socket is set using this value.
* This method should be used prior to a call to {@link #open open()}
* and should not be confused with {@link #setSoTimeout setSoTimeout()}
* which operates on the currently open socket. _timeout_ contains
* the new timeout value.
*
* @param timeout The timeout in milliseconds to use for the datagram socket
* connection.
***/
public void setDefaultTimeout(int timeout)
{
_timeout_ = timeout;
}
/***
* Returns the default timeout in milliseconds that is used when
* opening a socket.
*
* @return The default timeout in milliseconds that is used when
* opening a socket.
***/
public int getDefaultTimeout()
{
return _timeout_;
}
/***
* Set the timeout in milliseconds of a currently open connection.
* Only call this method after a connection has been opened
* by {@link #open open()}.
*
* @param timeout The timeout in milliseconds to use for the currently
* open datagram socket connection.
* @throws SocketException if an error setting the timeout
***/
public void setSoTimeout(int timeout) throws SocketException
{
_socket_.setSoTimeout(timeout);
}
/***
* Returns the timeout in milliseconds of the currently opened socket.
* If you call this method when the client socket is not open,
* a NullPointerException is thrown.
*
* @return The timeout in milliseconds of the currently opened socket.
* @throws SocketException if an error getting the timeout
***/
public int getSoTimeout() throws SocketException
{
return _socket_.getSoTimeout();
}
/***
* Returns the port number of the open socket on the local host used
* for the connection. If you call this method when the client socket
* is not open, a NullPointerException is thrown.
*
* @return The port number of the open socket on the local host used
* for the connection.
***/
public int getLocalPort()
{
return _socket_.getLocalPort();
}
/***
* Returns the local address to which the client's socket is bound.
* If you call this method when the client socket is not open, a
* NullPointerException is thrown.
*
* @return The local address to which the client's socket is bound.
***/
public InetAddress getLocalAddress()
{
return _socket_.getLocalAddress();
}
/***
* Sets the DatagramSocketFactory used by the DatagramSocketClient
* to open DatagramSockets. If the factory value is null, then a default
* factory is used (only do this to reset the factory after having
* previously altered it).
*
* @param factory The new DatagramSocketFactory the DatagramSocketClient
* should use.
***/
public void setDatagramSocketFactory(DatagramSocketFactory factory)
{
if (factory == null) {
_socketFactory_ = __DEFAULT_SOCKET_FACTORY;
} else {
_socketFactory_ = factory;
}
}
/**
* Gets the charset name.
*
* @return the charset name.
* @since 3.3
* TODO Will be deprecated once the code requires Java 1.6 as a mininmum
*/
public String getCharsetName() {
return charset.name();
}
/**
* Gets the charset.
*
* @return the charset.
* @since 3.3
*/
public Charset getCharset() {
return charset;
}
/**
* Sets the charset.
*
* @param charset the charset.
* @since 3.3
*/
public void setCharset(Charset charset) {
this.charset = charset;
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/DefaultSocketFactory.java | client/src/main/java/org/apache/commons/net/DefaultSocketFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.SocketFactory;
/***
* DefaultSocketFactory implements the SocketFactory interface by
* simply wrapping the java.net.Socket and java.net.ServerSocket
* constructors. It is the default SocketFactory used by
* {@link org.apache.commons.net.SocketClient}
* implementations.
*
*
* @see SocketFactory
* @see SocketClient
* @see SocketClient#setSocketFactory
***/
public class DefaultSocketFactory extends SocketFactory
{
/** The proxy to use when creating new sockets. */
private final Proxy connProxy;
/**
* The default constructor.
*/
public DefaultSocketFactory()
{
this(null);
}
/**
* A constructor for sockets with proxy support.
*
* @param proxy The Proxy to use when creating new Sockets.
* @since 3.2
*/
public DefaultSocketFactory(Proxy proxy)
{
connProxy = proxy;
}
/**
* Creates an unconnected Socket.
*
* @return A new unconnected Socket.
* @exception IOException If an I/O error occurs while creating the Socket.
* @since 3.2
*/
@Override
public Socket createSocket() throws IOException
{
if (connProxy != null)
{
return new Socket(connProxy);
}
return new Socket();
}
/***
* Creates a Socket connected to the given host and port.
*
* @param host The hostname to connect to.
* @param port The port to connect to.
* @return A Socket connected to the given host and port.
* @exception UnknownHostException If the hostname cannot be resolved.
* @exception IOException If an I/O error occurs while creating the Socket.
***/
@Override
public Socket createSocket(String host, int port)
throws UnknownHostException, IOException
{
if (connProxy != null)
{
Socket s = new Socket(connProxy);
s.connect(new InetSocketAddress(host, port));
return s;
}
return new Socket(host, port);
}
/***
* Creates a Socket connected to the given host and port.
*
* @param address The address of the host to connect to.
* @param port The port to connect to.
* @return A Socket connected to the given host and port.
* @exception IOException If an I/O error occurs while creating the Socket.
***/
@Override
public Socket createSocket(InetAddress address, int port)
throws IOException
{
if (connProxy != null)
{
Socket s = new Socket(connProxy);
s.connect(new InetSocketAddress(address, port));
return s;
}
return new Socket(address, port);
}
/***
* Creates a Socket connected to the given host and port and
* originating from the specified local address and port.
*
* @param host The hostname to connect to.
* @param port The port to connect to.
* @param localAddr The local address to use.
* @param localPort The local port to use.
* @return A Socket connected to the given host and port.
* @exception UnknownHostException If the hostname cannot be resolved.
* @exception IOException If an I/O error occurs while creating the Socket.
***/
@Override
public Socket createSocket(String host, int port,
InetAddress localAddr, int localPort)
throws UnknownHostException, IOException
{
if (connProxy != null)
{
Socket s = new Socket(connProxy);
s.bind(new InetSocketAddress(localAddr, localPort));
s.connect(new InetSocketAddress(host, port));
return s;
}
return new Socket(host, port, localAddr, localPort);
}
/***
* Creates a Socket connected to the given host and port and
* originating from the specified local address and port.
*
* @param address The address of the host to connect to.
* @param port The port to connect to.
* @param localAddr The local address to use.
* @param localPort The local port to use.
* @return A Socket connected to the given host and port.
* @exception IOException If an I/O error occurs while creating the Socket.
***/
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddr, int localPort)
throws IOException
{
if (connProxy != null)
{
Socket s = new Socket(connProxy);
s.bind(new InetSocketAddress(localAddr, localPort));
s.connect(new InetSocketAddress(address, port));
return s;
}
return new Socket(address, port, localAddr, localPort);
}
/***
* Creates a ServerSocket bound to a specified port. A port
* of 0 will create the ServerSocket on a system-determined free port.
*
* @param port The port on which to listen, or 0 to use any free port.
* @return A ServerSocket that will listen on a specified port.
* @exception IOException If an I/O error occurs while creating
* the ServerSocket.
***/
public ServerSocket createServerSocket(int port) throws IOException
{
return new ServerSocket(port);
}
/***
* Creates a ServerSocket bound to a specified port with a given
* maximum queue length for incoming connections. A port of 0 will
* create the ServerSocket on a system-determined free port.
*
* @param port The port on which to listen, or 0 to use any free port.
* @param backlog The maximum length of the queue for incoming connections.
* @return A ServerSocket that will listen on a specified port.
* @exception IOException If an I/O error occurs while creating
* the ServerSocket.
***/
public ServerSocket createServerSocket(int port, int backlog)
throws IOException
{
return new ServerSocket(port, backlog);
}
/***
* Creates a ServerSocket bound to a specified port on a given local
* address with a given maximum queue length for incoming connections.
* A port of 0 will
* create the ServerSocket on a system-determined free port.
*
* @param port The port on which to listen, or 0 to use any free port.
* @param backlog The maximum length of the queue for incoming connections.
* @param bindAddr The local address to which the ServerSocket should bind.
* @return A ServerSocket that will listen on a specified port.
* @exception IOException If an I/O error occurs while creating
* the ServerSocket.
***/
public ServerSocket createServerSocket(int port, int backlog,
InetAddress bindAddr)
throws IOException
{
return new ServerSocket(port, backlog, bindAddr);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/ProtocolCommandListener.java | client/src/main/java/org/apache/commons/net/ProtocolCommandListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.util.EventListener;
/***
* There exists a large class of IETF protocols that work by sending an
* ASCII text command and arguments to a server, and then receiving an
* ASCII text reply. For debugging and other purposes, it is extremely
* useful to log or keep track of the contents of the protocol messages.
* The ProtocolCommandListener interface coupled with the
* {@link ProtocolCommandEvent} class facilitate this process.
* <p>
* To receive ProtocolCommandEvents, you merely implement the
* ProtocolCommandListener interface and register the class as a listener
* with a ProtocolCommandEvent source such as
* {@link org.apache.commons.net.ftp.FTPClient}.
*
*
* @see ProtocolCommandEvent
* @see ProtocolCommandSupport
***/
public interface ProtocolCommandListener extends EventListener
{
/***
* This method is invoked by a ProtocolCommandEvent source after
* sending a protocol command to a server.
*
* @param event The ProtocolCommandEvent fired.
***/
public void protocolCommandSent(ProtocolCommandEvent event);
/***
* This method is invoked by a ProtocolCommandEvent source after
* receiving a reply from a server.
*
* @param event The ProtocolCommandEvent fired.
***/
public void protocolReplyReceived(ProtocolCommandEvent event);
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/DatagramSocketFactory.java | client/src/main/java/org/apache/commons/net/DatagramSocketFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/***
* The DatagramSocketFactory interface provides a means for the
* programmer to control the creation of datagram sockets and
* provide his own DatagramSocket implementations for use by all
* classes derived from
* {@link org.apache.commons.net.DatagramSocketClient}
* .
* This allows you to provide your own DatagramSocket implementations and
* to perform security checks or browser capability requests before
* creating a DatagramSocket.
*
*
***/
public interface DatagramSocketFactory
{
/***
* Creates a DatagramSocket on the local host at the first available port.
* @return the socket
*
* @exception SocketException If the socket could not be created.
***/
public DatagramSocket createDatagramSocket() throws SocketException;
/***
* Creates a DatagramSocket on the local host at a specified port.
*
* @param port The port to use for the socket.
* @return the socket
* @exception SocketException If the socket could not be created.
***/
public DatagramSocket createDatagramSocket(int port) throws SocketException;
/***
* Creates a DatagramSocket at the specified address on the local host
* at a specified port.
*
* @param port The port to use for the socket.
* @param laddr The local address to use.
* @return the socket
* @exception SocketException If the socket could not be created.
***/
public DatagramSocket createDatagramSocket(int port, InetAddress laddr)
throws SocketException;
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/PrintCommandListener.java | client/src/main/java/org/apache/commons/net/PrintCommandListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.io.PrintStream;
import java.io.PrintWriter;
/***
* This is a support class for some of the example programs. It is
* a sample implementation of the ProtocolCommandListener interface
* which just prints out to a specified stream all command/reply traffic.
*
* @since 2.0
***/
public class PrintCommandListener implements ProtocolCommandListener
{
private final PrintWriter __writer;
private final boolean __nologin;
private final char __eolMarker;
private final boolean __directionMarker;
/**
* Create the default instance which prints everything.
*
* @param stream where to write the commands and responses
* e.g. System.out
* @since 3.0
*/
public PrintCommandListener(PrintStream stream)
{
this(new PrintWriter(stream));
}
/**
* Create an instance which optionally suppresses login command text
* and indicates where the EOL starts with the specified character.
*
* @param stream where to write the commands and responses
* @param suppressLogin if {@code true}, only print command name for login
*
* @since 3.0
*/
public PrintCommandListener(PrintStream stream, boolean suppressLogin) {
this(new PrintWriter(stream), suppressLogin);
}
/**
* Create an instance which optionally suppresses login command text
* and indicates where the EOL starts with the specified character.
*
* @param stream where to write the commands and responses
* @param suppressLogin if {@code true}, only print command name for login
* @param eolMarker if non-zero, add a marker just before the EOL.
*
* @since 3.0
*/
public PrintCommandListener(PrintStream stream, boolean suppressLogin, char eolMarker) {
this(new PrintWriter(stream), suppressLogin, eolMarker);
}
/**
* Create an instance which optionally suppresses login command text
* and indicates where the EOL starts with the specified character.
*
* @param stream where to write the commands and responses
* @param suppressLogin if {@code true}, only print command name for login
* @param eolMarker if non-zero, add a marker just before the EOL.
* @param showDirection if {@code true}, add {@code "> "} or {@code "< "} as appropriate to the output
*
* @since 3.0
*/
public PrintCommandListener(PrintStream stream, boolean suppressLogin, char eolMarker, boolean showDirection) {
this(new PrintWriter(stream), suppressLogin, eolMarker, showDirection);
}
/**
* Create the default instance which prints everything.
*
* @param writer where to write the commands and responses
*/
public PrintCommandListener(PrintWriter writer)
{
this(writer, false);
}
/**
* Create an instance which optionally suppresses login command text.
*
* @param writer where to write the commands and responses
* @param suppressLogin if {@code true}, only print command name for login
*
* @since 3.0
*/
public PrintCommandListener(PrintWriter writer, boolean suppressLogin)
{
this(writer, suppressLogin, (char) 0);
}
/**
* Create an instance which optionally suppresses login command text
* and indicates where the EOL starts with the specified character.
*
* @param writer where to write the commands and responses
* @param suppressLogin if {@code true}, only print command name for login
* @param eolMarker if non-zero, add a marker just before the EOL.
*
* @since 3.0
*/
public PrintCommandListener(PrintWriter writer, boolean suppressLogin, char eolMarker)
{
this(writer, suppressLogin, eolMarker, false);
}
/**
* Create an instance which optionally suppresses login command text
* and indicates where the EOL starts with the specified character.
*
* @param writer where to write the commands and responses
* @param suppressLogin if {@code true}, only print command name for login
* @param eolMarker if non-zero, add a marker just before the EOL.
* @param showDirection if {@code true}, add {@code ">} " or {@code "< "} as appropriate to the output
*
* @since 3.0
*/
public PrintCommandListener(PrintWriter writer, boolean suppressLogin, char eolMarker, boolean showDirection)
{
__writer = writer;
__nologin = suppressLogin;
__eolMarker = eolMarker;
__directionMarker = showDirection;
}
@Override
public void protocolCommandSent(ProtocolCommandEvent event)
{
if (__directionMarker) {
__writer.print("> ");
}
if (__nologin) {
String cmd = event.getCommand();
if ("PASS".equalsIgnoreCase(cmd) || "USER".equalsIgnoreCase(cmd)) {
__writer.print(cmd);
__writer.println(" *******"); // Don't bother with EOL marker for this!
} else {
final String IMAP_LOGIN = "LOGIN";
if (IMAP_LOGIN.equalsIgnoreCase(cmd)) { // IMAP
String msg = event.getMessage();
msg=msg.substring(0, msg.indexOf(IMAP_LOGIN)+IMAP_LOGIN.length());
__writer.print(msg);
__writer.println(" *******"); // Don't bother with EOL marker for this!
} else {
__writer.print(getPrintableString(event.getMessage()));
}
}
} else {
__writer.print(getPrintableString(event.getMessage()));
}
__writer.flush();
}
private String getPrintableString(String msg){
if (__eolMarker == 0) {
return msg;
}
int pos = msg.indexOf(SocketClient.NETASCII_EOL);
if (pos > 0) {
return msg.substring(0, pos) +
__eolMarker +
msg.substring(pos);
}
return msg;
}
@Override
public void protocolReplyReceived(ProtocolCommandEvent event)
{
if (__directionMarker) {
__writer.print("< ");
}
__writer.print(event.getMessage());
__writer.flush();
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/DefaultDatagramSocketFactory.java | client/src/main/java/org/apache/commons/net/DefaultDatagramSocketFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/***
* DefaultDatagramSocketFactory implements the DatagramSocketFactory
* interface by simply wrapping the java.net.DatagramSocket
* constructors. It is the default DatagramSocketFactory used by
* {@link org.apache.commons.net.DatagramSocketClient}
* implementations.
*
*
* @see DatagramSocketFactory
* @see DatagramSocketClient
* @see DatagramSocketClient#setDatagramSocketFactory
***/
public class DefaultDatagramSocketFactory implements DatagramSocketFactory
{
/***
* Creates a DatagramSocket on the local host at the first available port.
* @return a new DatagramSocket
* @exception SocketException If the socket could not be created.
***/
@Override
public DatagramSocket createDatagramSocket() throws SocketException
{
return new DatagramSocket();
}
/***
* Creates a DatagramSocket on the local host at a specified port.
*
* @param port The port to use for the socket.
* @return a new DatagramSocket
* @exception SocketException If the socket could not be created.
***/
@Override
public DatagramSocket createDatagramSocket(int port) throws SocketException
{
return new DatagramSocket(port);
}
/***
* Creates a DatagramSocket at the specified address on the local host
* at a specified port.
*
* @param port The port to use for the socket.
* @param laddr The local address to use.
* @return a new DatagramSocket
* @exception SocketException If the socket could not be created.
***/
@Override
public DatagramSocket createDatagramSocket(int port, InetAddress laddr)
throws SocketException
{
return new DatagramSocket(port, laddr);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/SocketClient.java | client/src/main/java/org/apache/commons/net/SocketClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.Charset;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
/**
* The SocketClient provides the basic operations that are required of
* client objects accessing sockets. It is meant to be
* subclassed to avoid having to rewrite the same code over and over again
* to open a socket, close a socket, set timeouts, etc. Of special note
* is the {@link #setSocketFactory setSocketFactory }
* method, which allows you to control the type of Socket the SocketClient
* creates for initiating network connections. This is especially useful
* for adding SSL or proxy support as well as better support for applets. For
* example, you could create a
* {@link javax.net.SocketFactory} that
* requests browser security capabilities before creating a socket.
* All classes derived from SocketClient should use the
* {@link #_socketFactory_ _socketFactory_ } member variable to
* create Socket and ServerSocket instances rather than instantiating
* them by directly invoking a constructor. By honoring this contract
* you guarantee that a user will always be able to provide his own
* Socket implementations by substituting his own SocketFactory.
* @see SocketFactory
*/
public abstract class SocketClient
{
/**
* The end of line character sequence used by most IETF protocols. That
* is a carriage return followed by a newline: "\r\n"
*/
public static final String NETASCII_EOL = "\r\n";
/** The default SocketFactory shared by all SocketClient instances. */
private static final SocketFactory __DEFAULT_SOCKET_FACTORY =
SocketFactory.getDefault();
/** The default {@link ServerSocketFactory} */
private static final ServerSocketFactory __DEFAULT_SERVER_SOCKET_FACTORY =
ServerSocketFactory.getDefault();
/**
* A ProtocolCommandSupport object used to manage the registering of
* ProtocolCommandListeners and the firing of ProtocolCommandEvents.
*/
private ProtocolCommandSupport __commandSupport;
/** The timeout to use after opening a socket. */
protected int _timeout_;
/** The socket used for the connection. */
protected Socket _socket_;
/** The hostname used for the connection (null = no hostname supplied). */
protected String _hostname_;
/** The default port the client should connect to. */
protected int _defaultPort_;
/** The socket's InputStream. */
protected InputStream _input_;
/** The socket's OutputStream. */
protected OutputStream _output_;
/** The socket's SocketFactory. */
protected SocketFactory _socketFactory_;
/** The socket's ServerSocket Factory. */
protected ServerSocketFactory _serverSocketFactory_;
/** The socket's connect timeout (0 = infinite timeout) */
private static final int DEFAULT_CONNECT_TIMEOUT = 0;
protected int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
/** Hint for SO_RCVBUF size */
private int receiveBufferSize = -1;
/** Hint for SO_SNDBUF size */
private int sendBufferSize = -1;
/** The proxy to use when connecting. */
private Proxy connProxy;
/**
* Charset to use for byte IO.
*/
private Charset charset = Charset.defaultCharset();
/**
* Default constructor for SocketClient. Initializes
* _socket_ to null, _timeout_ to 0, _defaultPort to 0,
* _isConnected_ to false, charset to {@code Charset.defaultCharset()}
* and _socketFactory_ to a shared instance of
* {@link org.apache.commons.net.DefaultSocketFactory}.
*/
public SocketClient()
{
_socket_ = null;
_hostname_ = null;
_input_ = null;
_output_ = null;
_timeout_ = 0;
_defaultPort_ = 0;
_socketFactory_ = __DEFAULT_SOCKET_FACTORY;
_serverSocketFactory_ = __DEFAULT_SERVER_SOCKET_FACTORY;
}
/**
* Because there are so many connect() methods, the _connectAction_()
* method is provided as a means of performing some action immediately
* after establishing a connection, rather than reimplementing all
* of the connect() methods. The last action performed by every
* connect() method after opening a socket is to call this method.
* <p>
* This method sets the timeout on the just opened socket to the default
* timeout set by {@link #setDefaultTimeout setDefaultTimeout() },
* sets _input_ and _output_ to the socket's InputStream and OutputStream
* respectively, and sets _isConnected_ to true.
* <p>
* Subclasses overriding this method should start by calling
* <code> super._connectAction_() </code> first to ensure the
* initialization of the aforementioned protected variables.
* @throws IOException (SocketException) if a problem occurs with the socket
*/
protected void _connectAction_() throws IOException
{
_socket_.setSoTimeout(_timeout_);
_input_ = _socket_.getInputStream();
_output_ = _socket_.getOutputStream();
}
/**
* Opens a Socket connected to a remote host at the specified port and
* originating from the current host at a system assigned port.
* Before returning, {@link #_connectAction_ _connectAction_() }
* is called to perform connection initialization actions.
* <p>
* @param host The remote host.
* @param port The port to connect to on the remote host.
* @exception SocketException If the socket timeout could not be set.
* @exception IOException If the socket could not be opened. In most
* cases you will only want to catch IOException since SocketException is
* derived from it.
*/
public void connect(InetAddress host, int port)
throws SocketException, IOException
{
_hostname_ = null;
_socket_ = _socketFactory_.createSocket();
if (receiveBufferSize != -1) {
_socket_.setReceiveBufferSize(receiveBufferSize);
}
if (sendBufferSize != -1) {
_socket_.setSendBufferSize(sendBufferSize);
}
_socket_.connect(new InetSocketAddress(host, port), connectTimeout);
_connectAction_();
}
/**
* Opens a Socket connected to a remote host at the specified port and
* originating from the current host at a system assigned port.
* Before returning, {@link #_connectAction_ _connectAction_() }
* is called to perform connection initialization actions.
* <p>
* @param hostname The name of the remote host.
* @param port The port to connect to on the remote host.
* @exception SocketException If the socket timeout could not be set.
* @exception IOException If the socket could not be opened. In most
* cases you will only want to catch IOException since SocketException is
* derived from it.
* @exception java.net.UnknownHostException If the hostname cannot be resolved.
*/
public void connect(String hostname, int port)
throws SocketException, IOException
{
connect(InetAddress.getByName(hostname), port);
_hostname_ = hostname;
}
/**
* Opens a Socket connected to a remote host at the specified port and
* originating from the specified local address and port.
* Before returning, {@link #_connectAction_ _connectAction_() }
* is called to perform connection initialization actions.
* <p>
* @param host The remote host.
* @param port The port to connect to on the remote host.
* @param localAddr The local address to use.
* @param localPort The local port to use.
* @exception SocketException If the socket timeout could not be set.
* @exception IOException If the socket could not be opened. In most
* cases you will only want to catch IOException since SocketException is
* derived from it.
*/
public void connect(InetAddress host, int port,
InetAddress localAddr, int localPort)
throws SocketException, IOException
{
_hostname_ = null;
_socket_ = _socketFactory_.createSocket();
if (receiveBufferSize != -1) {
_socket_.setReceiveBufferSize(receiveBufferSize);
}
if (sendBufferSize != -1) {
_socket_.setSendBufferSize(sendBufferSize);
}
_socket_.bind(new InetSocketAddress(localAddr, localPort));
_socket_.connect(new InetSocketAddress(host, port), connectTimeout);
_connectAction_();
}
/**
* Opens a Socket connected to a remote host at the specified port and
* originating from the specified local address and port.
* Before returning, {@link #_connectAction_ _connectAction_() }
* is called to perform connection initialization actions.
* <p>
* @param hostname The name of the remote host.
* @param port The port to connect to on the remote host.
* @param localAddr The local address to use.
* @param localPort The local port to use.
* @exception SocketException If the socket timeout could not be set.
* @exception IOException If the socket could not be opened. In most
* cases you will only want to catch IOException since SocketException is
* derived from it.
* @exception java.net.UnknownHostException If the hostname cannot be resolved.
*/
public void connect(String hostname, int port,
InetAddress localAddr, int localPort)
throws SocketException, IOException
{
connect(InetAddress.getByName(hostname), port, localAddr, localPort);
_hostname_ = hostname;
}
/**
* Opens a Socket connected to a remote host at the current default port
* and originating from the current host at a system assigned port.
* Before returning, {@link #_connectAction_ _connectAction_() }
* is called to perform connection initialization actions.
* <p>
* @param host The remote host.
* @exception SocketException If the socket timeout could not be set.
* @exception IOException If the socket could not be opened. In most
* cases you will only want to catch IOException since SocketException is
* derived from it.
*/
public void connect(InetAddress host) throws SocketException, IOException
{
_hostname_ = null;
connect(host, _defaultPort_);
}
/**
* Opens a Socket connected to a remote host at the current default
* port and originating from the current host at a system assigned port.
* Before returning, {@link #_connectAction_ _connectAction_() }
* is called to perform connection initialization actions.
* <p>
* @param hostname The name of the remote host.
* @exception SocketException If the socket timeout could not be set.
* @exception IOException If the socket could not be opened. In most
* cases you will only want to catch IOException since SocketException is
* derived from it.
* @exception java.net.UnknownHostException If the hostname cannot be resolved.
*/
public void connect(String hostname) throws SocketException, IOException
{
connect(hostname, _defaultPort_);
_hostname_ = hostname;
}
/**
* Disconnects the socket connection.
* You should call this method after you've finished using the class
* instance and also before you call
* {@link #connect connect() }
* again. _isConnected_ is set to false, _socket_ is set to null,
* _input_ is set to null, and _output_ is set to null.
* <p>
* @exception IOException If there is an error closing the socket.
*/
public void disconnect() throws IOException
{
closeQuietly(_socket_);
closeQuietly(_input_);
closeQuietly(_output_);
_socket_ = null;
_hostname_ = null;
_input_ = null;
_output_ = null;
}
private void closeQuietly(Socket socket) {
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// Ignored
}
}
}
private void closeQuietly(Closeable close){
if (close != null){
try {
close.close();
} catch (IOException e) {
// Ignored
}
}
}
/**
* Returns true if the client is currently connected to a server.
* <p>
* Delegates to {@link Socket#isConnected()}
* @return True if the client is currently connected to a server,
* false otherwise.
*/
public boolean isConnected()
{
if (_socket_ == null) {
return false;
}
return _socket_.isConnected();
}
/**
* Make various checks on the socket to test if it is available for use.
* Note that the only sure test is to use it, but these checks may help
* in some cases.
* @see <a href="https://issues.apache.org/jira/browse/NET-350">NET-350</a>
* @return {@code true} if the socket appears to be available for use
* @since 3.0
*/
public boolean isAvailable(){
if (isConnected()) {
try
{
if (_socket_.getInetAddress() == null) {
return false;
}
if (_socket_.getPort() == 0) {
return false;
}
if (_socket_.getRemoteSocketAddress() == null) {
return false;
}
if (_socket_.isClosed()) {
return false;
}
/* these aren't exact checks (a Socket can be half-open),
but since we usually require two-way data transfer,
we check these here too: */
if (_socket_.isInputShutdown()) {
return false;
}
if (_socket_.isOutputShutdown()) {
return false;
}
/* ignore the result, catch exceptions: */
_socket_.getInputStream();
_socket_.getOutputStream();
}
catch (IOException ioex)
{
return false;
}
return true;
} else {
return false;
}
}
/**
* Sets the default port the SocketClient should connect to when a port
* is not specified. The {@link #_defaultPort_ _defaultPort_ }
* variable stores this value. If never set, the default port is equal
* to zero.
* <p>
* @param port The default port to set.
*/
public void setDefaultPort(int port)
{
_defaultPort_ = port;
}
/**
* Returns the current value of the default port (stored in
* {@link #_defaultPort_ _defaultPort_ }).
* <p>
* @return The current value of the default port.
*/
public int getDefaultPort()
{
return _defaultPort_;
}
/**
* Set the default timeout in milliseconds to use when opening a socket.
* This value is only used previous to a call to
* {@link #connect connect()}
* and should not be confused with {@link #setSoTimeout setSoTimeout()}
* which operates on an the currently opened socket. _timeout_ contains
* the new timeout value.
* <p>
* @param timeout The timeout in milliseconds to use for the socket
* connection.
*/
public void setDefaultTimeout(int timeout)
{
_timeout_ = timeout;
}
/**
* Returns the default timeout in milliseconds that is used when
* opening a socket.
* <p>
* @return The default timeout in milliseconds that is used when
* opening a socket.
*/
public int getDefaultTimeout()
{
return _timeout_;
}
/**
* Set the timeout in milliseconds of a currently open connection.
* Only call this method after a connection has been opened
* by {@link #connect connect()}.
* <p>
* To set the initial timeout, use {@link #setDefaultTimeout(int)} instead.
*
* @param timeout The timeout in milliseconds to use for the currently
* open socket connection.
* @exception SocketException If the operation fails.
* @throws NullPointerException if the socket is not currently open
*/
public void setSoTimeout(int timeout) throws SocketException
{
_socket_.setSoTimeout(timeout);
}
/**
* Set the underlying socket send buffer size.
* <p>
* @param size The size of the buffer in bytes.
* @throws SocketException never thrown, but subclasses might want to do so
* @since 2.0
*/
public void setSendBufferSize(int size) throws SocketException {
sendBufferSize = size;
}
/**
* Get the current sendBuffer size
* @return the size, or -1 if not initialised
* @since 3.0
*/
protected int getSendBufferSize(){
return sendBufferSize;
}
/**
* Sets the underlying socket receive buffer size.
* <p>
* @param size The size of the buffer in bytes.
* @throws SocketException never (but subclasses may wish to do so)
* @since 2.0
*/
public void setReceiveBufferSize(int size) throws SocketException {
receiveBufferSize = size;
}
/**
* Get the current receivedBuffer size
* @return the size, or -1 if not initialised
* @since 3.0
*/
protected int getReceiveBufferSize(){
return receiveBufferSize;
}
/**
* Returns the timeout in milliseconds of the currently opened socket.
* <p>
* @return The timeout in milliseconds of the currently opened socket.
* @exception SocketException If the operation fails.
* @throws NullPointerException if the socket is not currently open
*/
public int getSoTimeout() throws SocketException
{
return _socket_.getSoTimeout();
}
/**
* Enables or disables the Nagle's algorithm (TCP_NODELAY) on the
* currently opened socket.
* <p>
* @param on True if Nagle's algorithm is to be enabled, false if not.
* @exception SocketException If the operation fails.
* @throws NullPointerException if the socket is not currently open
*/
public void setTcpNoDelay(boolean on) throws SocketException
{
_socket_.setTcpNoDelay(on);
}
/**
* Returns true if Nagle's algorithm is enabled on the currently opened
* socket.
* <p>
* @return True if Nagle's algorithm is enabled on the currently opened
* socket, false otherwise.
* @exception SocketException If the operation fails.
* @throws NullPointerException if the socket is not currently open
*/
public boolean getTcpNoDelay() throws SocketException
{
return _socket_.getTcpNoDelay();
}
/**
* Sets the SO_KEEPALIVE flag on the currently opened socket.
*
* From the Javadocs, the default keepalive time is 2 hours (although this is
* implementation dependent). It looks as though the Windows WSA sockets implementation
* allows a specific keepalive value to be set, although this seems not to be the case on
* other systems.
* @param keepAlive If true, keepAlive is turned on
* @throws SocketException if there is a problem with the socket
* @throws NullPointerException if the socket is not currently open
* @since 2.2
*/
public void setKeepAlive(boolean keepAlive) throws SocketException {
_socket_.setKeepAlive(keepAlive);
}
/**
* Returns the current value of the SO_KEEPALIVE flag on the currently opened socket.
* Delegates to {@link Socket#getKeepAlive()}
* @return True if SO_KEEPALIVE is enabled.
* @throws SocketException if there is a problem with the socket
* @throws NullPointerException if the socket is not currently open
* @since 2.2
*/
public boolean getKeepAlive() throws SocketException {
return _socket_.getKeepAlive();
}
/**
* Sets the SO_LINGER timeout on the currently opened socket.
* <p>
* @param on True if linger is to be enabled, false if not.
* @param val The linger timeout (in hundredths of a second?)
* @exception SocketException If the operation fails.
* @throws NullPointerException if the socket is not currently open
*/
public void setSoLinger(boolean on, int val) throws SocketException
{
_socket_.setSoLinger(on, val);
}
/**
* Returns the current SO_LINGER timeout of the currently opened socket.
* <p>
* @return The current SO_LINGER timeout. If SO_LINGER is disabled returns
* -1.
* @exception SocketException If the operation fails.
* @throws NullPointerException if the socket is not currently open
*/
public int getSoLinger() throws SocketException
{
return _socket_.getSoLinger();
}
/**
* Returns the port number of the open socket on the local host used
* for the connection.
* Delegates to {@link Socket#getLocalPort()}
* <p>
* @return The port number of the open socket on the local host used
* for the connection.
* @throws NullPointerException if the socket is not currently open
*/
public int getLocalPort()
{
return _socket_.getLocalPort();
}
/**
* Returns the local address to which the client's socket is bound.
* Delegates to {@link Socket#getLocalAddress()}
* <p>
* @return The local address to which the client's socket is bound.
* @throws NullPointerException if the socket is not currently open
*/
public InetAddress getLocalAddress()
{
return _socket_.getLocalAddress();
}
/**
* Returns the port number of the remote host to which the client is
* connected.
* Delegates to {@link Socket#getPort()}
* <p>
* @return The port number of the remote host to which the client is
* connected.
* @throws NullPointerException if the socket is not currently open
*/
public int getRemotePort()
{
return _socket_.getPort();
}
/**
* @return The remote address to which the client is connected.
* Delegates to {@link Socket#getInetAddress()}
* @throws NullPointerException if the socket is not currently open
*/
public InetAddress getRemoteAddress()
{
return _socket_.getInetAddress();
}
/**
* Verifies that the remote end of the given socket is connected to the
* the same host that the SocketClient is currently connected to. This
* is useful for doing a quick security check when a client needs to
* accept a connection from a server, such as an FTP data connection or
* a BSD R command standard error stream.
* <p>
* @param socket the item to check against
* @return True if the remote hosts are the same, false if not.
*/
public boolean verifyRemote(Socket socket)
{
InetAddress host1, host2;
host1 = socket.getInetAddress();
host2 = getRemoteAddress();
return host1.equals(host2);
}
/**
* Sets the SocketFactory used by the SocketClient to open socket
* connections. If the factory value is null, then a default
* factory is used (only do this to reset the factory after having
* previously altered it).
* Any proxy setting is discarded.
* <p>
* @param factory The new SocketFactory the SocketClient should use.
*/
public void setSocketFactory(SocketFactory factory)
{
if (factory == null) {
_socketFactory_ = __DEFAULT_SOCKET_FACTORY;
} else {
_socketFactory_ = factory;
}
// re-setting the socket factory makes the proxy setting useless,
// so set the field to null so that getProxy() doesn't return a
// Proxy that we're actually not using.
connProxy = null;
}
/**
* Sets the ServerSocketFactory used by the SocketClient to open ServerSocket
* connections. If the factory value is null, then a default
* factory is used (only do this to reset the factory after having
* previously altered it).
* <p>
* @param factory The new ServerSocketFactory the SocketClient should use.
* @since 2.0
*/
public void setServerSocketFactory(ServerSocketFactory factory) {
if (factory == null) {
_serverSocketFactory_ = __DEFAULT_SERVER_SOCKET_FACTORY;
} else {
_serverSocketFactory_ = factory;
}
}
/**
* Sets the connection timeout in milliseconds, which will be passed to the {@link Socket} object's
* connect() method.
* @param connectTimeout The connection timeout to use (in ms)
* @since 2.0
*/
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
/**
* Get the underlying socket connection timeout.
* @return timeout (in ms)
* @since 2.0
*/
public int getConnectTimeout() {
return connectTimeout;
}
/**
* Get the underlying {@link ServerSocketFactory}
* @return The server socket factory
* @since 2.2
*/
public ServerSocketFactory getServerSocketFactory() {
return _serverSocketFactory_;
}
/**
* Adds a ProtocolCommandListener.
*
* @param listener The ProtocolCommandListener to add.
* @since 3.0
*/
public void addProtocolCommandListener(ProtocolCommandListener listener) {
getCommandSupport().addProtocolCommandListener(listener);
}
/**
* Removes a ProtocolCommandListener.
*
* @param listener The ProtocolCommandListener to remove.
* @since 3.0
*/
public void removeProtocolCommandListener(ProtocolCommandListener listener) {
getCommandSupport().removeProtocolCommandListener(listener);
}
/**
* If there are any listeners, send them the reply details.
*
* @param replyCode the code extracted from the reply
* @param reply the full reply text
* @since 3.0
*/
protected void fireReplyReceived(int replyCode, String reply) {
if (getCommandSupport().getListenerCount() > 0) {
getCommandSupport().fireReplyReceived(replyCode, reply);
}
}
/**
* If there are any listeners, send them the command details.
*
* @param command the command name
* @param message the complete message, including command name
* @since 3.0
*/
protected void fireCommandSent(String command, String message) {
if (getCommandSupport().getListenerCount() > 0) {
getCommandSupport().fireCommandSent(command, message);
}
}
/**
* Create the CommandSupport instance if required
*/
protected void createCommandSupport(){
__commandSupport = new ProtocolCommandSupport(this);
}
/**
* Subclasses can override this if they need to provide their own
* instance field for backwards compatibility.
*
* @return the CommandSupport instance, may be {@code null}
* @since 3.0
*/
protected ProtocolCommandSupport getCommandSupport() {
return __commandSupport;
}
/**
* Sets the proxy for use with all the connections.
* The proxy is used for connections established after the
* call to this method.
*
* @param proxy the new proxy for connections.
* @since 3.2
*/
public void setProxy(Proxy proxy) {
setSocketFactory(new DefaultSocketFactory(proxy));
connProxy = proxy;
}
/**
* Gets the proxy for use with all the connections.
* @return the current proxy for connections.
*/
public Proxy getProxy() {
return connProxy;
}
/**
* Gets the charset name.
*
* @return the charset.
* @since 3.3
* @deprecated Since the code now requires Java 1.6 as a mininmum
*/
@Deprecated
public String getCharsetName() {
return charset.name();
}
/**
* Gets the charset.
*
* @return the charset.
* @since 3.3
*/
public Charset getCharset() {
return charset;
}
/**
* Sets the charset.
*
* @param charset the charset.
* @since 3.3
*/
public void setCharset(Charset charset) {
this.charset = charset;
}
/*
* N.B. Fields cannot be pulled up into a super-class without breaking binary compatibility,
* so the abstract method is needed to pass the instance to the methods which were moved here.
*/
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/util/ListenerList.java | client/src/main/java/org/apache/commons/net/util/ListenerList.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.util;
import java.io.Serializable;
import java.util.EventListener;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
/**
*/
public class ListenerList implements Serializable, Iterable<EventListener>
{
private static final long serialVersionUID = -1934227607974228213L;
private final CopyOnWriteArrayList<EventListener> __listeners;
public ListenerList()
{
__listeners = new CopyOnWriteArrayList<EventListener>();
}
public void addListener(EventListener listener)
{
__listeners.add(listener);
}
public void removeListener(EventListener listener)
{
__listeners.remove(listener);
}
public int getListenerCount()
{
return __listeners.size();
}
/**
* Return an {@link Iterator} for the {@link EventListener} instances.
*
* @return an {@link Iterator} for the {@link EventListener} instances
* @since 2.0
* TODO Check that this is a good defensive strategy
*/
@Override
public Iterator<EventListener> iterator() {
return __listeners.iterator();
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/InvalidTelnetOptionException.java | client/src/main/java/org/apache/commons/net/telnet/InvalidTelnetOptionException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* The InvalidTelnetOptionException is the exception that is
* thrown whenever a TelnetOptionHandler with an invlaid
* option code is registered in TelnetClient with addOptionHandler.
***/
public class InvalidTelnetOptionException extends Exception
{
private static final long serialVersionUID = -2516777155928793597L;
/***
* Option code
***/
private final int optionCode;
/***
* Error message
***/
private final String msg;
/***
* Constructor for the exception.
* <p>
* @param message - Error message.
* @param optcode - Option code.
***/
public InvalidTelnetOptionException(String message, int optcode)
{
optionCode = optcode;
msg = message;
}
/***
* Gets the error message of ths exception.
* <p>
* @return the error message.
***/
@Override
public String getMessage()
{
return (msg + ": " + optionCode);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/EchoOptionHandler.java | client/src/main/java/org/apache/commons/net/telnet/EchoOptionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* Implements the telnet echo option RFC 857.
***/
public class EchoOptionHandler extends TelnetOptionHandler
{
/***
* Constructor for the EchoOptionHandler. Allows defining desired
* initial setting for local/remote activation of this option and
* behaviour in case a local/remote activation request for this
* option is received.
* <p>
* @param initlocal - if set to true, a WILL is sent upon connection.
* @param initremote - if set to true, a DO is sent upon connection.
* @param acceptlocal - if set to true, any DO request is accepted.
* @param acceptremote - if set to true, any WILL request is accepted.
***/
public EchoOptionHandler(boolean initlocal, boolean initremote,
boolean acceptlocal, boolean acceptremote)
{
super(TelnetOption.ECHO, initlocal, initremote,
acceptlocal, acceptremote);
}
/***
* Constructor for the EchoOptionHandler. Initial and accept
* behaviour flags are set to false
***/
public EchoOptionHandler()
{
super(TelnetOption.ECHO, false, false, false, false);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/SuppressGAOptionHandler.java | client/src/main/java/org/apache/commons/net/telnet/SuppressGAOptionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* Implements the telnet suppress go ahead option RFC 858.
***/
public class SuppressGAOptionHandler extends TelnetOptionHandler
{
/***
* Constructor for the SuppressGAOptionHandler. Allows defining desired
* initial setting for local/remote activation of this option and
* behaviour in case a local/remote activation request for this
* option is received.
* <p>
* @param initlocal - if set to true, a WILL is sent upon connection.
* @param initremote - if set to true, a DO is sent upon connection.
* @param acceptlocal - if set to true, any DO request is accepted.
* @param acceptremote - if set to true, any WILL request is accepted.
***/
public SuppressGAOptionHandler(boolean initlocal, boolean initremote,
boolean acceptlocal, boolean acceptremote)
{
super(TelnetOption.SUPPRESS_GO_AHEAD, initlocal, initremote,
acceptlocal, acceptremote);
}
/***
* Constructor for the SuppressGAOptionHandler. Initial and accept
* behaviour flags are set to false
***/
public SuppressGAOptionHandler()
{
super(TelnetOption.SUPPRESS_GO_AHEAD, false, false, false, false);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetInputStream.java | client/src/main/java/org/apache/commons/net/telnet/TelnetInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
final class TelnetInputStream extends BufferedInputStream implements Runnable
{
/** End of file has been reached */
private static final int EOF = -1;
/** Read would block */
private static final int WOULD_BLOCK = -2;
// TODO should these be private enums?
static final int _STATE_DATA = 0, _STATE_IAC = 1, _STATE_WILL = 2,
_STATE_WONT = 3, _STATE_DO = 4, _STATE_DONT = 5,
_STATE_SB = 6, _STATE_SE = 7, _STATE_CR = 8, _STATE_IAC_SB = 9;
private boolean __hasReachedEOF; // @GuardedBy("__queue")
private volatile boolean __isClosed;
private boolean __readIsWaiting;
private int __receiveState, __queueHead, __queueTail, __bytesAvailable;
private final int[] __queue;
private final TelnetClient __client;
private final Thread __thread;
private IOException __ioException;
/* TERMINAL-TYPE option (start)*/
private final int __suboption[] = new int[512];
private int __suboption_count = 0;
/* TERMINAL-TYPE option (end)*/
private volatile boolean __threaded;
TelnetInputStream(InputStream input, TelnetClient client,
boolean readerThread)
{
super(input);
__client = client;
__receiveState = _STATE_DATA;
__isClosed = true;
__hasReachedEOF = false;
// Make it 2049, because when full, one slot will go unused, and we
// want a 2048 byte buffer just to have a round number (base 2 that is)
__queue = new int[2049];
__queueHead = 0;
__queueTail = 0;
__bytesAvailable = 0;
__ioException = null;
__readIsWaiting = false;
__threaded = false;
if(readerThread) {
__thread = new Thread(this);
} else {
__thread = null;
}
}
TelnetInputStream(InputStream input, TelnetClient client) {
this(input, client, true);
}
void _start()
{
if(__thread == null) {
return;
}
int priority;
__isClosed = false;
// TODO remove this
// Need to set a higher priority in case JVM does not use pre-emptive
// threads. This should prevent scheduler induced deadlock (rather than
// deadlock caused by a bug in this code).
priority = Thread.currentThread().getPriority() + 1;
if (priority > Thread.MAX_PRIORITY) {
priority = Thread.MAX_PRIORITY;
}
__thread.setPriority(priority);
__thread.setDaemon(true);
__thread.start();
__threaded = true; // tell _processChar that we are running threaded
}
// synchronized(__client) critical sections are to protect against
// TelnetOutputStream writing through the telnet client at same time
// as a processDo/Will/etc. command invoked from TelnetInputStream
// tries to write.
/**
* Get the next byte of data.
* IAC commands are processed internally and do not return data.
*
* @param mayBlock true if method is allowed to block
* @return the next byte of data,
* or -1 (EOF) if end of stread reached,
* or -2 (WOULD_BLOCK) if mayBlock is false and there is no data available
*/
private int __read(boolean mayBlock) throws IOException
{
int ch;
while (true)
{
// If there is no more data AND we were told not to block,
// just return WOULD_BLOCK (-2). (More efficient than exception.)
if(!mayBlock && super.available() == 0) {
return WOULD_BLOCK;
}
// Otherwise, exit only when we reach end of stream.
if ((ch = super.read()) < 0) {
return EOF;
}
ch = (ch & 0xff);
/* Code Section added for supporting AYT (start)*/
synchronized (__client)
{
__client._processAYTResponse();
}
/* Code Section added for supporting AYT (end)*/
/* Code Section added for supporting spystreams (start)*/
__client._spyRead(ch);
/* Code Section added for supporting spystreams (end)*/
switch (__receiveState)
{
case _STATE_CR:
if (ch == '\0')
{
// Strip null
continue;
}
// How do we handle newline after cr?
// else if (ch == '\n' && _requestedDont(TelnetOption.ECHO) &&
// Handle as normal data by falling through to _STATE_DATA case
//$FALL-THROUGH$
case _STATE_DATA:
if (ch == TelnetCommand.IAC)
{
__receiveState = _STATE_IAC;
continue;
}
if (ch == '\r')
{
synchronized (__client)
{
if (__client._requestedDont(TelnetOption.BINARY)) {
__receiveState = _STATE_CR;
} else {
__receiveState = _STATE_DATA;
}
}
} else {
__receiveState = _STATE_DATA;
}
break;
case _STATE_IAC:
switch (ch)
{
case TelnetCommand.WILL:
__receiveState = _STATE_WILL;
continue;
case TelnetCommand.WONT:
__receiveState = _STATE_WONT;
continue;
case TelnetCommand.DO:
__receiveState = _STATE_DO;
continue;
case TelnetCommand.DONT:
__receiveState = _STATE_DONT;
continue;
/* TERMINAL-TYPE option (start)*/
case TelnetCommand.SB:
__suboption_count = 0;
__receiveState = _STATE_SB;
continue;
/* TERMINAL-TYPE option (end)*/
case TelnetCommand.IAC:
__receiveState = _STATE_DATA;
break; // exit to enclosing switch to return IAC from read
case TelnetCommand.SE: // unexpected byte! ignore it (don't send it as a command)
__receiveState = _STATE_DATA;
continue;
default:
__receiveState = _STATE_DATA;
__client._processCommand(ch); // Notify the user
continue; // move on the next char
}
break; // exit and return from read
case _STATE_WILL:
synchronized (__client)
{
__client._processWill(ch);
__client._flushOutputStream();
}
__receiveState = _STATE_DATA;
continue;
case _STATE_WONT:
synchronized (__client)
{
__client._processWont(ch);
__client._flushOutputStream();
}
__receiveState = _STATE_DATA;
continue;
case _STATE_DO:
synchronized (__client)
{
__client._processDo(ch);
__client._flushOutputStream();
}
__receiveState = _STATE_DATA;
continue;
case _STATE_DONT:
synchronized (__client)
{
__client._processDont(ch);
__client._flushOutputStream();
}
__receiveState = _STATE_DATA;
continue;
/* TERMINAL-TYPE option (start)*/
case _STATE_SB:
switch (ch)
{
case TelnetCommand.IAC:
__receiveState = _STATE_IAC_SB;
continue;
default:
// store suboption char
if (__suboption_count < __suboption.length) {
__suboption[__suboption_count++] = ch;
}
break;
}
__receiveState = _STATE_SB;
continue;
case _STATE_IAC_SB: // IAC received during SB phase
switch (ch)
{
case TelnetCommand.SE:
synchronized (__client)
{
__client._processSuboption(__suboption, __suboption_count);
__client._flushOutputStream();
}
__receiveState = _STATE_DATA;
continue;
case TelnetCommand.IAC: // De-dup the duplicated IAC
if (__suboption_count < __suboption.length) {
__suboption[__suboption_count++] = ch;
}
break;
default: // unexpected byte! ignore it
break;
}
__receiveState = _STATE_SB;
continue;
/* TERMINAL-TYPE option (end)*/
}
break;
}
return ch;
}
// synchronized(__client) critical sections are to protect against
// TelnetOutputStream writing through the telnet client at same time
// as a processDo/Will/etc. command invoked from TelnetInputStream
// tries to write. Returns true if buffer was previously empty.
private boolean __processChar(int ch) throws InterruptedException
{
// Critical section because we're altering __bytesAvailable,
// __queueTail, and the contents of _queue.
boolean bufferWasEmpty;
synchronized (__queue)
{
bufferWasEmpty = (__bytesAvailable == 0);
while (__bytesAvailable >= __queue.length - 1)
{
// The queue is full. We need to wait before adding any more data to it. Hopefully the stream owner
// will consume some data soon!
if(__threaded)
{
__queue.notify();
try
{
__queue.wait();
}
catch (InterruptedException e)
{
throw e;
}
}
else
{
// We've been asked to add another character to the queue, but it is already full and there's
// no other thread to drain it. This should not have happened!
throw new IllegalStateException("Queue is full! Cannot process another character.");
}
}
// Need to do this in case we're not full, but block on a read
if (__readIsWaiting && __threaded)
{
__queue.notify();
}
__queue[__queueTail] = ch;
++__bytesAvailable;
if (++__queueTail >= __queue.length) {
__queueTail = 0;
}
}
return bufferWasEmpty;
}
@Override
public int read() throws IOException
{
// Critical section because we're altering __bytesAvailable,
// __queueHead, and the contents of _queue in addition to
// testing value of __hasReachedEOF.
synchronized (__queue)
{
while (true)
{
if (__ioException != null)
{
IOException e;
e = __ioException;
__ioException = null;
throw e;
}
if (__bytesAvailable == 0)
{
// Return EOF if at end of file
if (__hasReachedEOF) {
return EOF;
}
// Otherwise, we have to wait for queue to get something
if(__threaded)
{
__queue.notify();
try
{
__readIsWaiting = true;
__queue.wait();
__readIsWaiting = false;
}
catch (InterruptedException e)
{
throw new InterruptedIOException("Fatal thread interruption during read.");
}
}
else
{
//__alreadyread = false;
__readIsWaiting = true;
int ch;
boolean mayBlock = true; // block on the first read only
do
{
try
{
if ((ch = __read(mayBlock)) < 0) { // must be EOF
if(ch != WOULD_BLOCK) {
return (ch);
}
}
}
catch (InterruptedIOException e)
{
synchronized (__queue)
{
__ioException = e;
__queue.notifyAll();
try
{
__queue.wait(100);
}
catch (InterruptedException interrupted)
{
// Ignored
}
}
return EOF;
}
try
{
if(ch != WOULD_BLOCK)
{
__processChar(ch);
}
}
catch (InterruptedException e)
{
if (__isClosed) {
return EOF;
}
}
// Reads should not block on subsequent iterations. Potentially, this could happen if the
// remaining buffered socket data consists entirely of Telnet command sequence and no "user" data.
mayBlock = false;
}
// Continue reading as long as there is data available and the queue is not full.
while (super.available() > 0 && __bytesAvailable < __queue.length - 1);
__readIsWaiting = false;
}
continue;
}
else
{
int ch;
ch = __queue[__queueHead];
if (++__queueHead >= __queue.length) {
__queueHead = 0;
}
--__bytesAvailable;
// Need to explicitly notify() so available() works properly
if(__bytesAvailable == 0 && __threaded) {
__queue.notify();
}
return ch;
}
}
}
}
/***
* Reads the next number of bytes from the stream into an array and
* returns the number of bytes read. Returns -1 if the end of the
* stream has been reached.
* <p>
* @param buffer The byte array in which to store the data.
* @return The number of bytes read. Returns -1 if the
* end of the message has been reached.
* @exception IOException If an error occurs in reading the underlying
* stream.
***/
@Override
public int read(byte buffer[]) throws IOException
{
return read(buffer, 0, buffer.length);
}
/***
* Reads the next number of bytes from the stream into an array and returns
* the number of bytes read. Returns -1 if the end of the
* message has been reached. The characters are stored in the array
* starting from the given offset and up to the length specified.
* <p>
* @param buffer The byte array in which to store the data.
* @param offset The offset into the array at which to start storing data.
* @param length The number of bytes to read.
* @return The number of bytes read. Returns -1 if the
* end of the stream has been reached.
* @exception IOException If an error occurs while reading the underlying
* stream.
***/
@Override
public int read(byte buffer[], int offset, int length) throws IOException
{
int ch, off;
if (length < 1) {
return 0;
}
// Critical section because run() may change __bytesAvailable
synchronized (__queue)
{
if (length > __bytesAvailable) {
length = __bytesAvailable;
}
}
if ((ch = read()) == EOF) {
return EOF;
}
off = offset;
do
{
buffer[offset++] = (byte)ch;
}
while (--length > 0 && (ch = read()) != EOF);
//__client._spyRead(buffer, off, offset - off);
return (offset - off);
}
/*** Returns false. Mark is not supported. ***/
@Override
public boolean markSupported()
{
return false;
}
@Override
public int available() throws IOException
{
// Critical section because run() may change __bytesAvailable
synchronized (__queue)
{
if (__threaded) { // Must not call super.available when running threaded: NET-466
return __bytesAvailable;
} else {
return __bytesAvailable + super.available();
}
}
}
// Cannot be synchronized. Will cause deadlock if run() is blocked
// in read because BufferedInputStream read() is synchronized.
@Override
public void close() throws IOException
{
// Completely disregard the fact thread may still be running.
// We can't afford to block on this close by waiting for
// thread to terminate because few if any JVM's will actually
// interrupt a system read() from the interrupt() method.
super.close();
synchronized (__queue)
{
__hasReachedEOF = true;
__isClosed = true;
if (__thread != null && __thread.isAlive())
{
__thread.interrupt();
}
__queue.notifyAll();
}
}
@Override
public void run()
{
int ch;
try
{
_outerLoop:
while (!__isClosed)
{
try
{
if ((ch = __read(true)) < 0) {
break;
}
}
catch (InterruptedIOException e)
{
synchronized (__queue)
{
__ioException = e;
__queue.notifyAll();
try
{
__queue.wait(100);
}
catch (InterruptedException interrupted)
{
if (__isClosed) {
break _outerLoop;
}
}
continue;
}
} catch(RuntimeException re) {
// We treat any runtime exceptions as though the
// stream has been closed. We close the
// underlying stream just to be sure.
super.close();
// Breaking the loop has the effect of setting
// the state to closed at the end of the method.
break _outerLoop;
}
// Process new character
boolean notify = false;
try
{
notify = __processChar(ch);
}
catch (InterruptedException e)
{
if (__isClosed) {
break _outerLoop;
}
}
// Notify input listener if buffer was previously empty
if (notify) {
__client.notifyInputListener();
}
}
}
catch (IOException ioe)
{
synchronized (__queue)
{
__ioException = ioe;
}
__client.notifyInputListener();
}
synchronized (__queue)
{
__isClosed = true; // Possibly redundant
__hasReachedEOF = true;
__queue.notify();
}
__threaded = false;
}
}
/* Emacs configuration
* Local variables: **
* mode: java **
* c-basic-offset: 4 **
* indent-tabs-mode: nil **
* End: **
*/
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/WindowSizeOptionHandler.java | client/src/main/java/org/apache/commons/net/telnet/WindowSizeOptionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* Implements the telnet window size option RFC 1073.
* @version $Id: WindowSizeOptionHandler.java 1697293 2015-08-24 01:01:00Z sebb $
* @since 2.0
***/
public class WindowSizeOptionHandler extends TelnetOptionHandler
{
/***
* Horizontal Size
***/
private int m_nWidth = 80;
/***
* Vertical Size
***/
private int m_nHeight = 24;
/***
* Window size option
***/
protected static final int WINDOW_SIZE = 31;
/***
* Constructor for the WindowSizeOptionHandler. Allows defining desired
* initial setting for local/remote activation of this option and
* behaviour in case a local/remote activation request for this
* option is received.
* <p>
* @param nWidth - Window width.
* @param nHeight - Window Height
* @param initlocal - if set to true, a WILL is sent upon connection.
* @param initremote - if set to true, a DO is sent upon connection.
* @param acceptlocal - if set to true, any DO request is accepted.
* @param acceptremote - if set to true, any WILL request is accepted.
***/
public WindowSizeOptionHandler(
int nWidth,
int nHeight,
boolean initlocal,
boolean initremote,
boolean acceptlocal,
boolean acceptremote
) {
super (
TelnetOption.WINDOW_SIZE,
initlocal,
initremote,
acceptlocal,
acceptremote
);
m_nWidth = nWidth;
m_nHeight = nHeight;
}
/***
* Constructor for the WindowSizeOptionHandler. Initial and accept
* behaviour flags are set to false
* <p>
* @param nWidth - Window width.
* @param nHeight - Window Height
***/
public WindowSizeOptionHandler(
int nWidth,
int nHeight
) {
super (
TelnetOption.WINDOW_SIZE,
false,
false,
false,
false
);
m_nWidth = nWidth;
m_nHeight = nHeight;
}
/***
* Implements the abstract method of TelnetOptionHandler.
* This will send the client Height and Width to the server.
* <p>
* @return array to send to remote system
***/
@Override
public int[] startSubnegotiationLocal()
{
int nCompoundWindowSize = m_nWidth * 0x10000 + m_nHeight;
int nResponseSize = 5;
int nIndex;
int nShift;
int nTurnedOnBits;
if ((m_nWidth % 0x100) == 0xFF) {
nResponseSize += 1;
}
if ((m_nWidth / 0x100) == 0xFF) {
nResponseSize += 1;
}
if ((m_nHeight % 0x100) == 0xFF) {
nResponseSize += 1;
}
if ((m_nHeight / 0x100) == 0xFF) {
nResponseSize += 1;
}
//
// allocate response array
//
int response[] = new int[nResponseSize];
//
// Build response array.
// ---------------------
// 1. put option name.
// 2. loop through Window size and fill the values,
// 3. duplicate 'ff' if needed.
//
response[0] = WINDOW_SIZE; // 1 //
for ( // 2 //
nIndex=1, nShift = 24;
nIndex < nResponseSize;
nIndex++, nShift -=8
) {
nTurnedOnBits = 0xFF;
nTurnedOnBits <<= nShift;
response[nIndex] = (nCompoundWindowSize & nTurnedOnBits) >>> nShift;
if (response[nIndex] == 0xff) { // 3 //
nIndex++;
response[nIndex] = 0xff;
}
}
return response;
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetOutputStream.java | client/src/main/java/org/apache/commons/net/telnet/TelnetOutputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
import java.io.IOException;
import java.io.OutputStream;
/**
* Wraps an output stream.
* <p>
* In binary mode, the only conversion is to double IAC.
* <p>
* In ASCII mode, if convertCRtoCRLF is true (currently always true), any CR is converted to CRLF.
* IACs are doubled.
* Also a bare LF is converted to CRLF and a bare CR is converted to CR\0
* <p>
***/
final class TelnetOutputStream extends OutputStream
{
private final TelnetClient __client;
// TODO there does not appear to be any way to change this value - should it be a ctor parameter?
private final boolean __convertCRtoCRLF = true;
private boolean __lastWasCR = false;
TelnetOutputStream(TelnetClient client)
{
__client = client;
}
/***
* Writes a byte to the stream.
* <p>
* @param ch The byte to write.
* @exception IOException If an error occurs while writing to the underlying
* stream.
***/
@Override
public void write(int ch) throws IOException
{
synchronized (__client)
{
ch &= 0xff;
if (__client._requestedWont(TelnetOption.BINARY)) // i.e. ASCII
{
if (__lastWasCR)
{
if (__convertCRtoCRLF)
{
__client._sendByte('\n');
if (ch == '\n') // i.e. was CRLF anyway
{
__lastWasCR = false;
return ;
}
} // __convertCRtoCRLF
else if (ch != '\n')
{
__client._sendByte('\0'); // RFC854 requires CR NUL for bare CR
}
}
switch (ch)
{
case '\r':
__client._sendByte('\r');
__lastWasCR = true;
break;
case '\n':
if (!__lastWasCR) { // convert LF to CRLF
__client._sendByte('\r');
}
__client._sendByte(ch);
__lastWasCR = false;
break;
case TelnetCommand.IAC:
__client._sendByte(TelnetCommand.IAC);
__client._sendByte(TelnetCommand.IAC);
__lastWasCR = false;
break;
default:
__client._sendByte(ch);
__lastWasCR = false;
break;
}
} // end ASCII
else if (ch == TelnetCommand.IAC)
{
__client._sendByte(ch);
__client._sendByte(TelnetCommand.IAC);
} else {
__client._sendByte(ch);
}
}
}
/***
* Writes a byte array to the stream.
* <p>
* @param buffer The byte array to write.
* @exception IOException If an error occurs while writing to the underlying
* stream.
***/
@Override
public void write(byte buffer[]) throws IOException
{
write(buffer, 0, buffer.length);
}
/***
* Writes a number of bytes from a byte array to the stream starting from
* a given offset.
* <p>
* @param buffer The byte array to write.
* @param offset The offset into the array at which to start copying data.
* @param length The number of bytes to write.
* @exception IOException If an error occurs while writing to the underlying
* stream.
***/
@Override
public void write(byte buffer[], int offset, int length) throws IOException
{
synchronized (__client)
{
while (length-- > 0) {
write(buffer[offset++]);
}
}
}
/*** Flushes the stream. ***/
@Override
public void flush() throws IOException
{
__client._flushOutputStream();
}
/*** Closes the stream. ***/
@Override
public void close() throws IOException
{
__client._closeOutputStream();
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TerminalTypeOptionHandler.java | client/src/main/java/org/apache/commons/net/telnet/TerminalTypeOptionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* Implements the telnet terminal type option RFC 1091.
***/
public class TerminalTypeOptionHandler extends TelnetOptionHandler
{
/***
* Terminal type
***/
private final String termType;
/***
* Terminal type option
***/
protected static final int TERMINAL_TYPE = 24;
/***
* Send (for subnegotiation)
***/
protected static final int TERMINAL_TYPE_SEND = 1;
/***
* Is (for subnegotiation)
***/
protected static final int TERMINAL_TYPE_IS = 0;
/***
* Constructor for the TerminalTypeOptionHandler. Allows defining desired
* initial setting for local/remote activation of this option and
* behaviour in case a local/remote activation request for this
* option is received.
* <p>
* @param termtype - terminal type that will be negotiated.
* @param initlocal - if set to true, a WILL is sent upon connection.
* @param initremote - if set to true, a DO is sent upon connection.
* @param acceptlocal - if set to true, any DO request is accepted.
* @param acceptremote - if set to true, any WILL request is accepted.
***/
public TerminalTypeOptionHandler(String termtype,
boolean initlocal,
boolean initremote,
boolean acceptlocal,
boolean acceptremote)
{
super(TelnetOption.TERMINAL_TYPE, initlocal, initremote,
acceptlocal, acceptremote);
termType = termtype;
}
/***
* Constructor for the TerminalTypeOptionHandler. Initial and accept
* behaviour flags are set to false
* <p>
* @param termtype - terminal type that will be negotiated.
***/
public TerminalTypeOptionHandler(String termtype)
{
super(TelnetOption.TERMINAL_TYPE, false, false, false, false);
termType = termtype;
}
/***
* Implements the abstract method of TelnetOptionHandler.
* <p>
* @param suboptionData - the sequence received, without IAC SB & IAC SE
* @param suboptionLength - the length of data in suboption_data
* <p>
* @return terminal type information
***/
@Override
public int[] answerSubnegotiation(int suboptionData[], int suboptionLength)
{
if ((suboptionData != null) && (suboptionLength > 1)
&& (termType != null))
{
if ((suboptionData[0] == TERMINAL_TYPE)
&& (suboptionData[1] == TERMINAL_TYPE_SEND))
{
int response[] = new int[termType.length() + 2];
response[0] = TERMINAL_TYPE;
response[1] = TERMINAL_TYPE_IS;
for (int ii = 0; ii < termType.length(); ii++)
{
response[ii + 2] = termType.charAt(ii);
}
return response;
}
}
return null;
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetOptionHandler.java | client/src/main/java/org/apache/commons/net/telnet/TelnetOptionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* The TelnetOptionHandler class is the base class to be used
* for implementing handlers for telnet options.
* <p>
* TelnetOptionHandler implements basic option handling
* functionality and defines abstract methods that must be
* implemented to define subnegotiation behaviour.
***/
public abstract class TelnetOptionHandler
{
/***
* Option code
***/
private int optionCode = -1;
/***
* true if the option should be activated on the local side
***/
private boolean initialLocal = false;
/***
* true if the option should be activated on the remote side
***/
private boolean initialRemote = false;
/***
* true if the option should be accepted on the local side
***/
private boolean acceptLocal = false;
/***
* true if the option should be accepted on the remote side
***/
private boolean acceptRemote = false;
/***
* true if the option is active on the local side
***/
private boolean doFlag = false;
/***
* true if the option is active on the remote side
***/
private boolean willFlag = false;
/***
* Constructor for the TelnetOptionHandler. Allows defining desired
* initial setting for local/remote activation of this option and
* behaviour in case a local/remote activation request for this
* option is received.
* <p>
* @param optcode - Option code.
* @param initlocal - if set to true, a WILL is sent upon connection.
* @param initremote - if set to true, a DO is sent upon connection.
* @param acceptlocal - if set to true, any DO request is accepted.
* @param acceptremote - if set to true, any WILL request is accepted.
***/
public TelnetOptionHandler(int optcode,
boolean initlocal,
boolean initremote,
boolean acceptlocal,
boolean acceptremote)
{
optionCode = optcode;
initialLocal = initlocal;
initialRemote = initremote;
acceptLocal = acceptlocal;
acceptRemote = acceptremote;
}
/***
* Returns the option code for this option.
* <p>
* @return Option code.
***/
public int getOptionCode()
{
return (optionCode);
}
/***
* Returns a boolean indicating whether to accept a DO
* request coming from the other end.
* <p>
* @return true if a DO request shall be accepted.
***/
public boolean getAcceptLocal()
{
return (acceptLocal);
}
/***
* Returns a boolean indicating whether to accept a WILL
* request coming from the other end.
* <p>
* @return true if a WILL request shall be accepted.
***/
public boolean getAcceptRemote()
{
return (acceptRemote);
}
/***
* Set behaviour of the option for DO requests coming from
* the other end.
* <p>
* @param accept - if true, subsequent DO requests will be accepted.
***/
public void setAcceptLocal(boolean accept)
{
acceptLocal = accept;
}
/***
* Set behaviour of the option for WILL requests coming from
* the other end.
* <p>
* @param accept - if true, subsequent WILL requests will be accepted.
***/
public void setAcceptRemote(boolean accept)
{
acceptRemote = accept;
}
/***
* Returns a boolean indicating whether to send a WILL request
* to the other end upon connection.
* <p>
* @return true if a WILL request shall be sent upon connection.
***/
public boolean getInitLocal()
{
return (initialLocal);
}
/***
* Returns a boolean indicating whether to send a DO request
* to the other end upon connection.
* <p>
* @return true if a DO request shall be sent upon connection.
***/
public boolean getInitRemote()
{
return (initialRemote);
}
/***
* Tells this option whether to send a WILL request upon connection.
* <p>
* @param init - if true, a WILL request will be sent upon subsequent
* connections.
***/
public void setInitLocal(boolean init)
{
initialLocal = init;
}
/***
* Tells this option whether to send a DO request upon connection.
* <p>
* @param init - if true, a DO request will be sent upon subsequent
* connections.
***/
public void setInitRemote(boolean init)
{
initialRemote = init;
}
/***
* Method called upon reception of a subnegotiation for this option
* coming from the other end.
* <p>
* This implementation returns null, and
* must be overridden by the actual TelnetOptionHandler to specify
* which response must be sent for the subnegotiation request.
* <p>
* @param suboptionData - the sequence received, without IAC SB & IAC SE
* @param suboptionLength - the length of data in suboption_data
* <p>
* @return response to be sent to the subnegotiation sequence. TelnetClient
* will add IAC SB & IAC SE. null means no response
***/
public int[] answerSubnegotiation(int suboptionData[], int suboptionLength) {
return null;
}
/***
* This method is invoked whenever this option is acknowledged active on
* the local end (TelnetClient sent a WILL, remote side sent a DO).
* The method is used to specify a subnegotiation sequence that will be
* sent by TelnetClient when the option is activated.
* <p>
* This implementation returns null, and must be overridden by
* the actual TelnetOptionHandler to specify
* which response must be sent for the subnegotiation request.
* @return subnegotiation sequence to be sent by TelnetClient. TelnetClient
* will add IAC SB & IAC SE. null means no subnegotiation.
***/
public int[] startSubnegotiationLocal() {
return null;
}
/***
* This method is invoked whenever this option is acknowledged active on
* the remote end (TelnetClient sent a DO, remote side sent a WILL).
* The method is used to specify a subnegotiation sequence that will be
* sent by TelnetClient when the option is activated.
* <p>
* This implementation returns null, and must be overridden by
* the actual TelnetOptionHandler to specify
* which response must be sent for the subnegotiation request.
* @return subnegotiation sequence to be sent by TelnetClient. TelnetClient
* will add IAC SB & IAC SE. null means no subnegotiation.
***/
public int[] startSubnegotiationRemote() {
return null;
}
/***
* Returns a boolean indicating whether a WILL request sent to the other
* side has been acknowledged.
* <p>
* @return true if a WILL sent to the other side has been acknowledged.
***/
boolean getWill()
{
return willFlag;
}
/***
* Tells this option whether a WILL request sent to the other
* side has been acknowledged (invoked by TelnetClient).
* <p>
* @param state - if true, a WILL request has been acknowledged.
***/
void setWill(boolean state)
{
willFlag = state;
}
/***
* Returns a boolean indicating whether a DO request sent to the other
* side has been acknowledged.
* <p>
* @return true if a DO sent to the other side has been acknowledged.
***/
boolean getDo()
{
return doFlag;
}
/***
* Tells this option whether a DO request sent to the other
* side has been acknowledged (invoked by TelnetClient).
* <p>
* @param state - if true, a DO request has been acknowledged.
***/
void setDo(boolean state)
{
doFlag = state;
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetCommand.java | client/src/main/java/org/apache/commons/net/telnet/TelnetCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/**
* The TelnetCommand class cannot be instantiated and only serves as a
* storehouse for telnet command constants.
* @see org.apache.commons.net.telnet.Telnet
* @see org.apache.commons.net.telnet.TelnetClient
*/
public final class TelnetCommand
{
/*** The maximum value a command code can have. This value is 255. ***/
public static final int MAX_COMMAND_VALUE = 255;
/*** Interpret As Command code. Value is 255 according to RFC 854. ***/
public static final int IAC = 255;
/*** Don't use option code. Value is 254 according to RFC 854. ***/
public static final int DONT = 254;
/*** Request to use option code. Value is 253 according to RFC 854. ***/
public static final int DO = 253;
/*** Refuse to use option code. Value is 252 according to RFC 854. ***/
public static final int WONT = 252;
/*** Agree to use option code. Value is 251 according to RFC 854. ***/
public static final int WILL = 251;
/*** Start subnegotiation code. Value is 250 according to RFC 854. ***/
public static final int SB = 250;
/*** Go Ahead code. Value is 249 according to RFC 854. ***/
public static final int GA = 249;
/*** Erase Line code. Value is 248 according to RFC 854. ***/
public static final int EL = 248;
/*** Erase Character code. Value is 247 according to RFC 854. ***/
public static final int EC = 247;
/*** Are You There code. Value is 246 according to RFC 854. ***/
public static final int AYT = 246;
/*** Abort Output code. Value is 245 according to RFC 854. ***/
public static final int AO = 245;
/*** Interrupt Process code. Value is 244 according to RFC 854. ***/
public static final int IP = 244;
/*** Break code. Value is 243 according to RFC 854. ***/
public static final int BREAK = 243;
/*** Data mark code. Value is 242 according to RFC 854. ***/
public static final int DM = 242;
/*** No Operation code. Value is 241 according to RFC 854. ***/
public static final int NOP = 241;
/*** End subnegotiation code. Value is 240 according to RFC 854. ***/
public static final int SE = 240;
/*** End of record code. Value is 239. ***/
public static final int EOR = 239;
/*** Abort code. Value is 238. ***/
public static final int ABORT = 238;
/*** Suspend process code. Value is 237. ***/
public static final int SUSP = 237;
/*** End of file code. Value is 236. ***/
public static final int EOF = 236;
/*** Synchronize code. Value is 242. ***/
public static final int SYNCH = 242;
/*** String representations of commands. ***/
private static final String __commandString[] = {
"IAC", "DONT", "DO", "WONT", "WILL", "SB", "GA", "EL", "EC", "AYT",
"AO", "IP", "BRK", "DMARK", "NOP", "SE", "EOR", "ABORT", "SUSP", "EOF"
};
private static final int __FIRST_COMMAND = IAC;
private static final int __LAST_COMMAND = EOF;
/***
* Returns the string representation of the telnet protocol command
* corresponding to the given command code.
* <p>
* @param code The command code of the telnet protocol command.
* @return The string representation of the telnet protocol command.
***/
public static final String getCommand(int code)
{
return __commandString[__FIRST_COMMAND - code];
}
/***
* Determines if a given command code is valid. Returns true if valid,
* false if not.
* <p>
* @param code The command code to test.
* @return True if the command code is valid, false if not.
**/
public static final boolean isValidCommand(int code)
{
return (code <= __FIRST_COMMAND && code >= __LAST_COMMAND);
}
// Cannot be instantiated
private TelnetCommand()
{ }
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetInputListener.java | client/src/main/java/org/apache/commons/net/telnet/TelnetInputListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* Listener interface used for notification that incoming data is
* available to be read.
*
* @see TelnetClient
* @since 3.0
***/
public interface TelnetInputListener
{
/***
* Callback method invoked when new incoming data is available on a
* {@link TelnetClient}'s {@link TelnetClient#getInputStream input stream}.
*
* @see TelnetClient#registerInputListener
***/
public void telnetInputAvailable();
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/Telnet.java | client/src/main/java/org/apache/commons/net/telnet/Telnet.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.net.SocketClient;
class Telnet extends SocketClient
{
static final boolean debug = /*true;*/ false;
static final boolean debugoptions = /*true;*/ false;
static final byte[] _COMMAND_DO = {
(byte)TelnetCommand.IAC, (byte)TelnetCommand.DO
};
static final byte[] _COMMAND_DONT = {
(byte)TelnetCommand.IAC, (byte)TelnetCommand.DONT
};
static final byte[] _COMMAND_WILL = {
(byte)TelnetCommand.IAC, (byte)TelnetCommand.WILL
};
static final byte[] _COMMAND_WONT = {
(byte)TelnetCommand.IAC, (byte)TelnetCommand.WONT
};
static final byte[] _COMMAND_SB = {
(byte)TelnetCommand.IAC, (byte)TelnetCommand.SB
};
static final byte[] _COMMAND_SE = {
(byte)TelnetCommand.IAC, (byte)TelnetCommand.SE
};
static final int _WILL_MASK = 0x01, _DO_MASK = 0x02,
_REQUESTED_WILL_MASK = 0x04, _REQUESTED_DO_MASK = 0x08;
/* public */
static final int DEFAULT_PORT = 23;
int[] _doResponse, _willResponse, _options;
/* TERMINAL-TYPE option (start)*/
/***
* Terminal type option
***/
protected static final int TERMINAL_TYPE = 24;
/***
* Send (for subnegotiation)
***/
protected static final int TERMINAL_TYPE_SEND = 1;
/***
* Is (for subnegotiation)
***/
protected static final int TERMINAL_TYPE_IS = 0;
/***
* Is sequence (for subnegotiation)
***/
static final byte[] _COMMAND_IS = {
(byte) TERMINAL_TYPE, (byte) TERMINAL_TYPE_IS
};
/***
* Terminal type
***/
private String terminalType = null;
/* TERMINAL-TYPE option (end)*/
/* open TelnetOptionHandler functionality (start)*/
/***
* Array of option handlers
***/
private final TelnetOptionHandler optionHandlers[];
/* open TelnetOptionHandler functionality (end)*/
/* Code Section added for supporting AYT (start)*/
/***
* AYT sequence
***/
static final byte[] _COMMAND_AYT = {
(byte) TelnetCommand.IAC, (byte) TelnetCommand.AYT
};
/***
* monitor to wait for AYT
***/
private final Object aytMonitor = new Object();
/***
* flag for AYT
***/
private volatile boolean aytFlag = true;
/* Code Section added for supporting AYT (end)*/
/***
* The stream on which to spy
***/
private volatile OutputStream spyStream = null;
/***
* The notification handler
***/
private TelnetNotificationHandler __notifhand = null;
/***
* Empty Constructor
***/
Telnet()
{
setDefaultPort(DEFAULT_PORT);
_doResponse = new int[TelnetOption.MAX_OPTION_VALUE + 1];
_willResponse = new int[TelnetOption.MAX_OPTION_VALUE + 1];
_options = new int[TelnetOption.MAX_OPTION_VALUE + 1];
optionHandlers =
new TelnetOptionHandler[TelnetOption.MAX_OPTION_VALUE + 1];
}
/* TERMINAL-TYPE option (start)*/
/***
* This constructor lets you specify the terminal type.
*
* @param termtype - terminal type to be negotiated (ej. VT100)
***/
Telnet(String termtype)
{
setDefaultPort(DEFAULT_PORT);
_doResponse = new int[TelnetOption.MAX_OPTION_VALUE + 1];
_willResponse = new int[TelnetOption.MAX_OPTION_VALUE + 1];
_options = new int[TelnetOption.MAX_OPTION_VALUE + 1];
terminalType = termtype;
optionHandlers =
new TelnetOptionHandler[TelnetOption.MAX_OPTION_VALUE + 1];
}
/* TERMINAL-TYPE option (end)*/
/***
* Looks for the state of the option.
*
* @return returns true if a will has been acknowledged
*
* @param option - option code to be looked up.
***/
boolean _stateIsWill(int option)
{
return ((_options[option] & _WILL_MASK) != 0);
}
/***
* Looks for the state of the option.
*
* @return returns true if a wont has been acknowledged
*
* @param option - option code to be looked up.
***/
boolean _stateIsWont(int option)
{
return !_stateIsWill(option);
}
/***
* Looks for the state of the option.
*
* @return returns true if a do has been acknowledged
*
* @param option - option code to be looked up.
***/
boolean _stateIsDo(int option)
{
return ((_options[option] & _DO_MASK) != 0);
}
/***
* Looks for the state of the option.
*
* @return returns true if a dont has been acknowledged
*
* @param option - option code to be looked up.
***/
boolean _stateIsDont(int option)
{
return !_stateIsDo(option);
}
/***
* Looks for the state of the option.
*
* @return returns true if a will has been reuqested
*
* @param option - option code to be looked up.
***/
boolean _requestedWill(int option)
{
return ((_options[option] & _REQUESTED_WILL_MASK) != 0);
}
/***
* Looks for the state of the option.
*
* @return returns true if a wont has been reuqested
*
* @param option - option code to be looked up.
***/
boolean _requestedWont(int option)
{
return !_requestedWill(option);
}
/***
* Looks for the state of the option.
*
* @return returns true if a do has been reuqested
*
* @param option - option code to be looked up.
***/
boolean _requestedDo(int option)
{
return ((_options[option] & _REQUESTED_DO_MASK) != 0);
}
/***
* Looks for the state of the option.
*
* @return returns true if a dont has been reuqested
*
* @param option - option code to be looked up.
***/
boolean _requestedDont(int option)
{
return !_requestedDo(option);
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
* @throws IOException
***/
void _setWill(int option) throws IOException
{
_options[option] |= _WILL_MASK;
/* open TelnetOptionHandler functionality (start)*/
if (_requestedWill(option))
{
if (optionHandlers[option] != null)
{
optionHandlers[option].setWill(true);
int subneg[] =
optionHandlers[option].startSubnegotiationLocal();
if (subneg != null)
{
_sendSubnegotiation(subneg);
}
}
}
/* open TelnetOptionHandler functionality (end)*/
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
* @throws IOException
***/
void _setDo(int option) throws IOException
{
_options[option] |= _DO_MASK;
/* open TelnetOptionHandler functionality (start)*/
if (_requestedDo(option))
{
if (optionHandlers[option] != null)
{
optionHandlers[option].setDo(true);
int subneg[] =
optionHandlers[option].startSubnegotiationRemote();
if (subneg != null)
{
_sendSubnegotiation(subneg);
}
}
}
/* open TelnetOptionHandler functionality (end)*/
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
***/
void _setWantWill(int option)
{
_options[option] |= _REQUESTED_WILL_MASK;
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
***/
void _setWantDo(int option)
{
_options[option] |= _REQUESTED_DO_MASK;
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
***/
void _setWont(int option)
{
_options[option] &= ~_WILL_MASK;
/* open TelnetOptionHandler functionality (start)*/
if (optionHandlers[option] != null)
{
optionHandlers[option].setWill(false);
}
/* open TelnetOptionHandler functionality (end)*/
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
***/
void _setDont(int option)
{
_options[option] &= ~_DO_MASK;
/* open TelnetOptionHandler functionality (start)*/
if (optionHandlers[option] != null)
{
optionHandlers[option].setDo(false);
}
/* open TelnetOptionHandler functionality (end)*/
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
***/
void _setWantWont(int option)
{
_options[option] &= ~_REQUESTED_WILL_MASK;
}
/***
* Sets the state of the option.
*
* @param option - option code to be set.
***/
void _setWantDont(int option)
{
_options[option] &= ~_REQUESTED_DO_MASK;
}
/**
* Processes a COMMAND.
*
* @param command - option code to be set.
**/
void _processCommand(int command)
{
if (debugoptions)
{
System.err.println("RECEIVED COMMAND: " + command);
}
if (__notifhand != null)
{
__notifhand.receivedNegotiation(
TelnetNotificationHandler.RECEIVED_COMMAND, command);
}
}
/**
* Processes a DO request.
*
* @param option - option code to be set.
* @throws IOException - Exception in I/O.
**/
void _processDo(int option) throws IOException
{
if (debugoptions)
{
System.err.println("RECEIVED DO: "
+ TelnetOption.getOption(option));
}
if (__notifhand != null)
{
__notifhand.receivedNegotiation(
TelnetNotificationHandler.RECEIVED_DO,
option);
}
boolean acceptNewState = false;
/* open TelnetOptionHandler functionality (start)*/
if (optionHandlers[option] != null)
{
acceptNewState = optionHandlers[option].getAcceptLocal();
}
else
{
/* open TelnetOptionHandler functionality (end)*/
/* TERMINAL-TYPE option (start)*/
if (option == TERMINAL_TYPE)
{
if ((terminalType != null) && (terminalType.length() > 0))
{
acceptNewState = true;
}
}
/* TERMINAL-TYPE option (end)*/
/* open TelnetOptionHandler functionality (start)*/
}
/* open TelnetOptionHandler functionality (end)*/
if (_willResponse[option] > 0)
{
--_willResponse[option];
if (_willResponse[option] > 0 && _stateIsWill(option))
{
--_willResponse[option];
}
}
if (_willResponse[option] == 0)
{
if (_requestedWont(option))
{
switch (option)
{
default:
break;
}
if (acceptNewState)
{
_setWantWill(option);
_sendWill(option);
}
else
{
++_willResponse[option];
_sendWont(option);
}
}
else
{
// Other end has acknowledged option.
switch (option)
{
default:
break;
}
}
}
_setWill(option);
}
/**
* Processes a DONT request.
*
* @param option - option code to be set.
* @throws IOException - Exception in I/O.
**/
void _processDont(int option) throws IOException
{
if (debugoptions)
{
System.err.println("RECEIVED DONT: "
+ TelnetOption.getOption(option));
}
if (__notifhand != null)
{
__notifhand.receivedNegotiation(
TelnetNotificationHandler.RECEIVED_DONT,
option);
}
if (_willResponse[option] > 0)
{
--_willResponse[option];
if (_willResponse[option] > 0 && _stateIsWont(option))
{
--_willResponse[option];
}
}
if (_willResponse[option] == 0 && _requestedWill(option))
{
switch (option)
{
default:
break;
}
/* FIX for a BUG in the negotiation (start)*/
if ((_stateIsWill(option)) || (_requestedWill(option)))
{
_sendWont(option);
}
_setWantWont(option);
/* FIX for a BUG in the negotiation (end)*/
}
_setWont(option);
}
/**
* Processes a WILL request.
*
* @param option - option code to be set.
* @throws IOException - Exception in I/O.
**/
void _processWill(int option) throws IOException
{
if (debugoptions)
{
System.err.println("RECEIVED WILL: "
+ TelnetOption.getOption(option));
}
if (__notifhand != null)
{
__notifhand.receivedNegotiation(
TelnetNotificationHandler.RECEIVED_WILL,
option);
}
boolean acceptNewState = false;
/* open TelnetOptionHandler functionality (start)*/
if (optionHandlers[option] != null)
{
acceptNewState = optionHandlers[option].getAcceptRemote();
}
/* open TelnetOptionHandler functionality (end)*/
if (_doResponse[option] > 0)
{
--_doResponse[option];
if (_doResponse[option] > 0 && _stateIsDo(option))
{
--_doResponse[option];
}
}
if (_doResponse[option] == 0 && _requestedDont(option))
{
switch (option)
{
default:
break;
}
if (acceptNewState)
{
_setWantDo(option);
_sendDo(option);
}
else
{
++_doResponse[option];
_sendDont(option);
}
}
_setDo(option);
}
/**
* Processes a WONT request.
*
* @param option - option code to be set.
* @throws IOException - Exception in I/O.
**/
void _processWont(int option) throws IOException
{
if (debugoptions)
{
System.err.println("RECEIVED WONT: "
+ TelnetOption.getOption(option));
}
if (__notifhand != null)
{
__notifhand.receivedNegotiation(
TelnetNotificationHandler.RECEIVED_WONT,
option);
}
if (_doResponse[option] > 0)
{
--_doResponse[option];
if (_doResponse[option] > 0 && _stateIsDont(option))
{
--_doResponse[option];
}
}
if (_doResponse[option] == 0 && _requestedDo(option))
{
switch (option)
{
default:
break;
}
/* FIX for a BUG in the negotiation (start)*/
if ((_stateIsDo(option)) || (_requestedDo(option)))
{
_sendDont(option);
}
_setWantDont(option);
/* FIX for a BUG in the negotiation (end)*/
}
_setDont(option);
}
/* TERMINAL-TYPE option (start)*/
/**
* Processes a suboption negotiation.
*
* @param suboption - subnegotiation data received
* @param suboptionLength - length of data received
* @throws IOException - Exception in I/O.
**/
void _processSuboption(int suboption[], int suboptionLength)
throws IOException
{
if (debug)
{
System.err.println("PROCESS SUBOPTION.");
}
/* open TelnetOptionHandler functionality (start)*/
if (suboptionLength > 0)
{
if (optionHandlers[suboption[0]] != null)
{
int responseSuboption[] =
optionHandlers[suboption[0]].answerSubnegotiation(suboption,
suboptionLength);
_sendSubnegotiation(responseSuboption);
}
else
{
if (suboptionLength > 1)
{
if (debug)
{
for (int ii = 0; ii < suboptionLength; ii++)
{
System.err.println("SUB[" + ii + "]: "
+ suboption[ii]);
}
}
if ((suboption[0] == TERMINAL_TYPE)
&& (suboption[1] == TERMINAL_TYPE_SEND))
{
_sendTerminalType();
}
}
}
}
/* open TelnetOptionHandler functionality (end)*/
}
/***
* Sends terminal type information.
*
* @throws IOException - Exception in I/O.
***/
final synchronized void _sendTerminalType()
throws IOException
{
if (debug)
{
System.err.println("SEND TERMINAL-TYPE: " + terminalType);
}
if (terminalType != null)
{
_output_.write(_COMMAND_SB);
_output_.write(_COMMAND_IS);
_output_.write(terminalType.getBytes(getCharset()));
_output_.write(_COMMAND_SE);
_output_.flush();
}
}
/* TERMINAL-TYPE option (end)*/
/* open TelnetOptionHandler functionality (start)*/
/**
* Manages subnegotiation for Terminal Type.
*
* @param subn - subnegotiation data to be sent
* @throws IOException - Exception in I/O.
**/
final synchronized void _sendSubnegotiation(int subn[])
throws IOException
{
if (debug)
{
System.err.println("SEND SUBNEGOTIATION: ");
if (subn != null)
{
System.err.println(Arrays.toString(subn));
}
}
if (subn != null)
{
_output_.write(_COMMAND_SB);
// Note _output_ is buffered, so might as well simplify by writing single bytes
for (int element : subn)
{
byte b = (byte) element;
if (b == (byte) TelnetCommand.IAC) { // cast is necessary because IAC is outside the signed byte range
_output_.write(b); // double any IAC bytes
}
_output_.write(b);
}
_output_.write(_COMMAND_SE);
/* Code Section added for sending the negotiation ASAP (start)*/
_output_.flush();
/* Code Section added for sending the negotiation ASAP (end)*/
}
}
/* open TelnetOptionHandler functionality (end)*/
/**
* Sends a command, automatically adds IAC prefix and flushes the output.
*
* @param cmd - command data to be sent
* @throws IOException - Exception in I/O.
* @since 3.0
*/
final synchronized void _sendCommand(byte cmd) throws IOException
{
_output_.write(TelnetCommand.IAC);
_output_.write(cmd);
_output_.flush();
}
/* Code Section added for supporting AYT (start)*/
/***
* Processes the response of an AYT
***/
final synchronized void _processAYTResponse()
{
if (!aytFlag)
{
synchronized (aytMonitor)
{
aytFlag = true;
aytMonitor.notifyAll();
}
}
}
/* Code Section added for supporting AYT (end)*/
/***
* Called upon connection.
*
* @throws IOException - Exception in I/O.
***/
@Override
protected void _connectAction_() throws IOException
{
/* (start). BUGFIX: clean the option info for each connection*/
for (int ii = 0; ii < TelnetOption.MAX_OPTION_VALUE + 1; ii++)
{
_doResponse[ii] = 0;
_willResponse[ii] = 0;
_options[ii] = 0;
if (optionHandlers[ii] != null)
{
optionHandlers[ii].setDo(false);
optionHandlers[ii].setWill(false);
}
}
/* (end). BUGFIX: clean the option info for each connection*/
super._connectAction_();
_input_ = new BufferedInputStream(_input_);
_output_ = new BufferedOutputStream(_output_);
/* open TelnetOptionHandler functionality (start)*/
for (int ii = 0; ii < TelnetOption.MAX_OPTION_VALUE + 1; ii++)
{
if (optionHandlers[ii] != null)
{
if (optionHandlers[ii].getInitLocal())
{
_requestWill(optionHandlers[ii].getOptionCode());
}
if (optionHandlers[ii].getInitRemote())
{
_requestDo(optionHandlers[ii].getOptionCode());
}
}
}
/* open TelnetOptionHandler functionality (end)*/
}
/**
* Sends a DO.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _sendDo(int option)
throws IOException
{
if (debug || debugoptions)
{
System.err.println("DO: " + TelnetOption.getOption(option));
}
_output_.write(_COMMAND_DO);
_output_.write(option);
/* Code Section added for sending the negotiation ASAP (start)*/
_output_.flush();
/* Code Section added for sending the negotiation ASAP (end)*/
}
/**
* Requests a DO.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _requestDo(int option)
throws IOException
{
if ((_doResponse[option] == 0 && _stateIsDo(option))
|| _requestedDo(option))
{
return ;
}
_setWantDo(option);
++_doResponse[option];
_sendDo(option);
}
/**
* Sends a DONT.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _sendDont(int option)
throws IOException
{
if (debug || debugoptions)
{
System.err.println("DONT: " + TelnetOption.getOption(option));
}
_output_.write(_COMMAND_DONT);
_output_.write(option);
/* Code Section added for sending the negotiation ASAP (start)*/
_output_.flush();
/* Code Section added for sending the negotiation ASAP (end)*/
}
/**
* Requests a DONT.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _requestDont(int option)
throws IOException
{
if ((_doResponse[option] == 0 && _stateIsDont(option))
|| _requestedDont(option))
{
return ;
}
_setWantDont(option);
++_doResponse[option];
_sendDont(option);
}
/**
* Sends a WILL.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _sendWill(int option)
throws IOException
{
if (debug || debugoptions)
{
System.err.println("WILL: " + TelnetOption.getOption(option));
}
_output_.write(_COMMAND_WILL);
_output_.write(option);
/* Code Section added for sending the negotiation ASAP (start)*/
_output_.flush();
/* Code Section added for sending the negotiation ASAP (end)*/
}
/**
* Requests a WILL.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _requestWill(int option)
throws IOException
{
if ((_willResponse[option] == 0 && _stateIsWill(option))
|| _requestedWill(option))
{
return ;
}
_setWantWill(option);
++_doResponse[option];
_sendWill(option);
}
/**
* Sends a WONT.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _sendWont(int option)
throws IOException
{
if (debug || debugoptions)
{
System.err.println("WONT: " + TelnetOption.getOption(option));
}
_output_.write(_COMMAND_WONT);
_output_.write(option);
/* Code Section added for sending the negotiation ASAP (start)*/
_output_.flush();
/* Code Section added for sending the negotiation ASAP (end)*/
}
/**
* Requests a WONT.
*
* @param option - Option code.
* @throws IOException - Exception in I/O.
**/
final synchronized void _requestWont(int option)
throws IOException
{
if ((_willResponse[option] == 0 && _stateIsWont(option))
|| _requestedWont(option))
{
return ;
}
_setWantWont(option);
++_doResponse[option];
_sendWont(option);
}
/**
* Sends a byte.
*
* @param b - byte to send
* @throws IOException - Exception in I/O.
**/
final synchronized void _sendByte(int b)
throws IOException
{
_output_.write(b);
/* Code Section added for supporting spystreams (start)*/
_spyWrite(b);
/* Code Section added for supporting spystreams (end)*/
}
/* Code Section added for supporting AYT (start)*/
/**
* Sends an Are You There sequence and waits for the result.
*
* @param timeout - Time to wait for a response (millis.)
* @throws IOException - Exception in I/O.
* @throws IllegalArgumentException - Illegal argument
* @throws InterruptedException - Interrupted during wait.
* @return true if AYT received a response, false otherwise
**/
final boolean _sendAYT(long timeout)
throws IOException, IllegalArgumentException, InterruptedException
{
boolean retValue = false;
synchronized (aytMonitor)
{
synchronized (this)
{
aytFlag = false;
_output_.write(_COMMAND_AYT);
_output_.flush();
}
aytMonitor.wait(timeout);
if (!aytFlag)
{
retValue = false;
aytFlag = true;
}
else
{
retValue = true;
}
}
return (retValue);
}
/* Code Section added for supporting AYT (end)*/
/* open TelnetOptionHandler functionality (start)*/
/**
* Registers a new TelnetOptionHandler for this telnet to use.
*
* @param opthand - option handler to be registered.
* @throws InvalidTelnetOptionException - The option code is invalid.
* @throws IOException on error
**/
void addOptionHandler(TelnetOptionHandler opthand)
throws InvalidTelnetOptionException, IOException
{
int optcode = opthand.getOptionCode();
if (TelnetOption.isValidOption(optcode))
{
if (optionHandlers[optcode] == null)
{
optionHandlers[optcode] = opthand;
if (isConnected())
{
if (opthand.getInitLocal())
{
_requestWill(optcode);
}
if (opthand.getInitRemote())
{
_requestDo(optcode);
}
}
}
else
{
throw (new InvalidTelnetOptionException(
"Already registered option", optcode));
}
}
else
{
throw (new InvalidTelnetOptionException(
"Invalid Option Code", optcode));
}
}
/**
* Unregisters a TelnetOptionHandler.
*
* @param optcode - Code of the option to be unregistered.
* @throws InvalidTelnetOptionException - The option code is invalid.
* @throws IOException on error
**/
void deleteOptionHandler(int optcode)
throws InvalidTelnetOptionException, IOException
{
if (TelnetOption.isValidOption(optcode))
{
if (optionHandlers[optcode] == null)
{
throw (new InvalidTelnetOptionException(
"Unregistered option", optcode));
}
else
{
TelnetOptionHandler opthand = optionHandlers[optcode];
optionHandlers[optcode] = null;
if (opthand.getWill())
{
_requestWont(optcode);
}
if (opthand.getDo())
{
_requestDont(optcode);
}
}
}
else
{
throw (new InvalidTelnetOptionException(
"Invalid Option Code", optcode));
}
}
/* open TelnetOptionHandler functionality (end)*/
/* Code Section added for supporting spystreams (start)*/
/***
* Registers an OutputStream for spying what's going on in
* the Telnet session.
*
* @param spystream - OutputStream on which session activity
* will be echoed.
***/
void _registerSpyStream(OutputStream spystream)
{
spyStream = spystream;
}
/***
* Stops spying this Telnet.
*
***/
void _stopSpyStream()
{
spyStream = null;
}
/***
* Sends a read char on the spy stream.
*
* @param ch - character read from the session
***/
void _spyRead(int ch)
{
OutputStream spy = spyStream;
if (spy != null)
{
try
{
if (ch != '\r') // never write '\r' on its own
{
if (ch == '\n')
{
spy.write('\r'); // add '\r' before '\n'
}
spy.write(ch); // write original character
spy.flush();
}
}
catch (IOException e)
{
spyStream = null;
}
}
}
/***
* Sends a written char on the spy stream.
*
* @param ch - character written to the session
***/
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | true |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetOption.java | client/src/main/java/org/apache/commons/net/telnet/TelnetOption.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* The TelnetOption class cannot be instantiated and only serves as a
* storehouse for telnet option constants.
* <p>
* Details regarding Telnet option specification can be found in RFC 855.
*
*
* @see org.apache.commons.net.telnet.Telnet
* @see org.apache.commons.net.telnet.TelnetClient
***/
public class TelnetOption
{
/*** The maximum value an option code can have. This value is 255. ***/
public static final int MAX_OPTION_VALUE = 255;
public static final int BINARY = 0;
public static final int ECHO = 1;
public static final int PREPARE_TO_RECONNECT = 2;
public static final int SUPPRESS_GO_AHEAD = 3;
public static final int APPROXIMATE_MESSAGE_SIZE = 4;
public static final int STATUS = 5;
public static final int TIMING_MARK = 6;
public static final int REMOTE_CONTROLLED_TRANSMISSION = 7;
public static final int NEGOTIATE_OUTPUT_LINE_WIDTH = 8;
public static final int NEGOTIATE_OUTPUT_PAGE_SIZE = 9;
public static final int NEGOTIATE_CARRIAGE_RETURN = 10;
public static final int NEGOTIATE_HORIZONTAL_TAB_STOP = 11;
public static final int NEGOTIATE_HORIZONTAL_TAB = 12;
public static final int NEGOTIATE_FORMFEED = 13;
public static final int NEGOTIATE_VERTICAL_TAB_STOP = 14;
public static final int NEGOTIATE_VERTICAL_TAB = 15;
public static final int NEGOTIATE_LINEFEED = 16;
public static final int EXTENDED_ASCII = 17;
public static final int FORCE_LOGOUT = 18;
public static final int BYTE_MACRO = 19;
public static final int DATA_ENTRY_TERMINAL = 20;
public static final int SUPDUP = 21;
public static final int SUPDUP_OUTPUT = 22;
public static final int SEND_LOCATION = 23;
public static final int TERMINAL_TYPE = 24;
public static final int END_OF_RECORD = 25;
public static final int TACACS_USER_IDENTIFICATION = 26;
public static final int OUTPUT_MARKING = 27;
public static final int TERMINAL_LOCATION_NUMBER = 28;
public static final int REGIME_3270 = 29;
public static final int X3_PAD = 30;
public static final int WINDOW_SIZE = 31;
public static final int TERMINAL_SPEED = 32;
public static final int REMOTE_FLOW_CONTROL = 33;
public static final int LINEMODE = 34;
public static final int X_DISPLAY_LOCATION = 35;
public static final int OLD_ENVIRONMENT_VARIABLES = 36;
public static final int AUTHENTICATION = 37;
public static final int ENCRYPTION = 38;
public static final int NEW_ENVIRONMENT_VARIABLES = 39;
public static final int EXTENDED_OPTIONS_LIST = 255;
@SuppressWarnings("unused")
private static final int __FIRST_OPTION = BINARY;
private static final int __LAST_OPTION = EXTENDED_OPTIONS_LIST;
private static final String __optionString[] = {
"BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAME", "STATUS",
"TIMING MARK", "RCTE", "NAOL", "NAOP", "NAOCRD", "NAOHTS", "NAOHTD",
"NAOFFD", "NAOVTS", "NAOVTD", "NAOLFD", "EXTEND ASCII", "LOGOUT",
"BYTE MACRO", "DATA ENTRY TERMINAL", "SUPDUP", "SUPDUP OUTPUT",
"SEND LOCATION", "TERMINAL TYPE", "END OF RECORD", "TACACS UID",
"OUTPUT MARKING", "TTYLOC", "3270 REGIME", "X.3 PAD", "NAWS", "TSPEED",
"LFLOW", "LINEMODE", "XDISPLOC", "OLD-ENVIRON", "AUTHENTICATION",
"ENCRYPT", "NEW-ENVIRON", "TN3270E", "XAUTH", "CHARSET", "RSP",
"Com Port Control", "Suppress Local Echo", "Start TLS",
"KERMIT", "SEND-URL", "FORWARD_X", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "TELOPT PRAGMA LOGON", "TELOPT SSPI LOGON",
"TELOPT PRAGMA HEARTBEAT", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"Extended-Options-List"
};
/***
* Returns the string representation of the telnet protocol option
* corresponding to the given option code.
*
* @param code The option code of the telnet protocol option
* @return The string representation of the telnet protocol option.
***/
public static final String getOption(int code)
{
if(__optionString[code].length() == 0)
{
return "UNASSIGNED";
}
else
{
return __optionString[code];
}
}
/***
* Determines if a given option code is valid. Returns true if valid,
* false if not.
*
* @param code The option code to test.
* @return True if the option code is valid, false if not.
**/
public static final boolean isValidOption(int code)
{
return (code <= __LAST_OPTION);
}
// Cannot be instantiated
private TelnetOption()
{ }
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetClient.java | client/src/main/java/org/apache/commons/net/telnet/TelnetClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/***
* The TelnetClient class implements the simple network virtual
* terminal (NVT) for the Telnet protocol according to RFC 854. It
* does not implement any of the extra Telnet options because it
* is meant to be used within a Java program providing automated
* access to Telnet accessible resources.
* <p>
* The class can be used by first connecting to a server using the
* SocketClient
* {@link org.apache.commons.net.SocketClient#connect connect}
* method. Then an InputStream and OutputStream for sending and
* receiving data over the Telnet connection can be obtained by
* using the {@link #getInputStream getInputStream() } and
* {@link #getOutputStream getOutputStream() } methods.
* When you finish using the streams, you must call
* {@link #disconnect disconnect } rather than simply
* closing the streams.
***/
public class TelnetClient extends Telnet
{
private InputStream __input;
private OutputStream __output;
protected boolean readerThread = true;
private TelnetInputListener inputListener;
/***
* Default TelnetClient constructor, sets terminal-type {@code VT100}.
***/
public TelnetClient()
{
/* TERMINAL-TYPE option (start)*/
super ("VT100");
/* TERMINAL-TYPE option (end)*/
__input = null;
__output = null;
}
/**
* Construct an instance with the specified terminal type.
*
* @param termtype the terminal type to use, e.g. {@code VT100}
*/
/* TERMINAL-TYPE option (start)*/
public TelnetClient(String termtype)
{
super (termtype);
__input = null;
__output = null;
}
/* TERMINAL-TYPE option (end)*/
void _flushOutputStream() throws IOException
{
_output_.flush();
}
void _closeOutputStream() throws IOException
{
_output_.close();
}
/***
* Handles special connection requirements.
*
* @exception IOException If an error occurs during connection setup.
***/
@Override
protected void _connectAction_() throws IOException
{
super._connectAction_();
TelnetInputStream tmp = new TelnetInputStream(_input_, this, readerThread);
if(readerThread)
{
tmp._start();
}
// __input CANNOT refer to the TelnetInputStream. We run into
// blocking problems when some classes use TelnetInputStream, so
// we wrap it with a BufferedInputStream which we know is safe.
// This blocking behavior requires further investigation, but right
// now it looks like classes like InputStreamReader are not implemented
// in a safe manner.
__input = new BufferedInputStream(tmp);
__output = new TelnetOutputStream(this);
}
/***
* Disconnects the telnet session, closing the input and output streams
* as well as the socket. If you have references to the
* input and output streams of the telnet connection, you should not
* close them yourself, but rather call disconnect to properly close
* the connection.
***/
@Override
public void disconnect() throws IOException
{
if (__input != null) {
__input.close();
}
if (__output != null) {
__output.close();
}
super.disconnect();
}
/***
* Returns the telnet connection output stream. You should not close the
* stream when you finish with it. Rather, you should call
* {@link #disconnect disconnect }.
*
* @return The telnet connection output stream.
***/
public OutputStream getOutputStream()
{
return __output;
}
/***
* Returns the telnet connection input stream. You should not close the
* stream when you finish with it. Rather, you should call
* {@link #disconnect disconnect }.
*
* @return The telnet connection input stream.
***/
public InputStream getInputStream()
{
return __input;
}
/***
* Returns the state of the option on the local side.
*
* @param option - Option to be checked.
*
* @return The state of the option on the local side.
***/
public boolean getLocalOptionState(int option)
{
/* BUG (option active when not already acknowledged) (start)*/
return (_stateIsWill(option) && _requestedWill(option));
/* BUG (option active when not already acknowledged) (end)*/
}
/***
* Returns the state of the option on the remote side.
*
* @param option - Option to be checked.
*
* @return The state of the option on the remote side.
***/
public boolean getRemoteOptionState(int option)
{
/* BUG (option active when not already acknowledged) (start)*/
return (_stateIsDo(option) && _requestedDo(option));
/* BUG (option active when not already acknowledged) (end)*/
}
/* open TelnetOptionHandler functionality (end)*/
/* Code Section added for supporting AYT (start)*/
/***
* Sends an Are You There sequence and waits for the result.
*
* @param timeout - Time to wait for a response (millis.)
*
* @return true if AYT received a response, false otherwise
*
* @throws InterruptedException on error
* @throws IllegalArgumentException on error
* @throws IOException on error
***/
public boolean sendAYT(long timeout)
throws IOException, IllegalArgumentException, InterruptedException
{
return (_sendAYT(timeout));
}
/* Code Section added for supporting AYT (start)*/
/***
* Sends a protocol-specific subnegotiation message to the remote peer.
* {@link TelnetClient} will add the IAC SB & IAC SE framing bytes;
* the first byte in {@code message} should be the appropriate telnet
* option code.
*
* <p>
* This method does not wait for any response. Subnegotiation messages
* sent by the remote end can be handled by registering an approrpriate
* {@link TelnetOptionHandler}.
* </p>
*
* @param message option code followed by subnegotiation payload
* @throws IllegalArgumentException if {@code message} has length zero
* @throws IOException if an I/O error occurs while writing the message
* @since 3.0
***/
public void sendSubnegotiation(int[] message)
throws IOException, IllegalArgumentException
{
if (message.length < 1) {
throw new IllegalArgumentException("zero length message");
}
_sendSubnegotiation(message);
}
/***
* Sends a command byte to the remote peer, adding the IAC prefix.
*
* <p>
* This method does not wait for any response. Messages
* sent by the remote end can be handled by registering an approrpriate
* {@link TelnetOptionHandler}.
* </p>
*
* @param command the code for the command
* @throws IOException if an I/O error occurs while writing the message
* @throws IllegalArgumentException on error
* @since 3.0
***/
public void sendCommand(byte command)
throws IOException, IllegalArgumentException
{
_sendCommand(command);
}
/* open TelnetOptionHandler functionality (start)*/
/***
* Registers a new TelnetOptionHandler for this telnet client to use.
*
* @param opthand - option handler to be registered.
*
* @throws InvalidTelnetOptionException on error
* @throws IOException on error
***/
@Override
public void addOptionHandler(TelnetOptionHandler opthand)
throws InvalidTelnetOptionException, IOException
{
super.addOptionHandler(opthand);
}
/* open TelnetOptionHandler functionality (end)*/
/***
* Unregisters a TelnetOptionHandler.
*
* @param optcode - Code of the option to be unregistered.
*
* @throws InvalidTelnetOptionException on error
* @throws IOException on error
***/
@Override
public void deleteOptionHandler(int optcode)
throws InvalidTelnetOptionException, IOException
{
super.deleteOptionHandler(optcode);
}
/* Code Section added for supporting spystreams (start)*/
/***
* Registers an OutputStream for spying what's going on in
* the TelnetClient session.
*
* @param spystream - OutputStream on which session activity
* will be echoed.
***/
public void registerSpyStream(OutputStream spystream)
{
super._registerSpyStream(spystream);
}
/***
* Stops spying this TelnetClient.
*
***/
public void stopSpyStream()
{
super._stopSpyStream();
}
/* Code Section added for supporting spystreams (end)*/
/***
* Registers a notification handler to which will be sent
* notifications of received telnet option negotiation commands.
*
* @param notifhand - TelnetNotificationHandler to be registered
***/
@Override
public void registerNotifHandler(TelnetNotificationHandler notifhand)
{
super.registerNotifHandler(notifhand);
}
/***
* Unregisters the current notification handler.
*
***/
@Override
public void unregisterNotifHandler()
{
super.unregisterNotifHandler();
}
/***
* Sets the status of the reader thread.
*
* <p>
* When enabled, a seaparate internal reader thread is created for new
* connections to read incoming data as it arrives. This results in
* immediate handling of option negotiation, notifications, etc.
* (at least until the fixed-size internal buffer fills up).
* Otherwise, no thread is created an all negotiation and option
* handling is deferred until a read() is performed on the
* {@link #getInputStream input stream}.
* </p>
*
* <p>
* The reader thread must be enabled for {@link TelnetInputListener}
* support.
* </p>
*
* <p>
* When this method is invoked, the reader thread status will apply to all
* subsequent connections; the current connection (if any) is not affected.
* </p>
*
* @param flag true to enable the reader thread, false to disable
* @see #registerInputListener
***/
public void setReaderThread(boolean flag)
{
readerThread = flag;
}
/***
* Gets the status of the reader thread.
*
* @return true if the reader thread is enabled, false otherwise
***/
public boolean getReaderThread()
{
return (readerThread);
}
/***
* Register a listener to be notified when new incoming data is
* available to be read on the {@link #getInputStream input stream}.
* Only one listener is supported at a time.
*
* <p>
* More precisely, notifications are issued whenever the number of
* bytes available for immediate reading (i.e., the value returned
* by {@link InputStream#available}) transitions from zero to non-zero.
* Note that (in general) multiple reads may be required to empty the
* buffer and reset this notification, because incoming bytes are being
* added to the internal buffer asynchronously.
* </p>
*
* <p>
* Notifications are only supported when a {@link #setReaderThread
* reader thread} is enabled for the connection.
* </p>
*
* @param listener listener to be registered; replaces any previous
* @since 3.0
***/
public synchronized void registerInputListener(TelnetInputListener listener)
{
this.inputListener = listener;
}
/***
* Unregisters the current {@link TelnetInputListener}, if any.
*
* @since 3.0
***/
public synchronized void unregisterInputListener()
{
this.inputListener = null;
}
// Notify input listener
void notifyInputListener() {
TelnetInputListener listener;
synchronized (this) {
listener = this.inputListener;
}
if (listener != null) {
listener.telnetInputAvailable();
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/SimpleOptionHandler.java | client/src/main/java/org/apache/commons/net/telnet/SimpleOptionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* Simple option handler that can be used for options
* that don't require subnegotiation.
***/
public class SimpleOptionHandler extends TelnetOptionHandler
{
/***
* Constructor for the SimpleOptionHandler. Allows defining desired
* initial setting for local/remote activation of this option and
* behaviour in case a local/remote activation request for this
* option is received.
* <p>
* @param optcode - option code.
* @param initlocal - if set to true, a WILL is sent upon connection.
* @param initremote - if set to true, a DO is sent upon connection.
* @param acceptlocal - if set to true, any DO request is accepted.
* @param acceptremote - if set to true, any WILL request is accepted.
***/
public SimpleOptionHandler(int optcode,
boolean initlocal,
boolean initremote,
boolean acceptlocal,
boolean acceptremote)
{
super(optcode, initlocal, initremote,
acceptlocal, acceptremote);
}
/***
* Constructor for the SimpleOptionHandler. Initial and accept
* behaviour flags are set to false
* <p>
* @param optcode - option code.
***/
public SimpleOptionHandler(int optcode)
{
super(optcode, false, false, false, false);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/telnet/TelnetNotificationHandler.java | client/src/main/java/org/apache/commons/net/telnet/TelnetNotificationHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.telnet;
/***
* The TelnetNotificationHandler interface can be used to handle
* notification of options negotiation commands received on a telnet
* session.
* <p>
* The user can implement this interface and register a
* TelnetNotificationHandler by using the registerNotificationHandler()
* of TelnetClient to be notified of option negotiation commands.
***/
public interface TelnetNotificationHandler
{
/***
* The remote party sent a DO command.
***/
public static final int RECEIVED_DO = 1;
/***
* The remote party sent a DONT command.
***/
public static final int RECEIVED_DONT = 2;
/***
* The remote party sent a WILL command.
***/
public static final int RECEIVED_WILL = 3;
/***
* The remote party sent a WONT command.
***/
public static final int RECEIVED_WONT = 4;
/***
* The remote party sent a COMMAND.
* @since 2.2
***/
public static final int RECEIVED_COMMAND = 5;
/***
* Callback method called when TelnetClient receives an
* command or option negotiation command
*
* @param negotiation_code - type of (negotiation) command received
* (RECEIVED_DO, RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT, RECEIVED_COMMAND)
*
* @param option_code - code of the option negotiated, or the command code itself (e.g. NOP).
***/
public void receivedNegotiation(int negotiation_code, int option_code);
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/math-game/src/main/java/demo/MathGame.java | math-game/src/main/java/demo/MathGame.java | package demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MathGame {
private static Random random = new Random();
private int illegalArgumentCount = 0;
public static void main(String[] args) throws InterruptedException {
MathGame game = new MathGame();
while (true) {
game.run();
TimeUnit.SECONDS.sleep(1);
}
}
public void run() throws InterruptedException {
try {
int number = random.nextInt()/10000;
List<Integer> primeFactors = primeFactors(number);
print(number, primeFactors);
} catch (Exception e) {
System.out.println(String.format("illegalArgumentCount:%3d, ", illegalArgumentCount) + e.getMessage());
}
}
public static void print(int number, List<Integer> primeFactors) {
StringBuffer sb = new StringBuffer(number + "=");
for (int factor : primeFactors) {
sb.append(factor).append('*');
}
if (sb.charAt(sb.length() - 1) == '*') {
sb.deleteCharAt(sb.length() - 1);
}
System.out.println(sb);
}
public List<Integer> primeFactors(int number) {
if (number < 2) {
illegalArgumentCount++;
throw new IllegalArgumentException("number is: " + number + ", need >= 2");
}
List<Integer> result = new ArrayList<Integer>();
int i = 2;
while (i <= number) {
if (number % i == 0) {
result.add(i);
number = number / i;
i = 2;
} else {
i++;
}
}
return result;
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-integration-test/src/test/java/com/taobao/arthas/mcp/it/TargetJvmApp.java | arthas-mcp-integration-test/src/test/java/com/taobao/arthas/mcp/it/TargetJvmApp.java | package com.taobao.arthas.mcp.it;
public class TargetJvmApp {
private static final TargetJvmApp INSTANCE = new TargetJvmApp();
/**
* 持续调用的方法,用于触发 watch/trace/monitor/stack/tt 等需要方法执行事件的工具。
*/
public int hotMethod(int value) {
return compute(value) + 1;
}
private int compute(int value) {
return value * 2;
}
public static void main(String[] args) throws Exception {
System.out.println("TargetJvmApp started.");
while (true) {
INSTANCE.hotMethod((int) (System.nanoTime() & 0xFF));
Thread.sleep(50);
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-integration-test/src/test/java/com/taobao/arthas/mcp/it/ArthasMcpToolsIT.java | arthas-mcp-integration-test/src/test/java/com/taobao/arthas/mcp/it/ArthasMcpToolsIT.java | package com.taobao.arthas.mcp.it;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.arthas.mcp.server.protocol.spec.HttpHeaders;
import com.taobao.arthas.mcp.server.protocol.spec.McpSchema;
import com.taobao.arthas.mcp.server.util.JsonParser;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
class ArthasMcpToolsIT {
private static final ObjectMapper OBJECT_MAPPER = JsonParser.getObjectMapper();
@Test
@Timeout(value = 3, unit = TimeUnit.MINUTES)
void should_list_tools_and_call_tool_via_mcp() throws Exception {
Assumptions.assumeFalse(isWindows(), "集成测试依赖 bash/as.sh,Windows 环境跳过");
Path arthasHome = resolveArthasBinDir();
assertThat(arthasHome).isDirectory();
assertThat(arthasHome.resolve("as.sh")).exists();
assertThat(arthasHome.resolve("arthas-core.jar")).exists();
assertThat(arthasHome.resolve("arthas-agent.jar")).exists();
int telnetPort = 0;
int httpPort = findFreePort();
Process targetJvm = null;
Path tempHome = null;
try {
tempHome = Files.createTempDirectory("arthas-mcp-it-home");
Path targetLog = tempHome.resolve("target-jvm.log");
targetJvm = startTargetJvm(targetLog);
long targetPid = ProcessPid.pidOf(targetJvm);
Path attachLog = tempHome.resolve("attach.log");
runAttach(arthasHome, tempHome, attachLog, targetPid, telnetPort, httpPort);
waitForPortOpen("127.0.0.1", httpPort, Duration.ofSeconds(30));
StreamableMcpHttpClient client = new StreamableMcpHttpClient("127.0.0.1", httpPort, "/mcp");
String sessionId = retry(Duration.ofSeconds(30), client::initialize);
client.sendInitializedNotification(sessionId);
McpSchema.ListToolsResult toolsResult = client.listTools(sessionId);
assertThat(toolsResult.getTools()).isNotNull();
assertThat(toolsResult.getTools().size()).isGreaterThanOrEqualTo(10);
Set<String> toolNames = new HashSet<>();
for (McpSchema.Tool tool : toolsResult.getTools()) {
toolNames.add(tool.getName());
}
assertThat(toolNames).contains("jvm", "jad", "thread");
McpSchema.CallToolResult callToolResult = client.callTool(sessionId, "jvm", Collections.emptyMap());
assertThat(callToolResult).isNotNull();
assertThat(callToolResult.getIsError()).isNotEqualTo(Boolean.TRUE);
assertThat(callToolResult.getContent()).isNotNull().isNotEmpty();
} finally {
if (targetJvm != null) {
targetJvm.destroy();
if (!targetJvm.waitFor(5, TimeUnit.SECONDS)) {
targetJvm.destroyForcibly();
}
}
if (tempHome != null) {
deleteDirectoryQuietly(tempHome);
}
}
}
private static String retry(Duration timeout, IoSupplier<String> supplier) throws Exception {
long deadline = System.nanoTime() + timeout.toNanos();
Exception last = null;
while (System.nanoTime() < deadline) {
try {
return supplier.get();
} catch (Exception e) {
last = e;
Thread.sleep(200);
}
}
if (last != null) {
throw last;
}
throw new IllegalStateException("重试超时");
}
@FunctionalInterface
private interface IoSupplier<T> {
T get() throws Exception;
}
private static void runAttach(Path arthasHome, Path tempHome, Path attachLog, long targetPid,
int telnetPort, int httpPort) throws Exception {
List<String> command = new ArrayList<>();
command.add("bash");
command.add(arthasHome.resolve("as.sh").toString());
command.add("--attach-only");
command.add("--arthas-home");
command.add(arthasHome.toString());
command.add("--target-ip");
command.add("127.0.0.1");
command.add("--telnet-port");
command.add(String.valueOf(telnetPort));
command.add("--http-port");
command.add(String.valueOf(httpPort));
command.add(String.valueOf(targetPid));
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
pb.redirectOutput(attachLog.toFile());
Map<String, String> env = pb.environment();
env.put("JAVA_HOME", System.getProperty("java.home"));
env.put("HOME", tempHome.toAbsolutePath().toString());
Process attach = pb.start();
if (!attach.waitFor(90, TimeUnit.SECONDS)) {
attach.destroyForcibly();
Assertions.fail("as.sh attach 超时: " + attachLog);
}
if (attach.exitValue() != 0) {
Assertions.fail("as.sh attach 失败(exit=" + attach.exitValue() + "): " + attachLog);
}
}
private static Process startTargetJvm(Path targetLog) throws IOException {
String javaBin = Paths.get(System.getProperty("java.home"), "bin", "java").toString();
String classpath = Paths.get(System.getProperty("basedir"), "target", "test-classes").toString();
ProcessBuilder pb = new ProcessBuilder(javaBin, "-cp", classpath, TargetJvmApp.class.getName());
pb.redirectErrorStream(true);
pb.redirectOutput(targetLog.toFile());
return pb.start();
}
private static Path resolveArthasBinDir() {
String basedir = System.getProperty("basedir");
assertThat(basedir).as("Maven surefire/failsafe should set system property 'basedir'").isNotBlank();
return Paths.get(basedir).resolve("../packaging/target/arthas-bin").normalize();
}
private static int findFreePort() throws IOException {
try (java.net.ServerSocket socket = new java.net.ServerSocket(0)) {
socket.setReuseAddress(true);
return socket.getLocalPort();
}
}
private static void waitForPortOpen(String host, int port, Duration timeout) throws InterruptedException {
long deadline = System.nanoTime() + timeout.toNanos();
while (System.nanoTime() < deadline) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), 500);
return;
} catch (IOException ignored) {
Thread.sleep(200);
}
}
throw new IllegalStateException("等待端口监听超时: " + host + ":" + port);
}
private static boolean isWindows() {
String os = System.getProperty("os.name");
return os != null && os.toLowerCase(Locale.ROOT).contains("win");
}
private static void deleteDirectoryQuietly(Path dir) {
try {
if (!Files.exists(dir)) {
return;
}
Files.walk(dir)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (Exception ignored) {
}
}
private static final class ProcessPid {
private ProcessPid() {
}
static long pidOf(Process process) {
// Java 9+
try {
return (Long) Process.class.getMethod("pid").invoke(process);
} catch (Exception ignored) {
// Java 8 fallback
}
try {
java.lang.reflect.Field pidField = process.getClass().getDeclaredField("pid");
pidField.setAccessible(true);
Object value = pidField.get(process);
if (value instanceof Number) {
return ((Number) value).longValue();
}
throw new IllegalStateException("Unsupported pid field type: " + value);
} catch (Exception e) {
throw new IllegalStateException("无法获取目标 JVM pid", e);
}
}
}
private static final class StreamableMcpHttpClient {
private final String baseUrl;
private final String mcpEndpoint;
StreamableMcpHttpClient(String host, int port, String mcpEndpoint) {
this.baseUrl = "http://" + host + ":" + port;
this.mcpEndpoint = mcpEndpoint;
}
String initialize() throws Exception {
McpSchema.InitializeRequest init = new McpSchema.InitializeRequest(
McpSchema.LATEST_PROTOCOL_VERSION,
new McpSchema.ClientCapabilities(null, null, null, null),
new McpSchema.Implementation("arthas-mcp-it", "1.0.0")
);
McpSchema.JSONRPCRequest request = new McpSchema.JSONRPCRequest(
McpSchema.JSONRPC_VERSION,
McpSchema.METHOD_INITIALIZE,
1,
init
);
HttpURLConnection conn = openPostConnection(null);
writeJson(conn, request);
int code = conn.getResponseCode();
String body = readBody(conn);
if (code != 200) {
throw new IllegalStateException("initialize 失败: http=" + code + ", body=" + body);
}
String sessionId = conn.getHeaderField(HttpHeaders.MCP_SESSION_ID);
if (sessionId == null || sessionId.trim().isEmpty()) {
throw new IllegalStateException("initialize 未返回 mcp-session-id header, body=" + body);
}
McpSchema.JSONRPCMessage msg = McpSchema.deserializeJsonRpcMessage(OBJECT_MAPPER, body);
if (!(msg instanceof McpSchema.JSONRPCResponse)) {
throw new IllegalStateException("initialize 响应不是 JSONRPCResponse: " + body);
}
McpSchema.JSONRPCResponse resp = (McpSchema.JSONRPCResponse) msg;
if (resp.getError() != null) {
throw new IllegalStateException("initialize 返回 error: " + OBJECT_MAPPER.writeValueAsString(resp.getError()));
}
return sessionId;
}
void sendInitializedNotification(String sessionId) throws Exception {
McpSchema.JSONRPCNotification notification = new McpSchema.JSONRPCNotification(
McpSchema.JSONRPC_VERSION,
McpSchema.METHOD_NOTIFICATION_INITIALIZED,
Collections.emptyMap()
);
HttpURLConnection conn = openPostConnection(sessionId);
writeJson(conn, notification);
int code = conn.getResponseCode();
if (code != 202 && code != 200) {
throw new IllegalStateException("notifications/initialized 失败: http=" + code + ", body=" + readBody(conn));
}
}
McpSchema.ListToolsResult listTools(String sessionId) throws Exception {
McpSchema.PaginatedRequest params = new McpSchema.PaginatedRequest(null);
McpSchema.JSONRPCRequest request = new McpSchema.JSONRPCRequest(
McpSchema.JSONRPC_VERSION,
McpSchema.METHOD_TOOLS_LIST,
2,
params
);
McpSchema.JSONRPCResponse response = postRequestExpectSseResponse(sessionId, request, Duration.ofSeconds(30));
if (response.getError() != null) {
throw new IllegalStateException("tools/list 返回 error: " + OBJECT_MAPPER.writeValueAsString(response.getError()));
}
return OBJECT_MAPPER.convertValue(response.getResult(), McpSchema.ListToolsResult.class);
}
McpSchema.CallToolResult callTool(String sessionId, String toolName, Map<String, Object> arguments) throws Exception {
McpSchema.CallToolRequest params = new McpSchema.CallToolRequest(toolName, arguments, null);
McpSchema.JSONRPCRequest request = new McpSchema.JSONRPCRequest(
McpSchema.JSONRPC_VERSION,
McpSchema.METHOD_TOOLS_CALL,
3,
params
);
McpSchema.JSONRPCResponse response = postRequestExpectSseResponse(sessionId, request, Duration.ofSeconds(60));
if (response.getError() != null) {
throw new IllegalStateException("tools/call 返回 error: " + OBJECT_MAPPER.writeValueAsString(response.getError()));
}
return OBJECT_MAPPER.convertValue(response.getResult(), McpSchema.CallToolResult.class);
}
private HttpURLConnection openPostConnection(String sessionId) throws IOException {
URL url = new URL(baseUrl + mcpEndpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5_000);
conn.setReadTimeout(30_000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "text/event-stream, application/json");
if (sessionId != null) {
conn.setRequestProperty(HttpHeaders.MCP_SESSION_ID, sessionId);
}
return conn;
}
private static void writeJson(HttpURLConnection conn, Object body) throws IOException {
byte[] bytes = OBJECT_MAPPER.writeValueAsBytes(body);
conn.setFixedLengthStreamingMode(bytes.length);
try (OutputStream os = conn.getOutputStream()) {
os.write(bytes);
}
}
private static String readBody(HttpURLConnection conn) throws IOException {
InputStream is = null;
try {
is = conn.getInputStream();
} catch (IOException e) {
is = conn.getErrorStream();
}
if (is == null) {
return "";
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
private McpSchema.JSONRPCResponse postRequestExpectSseResponse(String sessionId, McpSchema.JSONRPCRequest request, Duration timeout)
throws Exception {
HttpURLConnection conn = openPostConnection(sessionId);
conn.setReadTimeout((int) timeout.toMillis());
writeJson(conn, request);
int code = conn.getResponseCode();
if (code != 200) {
throw new IllegalStateException(request.getMethod() + " 失败: http=" + code + ", body=" + readBody(conn));
}
try (InputStream is = conn.getInputStream()) {
return readJsonRpcResponseFromSse(is, request.getId());
}
}
private static McpSchema.JSONRPCResponse readJsonRpcResponseFromSse(InputStream inputStream, Object expectedId) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
String data = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("data:")) {
data = line.substring("data:".length()).trim();
continue;
}
if (line.isEmpty() && data != null) {
McpSchema.JSONRPCMessage msg = McpSchema.deserializeJsonRpcMessage(OBJECT_MAPPER, data);
data = null;
if (msg instanceof McpSchema.JSONRPCResponse) {
McpSchema.JSONRPCResponse resp = (McpSchema.JSONRPCResponse) msg;
if (Objects.equals(resp.getId(), expectedId)) {
return resp;
}
}
}
}
throw new IllegalStateException("未从 SSE 流中读取到期望的 JSONRPCResponse, id=" + expectedId);
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-integration-test/src/test/java/com/taobao/arthas/mcp/it/ArthasMcpJavaSdkIT.java | arthas-mcp-integration-test/src/test/java/com/taobao/arthas/mcp/it/ArthasMcpJavaSdkIT.java | package com.taobao.arthas.mcp.it;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.arthas.mcp.server.util.JsonParser;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpSchema;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Execution(ExecutionMode.SAME_THREAD)
class ArthasMcpJavaSdkIT {
private static final ObjectMapper OBJECT_MAPPER = JsonParser.getObjectMapper();
private static final String TARGET_CLASS_PATTERN = TargetJvmApp.class.getName();
private static final String TARGET_METHOD_PATTERN = "hotMethod";
private static final List<String> EXPECTED_TOOL_NAMES = Arrays.asList(
"classloader",
"dashboard",
"dump",
"getstatic",
"heapdump",
"jad",
"jvm",
"mc",
"mbean",
"memory",
"monitor",
"ognl",
"options",
"perfcounter",
"redefine",
"retransform",
"sc",
"sm",
"stack",
"stop",
"sysenv",
"sysprop",
"thread",
"trace",
"tt",
"vmoption",
"vmtool",
"watch"
);
private Environment env;
@BeforeAll
void setUp() throws Exception {
Assumptions.assumeFalse(isWindows(), "集成测试依赖 bash/as.sh,Windows 环境跳过");
this.env = Environment.start("arthas-mcp-java-sdk-it", "arthas-mcp-java-sdk-it-home");
}
@AfterAll
void tearDown() {
if (this.env != null) {
this.env.close();
this.env = null;
}
}
@Test
@Timeout(value = 3, unit = TimeUnit.MINUTES)
void should_list_all_mcp_tools_via_java_mcp_sdk() {
Set<String> expected = new HashSet<String>(EXPECTED_TOOL_NAMES);
Set<String> actual = new HashSet<String>(this.env.toolNames);
Set<String> missing = new HashSet<String>(expected);
missing.removeAll(actual);
Set<String> extra = new HashSet<String>(actual);
extra.removeAll(expected);
assertThat(missing).as("tools/list 缺少工具: %s", missing).isEmpty();
assertThat(extra).as("tools/list 存在未覆盖的工具: %s", extra).isEmpty();
}
static Stream<String> toolNamesExceptStop() {
List<String> toolNames = new ArrayList<String>(EXPECTED_TOOL_NAMES);
toolNames.remove("stop");
return toolNames.stream();
}
@ParameterizedTest(name = "{0}")
@MethodSource("toolNamesExceptStop")
@Timeout(value = 3, unit = TimeUnit.MINUTES)
void should_call_each_mcp_tool_via_java_mcp_sdk(String toolName) throws Exception {
Map<String, Object> args = createArgumentsForTool(toolName, this.env);
McpSchema.CallToolResult result = this.env.client.callTool(new McpSchema.CallToolRequest(toolName, args));
String body = assertCallToolSuccess(toolName, result);
assertToolSideEffects(toolName, this.env, body);
}
@Test
@Timeout(value = 3, unit = TimeUnit.MINUTES)
void should_call_stop_tool_via_java_mcp_sdk() throws Exception {
Assumptions.assumeFalse(isWindows(), "集成测试依赖 bash/as.sh,Windows 环境跳过");
Environment stopEnv = null;
try {
stopEnv = Environment.start("arthas-mcp-java-sdk-stop-it", "arthas-mcp-java-sdk-stop-it-home");
Map<String, Object> args = new HashMap<String, Object>();
args.put("delayMs", 200);
McpSchema.CallToolResult result = stopEnv.client.callTool(new McpSchema.CallToolRequest("stop", args));
assertCallToolSuccess("stop", result);
waitForPortClosed("127.0.0.1", stopEnv.httpPort, Duration.ofSeconds(15));
} finally {
if (stopEnv != null) {
stopEnv.close();
}
}
}
private static void assertToolSideEffects(String toolName, Environment env, String body) throws Exception {
if ("heapdump".equals(toolName)) {
Path heapdumpFile = env.tempHome.resolve("heapdump.hprof");
assertThat(heapdumpFile).exists();
assertThat(Files.size(heapdumpFile)).isGreaterThan(0L);
try {
Files.deleteIfExists(heapdumpFile);
} catch (Exception ignored) {
}
return;
}
if ("dump".equals(toolName)) {
Path dumpOutputDir = env.tempHome.resolve("dump-output");
assertThat(dumpOutputDir).isDirectory();
assertThat(countFilesWithSuffix(dumpOutputDir, ".class")).isGreaterThan(0);
return;
}
if ("mc".equals(toolName)) {
Path mcOutputDir = env.tempHome.resolve("mc-output");
assertThat(mcOutputDir).isDirectory();
assertThat(countFilesWithSuffix(mcOutputDir, ".class")).isGreaterThan(0);
return;
}
if (isStreamableTool(toolName)) {
JsonNode node = OBJECT_MAPPER.readTree(body);
if (node != null && node.isObject()) {
JsonNode resultCount = node.get("resultCount");
if (resultCount != null && resultCount.canConvertToInt()) {
int count = resultCount.asInt();
assertThat(count).as("tool=%s resultCount, body=%s", toolName, body).isGreaterThan(0);
} else {
Assertions.fail("streamable tool 未返回 resultCount: tool=" + toolName + ", body=" + body);
}
}
}
}
private static boolean isStreamableTool(String toolName) {
return "dashboard".equals(toolName)
|| "monitor".equals(toolName)
|| "watch".equals(toolName)
|| "trace".equals(toolName)
|| "stack".equals(toolName)
|| "tt".equals(toolName);
}
private static int countFilesWithSuffix(Path dir, String suffix) throws IOException {
if (dir == null || !Files.isDirectory(dir)) {
return 0;
}
try (Stream<Path> stream = Files.walk(dir)) {
return (int) stream
.filter(p -> Files.isRegularFile(p)
&& p.getFileName() != null
&& p.getFileName().toString().endsWith(suffix))
.count();
}
}
private static Map<String, Object> createArgumentsForTool(String toolName, Environment env) throws IOException {
Map<String, Object> args = new HashMap<String, Object>();
if ("jvm".equals(toolName)
|| "thread".equals(toolName)
|| "memory".equals(toolName)
|| "options".equals(toolName)
|| "vmoption".equals(toolName)
|| "classloader".equals(toolName)
|| "perfcounter".equals(toolName)) {
return args;
}
if ("jad".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
return args;
}
if ("sc".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
return args;
}
if ("sm".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
args.put("methodPattern", TARGET_METHOD_PATTERN);
return args;
}
if ("dump".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
Path outDir = env.tempHome.resolve("dump-output");
Files.createDirectories(outDir);
args.put("outputDir", outDir.toString());
args.put("limit", 1);
return args;
}
if ("mc".equals(toolName)) {
Path sourceFile = env.ensureMcSourceFile();
Path outDir = env.tempHome.resolve("mc-output");
Files.createDirectories(outDir);
args.put("javaFilePaths", sourceFile.toString());
args.put("outputDir", outDir.toString());
return args;
}
if ("retransform".equals(toolName) || "redefine".equals(toolName)) {
args.put("classFilePaths", env.targetClassFile.toString());
return args;
}
if ("getstatic".equals(toolName)) {
args.put("className", "java.lang.Integer");
args.put("fieldName", "MAX_VALUE");
return args;
}
if ("ognl".equals(toolName)) {
args.put("expression", "@java.lang.System@getProperty(\"java.version\")");
args.put("expandLevel", 1);
return args;
}
if ("mbean".equals(toolName)) {
args.put("namePattern", "java.lang:type=Runtime");
args.put("attributePattern", "Uptime");
return args;
}
if ("sysenv".equals(toolName)) {
args.put("envName", "PATH");
return args;
}
if ("sysprop".equals(toolName)) {
args.put("propertyName", "java.version");
return args;
}
if ("vmtool".equals(toolName)) {
args.put("action", "getInstances");
args.put("className", TARGET_CLASS_PATTERN);
args.put("limit", 1);
args.put("expandLevel", 1);
args.put("express", "instances.length");
return args;
}
if ("heapdump".equals(toolName)) {
Path heapdumpFile = env.tempHome.resolve("heapdump.hprof");
args.put("filePath", heapdumpFile.toString());
return args;
}
if ("dashboard".equals(toolName)) {
args.put("intervalMs", 200);
args.put("numberOfExecutions", 1);
return args;
}
if ("watch".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
args.put("methodPattern", TARGET_METHOD_PATTERN);
args.put("numberOfExecutions", 1);
args.put("timeout", 10);
return args;
}
if ("trace".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
args.put("methodPattern", TARGET_METHOD_PATTERN);
args.put("numberOfExecutions", 1);
args.put("timeout", 10);
return args;
}
if ("monitor".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
args.put("methodPattern", TARGET_METHOD_PATTERN);
args.put("intervalMs", 1000);
args.put("numberOfExecutions", 1);
args.put("timeout", 15);
return args;
}
if ("stack".equals(toolName)) {
args.put("classPattern", TARGET_CLASS_PATTERN);
args.put("methodPattern", TARGET_METHOD_PATTERN);
args.put("numberOfExecutions", 1);
// CI 环境下 stack 增强+触发可能更慢,适当放大超时时间以减少偶发失败
args.put("timeout", 30);
return args;
}
if ("tt".equals(toolName)) {
args.put("action", "record");
args.put("classPattern", TARGET_CLASS_PATTERN);
args.put("methodPattern", TARGET_METHOD_PATTERN);
args.put("numberOfExecutions", 1);
args.put("timeout", 10);
return args;
}
throw new IllegalArgumentException("未为 tool 配置参数: " + toolName);
}
private static String assertCallToolSuccess(String toolName, McpSchema.CallToolResult result) throws Exception {
assertThat(result).as("tool=%s", toolName).isNotNull();
assertThat(result.isError()).as("tool=%s, content=%s", toolName, result.content()).isNotEqualTo(Boolean.TRUE);
assertThat(result.content()).as("tool=%s", toolName).isNotNull().isNotEmpty();
String text = extractTextContent(result);
assertThat(text).as("tool=%s", toolName).isNotBlank();
JsonNode node = OBJECT_MAPPER.readTree(text);
if (node != null && node.isObject()) {
JsonNode error = node.get("error");
if (error != null && error.isBoolean() && error.booleanValue()) {
Assertions.fail("tool 执行返回 error=true: tool=" + toolName + ", body=" + text);
}
JsonNode status = node.get("status");
if (status != null && status.isTextual() && "error".equalsIgnoreCase(status.asText())) {
Assertions.fail("tool 执行返回 status=error: tool=" + toolName + ", body=" + text);
}
}
return text;
}
private static String extractTextContent(McpSchema.CallToolResult result) {
StringBuilder sb = new StringBuilder();
for (McpSchema.Content content : result.content()) {
if (content instanceof McpSchema.TextContent) {
String text = ((McpSchema.TextContent) content).text();
if (text != null) {
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(text);
}
}
}
return sb.toString();
}
private static final class Environment implements AutoCloseable {
private final Path arthasHome;
private final Path tempHome;
private final int httpPort;
private final Process targetJvm;
private final McpSyncClient client;
private final Set<String> toolNames;
private final Path targetClassFile;
private Path mcSourceFile;
private Environment(Path arthasHome, Path tempHome, int httpPort, Process targetJvm,
McpSyncClient client, Set<String> toolNames, Path targetClassFile) {
this.arthasHome = arthasHome;
this.tempHome = tempHome;
this.httpPort = httpPort;
this.targetJvm = targetJvm;
this.client = client;
this.toolNames = toolNames;
this.targetClassFile = targetClassFile;
}
static Environment start(String clientName, String tempDirPrefix) throws Exception {
Path arthasHome = resolveArthasBinDir();
assertThat(arthasHome).isDirectory();
assertThat(arthasHome.resolve("as.sh")).exists();
assertThat(arthasHome.resolve("arthas-core.jar")).exists();
assertThat(arthasHome.resolve("arthas-agent.jar")).exists();
int telnetPort = 0;
int httpPort = findFreePort();
Path tempHome = Files.createTempDirectory(tempDirPrefix);
Process targetJvm = null;
McpSyncClient client = null;
try {
Path targetLog = tempHome.resolve("target-jvm.log");
targetJvm = startTargetJvm(tempHome, targetLog);
long targetPid = ProcessPid.pidOf(targetJvm);
Path attachLog = tempHome.resolve("attach.log");
runAttach(arthasHome, tempHome, attachLog, targetPid, telnetPort, httpPort);
waitForPortOpen("127.0.0.1", httpPort, Duration.ofSeconds(30));
McpClientTransport transport = HttpClientStreamableHttpTransport.builder("http://127.0.0.1:" + httpPort).build();
client = McpClient.sync(transport)
.clientInfo(new McpSchema.Implementation(clientName, "1.0.0"))
.requestTimeout(Duration.ofSeconds(120))
.initializationTimeout(Duration.ofSeconds(10))
.build();
McpSchema.InitializeResult initResult = client.initialize();
assertThat(initResult).isNotNull();
McpSchema.ListToolsResult toolsResult = client.listTools();
assertThat(toolsResult).isNotNull();
assertThat(toolsResult.tools()).isNotNull();
Set<String> toolNames = new HashSet<String>();
for (McpSchema.Tool tool : toolsResult.tools()) {
toolNames.add(tool.name());
}
Path targetClassFile = resolveTargetJvmAppClassFile();
assertThat(targetClassFile).exists();
return new Environment(arthasHome, tempHome, httpPort, targetJvm, client, toolNames, targetClassFile);
} catch (Exception e) {
if (client != null) {
try {
client.closeGracefully();
} catch (Exception ignored) {
}
}
if (targetJvm != null) {
targetJvm.destroy();
if (!targetJvm.waitFor(5, TimeUnit.SECONDS)) {
targetJvm.destroyForcibly();
}
}
deleteDirectoryQuietly(tempHome);
throw e;
}
}
Path ensureMcSourceFile() throws IOException {
if (this.mcSourceFile != null) {
return this.mcSourceFile;
}
Path source = this.tempHome.resolve("McpMcTestClass.java");
String code = ""
+ "public class McpMcTestClass {\n"
+ " public static int add(int a, int b) {\n"
+ " return a + b;\n"
+ " }\n"
+ "}\n";
Files.write(source, code.getBytes(StandardCharsets.UTF_8));
this.mcSourceFile = source;
return source;
}
@Override
public void close() {
if (this.client != null) {
try {
this.client.closeGracefully();
} catch (Exception ignored) {
}
}
if (this.targetJvm != null) {
this.targetJvm.destroy();
try {
if (!this.targetJvm.waitFor(5, TimeUnit.SECONDS)) {
this.targetJvm.destroyForcibly();
}
} catch (Exception ignored) {
}
}
deleteDirectoryQuietly(this.tempHome);
}
}
private static void runAttach(Path arthasHome, Path tempHome, Path attachLog, long targetPid,
int telnetPort, int httpPort) throws Exception {
ProcessBuilder pb = new ProcessBuilder(
"bash",
arthasHome.resolve("as.sh").toString(),
"--attach-only",
"--arthas-home", arthasHome.toString(),
"--target-ip", "127.0.0.1",
"--telnet-port", String.valueOf(telnetPort),
"--http-port", String.valueOf(httpPort),
String.valueOf(targetPid)
);
pb.redirectErrorStream(true);
pb.redirectOutput(attachLog.toFile());
pb.environment().put("JAVA_HOME", System.getProperty("java.home"));
pb.environment().put("HOME", tempHome.toAbsolutePath().toString());
Process attach = pb.start();
if (!attach.waitFor(90, TimeUnit.SECONDS)) {
attach.destroyForcibly();
Assertions.fail("as.sh attach 超时: " + attachLog);
}
if (attach.exitValue() != 0) {
Assertions.fail("as.sh attach 失败(exit=" + attach.exitValue() + "): " + attachLog);
}
}
private static Process startTargetJvm(Path workDir, Path targetLog) throws IOException {
String javaBin = Paths.get(System.getProperty("java.home"), "bin", "java").toString();
String classpath = Paths.get(System.getProperty("basedir"), "target", "test-classes").toString();
ProcessBuilder pb = new ProcessBuilder(javaBin, "-cp", classpath, TargetJvmApp.class.getName());
if (workDir != null) {
pb.directory(workDir.toFile());
}
pb.redirectErrorStream(true);
pb.redirectOutput(targetLog.toFile());
return pb.start();
}
private static Path resolveArthasBinDir() {
String basedir = System.getProperty("basedir");
assertThat(basedir).as("Maven surefire/failsafe should set system property 'basedir'").isNotBlank();
return Paths.get(basedir).resolve("../packaging/target/arthas-bin").normalize();
}
private static Path resolveTargetJvmAppClassFile() {
String basedir = System.getProperty("basedir");
assertThat(basedir).as("Maven surefire/failsafe should set system property 'basedir'").isNotBlank();
return Paths.get(basedir, "target", "test-classes", "com", "taobao", "arthas", "mcp", "it", "TargetJvmApp.class").normalize();
}
private static int findFreePort() throws IOException {
try (java.net.ServerSocket socket = new java.net.ServerSocket(0)) {
socket.setReuseAddress(true);
return socket.getLocalPort();
}
}
private static void waitForPortOpen(String host, int port, Duration timeout) throws InterruptedException {
long deadline = System.nanoTime() + timeout.toNanos();
while (System.nanoTime() < deadline) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), 500);
return;
} catch (IOException ignored) {
Thread.sleep(200);
}
}
throw new IllegalStateException("等待端口监听超时: " + host + ":" + port);
}
private static void waitForPortClosed(String host, int port, Duration timeout) throws InterruptedException {
long deadline = System.nanoTime() + timeout.toNanos();
while (System.nanoTime() < deadline) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), 500);
Thread.sleep(200);
} catch (IOException ignored) {
return;
}
}
throw new IllegalStateException("等待端口关闭超时: " + host + ":" + port);
}
private static boolean isWindows() {
String os = System.getProperty("os.name");
return os != null && os.toLowerCase(Locale.ROOT).contains("win");
}
private static void deleteDirectoryQuietly(Path dir) {
try {
if (!Files.exists(dir)) {
return;
}
Files.walk(dir)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (Exception ignored) {
}
}
private static final class ProcessPid {
private ProcessPid() {
}
static long pidOf(Process process) {
// Java 9+ 获取 pid
try {
return (Long) Process.class.getMethod("pid").invoke(process);
} catch (Exception ignored) {
// Java 8 兼容处理
}
try {
java.lang.reflect.Field pidField = process.getClass().getDeclaredField("pid");
pidField.setAccessible(true);
Object value = pidField.get(process);
if (value instanceof Number) {
return ((Number) value).longValue();
}
throw new IllegalStateException("Unsupported pid field type: " + value);
} catch (Exception e) {
throw new IllegalStateException("无法获取目标 JVM pid", e);
}
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-common/src/test/java/com/alibaba/arthas/tunnel/common/SimpleHttpResponseTest.java | tunnel-common/src/test/java/com/alibaba/arthas/tunnel/common/SimpleHttpResponseTest.java | package com.alibaba.arthas.tunnel.common;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class SimpleHttpResponseTest {
@Test
public void testSerialization() throws IOException, ClassNotFoundException {
SimpleHttpResponse response = new SimpleHttpResponse();
response.setStatus(200);
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "text/plain");
response.setHeaders(headers);
String content = "Hello, world!";
response.setContent(content.getBytes());
byte[] bytes = SimpleHttpResponse.toBytes(response);
SimpleHttpResponse deserializedResponse = SimpleHttpResponse.fromBytes(bytes);
assertEquals(response.getStatus(), deserializedResponse.getStatus());
assertEquals(response.getHeaders(), deserializedResponse.getHeaders());
assertArrayEquals(response.getContent(), deserializedResponse.getContent());
}
private static byte[] toBytes(Object object) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(object);
out.flush();
return bos.toByteArray();
}
}
@Test(expected = InvalidClassException.class)
public void testDeserializationWithUnauthorizedClass() throws IOException, ClassNotFoundException {
Date date = new Date();
byte[] bytes = toBytes(date);
// Try to deserialize the object with an unauthorized class
// This should throw an InvalidClassException
SimpleHttpResponse.fromBytes(bytes);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-common/src/main/java/com/alibaba/arthas/tunnel/common/URIConstans.java | tunnel-common/src/main/java/com/alibaba/arthas/tunnel/common/URIConstans.java | package com.alibaba.arthas.tunnel.common;
/**
*
* @author hengyunabc 2020-10-22
*
*/
public class URIConstans {
/**
* @see MethodConstants
*/
public static final String METHOD = "method";
public static final String RESPONSE = "response";
/**
* agent id
*/
public static final String ID = "id";
/**
* tunnel server用于区分不同 tunnel client的内部 id
*/
public static final String CLIENT_CONNECTION_ID = "clientConnectionId";
/**
* tunnel server向 tunnel client请求http代理时的目标 url
*
* @see com.alibaba.arthas.tunnel.common.MethodConstants#HTTP_PROXY
*/
public static final String TARGET_URL = "targetUrl";
/**
* 标识一次proxy请求,随机生成
*/
public static final String PROXY_REQUEST_ID = "requestId";
/**
* proxy请求的返回值,base64编码
*/
public static final String PROXY_RESPONSE_DATA = "responseData";
public static final String ARTHAS_VERSION = "arthasVersion";
public static final String APP_NAME = "appName";
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-common/src/main/java/com/alibaba/arthas/tunnel/common/SimpleHttpResponse.java | tunnel-common/src/main/java/com/alibaba/arthas/tunnel/common/SimpleHttpResponse.java | package com.alibaba.arthas.tunnel.common;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author hengyunabc 2020-10-22
*
*/
public class SimpleHttpResponse implements Serializable {
private static final long serialVersionUID = 1L;
private static final List<String> whitelist = Arrays.asList(byte[].class.getName(), String.class.getName(),
Map.class.getName(), HashMap.class.getName(), SimpleHttpResponse.class.getName());
private int status = 200;
private Map<String, String> headers = new HashMap<String, String>();
private byte[] content;
public void addHeader(String key, String value) {
headers.put(key, value);
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static byte[] toBytes(SimpleHttpResponse response) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(response);
out.flush();
return bos.toByteArray();
}
}
public static SimpleHttpResponse fromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
try (ObjectInputStream in = new ObjectInputStream(bis) {
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
if (!whitelist.contains(desc.getName())) {
throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName());
}
return super.resolveClass(desc);
}
}) {
return (SimpleHttpResponse) in.readObject();
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-common/src/main/java/com/alibaba/arthas/tunnel/common/MethodConstants.java | tunnel-common/src/main/java/com/alibaba/arthas/tunnel/common/MethodConstants.java | package com.alibaba.arthas.tunnel.common;
/**
* tunnel client和server之间通过 URI来通迅,在URI里定义了一个 method的参数,定义不同的行为
*
* @author hengyunabc 2020-10-22
*
*/
public class MethodConstants {
/**
*
* <pre>
* tunnel client启动时注册的 method
*
* ws://192.168.1.10:7777/ws?method=agentRegister
*
* tunnel server回应:
*
* response:/?method=agentRegister&id=bvDOe8XbTM2pQWjF4cfw
*
* id不指定,则随机生成
* </pre>
*/
public static final String AGENT_REGISTER = "agentRegister";
/**
* <pre>
* tunnel server 通知 tunnel client启动一个新的连接
*
* response:/?method=startTunnel&id=bvDOe8XbTM2pQWjF4cfw&clientConnectionId=AMku9EFz2gxeL2gedGOC
* </pre>
*/
public static final String START_TUNNEL = "startTunnel";
/**
* <pre>
* browser 通知tunnel server去连接 tunnel client
*
* ws://192.168.1.10:7777/ws?method=connectArthas&id=bvDOe8XbTM2pQWjF4cfw
* </pre>
*/
public static final String CONNECT_ARTHAS = "connectArthas";
/**
* <pre>
* tunnel client收到 startTunnel 指令之后,以下面的 URI新建一个连接:
*
* ws://127.0.0.1:7777/ws/?method=openTunnel&clientConnectionId=AMku9EFz2gxeL2gedGOC&id=bvDOe8XbTM2pQWjF4cfw
* </pre>
*/
public static final String OPEN_TUNNEL = "openTunnel";
/**
* <pre>
* tunnel server向 tunnel client请求 http中转,比如访问 http://localhost:3658/arthas-output/xxx.html
* </pre>
*/
public static final String HTTP_PROXY = "httpProxy";
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/agent/src/main/java/com/taobao/arthas/agent334/AgentBootstrap.java | agent/src/main/java/com/taobao/arthas/agent334/AgentBootstrap.java | package com.taobao.arthas.agent334;
import java.arthas.SpyAPI;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.instrument.Instrumentation;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import com.taobao.arthas.agent.ArthasClassloader;
/**
* 代理启动类
*
* @author vlinux on 15/5/19.
*/
public class AgentBootstrap {
private static final String ARTHAS_CORE_JAR = "arthas-core.jar";
private static final String ARTHAS_BOOTSTRAP = "com.taobao.arthas.core.server.ArthasBootstrap";
private static final String GET_INSTANCE = "getInstance";
private static final String IS_BIND = "isBind";
private static PrintStream ps = System.err;
static {
try {
File arthasLogDir = new File(System.getProperty("user.home") + File.separator + "logs" + File.separator
+ "arthas" + File.separator);
if (!arthasLogDir.exists()) {
arthasLogDir.mkdirs();
}
if (!arthasLogDir.exists()) {
// #572
arthasLogDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "logs" + File.separator
+ "arthas" + File.separator);
if (!arthasLogDir.exists()) {
arthasLogDir.mkdirs();
}
}
File log = new File(arthasLogDir, "arthas.log");
if (!log.exists()) {
log.createNewFile();
}
ps = new PrintStream(new FileOutputStream(log, true));
} catch (Throwable t) {
t.printStackTrace(ps);
}
}
/**
* <pre>
* 1. 全局持有classloader用于隔离 Arthas 实现,防止多次attach重复初始化
* 2. ClassLoader在arthas停止时会被reset
* 3. 如果ClassLoader一直没变,则 com.taobao.arthas.core.server.ArthasBootstrap#getInstance 返回结果一直是一样的
* </pre>
*/
private static volatile ClassLoader arthasClassLoader;
public static void premain(String args, Instrumentation inst) {
main(args, inst);
}
public static void agentmain(String args, Instrumentation inst) {
main(args, inst);
}
/**
* 让下次再次启动时有机会重新加载
*/
public static void resetArthasClassLoader() {
arthasClassLoader = null;
}
private static ClassLoader getClassLoader(Instrumentation inst, File arthasCoreJarFile) throws Throwable {
// 构造自定义的类加载器,尽量减少Arthas对现有工程的侵蚀
return loadOrDefineClassLoader(arthasCoreJarFile);
}
private static ClassLoader loadOrDefineClassLoader(File arthasCoreJarFile) throws Throwable {
if (arthasClassLoader == null) {
arthasClassLoader = new ArthasClassloader(new URL[]{arthasCoreJarFile.toURI().toURL()});
}
return arthasClassLoader;
}
private static synchronized void main(String args, final Instrumentation inst) {
// 尝试判断arthas是否已在运行,如果是的话,直接就退出
try {
Class.forName("java.arthas.SpyAPI"); // 加载不到会抛异常
if (SpyAPI.isInited()) {
ps.println("Arthas server already stared, skip attach.");
ps.flush();
return;
}
} catch (Throwable e) {
// ignore
}
try {
ps.println("Arthas server agent start...");
// 传递的args参数分两个部分:arthasCoreJar路径和agentArgs, 分别是Agent的JAR包路径和期望传递到服务端的参数
if (args == null) {
args = "";
}
args = decodeArg(args);
String arthasCoreJar;
final String agentArgs;
int index = args.indexOf(';');
if (index != -1) {
arthasCoreJar = args.substring(0, index);
agentArgs = args.substring(index);
} else {
arthasCoreJar = "";
agentArgs = args;
}
File arthasCoreJarFile = new File(arthasCoreJar);
if (!arthasCoreJarFile.exists()) {
ps.println("Can not find arthas-core jar file from args: " + arthasCoreJarFile);
// try to find from arthas-agent.jar directory
CodeSource codeSource = AgentBootstrap.class.getProtectionDomain().getCodeSource();
if (codeSource != null) {
try {
File arthasAgentJarFile = new File(codeSource.getLocation().toURI().getSchemeSpecificPart());
arthasCoreJarFile = new File(arthasAgentJarFile.getParentFile(), ARTHAS_CORE_JAR);
if (!arthasCoreJarFile.exists()) {
ps.println("Can not find arthas-core jar file from agent jar directory: " + arthasAgentJarFile);
}
} catch (Throwable e) {
ps.println("Can not find arthas-core jar file from " + codeSource.getLocation());
e.printStackTrace(ps);
}
}
}
if (!arthasCoreJarFile.exists()) {
return;
}
/**
* Use a dedicated thread to run the binding logic to prevent possible memory leak. #195
*/
final ClassLoader agentLoader = getClassLoader(inst, arthasCoreJarFile);
Thread bindingThread = new Thread() {
@Override
public void run() {
try {
bind(inst, agentLoader, agentArgs);
} catch (Throwable throwable) {
throwable.printStackTrace(ps);
}
}
};
bindingThread.setName("arthas-binding-thread");
bindingThread.start();
bindingThread.join();
} catch (Throwable t) {
t.printStackTrace(ps);
try {
if (ps != System.err) {
ps.close();
}
} catch (Throwable tt) {
// ignore
}
throw new RuntimeException(t);
}
}
private static void bind(Instrumentation inst, ClassLoader agentLoader, String args) throws Throwable {
/**
* <pre>
* ArthasBootstrap bootstrap = ArthasBootstrap.getInstance(inst);
* </pre>
*/
Class<?> bootstrapClass = agentLoader.loadClass(ARTHAS_BOOTSTRAP);
Object bootstrap = bootstrapClass.getMethod(GET_INSTANCE, Instrumentation.class, String.class).invoke(null, inst, args);
boolean isBind = (Boolean) bootstrapClass.getMethod(IS_BIND).invoke(bootstrap);
if (!isBind) {
String errorMsg = "Arthas server port binding failed! Please check $HOME/logs/arthas/arthas.log for more details.";
ps.println(errorMsg);
throw new RuntimeException(errorMsg);
}
ps.println("Arthas server already bind.");
}
private static String decodeArg(String arg) {
try {
return URLDecoder.decode(arg, "utf-8");
} catch (UnsupportedEncodingException e) {
return arg;
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/agent/src/main/java/com/taobao/arthas/agent/ArthasClassloader.java | agent/src/main/java/com/taobao/arthas/agent/ArthasClassloader.java | package com.taobao.arthas.agent;
import java.net.URL;
import java.net.URLClassLoader;
/**
* @author beiwei30 on 09/12/2016.
*/
public class ArthasClassloader extends URLClassLoader {
public ArthasClassloader(URL[] urls) {
super(urls, ClassLoader.getSystemClassLoader().getParent());
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
final Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
return loadedClass;
}
// 优先从parent(SystemClassLoader)里加载系统类,避免抛出ClassNotFoundException
if (name != null && (name.startsWith("sun.") || name.startsWith("java."))) {
return super.loadClass(name, resolve);
}
try {
Class<?> aClass = findClass(name);
if (resolve) {
resolveClass(aClass);
}
return aClass;
} catch (Exception e) {
// ignore
}
return super.loadClass(name, resolve);
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/RelayHandler.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/RelayHandler.java | package com.alibaba.arthas.tunnel.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
public final class RelayHandler extends ChannelInboundHandlerAdapter {
private final static Logger logger = LoggerFactory.getLogger(RelayHandler.class);
private final Channel relayChannel;
public RelayHandler(Channel relayChannel) {
this.relayChannel = relayChannel;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (relayChannel.isActive()) {
relayChannel.writeAndFlush(msg);
} else {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
if (relayChannel.isActive()) {
ChannelUtils.closeOnFlush(relayChannel);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("RelayHandler error", cause);
try {
if (relayChannel.isActive()) {
relayChannel.close();
}
} finally {
ctx.close();
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ProxyClient.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ProxyClient.java | package com.alibaba.arthas.tunnel.client;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.arthas.tunnel.common.SimpleHttpResponse;
import com.taobao.arthas.common.ArthasConstants;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
/**
*
* @author hengyunabc 2020-10-22
*
*/
public class ProxyClient {
private static final Logger logger = LoggerFactory.getLogger(ProxyClient.class);
public SimpleHttpResponse query(String targetUrl) throws InterruptedException {
final Promise<SimpleHttpResponse> httpResponsePromise = GlobalEventExecutor.INSTANCE.newPromise();
final EventLoopGroup group = new NioEventLoopGroup(1, new DefaultThreadFactory("arthas-ProxyClient", true));
ChannelFuture closeFuture = null;
try {
Bootstrap b = new Bootstrap();
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
b.group(group).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
@Override
protected void initChannel(LocalChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec(), new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH),
new HttpProxyClientHandler(httpResponsePromise));
}
});
LocalAddress localAddress = new LocalAddress(ArthasConstants.NETTY_LOCAL_ADDRESS);
Channel localChannel = b.connect(localAddress).sync().channel();
// Prepare the HTTP request.
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, targetUrl,
Unpooled.EMPTY_BUFFER);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
localChannel.writeAndFlush(request);
closeFuture = localChannel.closeFuture();
logger.info("proxy client connect to server success, targetUrl: " + targetUrl);
return httpResponsePromise.get(5000, TimeUnit.MILLISECONDS);
} catch (Throwable e) {
logger.error("ProxyClient error, targetUrl: {}", targetUrl, e);
} finally {
if (closeFuture != null) {
closeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
group.shutdownGracefully();
}
});
} else {
group.shutdownGracefully();
}
}
SimpleHttpResponse httpResponse = new SimpleHttpResponse();
try {
httpResponse.setContent("error".getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
// ignore
}
return httpResponse;
}
static class HttpProxyClientHandler extends SimpleChannelInboundHandler<HttpObject> {
private Promise<SimpleHttpResponse> promise;
private SimpleHttpResponse simpleHttpResponse = new SimpleHttpResponse();
public HttpProxyClientHandler(Promise<SimpleHttpResponse> promise) {
this.promise = promise;
}
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
simpleHttpResponse.setStatus(response.status().code());
if (!response.headers().isEmpty()) {
for (String name : response.headers().names()) {
for (String value : response.headers().getAll(name)) {
if (logger.isDebugEnabled()) {
logger.debug("header: {}, value: {}", name, value);
}
simpleHttpResponse.addHeader(name, value);
}
}
}
}
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
ByteBuf byteBuf = null;
try{
byteBuf = content.content();
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
simpleHttpResponse.setContent(bytes);
promise.setSuccess(simpleHttpResponse);
if (content instanceof LastHttpContent) {
ctx.close();
}
}finally {
if (byteBuf != null) {
byteBuf.release();
}
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("Proxy Client error", cause);
ctx.close();
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/LocalFrameHandler.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/LocalFrameHandler.java | package com.alibaba.arthas.tunnel.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler.ClientHandshakeStateEvent;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
public class LocalFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
private final static Logger logger = LoggerFactory.getLogger(LocalFrameHandler.class);
private ChannelPromise handshakeFuture;
public LocalFrameHandler() {
}
public ChannelPromise handshakeFuture() {
return handshakeFuture;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
handshakeFuture = ctx.newPromise();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt instanceof ClientHandshakeStateEvent) {
if (evt.equals(ClientHandshakeStateEvent.HANDSHAKE_COMPLETE)) {
handshakeFuture.setSuccess();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("LocalFrameHandler error", cause);
if (!handshakeFuture.isDone()) {
handshakeFuture.setFailure(cause);
}
ctx.close();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ChannelUtils.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ChannelUtils.java | package com.alibaba.arthas.tunnel.client;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
public final class ChannelUtils {
/**
* Closes the specified channel after all queued write requests are flushed.
*/
public static void closeOnFlush(Channel ch) {
if (ch.isActive()) {
ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
private ChannelUtils() {
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ForwardClient.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ForwardClient.java | package com.alibaba.arthas.tunnel.client;
import java.net.URI;
import java.net.URISyntaxException;
import javax.net.ssl.SSLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.taobao.arthas.common.ArthasConstants;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.util.concurrent.DefaultThreadFactory;
/**
*
* @author hengyunabc 2019-08-28
*
*/
public class ForwardClient {
private final static Logger logger = LoggerFactory.getLogger(ForwardClient.class);
private URI tunnelServerURI;
public ForwardClient(URI tunnelServerURI) {
this.tunnelServerURI = tunnelServerURI;
}
public void start() throws URISyntaxException, SSLException, InterruptedException {
String scheme = tunnelServerURI.getScheme() == null ? "ws" : tunnelServerURI.getScheme();
final String host = tunnelServerURI.getHost() == null ? "127.0.0.1" : tunnelServerURI.getHost();
final int port;
if (tunnelServerURI.getPort() == -1) {
if ("ws".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("wss".equalsIgnoreCase(scheme)) {
port = 443;
} else {
port = -1;
}
} else {
port = tunnelServerURI.getPort();
}
if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
logger.error("Only WS(S) is supported, uri: {}", tunnelServerURI);
return;
}
final boolean ssl = "wss".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
// connect to local server
WebSocketClientProtocolConfig clientProtocolConfig = WebSocketClientProtocolConfig.newBuilder()
.webSocketUri(tunnelServerURI)
.maxFramePayloadLength(ArthasConstants.MAX_HTTP_CONTENT_LENGTH).build();
final WebSocketClientProtocolHandler websocketClientHandler = new WebSocketClientProtocolHandler(
clientProtocolConfig);
final ForwardClientSocketClientHandler forwardClientSocketClientHandler = new ForwardClientSocketClientHandler();
final EventLoopGroup group = new NioEventLoopGroup(1, new DefaultThreadFactory("arthas-ForwardClient", true));
ChannelFuture closeFuture = null;
try {
Bootstrap b = new Bootstrap();
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
}
p.addLast(new HttpClientCodec(), new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH), websocketClientHandler,
forwardClientSocketClientHandler);
}
});
closeFuture = b.connect(tunnelServerURI.getHost(), port).sync().channel().closeFuture();
logger.info("forward client connect to server success, uri: " + tunnelServerURI);
} finally {
if (closeFuture != null) {
closeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
group.shutdownGracefully();
}
});
} else {
group.shutdownGracefully();
}
}
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/TunnelClientSocketClientHandler.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/TunnelClientSocketClientHandler.java |
package com.alibaba.arthas.tunnel.client;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.arthas.tunnel.common.MethodConstants;
import com.alibaba.arthas.tunnel.common.SimpleHttpResponse;
import com.alibaba.arthas.tunnel.common.URIConstans;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.base64.Base64;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.QueryStringEncoder;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
/**
*
* @author hengyunabc 2019-08-28
*
*/
public class TunnelClientSocketClientHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
private final static Logger logger = LoggerFactory.getLogger(TunnelClientSocketClientHandler.class);
private final TunnelClient tunnelClient;
private ChannelPromise registerPromise;
public TunnelClientSocketClientHandler(TunnelClient tunnelClient) {
this.tunnelClient = tunnelClient;
}
public ChannelFuture registerFuture() {
return registerPromise;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
registerPromise = ctx.newPromise();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
if (frame instanceof TextWebSocketFrame) {
TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
String text = textFrame.text();
logger.info("receive TextWebSocketFrame: {}", text);
QueryStringDecoder queryDecoder = new QueryStringDecoder(text);
Map<String, List<String>> parameters = queryDecoder.parameters();
List<String> methodList = parameters.get(URIConstans.METHOD);
String method = null;
if (methodList != null && !methodList.isEmpty()) {
method = methodList.get(0);
}
if (MethodConstants.AGENT_REGISTER.equals(method)) {
List<String> idList = parameters.get(URIConstans.ID);
if (idList != null && !idList.isEmpty()) {
this.tunnelClient.setId(idList.get(0));
}
tunnelClient.setConnected(true);
registerPromise.setSuccess();
}
if (MethodConstants.START_TUNNEL.equals(method)) {
QueryStringEncoder queryEncoder = new QueryStringEncoder(this.tunnelClient.getTunnelServerUrl());
queryEncoder.addParam(URIConstans.METHOD, MethodConstants.OPEN_TUNNEL);
queryEncoder.addParam(URIConstans.CLIENT_CONNECTION_ID, parameters.get(URIConstans.CLIENT_CONNECTION_ID).get(0));
queryEncoder.addParam(URIConstans.ID, parameters.get(URIConstans.ID).get(0));
final URI forwardUri = queryEncoder.toUri();
logger.info("start ForwardClient, uri: {}", forwardUri);
try {
ForwardClient forwardClient = new ForwardClient(forwardUri);
forwardClient.start();
} catch (Throwable e) {
logger.error("start ForwardClient error, forwardUri: {}", forwardUri, e);
}
}
if (MethodConstants.HTTP_PROXY.equals(method)) {
/**
* <pre>
* 1. 从proxy请求里读取到目标的 targetUrl,和 requestId
* 2. 然后通过 ProxyClient直接请求得到结果
* 3. 把response结果转为 byte[],再转为base64,再统一组合的一个url,再用 TextWebSocketFrame 发回去
* </pre>
*
*/
ProxyClient proxyClient = new ProxyClient();
List<String> targetUrls = parameters.get(URIConstans.TARGET_URL);
List<String> requestIDs = parameters.get(URIConstans.PROXY_REQUEST_ID);
String id = null;
if (requestIDs != null && !requestIDs.isEmpty()) {
id = requestIDs.get(0);
}
if (id == null) {
logger.error("error, http proxy need {}", URIConstans.PROXY_REQUEST_ID);
return;
}
if (targetUrls != null && !targetUrls.isEmpty()) {
String targetUrl = targetUrls.get(0);
SimpleHttpResponse simpleHttpResponse = proxyClient.query(targetUrl);
ByteBuf byteBuf = null;
try{
byteBuf = Base64
.encode(Unpooled.wrappedBuffer(SimpleHttpResponse.toBytes(simpleHttpResponse)));
String requestData = byteBuf.toString(CharsetUtil.UTF_8);
QueryStringEncoder queryEncoder = new QueryStringEncoder("");
queryEncoder.addParam(URIConstans.METHOD, MethodConstants.HTTP_PROXY);
queryEncoder.addParam(URIConstans.PROXY_REQUEST_ID, id);
queryEncoder.addParam(URIConstans.PROXY_RESPONSE_DATA, requestData);
String url = queryEncoder.toString();
ctx.writeAndFlush(new TextWebSocketFrame(url));
}finally {
if (byteBuf != null) {
byteBuf.release();
}
}
}
}
}
}
@Override
public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception {
tunnelClient.setConnected(false);
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
logger.error("try to reconnect to tunnel server, uri: {}", tunnelClient.getTunnelServerUrl());
try {
tunnelClient.connect(true);
} catch (Throwable e) {
logger.error("reconnect error", e);
}
}
}, tunnelClient.getReconnectDelay(), TimeUnit.SECONDS);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ctx.writeAndFlush(new PingWebSocketFrame());
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("TunnelClient error, tunnel server url: " + tunnelClient.getTunnelServerUrl(), cause);
if (!registerPromise.isDone()) {
registerPromise.setFailure(cause);
}
ctx.close();
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/TunnelClient.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/TunnelClient.java | package com.alibaba.arthas.tunnel.client;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.net.ssl.SSLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.arthas.tunnel.common.MethodConstants;
import com.alibaba.arthas.tunnel.common.URIConstans;
import com.taobao.arthas.common.ArthasConstants;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.QueryStringEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
/**
*
* @author hengyunabc 2019-08-28
*
*/
public class TunnelClient {
private final static Logger logger = LoggerFactory.getLogger(TunnelClient.class);
private String tunnelServerUrl;
private int reconnectDelay = 5;
// connect to proxy server
// two thread because need to reconnect. #1284
private EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2, new DefaultThreadFactory("arthas-TunnelClient", true));
private String appName;
// agent id, generated by tunnel server. if reconnect, reuse the id
volatile private String id;
/**
* arthas version
*/
private String version = "unknown";
private volatile boolean connected = false;
public ChannelFuture start() throws IOException, InterruptedException, URISyntaxException {
return connect(false);
}
public ChannelFuture connect(boolean reconnect) throws SSLException, URISyntaxException, InterruptedException {
QueryStringEncoder queryEncoder = new QueryStringEncoder(this.tunnelServerUrl);
queryEncoder.addParam(URIConstans.METHOD, MethodConstants.AGENT_REGISTER);
queryEncoder.addParam(URIConstans.ARTHAS_VERSION, this.version);
if (appName != null) {
queryEncoder.addParam(URIConstans.APP_NAME, appName);
}
if (id != null) {
queryEncoder.addParam(URIConstans.ID, id);
}
// ws://127.0.0.1:7777/ws?method=agentRegister
final URI agentRegisterURI = queryEncoder.toUri();
logger.info("Try to register arthas agent, uri: {}", agentRegisterURI);
String scheme = agentRegisterURI.getScheme() == null ? "ws" : agentRegisterURI.getScheme();
final String host = agentRegisterURI.getHost() == null ? "127.0.0.1" : agentRegisterURI.getHost();
final int port;
if (agentRegisterURI.getPort() == -1) {
if ("ws".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("wss".equalsIgnoreCase(scheme)) {
port = 443;
} else {
port = -1;
}
} else {
port = agentRegisterURI.getPort();
}
if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
throw new IllegalArgumentException("Only WS(S) is supported. tunnelServerUrl: " + tunnelServerUrl);
}
final boolean ssl = "wss".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
WebSocketClientProtocolConfig clientProtocolConfig = WebSocketClientProtocolConfig.newBuilder()
.webSocketUri(agentRegisterURI)
.maxFramePayloadLength(ArthasConstants.MAX_HTTP_CONTENT_LENGTH).build();
final WebSocketClientProtocolHandler websocketClientHandler = new WebSocketClientProtocolHandler(
clientProtocolConfig);
final TunnelClientSocketClientHandler handler = new TunnelClientSocketClientHandler(TunnelClient.this);
Bootstrap bs = new Bootstrap();
bs.group(eventLoopGroup)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.option(ChannelOption.TCP_NODELAY, true)
.channel(NioSocketChannel.class).remoteAddress(host, port)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
}
p.addLast(new HttpClientCodec(), new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH), websocketClientHandler,
new IdleStateHandler(0, 0, ArthasConstants.WEBSOCKET_IDLE_SECONDS),
handler);
}
});
ChannelFuture connectFuture = bs.connect();
if (reconnect) {
connectFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.cause() != null) {
logger.error("connect to tunnel server error, uri: {}", tunnelServerUrl, future.cause());
}
}
});
}
connectFuture.sync();
return handler.registerFuture();
}
public void stop() {
eventLoopGroup.shutdownGracefully();
}
public String getTunnelServerUrl() {
return tunnelServerUrl;
}
public void setTunnelServerUrl(String tunnelServerUrl) {
this.tunnelServerUrl = tunnelServerUrl;
}
public int getReconnectDelay() {
return reconnectDelay;
}
public void setReconnectDelay(int reconnectDelay) {
this.reconnectDelay = reconnectDelay;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
alibaba/arthas | https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ForwardClientSocketClientHandler.java | tunnel-client/src/main/java/com/alibaba/arthas/tunnel/client/ForwardClientSocketClientHandler.java | package com.alibaba.arthas.tunnel.client;
import java.net.URISyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.taobao.arthas.common.ArthasConstants;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler.ClientHandshakeStateEvent;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.GenericFutureListener;
/**
* @author hengyunabc 2019-08-28
*/
public class ForwardClientSocketClientHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
private static final Logger logger = LoggerFactory.getLogger(ForwardClientSocketClientHandler.class);
private ChannelPromise handshakeFuture;
@Override
public void channelActive(ChannelHandlerContext ctx) {
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
logger.info("WebSocket Client disconnected!");
}
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) {
if (evt.equals(ClientHandshakeStateEvent.HANDSHAKE_COMPLETE)) {
try {
connectLocalServer(ctx);
} catch (Throwable e) {
logger.error("ForwardClientSocketClientHandler connect local arthas server error", e);
}
} else {
ctx.fireUserEventTriggered(evt);
}
}
private void connectLocalServer(final ChannelHandlerContext ctx) throws InterruptedException, URISyntaxException {
final EventLoopGroup group = new NioEventLoopGroup(1, new DefaultThreadFactory("arthas-forward-client-connect-local", true));
ChannelFuture closeFuture = null;
try {
logger.info("ForwardClientSocketClientHandler star connect local arthas server");
// 入参URI实际无意义,只为了程序不出错
WebSocketClientProtocolConfig clientProtocolConfig = WebSocketClientProtocolConfig.newBuilder()
.webSocketUri("ws://127.0.0.1:8563/ws")
.maxFramePayloadLength(ArthasConstants.MAX_HTTP_CONTENT_LENGTH).build();
final WebSocketClientProtocolHandler websocketClientHandler = new WebSocketClientProtocolHandler(
clientProtocolConfig);
final LocalFrameHandler localFrameHandler = new LocalFrameHandler();
Bootstrap b = new Bootstrap();
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
b.group(group).channel(LocalChannel.class)
.handler(new ChannelInitializer<LocalChannel>() {
@Override
protected void initChannel(LocalChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec(), new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH), websocketClientHandler,
localFrameHandler);
}
});
LocalAddress localAddress = new LocalAddress(ArthasConstants.NETTY_LOCAL_ADDRESS);
Channel localChannel = b.connect(localAddress).sync().channel();
// Channel localChannel = b.connect(localServerURI.getHost(), localServerURI.getPort()).sync().channel();
this.handshakeFuture = localFrameHandler.handshakeFuture();
handshakeFuture.addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
ChannelPipeline pipeline = future.channel().pipeline();
pipeline.remove(localFrameHandler);
pipeline.addLast(new RelayHandler(ctx.channel()));
}
});
handshakeFuture.sync();
ctx.pipeline().remove(ForwardClientSocketClientHandler.this);
ctx.pipeline().addLast(new RelayHandler(localChannel));
logger.info("ForwardClientSocketClientHandler connect local arthas server success");
closeFuture = localChannel.closeFuture();
} finally {
if (closeFuture != null) {
closeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
group.shutdownGracefully();
}
});
} else {
group.shutdownGracefully();
}
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("ForwardClientSocketClient channel: {}" , ctx.channel(), cause);
if (!handshakeFuture.isDone()) {
handshakeFuture.setFailure(cause);
}
ctx.close();
}
}
| java | Apache-2.0 | 17eb3c17e764728e6bf2cf3a37d56620e8835fd0 | 2026-01-04T14:45:57.082411Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/test/java/org/apache/dubbo/spring/security/oauth2/DeserializationTest.java | dubbo-plugin/dubbo-spring6-security/src/test/java/org/apache/dubbo/spring/security/oauth2/DeserializationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.spring.security.jackson.ObjectMapperCodec;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
@SpringBootTest(
properties = {"dubbo.registry.address=N/A"},
classes = {DeserializationTest.class})
@Configuration
public class DeserializationTest {
private static ObjectMapperCodec mapper;
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
mapper = ApplicationModel.defaultModel().getDefaultModule().getBean(ObjectMapperCodec.class);
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
public void bearerTokenAuthenticationTest() {
BearerTokenAuthentication bearerTokenAuthentication = new BearerTokenAuthentication(
new DefaultOAuth2AuthenticatedPrincipal(
"principal-name",
Collections.singletonMap("name", "kali"),
Collections.singleton(new SimpleGrantedAuthority("1"))),
new OAuth2AccessToken(TokenType.BEARER, "111", Instant.MIN, Instant.MAX),
Collections.emptyList());
String content = mapper.serialize(bearerTokenAuthentication);
BearerTokenAuthentication deserialize = mapper.deserialize(content.getBytes(), BearerTokenAuthentication.class);
Assertions.assertNotNull(deserialize);
}
@Test
public void oauth2ClientAuthenticationTokenTest() {
OAuth2ClientAuthenticationToken oAuth2ClientAuthenticationToken = new OAuth2ClientAuthenticationToken(
"client-id", ClientAuthenticationMethod.CLIENT_SECRET_POST, "111", Collections.emptyMap());
String content = mapper.serialize(oAuth2ClientAuthenticationToken);
OAuth2ClientAuthenticationToken deserialize =
mapper.deserialize(content.getBytes(), OAuth2ClientAuthenticationToken.class);
Assertions.assertNotNull(deserialize);
}
@Test
public void registeredClientTest() {
RegisteredClient registeredClient = RegisteredClient.withId("id")
.clientId("client-id")
.clientName("client-name")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("https://example.com")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.clientSecret("client-secret")
.clientIdIssuedAt(Instant.MIN)
.clientSecretExpiresAt(Instant.MAX)
.tokenSettings(TokenSettings.builder()
.accessTokenFormat(OAuth2TokenFormat.REFERENCE)
.accessTokenTimeToLive(Duration.ofSeconds(1000))
.build())
.clientSettings(ClientSettings.builder()
.setting("name", "value")
.requireProofKey(true)
.build())
.build();
String content = mapper.serialize(registeredClient);
RegisteredClient deserialize = mapper.deserialize(content.getBytes(), RegisteredClient.class);
Assertions.assertEquals(registeredClient, deserialize);
}
@Configuration
@ImportResource("classpath:/dubbo-test.xml")
public static class OAuth2SecurityTestConfiguration {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/AuthorizationGrantTypeMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/AuthorizationGrantTypeMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class AuthorizationGrantTypeMixin {
@JsonCreator
public AuthorizationGrantTypeMixin(@JsonProperty("value") String value) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/UnmodifiableCollectionMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/UnmodifiableCollectionMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import org.apache.dubbo.spring.security.oauth2.UnmodifiableCollectionMixin.UnmodifiableCollectionConverter;
import java.util.Collection;
import java.util.Collections;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.util.StdConverter;
@JsonDeserialize(converter = UnmodifiableCollectionConverter.class)
abstract class UnmodifiableCollectionMixin {
public static class UnmodifiableCollectionConverter extends StdConverter<Collection<Object>, Collection<Object>> {
@Override
public Collection<Object> convert(Collection<Object> value) {
return Collections.unmodifiableCollection(value);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/OAuth2ClientAuthenticationTokenMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/OAuth2ClientAuthenticationTokenMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2ClientAuthenticationTokenMixin {
@JsonCreator
public OAuth2ClientAuthenticationTokenMixin(
@JsonProperty("clientId") String clientId,
@JsonProperty("clientAuthenticationMethod") ClientAuthenticationMethod clientAuthenticationMethod,
@JsonProperty("credentials") @Nullable Object credentials,
@JsonProperty("additionalParameters") @Nullable Map<String, Object> additionalParameters) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/RegisteredClientMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/RegisteredClientMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import java.time.Instant;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class RegisteredClientMixin {
@JsonCreator
public RegisteredClientMixin(
@JsonProperty("id") String id,
@JsonProperty("clientId") String clientId,
@JsonProperty("clientIdIssuedAt") Instant clientIdIssuedAt,
@JsonProperty("clientSecret") String clientSecret,
@JsonProperty("clientSecretExpiresAt") Instant clientSecretExpiresAt,
@JsonProperty("clientName") String clientName,
@JsonProperty("clientAuthenticationMethods") Set<ClientAuthenticationMethod> clientAuthenticationMethods,
@JsonProperty("authorizationGrantTypes") Set<AuthorizationGrantType> authorizationGrantTypes,
@JsonProperty("redirectUris") Set<String> redirectUris,
@JsonProperty("postLogoutRedirectUris") Set<String> postLogoutRedirectUris,
@JsonProperty("scopes") Set<String> scopes,
@JsonProperty("clientSettings") ClientSettings clientSettings,
@JsonProperty("tokenSettings") TokenSettings tokenSettings) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/TokenSettingsMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/TokenSettingsMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class TokenSettingsMixin {
@JsonCreator
public TokenSettingsMixin(@JsonProperty("settings") Map<String, Object> settings) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/OAuth2AuthenticatedPrincipalMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/OAuth2AuthenticatedPrincipalMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import java.util.Collection;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.core.GrantedAuthority;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2AuthenticatedPrincipalMixin {
@JsonCreator
public OAuth2AuthenticatedPrincipalMixin(
@JsonProperty("name") String name,
@JsonProperty("attributes") Map<String, Object> attributes,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/ClientSettingsMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/ClientSettingsMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class ClientSettingsMixin {
@JsonCreator
public ClientSettingsMixin(@JsonProperty("settings") Map<String, Object> settings) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/BearerTokenAuthenticationMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/BearerTokenAuthenticationMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class BearerTokenAuthenticationMixin {
@JsonCreator
public BearerTokenAuthenticationMixin(
@JsonProperty("principal") OAuth2AuthenticatedPrincipal principal,
@JsonProperty("credentials") OAuth2AccessToken credentials,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/ClientAuthenticationMethodMixin.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/ClientAuthenticationMethodMixin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class ClientAuthenticationMethodMixin {
@JsonCreator
public ClientAuthenticationMethodMixin(@JsonProperty("value") String value) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/OAuth2SecurityModule.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/OAuth2SecurityModule.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2;
import org.apache.dubbo.common.utils.ClassUtils;
import java.util.ArrayList;
import java.util.Collections;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class OAuth2SecurityModule extends SimpleModule {
public OAuth2SecurityModule() {
super(OAuth2SecurityModule.class.getName());
}
@Override
public void setupModule(SetupContext context) {
setMixInAnnotations(
context,
"org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal",
"org.apache.dubbo.spring.security.oauth2.OAuth2AuthenticatedPrincipalMixin");
setMixInAnnotations(
context,
"org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal",
"org.apache.dubbo.spring.security.oauth2.OAuth2AuthenticatedPrincipalMixin");
setMixInAnnotations(
context,
"org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication",
"org.apache.dubbo.spring.security.oauth2.BearerTokenAuthenticationMixin");
setMixInAnnotations(
context,
"org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken",
"org.apache.dubbo.spring.security.oauth2.OAuth2ClientAuthenticationTokenMixin");
setMixInAnnotations(
context,
"org.springframework.security.oauth2.core.ClientAuthenticationMethod",
ClientAuthenticationMethodMixin.class);
setMixInAnnotations(
context,
"org.springframework.security.oauth2.server.authorization.client.RegisteredClient",
"org.apache.dubbo.spring.security.oauth2.RegisteredClientMixin");
setMixInAnnotations(
context,
"org.springframework.security.oauth2.core.AuthorizationGrantType",
AuthorizationGrantTypeMixin.class);
setMixInAnnotations(
context,
"org.springframework.security.oauth2.server.authorization.settings.ClientSettings",
ClientSettingsMixin.class);
setMixInAnnotations(
context,
"org.springframework.security.oauth2.server.authorization.settings.TokenSettings",
TokenSettingsMixin.class);
context.setMixInAnnotations(
Collections.unmodifiableCollection(new ArrayList<>()).getClass(), UnmodifiableCollectionMixin.class);
}
private void setMixInAnnotations(SetupContext context, String oauth2ClassName, String mixinClassName) {
Class<?> oauth2Class = loadClassIfPresent(oauth2ClassName);
if (oauth2Class != null) {
context.setMixInAnnotations(oauth2Class, loadClassIfPresent(mixinClassName));
}
}
private void setMixInAnnotations(SetupContext context, String oauth2ClassName, Class<?> mixinClass) {
Class<?> oauth2Class = loadClassIfPresent(oauth2ClassName);
if (oauth2Class != null) {
context.setMixInAnnotations(oauth2Class, mixinClass);
}
}
private Class<?> loadClassIfPresent(String oauth2ClassName) {
try {
return ClassUtils.forName(oauth2ClassName, OAuth2SecurityModule.class.getClassLoader());
} catch (Throwable ignored) {
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/jackson/OAuth2ObjectMapperCodecCustomer.java | dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/jackson/OAuth2ObjectMapperCodecCustomer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.spring.security.oauth2.jackson;
import org.apache.dubbo.spring.security.jackson.ObjectMapperCodec;
import org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer;
import org.apache.dubbo.spring.security.oauth2.OAuth2SecurityModule;
import java.util.List;
import com.fasterxml.jackson.databind.Module;
import org.springframework.security.jackson2.SecurityJackson2Modules;
public class OAuth2ObjectMapperCodecCustomer implements ObjectMapperCodecCustomer {
@Override
public void customize(ObjectMapperCodec objectMapperCodec) {
objectMapperCodec.configureMapper(mapper -> {
mapper.registerModule(new OAuth2SecurityModule());
List<Module> securityModules =
SecurityJackson2Modules.getModules(this.getClass().getClassLoader());
mapper.registerModules(securityModules);
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/CertDeployerListenerTest.java | dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/CertDeployerListenerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
class CertDeployerListenerTest {
@Test
void testEmpty1() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(0)).connect(Mockito.any());
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testEmpty2() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
applicationModel.getApplicationConfigManager().setSsl(new SslConfig());
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(0)).connect(Mockito.any());
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testCreate() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(1)).connect(Mockito.any());
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testFailure() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getApplicationConfigManager().addMetadataReport(new MetadataReportConfig("absent"));
ApplicationDeployer deployer = applicationModel.getDeployer();
Assertions.assertThrows(IllegalArgumentException.class, deployer::start);
Mockito.verify(reference.get(), Mockito.times(1)).connect(Mockito.any());
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testNotFound1() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("io.grpc.Channel")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
applicationModel.getDeployer().stop();
Assertions.assertEquals(0, construction.constructed().size());
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void testNotFound2() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
applicationModel.getDeployer().stop();
Assertions.assertEquals(0, construction.constructed().size());
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void testParams1() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
sslConfig.setCaCertPath("certs/ca.crt");
sslConfig.setOidcTokenPath("token");
sslConfig.setEnvType("test");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(1))
.connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token"));
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Disabled("Enable me until properties from envs work.")
@Test
void testParams2() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
System.setProperty("dubbo.ssl.ca-address", "127.0.0.1:30060");
System.setProperty("dubbo.ssl.ca-cert-path", "certs/ca.crt");
System.setProperty("dubbo.ssl.oidc-token-path", "token");
System.setProperty("dubbo.ssl.env-type", "test");
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(1))
.connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token"));
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
System.clearProperty("dubbo.ssl.ca-address");
System.clearProperty("dubbo.ssl.ca-cert-path");
System.clearProperty("dubbo.ssl.oidc-token-path");
System.clearProperty("dubbo.ssl.env-type");
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertManagerTest.java | dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertManagerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateResponse;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateServiceGrpc;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.IOException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import io.grpc.Channel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.awaitility.Awaitility.await;
import static org.mockito.Answers.CALLS_REAL_METHODS;
class DubboCertManagerTest {
@Test
void test1() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel) {
@Override
protected void connect0(CertConfig certConfig) {
Assertions.assertEquals("127.0.0.1:30060", certConfig.getRemoteAddress());
Assertions.assertEquals("caCertPath", certConfig.getCaCertPath());
}
@Override
protected CertPair generateCert() {
return null;
}
@Override
protected void scheduleRefresh() {}
};
certManager.connect(new CertConfig("127.0.0.1:30060", null, "caCertPath", "oidc"));
Assertions.assertEquals(new CertConfig("127.0.0.1:30060", null, "caCertPath", "oidc"), certManager.certConfig);
certManager.connect(new CertConfig("127.0.0.1:30060", "Kubernetes", "caCertPath", "oidc123"));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "Kubernetes", "caCertPath", "oidc123"), certManager.certConfig);
certManager.connect(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
CertConfig certConfig = new CertConfig("127.0.0.1:30060", "vm", "caCertPath", "oidc");
Assertions.assertThrows(IllegalArgumentException.class, () -> certManager.connect(certConfig));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
certManager.connect(null);
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
certManager.connect(new CertConfig(null, null, null, null));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
certManager.channel = Mockito.mock(Channel.class);
certManager.connect(new CertConfig("error", null, "error", "error"));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
frameworkModel.destroy();
}
@Test
void testRefresh() {
FrameworkModel frameworkModel = new FrameworkModel();
AtomicInteger count = new AtomicInteger(0);
DubboCertManager certManager = new DubboCertManager(frameworkModel) {
@Override
protected CertPair generateCert() {
count.incrementAndGet();
return null;
}
};
certManager.certConfig = new CertConfig(null, null, null, null, 10);
certManager.scheduleRefresh();
Assertions.assertNotNull(certManager.refreshFuture);
await().until(() -> count.get() > 1);
certManager.refreshFuture.cancel(false);
frameworkModel.destroy();
}
@Test
void testConnect1() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, null, null);
certManager.connect0(certConfig);
Assertions.assertNotNull(certManager.channel);
Assertions.assertEquals("127.0.0.1:30062", certManager.channel.authority());
frameworkModel.destroy();
}
@Test
void testConnect2() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
String file =
this.getClass().getClassLoader().getResource("certs/ca.crt").getFile();
CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, file, null);
certManager.connect0(certConfig);
Assertions.assertNotNull(certManager.channel);
Assertions.assertEquals("127.0.0.1:30062", certManager.channel.authority());
frameworkModel.destroy();
}
@Test
void testConnect3() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
String file = this.getClass()
.getClassLoader()
.getResource("certs/broken-ca.crt")
.getFile();
CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, file, null);
Assertions.assertThrows(RuntimeException.class, () -> certManager.connect0(certConfig));
frameworkModel.destroy();
}
@Test
void testDisconnect() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
ScheduledFuture scheduledFuture = Mockito.mock(ScheduledFuture.class);
certManager.refreshFuture = scheduledFuture;
certManager.disConnect();
Assertions.assertNull(certManager.refreshFuture);
Mockito.verify(scheduledFuture, Mockito.times(1)).cancel(true);
certManager.channel = Mockito.mock(Channel.class);
certManager.disConnect();
Assertions.assertNull(certManager.channel);
frameworkModel.destroy();
}
@Test
void testConnected() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
Assertions.assertFalse(certManager.isConnected());
certManager.certConfig = Mockito.mock(CertConfig.class);
Assertions.assertFalse(certManager.isConnected());
certManager.channel = Mockito.mock(Channel.class);
Assertions.assertFalse(certManager.isConnected());
certManager.certPair = Mockito.mock(CertPair.class);
Assertions.assertTrue(certManager.isConnected());
frameworkModel.destroy();
}
@Test
void testGenerateCert() {
FrameworkModel frameworkModel = new FrameworkModel();
AtomicBoolean exception = new AtomicBoolean(false);
AtomicReference<CertPair> certPairReference = new AtomicReference<>();
DubboCertManager certManager = new DubboCertManager(frameworkModel) {
@Override
protected CertPair refreshCert() throws IOException {
if (exception.get()) {
throw new IOException("test");
}
return certPairReference.get();
}
};
CertPair certPair = new CertPair("", "", "", Long.MAX_VALUE);
certPairReference.set(certPair);
Assertions.assertEquals(certPair, certManager.generateCert());
certManager.certPair = new CertPair("", "", "", Long.MAX_VALUE - 10000);
Assertions.assertEquals(new CertPair("", "", "", Long.MAX_VALUE - 10000), certManager.generateCert());
certManager.certPair = new CertPair("", "", "", 0);
Assertions.assertEquals(certPair, certManager.generateCert());
certManager.certPair = new CertPair("", "", "", 0);
certPairReference.set(null);
Assertions.assertEquals(new CertPair("", "", "", 0), certManager.generateCert());
exception.set(true);
Assertions.assertEquals(new CertPair("", "", "", 0), certManager.generateCert());
frameworkModel.destroy();
}
@Test
void testSignWithRsa() {
DubboCertManager.KeyPair keyPair = DubboCertManager.signWithRsa();
Assertions.assertNotNull(keyPair);
Assertions.assertNotNull(keyPair.getPrivateKey());
Assertions.assertNotNull(keyPair.getPublicKey());
Assertions.assertNotNull(keyPair.getSigner());
}
@Test
void testSignWithEcdsa() {
DubboCertManager.KeyPair keyPair = DubboCertManager.signWithEcdsa();
Assertions.assertNotNull(keyPair);
Assertions.assertNotNull(keyPair.getPrivateKey());
Assertions.assertNotNull(keyPair.getPublicKey());
Assertions.assertNotNull(keyPair.getSigner());
}
@Test
void testRefreshCert() throws IOException {
try (MockedStatic<DubboCertManager> managerMock =
Mockito.mockStatic(DubboCertManager.class, CALLS_REAL_METHODS)) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
managerMock.when(DubboCertManager::signWithEcdsa).thenReturn(null);
managerMock.when(DubboCertManager::signWithRsa).thenReturn(null);
Assertions.assertNull(certManager.refreshCert());
managerMock.when(DubboCertManager::signWithEcdsa).thenCallRealMethod();
certManager.channel = Mockito.mock(Channel.class);
try (MockedStatic<DubboCertificateServiceGrpc> mockGrpc =
Mockito.mockStatic(DubboCertificateServiceGrpc.class, CALLS_REAL_METHODS)) {
DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub =
Mockito.mock(DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub.class);
mockGrpc.when(() -> DubboCertificateServiceGrpc.newBlockingStub(Mockito.any(Channel.class)))
.thenReturn(stub);
Mockito.when(stub.createCertificate(Mockito.any()))
.thenReturn(DubboCertificateResponse.newBuilder()
.setSuccess(false)
.build());
certManager.certConfig = new CertConfig(null, null, null, null);
Assertions.assertNull(certManager.refreshCert());
String file = this.getClass()
.getClassLoader()
.getResource("certs/token")
.getFile();
Mockito.when(stub.withInterceptors(Mockito.any())).thenReturn(stub);
certManager.certConfig = new CertConfig(null, null, null, file);
Assertions.assertNull(certManager.refreshCert());
Mockito.verify(stub, Mockito.times(1)).withInterceptors(Mockito.any());
Mockito.when(stub.createCertificate(Mockito.any()))
.thenReturn(DubboCertificateResponse.newBuilder()
.setSuccess(true)
.setCertPem("certPem")
.addTrustCerts("trustCerts")
.setExpireTime(123456)
.build());
CertPair certPair = certManager.refreshCert();
Assertions.assertNotNull(certPair);
Assertions.assertEquals("certPem", certPair.getCertificate());
Assertions.assertEquals("trustCerts", certPair.getTrustCerts());
Assertions.assertEquals(123456, certPair.getExpireTime());
Mockito.when(stub.createCertificate(Mockito.any())).thenReturn(null);
Assertions.assertNull(certManager.refreshCert());
}
frameworkModel.destroy();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertProviderTest.java | dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertProviderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import org.apache.dubbo.common.ssl.AuthPolicy;
import org.apache.dubbo.common.ssl.Cert;
import org.apache.dubbo.common.ssl.ProviderCert;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
class DubboCertProviderTest {
@Test
void testEnable() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Mockito.when(reference.get().isConnected()).thenReturn(true);
Assertions.assertTrue(provider.isSupport(null));
Mockito.when(reference.get().isConnected()).thenReturn(false);
Assertions.assertFalse(provider.isSupport(null));
frameworkModel.destroy();
}
}
@Test
void testEnable1() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("io.grpc.Channel")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertFalse(provider.isSupport(null));
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void testEnable2() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertFalse(provider.isSupport(null));
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void getProviderConnectionConfigTest() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertNull(provider.getProviderConnectionConfig(null));
CertPair certPair = new CertPair("privateKey", "publicKey", "trustCerts", 12345);
Mockito.when(reference.get().generateCert()).thenReturn(certPair);
ProviderCert providerConnectionConfig = provider.getProviderConnectionConfig(null);
Assertions.assertArrayEquals("privateKey".getBytes(), providerConnectionConfig.getPrivateKey());
Assertions.assertArrayEquals("publicKey".getBytes(), providerConnectionConfig.getKeyCertChain());
Assertions.assertArrayEquals("trustCerts".getBytes(), providerConnectionConfig.getTrustCert());
Assertions.assertEquals(AuthPolicy.NONE, providerConnectionConfig.getAuthPolicy());
frameworkModel.destroy();
}
}
@Test
void getConsumerConnectionConfigTest() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertNull(provider.getConsumerConnectionConfig(null));
CertPair certPair = new CertPair("privateKey", "publicKey", "trustCerts", 12345);
Mockito.when(reference.get().generateCert()).thenReturn(certPair);
Cert connectionConfig = provider.getConsumerConnectionConfig(null);
Assertions.assertArrayEquals("privateKey".getBytes(), connectionConfig.getPrivateKey());
Assertions.assertArrayEquals("publicKey".getBytes(), connectionConfig.getKeyCertChain());
Assertions.assertArrayEquals("trustCerts".getBytes(), connectionConfig.getTrustCert());
frameworkModel.destroy();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertPair.java | dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertPair.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import java.util.Objects;
public class CertPair {
private final String privateKey;
private final String certificate;
private final String trustCerts;
private final long expireTime;
public CertPair(String privateKey, String certificate, String trustCerts, long expireTime) {
this.privateKey = privateKey;
this.certificate = certificate;
this.trustCerts = trustCerts;
this.expireTime = expireTime;
}
public String getPrivateKey() {
return privateKey;
}
public String getCertificate() {
return certificate;
}
public String getTrustCerts() {
return trustCerts;
}
public long getExpireTime() {
return expireTime;
}
public boolean isExpire() {
return System.currentTimeMillis() > expireTime;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CertPair certPair = (CertPair) o;
return expireTime == certPair.expireTime
&& Objects.equals(privateKey, certPair.privateKey)
&& Objects.equals(certificate, certPair.certificate)
&& Objects.equals(trustCerts, certPair.trustCerts);
}
@Override
public int hashCode() {
return Objects.hash(privateKey, certificate, trustCerts, expireTime);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertScopeModelInitializer.java | dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertScopeModelInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class CertScopeModelInitializer implements ScopeModelInitializer {
public static boolean isSupported() {
try {
ClassUtils.forName("io.grpc.Channel");
ClassUtils.forName("org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder");
return true;
} catch (Throwable t) {
return false;
}
}
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
if (isSupported()) {
beanFactory.registerBean(DubboCertManager.class);
}
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertConfig.java | dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import java.util.Objects;
import static org.apache.dubbo.security.cert.Constants.DEFAULT_REFRESH_INTERVAL;
public class CertConfig {
private final String remoteAddress;
private final String envType;
private final String caCertPath;
/**
* Path to OpenID Connect Token file
*/
private final String oidcTokenPath;
private final int refreshInterval;
public CertConfig(String remoteAddress, String envType, String caCertPath, String oidcTokenPath) {
this(remoteAddress, envType, caCertPath, oidcTokenPath, DEFAULT_REFRESH_INTERVAL);
}
public CertConfig(
String remoteAddress, String envType, String caCertPath, String oidcTokenPath, int refreshInterval) {
this.remoteAddress = remoteAddress;
this.envType = envType;
this.caCertPath = caCertPath;
this.oidcTokenPath = oidcTokenPath;
this.refreshInterval = refreshInterval;
}
public String getRemoteAddress() {
return remoteAddress;
}
public String getEnvType() {
return envType;
}
public String getCaCertPath() {
return caCertPath;
}
public String getOidcTokenPath() {
return oidcTokenPath;
}
public int getRefreshInterval() {
return refreshInterval;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CertConfig that = (CertConfig) o;
return Objects.equals(remoteAddress, that.remoteAddress)
&& Objects.equals(envType, that.envType)
&& Objects.equals(caCertPath, that.caCertPath)
&& Objects.equals(oidcTokenPath, that.oidcTokenPath);
}
@Override
public int hashCode() {
return Objects.hash(remoteAddress, envType, caCertPath, oidcTokenPath);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertManager.java | dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateRequest;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateResponse;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateServiceGrpc;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.IOUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import io.grpc.Channel;
import io.grpc.Metadata;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.bouncycastle.util.io.pem.PemObject;
import static io.grpc.stub.MetadataUtils.newAttachHeadersInterceptor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SSL_CERT_GENERATE_FAILED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SSL_CONNECT_INSECURE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_CERT_ISTIO;
public class DubboCertManager {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboCertManager.class);
private final FrameworkModel frameworkModel;
/**
* gRPC channel to Dubbo Cert Authority server
*/
protected volatile Channel channel;
/**
* Cert pair for current Dubbo instance
*/
protected volatile CertPair certPair;
/**
* Path to OpenID Connect Token file
*/
protected volatile CertConfig certConfig;
/**
* Refresh cert pair for current Dubbo instance
*/
protected volatile ScheduledFuture<?> refreshFuture;
public DubboCertManager(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
public synchronized void connect(CertConfig certConfig) {
if (channel != null) {
logger.error(INTERNAL_ERROR, "", "", "Dubbo Cert Authority server is already connected.");
return;
}
if (certConfig == null) {
// No cert config, return
return;
}
if (StringUtils.isEmpty(certConfig.getRemoteAddress())) {
// No remote address configured, return
return;
}
if (StringUtils.isNotEmpty(certConfig.getEnvType())
&& !"Kubernetes".equalsIgnoreCase(certConfig.getEnvType())) {
throw new IllegalArgumentException("Only support Kubernetes env now.");
}
// Create gRPC connection
connect0(certConfig);
this.certConfig = certConfig;
// Try to generate cert from remote
generateCert();
// Schedule refresh task
scheduleRefresh();
}
/**
* Create task to refresh cert pair for current Dubbo instance
*/
protected void scheduleRefresh() {
FrameworkExecutorRepository repository =
frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class);
refreshFuture = repository
.getSharedScheduledExecutor()
.scheduleAtFixedRate(
this::generateCert,
certConfig.getRefreshInterval(),
certConfig.getRefreshInterval(),
TimeUnit.MILLISECONDS);
}
/**
* Try to connect to remote certificate authorization
*
* @param certConfig certificate authorization address
*/
protected void connect0(CertConfig certConfig) {
String caCertPath = certConfig.getCaCertPath();
String remoteAddress = certConfig.getRemoteAddress();
logger.info(
"Try to connect to Dubbo Cert Authority server: " + remoteAddress + ", caCertPath: " + remoteAddress);
try {
if (StringUtils.isNotEmpty(caCertPath)) {
channel = NettyChannelBuilder.forTarget(remoteAddress)
.sslContext(GrpcSslContexts.forClient()
.trustManager(new File(caCertPath))
.build())
.build();
} else {
logger.warn(
CONFIG_SSL_CONNECT_INSECURE,
"",
"",
"No caCertPath is provided, will use insecure connection.");
channel = NettyChannelBuilder.forTarget(remoteAddress)
.sslContext(GrpcSslContexts.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build())
.build();
}
} catch (Exception e) {
logger.error(LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load SSL cert file.", e);
throw new RuntimeException(e);
}
}
public synchronized void disConnect() {
if (refreshFuture != null) {
refreshFuture.cancel(true);
refreshFuture = null;
}
if (channel != null) {
channel = null;
}
}
public boolean isConnected() {
return certConfig != null && channel != null && certPair != null;
}
protected CertPair generateCert() {
if (certPair != null && !certPair.isExpire()) {
return certPair;
}
synchronized (this) {
if (certPair == null || certPair.isExpire()) {
try {
logger.info("Try to generate cert from Dubbo Certificate Authority.");
CertPair certFromRemote = refreshCert();
if (certFromRemote != null) {
certPair = certFromRemote;
} else {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Cert from Dubbo Certificate Authority failed.");
}
} catch (Exception e) {
logger.error(REGISTRY_FAILED_GENERATE_CERT_ISTIO, "", "", "Generate Cert from Istio failed.", e);
}
}
}
return certPair;
}
/**
* Request remote certificate authorization to generate cert pair for current Dubbo instance
*
* @return cert pair
* @throws IOException ioException
*/
protected CertPair refreshCert() throws IOException {
KeyPair keyPair = signWithEcdsa();
if (keyPair == null) {
keyPair = signWithRsa();
}
if (keyPair == null) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Key failed. Please check if your system support.");
return null;
}
String csr = generateCsr(keyPair);
DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub =
DubboCertificateServiceGrpc.newBlockingStub(channel);
stub = setHeaderIfNeed(stub);
String privateKeyPem = generatePrivatePemKey(keyPair);
DubboCertificateResponse certificateResponse = stub.createCertificate(generateRequest(csr));
if (certificateResponse == null || !certificateResponse.getSuccess()) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Failed to generate cert from Dubbo Certificate Authority. " + "Message: "
+ (certificateResponse == null ? "null" : certificateResponse.getMessage()));
return null;
}
logger.info("Successfully generate cert from Dubbo Certificate Authority. Cert expire time: "
+ certificateResponse.getExpireTime());
return new CertPair(
privateKeyPem,
certificateResponse.getCertPem(),
String.join("\n", certificateResponse.getTrustCertsList()),
certificateResponse.getExpireTime());
}
private DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub setHeaderIfNeed(
DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub) throws IOException {
String oidcTokenPath = certConfig.getOidcTokenPath();
if (StringUtils.isNotEmpty(oidcTokenPath)) {
Metadata header = new Metadata();
Metadata.Key<String> key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
header.put(
key,
"Bearer "
+ IOUtils.read(new FileReader(oidcTokenPath))
.replace("\n", "")
.replace("\t", "")
.replace("\r", "")
.trim());
stub = stub.withInterceptors(newAttachHeadersInterceptor(header));
logger.info("Use oidc token from " + oidcTokenPath + " to connect to Dubbo Certificate Authority.");
} else {
logger.warn(
CONFIG_SSL_CONNECT_INSECURE,
"",
"",
"Use insecure connection to connect to Dubbo Certificate Authority. Reason: No oidc token is provided.");
}
return stub;
}
/**
* Generate key pair with RSA
*
* @return key pair
*/
protected static KeyPair signWithRsa() {
KeyPair keyPair = null;
try {
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
kpGenerator.initialize(4096);
java.security.KeyPair keypair = kpGenerator.generateKeyPair();
PublicKey publicKey = keypair.getPublic();
PrivateKey privateKey = keypair.getPrivate();
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate());
keyPair = new KeyPair(publicKey, privateKey, signer);
} catch (NoSuchAlgorithmException | OperatorCreationException e) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.",
e);
}
return keyPair;
}
/**
* Generate key pair with ECDSA
*
* @return key pair
*/
protected static KeyPair signWithEcdsa() {
KeyPair keyPair = null;
try {
ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
g.initialize(ecSpec, new SecureRandom());
java.security.KeyPair keypair = g.generateKeyPair();
PublicKey publicKey = keypair.getPublic();
PrivateKey privateKey = keypair.getPrivate();
ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(privateKey);
keyPair = new KeyPair(publicKey, privateKey, signer);
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException e) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Key with secp256r1 algorithm failed. Please check if your system support. "
+ "Will attempt to generate with RSA2048.",
e);
}
return keyPair;
}
private DubboCertificateRequest generateRequest(String csr) {
return DubboCertificateRequest.newBuilder()
.setCsr(csr)
.setType("CONNECTION")
.build();
}
/**
* Generate private key in pem encoded
*
* @param keyPair key pair
* @return private key
* @throws IOException ioException
*/
private String generatePrivatePemKey(KeyPair keyPair) throws IOException {
String key = generatePemKey("RSA PRIVATE KEY", keyPair.getPrivateKey().getEncoded());
if (logger.isDebugEnabled()) {
logger.debug("Generated Private Key. \n" + key);
}
return key;
}
/**
* Generate content in pem encoded
*
* @param type content type
* @param content content
* @return encoded data
* @throws IOException ioException
*/
private String generatePemKey(String type, byte[] content) throws IOException {
PemObject pemObject = new PemObject(type, content);
StringWriter str = new StringWriter();
JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(str);
jcaPEMWriter.writeObject(pemObject);
jcaPEMWriter.close();
str.close();
return str.toString();
}
/**
* Generate CSR (Certificate Sign Request)
*
* @param keyPair key pair to request
* @return csr
* @throws IOException ioException
*/
private String generateCsr(KeyPair keyPair) throws IOException {
PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder(
new X500Name("O=" + "cluster.domain"), keyPair.getPublicKey())
.build(keyPair.getSigner());
String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded());
if (logger.isDebugEnabled()) {
logger.debug("CSR Request to Dubbo Certificate Authorization. \n" + csr);
}
return csr;
}
protected static class KeyPair {
private final PublicKey publicKey;
private final PrivateKey privateKey;
private final ContentSigner signer;
public KeyPair(PublicKey publicKey, PrivateKey privateKey, ContentSigner signer) {
this.publicKey = publicKey;
this.privateKey = privateKey;
this.signer = signer;
}
public PublicKey getPublicKey() {
return publicKey;
}
public PrivateKey getPrivateKey() {
return privateKey;
}
public ContentSigner getSigner() {
return signer;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertProvider.java | dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.ssl.AuthPolicy;
import org.apache.dubbo.common.ssl.Cert;
import org.apache.dubbo.common.ssl.CertProvider;
import org.apache.dubbo.common.ssl.ProviderCert;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.nio.charset.StandardCharsets;
@Activate
public class DubboCertProvider implements CertProvider {
private final DubboCertManager dubboCertManager;
public DubboCertProvider(FrameworkModel frameworkModel) {
dubboCertManager = frameworkModel.getBeanFactory().getBean(DubboCertManager.class);
}
@Override
public boolean isSupport(URL address) {
return dubboCertManager != null && dubboCertManager.isConnected();
}
@Override
public ProviderCert getProviderConnectionConfig(URL localAddress) {
CertPair certPair = dubboCertManager.generateCert();
if (certPair == null) {
return null;
}
return new ProviderCert(
certPair.getCertificate().getBytes(StandardCharsets.UTF_8),
certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8),
certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8),
AuthPolicy.NONE);
}
@Override
public Cert getConsumerConnectionConfig(URL remoteAddress) {
CertPair certPair = dubboCertManager.generateCert();
if (certPair == null) {
return null;
}
return new Cert(
certPair.getCertificate().getBytes(StandardCharsets.UTF_8),
certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8),
certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertDeployerListener.java | dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertDeployerListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
import org.apache.dubbo.common.deploy.ApplicationDeployListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Objects;
public class CertDeployerListener implements ApplicationDeployListener {
private final DubboCertManager dubboCertManager;
public CertDeployerListener(FrameworkModel frameworkModel) {
dubboCertManager = frameworkModel.getBeanFactory().getBean(DubboCertManager.class);
}
@Override
public void onInitialize(ApplicationModel scopeModel) {}
@Override
public void onStarting(ApplicationModel scopeModel) {
scopeModel.getApplicationConfigManager().getSsl().ifPresent(sslConfig -> {
if (Objects.nonNull(sslConfig.getCaAddress()) && dubboCertManager != null) {
CertConfig certConfig = new CertConfig(
sslConfig.getCaAddress(),
sslConfig.getEnvType(),
sslConfig.getCaCertPath(),
sslConfig.getOidcTokenPath());
dubboCertManager.connect(certConfig);
}
});
}
@Override
public void onStarted(ApplicationModel scopeModel) {}
@Override
public void onCompletion(ApplicationModel scopeModel) {}
@Override
public void onStopping(ApplicationModel scopeModel) {
if (dubboCertManager != null) {
dubboCertManager.disConnect();
}
}
@Override
public void onStopped(ApplicationModel scopeModel) {}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {
if (dubboCertManager != null) {
dubboCertManager.disConnect();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/Constants.java | dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.security.cert;
public interface Constants {
int DEFAULT_REFRESH_INTERVAL = 30_000;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/DemoServiceImpl.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos;
public class DemoServiceImpl implements DemoService {
@Override
public String echo(String str) {
return "hello world";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/DemoService.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/DemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos;
public interface DemoService {
String echo(String str);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command;
import org.apache.dubbo.qos.api.CommandContext;
import io.netty.channel.Channel;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CommandContextTest {
@Test
void test() {
CommandContext context = new CommandContext("test", new String[] {"hello"}, true);
Object request = new Object();
context.setOriginRequest(request);
Channel channel = Mockito.mock(Channel.class);
context.setRemote(channel);
assertThat(context.getCommandName(), equalTo("test"));
assertThat(context.getArgs(), arrayContaining("hello"));
assertThat(context.getOriginRequest(), is(request));
assertTrue(context.isHttp());
assertThat(context.getRemote(), is(channel));
context = new CommandContext("command");
context.setRemote(channel);
context.setOriginRequest(request);
context.setArgs(new String[] {"world"});
context.setHttp(false);
assertThat(context.getCommandName(), equalTo("command"));
assertThat(context.getArgs(), arrayContaining("world"));
assertThat(context.getOriginRequest(), is(request));
assertFalse(context.isHttp());
assertThat(context.getRemote(), is(channel));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.api.QosConfiguration;
import org.apache.dubbo.qos.command.exception.NoSuchCommandException;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class DefaultCommandExecutorTest {
@Test
void testExecute1() {
Assertions.assertThrows(NoSuchCommandException.class, () -> {
DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel());
executor.execute(CommandContextFactory.newInstance("not-exit"));
});
}
@Test
void testExecute2() throws Exception {
DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel());
final CommandContext commandContext =
CommandContextFactory.newInstance("greeting", new String[] {"dubbo"}, false);
commandContext.setQosConfiguration(QosConfiguration.builder()
.anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name())
.build());
String result = executor.execute(commandContext);
assertThat(result, equalTo("greeting dubbo"));
}
@Test
void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndMatchDefaultPUBLICCmdPermissionLevel() {
DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel());
final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false);
commandContext.setQosConfiguration(QosConfiguration.builder().build());
Assertions.assertDoesNotThrow(() -> executor.execute(commandContext));
}
@Test
void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndNotMatchCmdPermissionLevel() {
DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel());
final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false);
// 1 PROTECTED
commandContext.setQosConfiguration(
QosConfiguration.builder().anonymousAccessPermissionLevel("1").build());
Assertions.assertDoesNotThrow(() -> executor.execute(commandContext));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextFactoryTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command;
import org.apache.dubbo.qos.api.CommandContext;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CommandContextFactoryTest {
@Test
void testNewInstance() {
CommandContext context = CommandContextFactory.newInstance("test");
assertThat(context.getCommandName(), equalTo("test"));
context = CommandContextFactory.newInstance("command", new String[] {"hello"}, true);
assertThat(context.getCommandName(), equalTo("command"));
assertThat(context.getArgs(), Matchers.arrayContaining("hello"));
assertTrue(context.isHttp());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/GreetingCommand.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/GreetingCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
@Cmd(
name = "greeting",
summary = "greeting message",
example = {
"greeting dubbo",
})
public class GreetingCommand implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
return ArrayUtils.isNotEmpty(args) ? "greeting " + args[0] : "greeting";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/ServiceCheckUtilsTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/ServiceCheckUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.qos.DemoService;
import org.apache.dubbo.qos.DemoServiceImpl;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test for ServiceCheckUtils
*/
class ServiceCheckUtilsTest {
private final ModuleServiceRepository repository =
ApplicationModel.defaultModel().getDefaultModule().getServiceRepository();
@Test
void testIsRegistered() {
DemoService demoServiceImpl = new DemoServiceImpl();
int availablePort = NetUtils.getAvailablePort();
URL url = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + DemoService.class.getName());
ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class);
ProviderModel providerModel = new ProviderModel(
url.getServiceKey(),
demoServiceImpl,
serviceDescriptor,
new ServiceMetadata(),
ClassUtils.getClassLoader(DemoService.class));
repository.registerProvider(providerModel);
String url1 =
"service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099®istry=zookeeper×tamp=1654588337653";
String url2 =
"zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653";
providerModel.getStatedUrl().add(new ProviderModel.RegisterStatedURL(url, URL.valueOf(url1), true));
providerModel.getStatedUrl().add(new ProviderModel.RegisterStatedURL(url, URL.valueOf(url2), false));
Assertions.assertEquals("zookeeper-A(Y)/zookeeper-I(N)", ServiceCheckUtils.getRegisterStatus(providerModel));
}
@Test
void testGetConsumerAddressNum() {
ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class);
ServiceMetadata serviceMetadata = Mockito.mock(ServiceMetadata.class);
Mockito.when(consumerModel.getServiceMetadata()).thenReturn(serviceMetadata);
String registry1 =
"service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099®istry=zookeeper×tamp=1654588337653";
String registry2 =
"zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653";
String registry3 =
"nacos://127.0.0.1:8848/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653";
Map<Registry, MigrationInvoker<?>> invokerMap = new LinkedHashMap<>();
{
Registry registry = Mockito.mock(Registry.class);
Mockito.when(registry.getUrl()).thenReturn(URL.valueOf(registry1));
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
Mockito.when(migrationInvoker.getMigrationStep()).thenReturn(MigrationStep.FORCE_APPLICATION);
ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class);
Mockito.when(migrationInvoker.getServiceDiscoveryInvoker()).thenReturn(serviceDiscoveryInvoker);
Directory<?> sdDirectory = Mockito.mock(Directory.class);
Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(sdDirectory);
List sdInvokers = Mockito.mock(List.class);
Mockito.when(sdDirectory.getAllInvokers()).thenReturn(sdInvokers);
Mockito.when(sdInvokers.size()).thenReturn(5);
invokerMap.put(registry, migrationInvoker);
}
{
Registry registry = Mockito.mock(Registry.class);
Mockito.when(registry.getUrl()).thenReturn(URL.valueOf(registry2));
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
Mockito.when(migrationInvoker.getMigrationStep()).thenReturn(MigrationStep.APPLICATION_FIRST);
ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class);
Mockito.when(migrationInvoker.getServiceDiscoveryInvoker()).thenReturn(serviceDiscoveryInvoker);
Directory<?> sdDirectory = Mockito.mock(Directory.class);
Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(sdDirectory);
List sdInvokers = Mockito.mock(List.class);
Mockito.when(sdDirectory.getAllInvokers()).thenReturn(sdInvokers);
Mockito.when(sdInvokers.size()).thenReturn(0);
ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class);
Mockito.when(migrationInvoker.getInvoker()).thenReturn(invoker);
Directory<?> directory = Mockito.mock(Directory.class);
Mockito.when(invoker.getDirectory()).thenReturn(directory);
List invokers = Mockito.mock(List.class);
Mockito.when(directory.getAllInvokers()).thenReturn(invokers);
Mockito.when(invokers.size()).thenReturn(10);
invokerMap.put(registry, migrationInvoker);
}
{
Registry registry = Mockito.mock(Registry.class);
Mockito.when(registry.getUrl()).thenReturn(URL.valueOf(registry3));
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
Mockito.when(migrationInvoker.getMigrationStep()).thenReturn(MigrationStep.FORCE_INTERFACE);
ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class);
Mockito.when(migrationInvoker.getInvoker()).thenReturn(invoker);
Directory<?> directory = Mockito.mock(Directory.class);
Mockito.when(invoker.getDirectory()).thenReturn(directory);
List invokers = Mockito.mock(List.class);
Mockito.when(directory.getAllInvokers()).thenReturn(invokers);
Mockito.when(invokers.size()).thenReturn(10);
invokerMap.put(registry, migrationInvoker);
}
Mockito.when(serviceMetadata.getAttribute("currentClusterInvoker")).thenReturn(invokerMap);
assertEquals(
"zookeeper-A(5)/zookeeper-AF(I-10,A-0)/nacos-I(10)",
ServiceCheckUtils.getConsumerAddressNum(consumerModel));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/SerializeCheckUtilsTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/SerializeCheckUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.util;
import org.apache.dubbo.common.utils.SerializeCheckStatus;
import org.apache.dubbo.common.utils.SerializeSecurityManager;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SerializeCheckUtilsTest {
@Test
void testNotify() {
FrameworkModel frameworkModel = new FrameworkModel();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeCheckUtils serializeCheckUtils = new SerializeCheckUtils(frameworkModel);
ssm.addToAllowed("Test1234");
Assertions.assertTrue(serializeCheckUtils.getAllowedList().contains("Test1234"));
ssm.addToDisAllowed("Test4321");
Assertions.assertTrue(serializeCheckUtils.getDisAllowedList().contains("Test4321"));
ssm.setCheckSerializable(false);
Assertions.assertFalse(serializeCheckUtils.isCheckSerializable());
ssm.setCheckStatus(SerializeCheckStatus.DISABLE);
Assertions.assertEquals(SerializeCheckStatus.DISABLE, serializeCheckUtils.getStatus());
frameworkModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.util;
import org.apache.dubbo.qos.command.GreetingCommand;
import org.apache.dubbo.qos.command.impl.ChangeTelnet;
import org.apache.dubbo.qos.command.impl.CountTelnet;
import org.apache.dubbo.qos.command.impl.DefaultMetricsReporterCmd;
import org.apache.dubbo.qos.command.impl.DisableDetailProfiler;
import org.apache.dubbo.qos.command.impl.DisableRouterSnapshot;
import org.apache.dubbo.qos.command.impl.DisableSimpleProfiler;
import org.apache.dubbo.qos.command.impl.EnableDetailProfiler;
import org.apache.dubbo.qos.command.impl.EnableRouterSnapshot;
import org.apache.dubbo.qos.command.impl.EnableSimpleProfiler;
import org.apache.dubbo.qos.command.impl.GetAddress;
import org.apache.dubbo.qos.command.impl.GetConfig;
import org.apache.dubbo.qos.command.impl.GetEnabledRouterSnapshot;
import org.apache.dubbo.qos.command.impl.GetOpenAPI;
import org.apache.dubbo.qos.command.impl.GetRecentRouterSnapshot;
import org.apache.dubbo.qos.command.impl.GetRouterSnapshot;
import org.apache.dubbo.qos.command.impl.GracefulShutdown;
import org.apache.dubbo.qos.command.impl.Help;
import org.apache.dubbo.qos.command.impl.InvokeTelnet;
import org.apache.dubbo.qos.command.impl.Live;
import org.apache.dubbo.qos.command.impl.LoggerInfo;
import org.apache.dubbo.qos.command.impl.Ls;
import org.apache.dubbo.qos.command.impl.Offline;
import org.apache.dubbo.qos.command.impl.OfflineApp;
import org.apache.dubbo.qos.command.impl.OfflineInterface;
import org.apache.dubbo.qos.command.impl.Online;
import org.apache.dubbo.qos.command.impl.OnlineApp;
import org.apache.dubbo.qos.command.impl.OnlineInterface;
import org.apache.dubbo.qos.command.impl.PortTelnet;
import org.apache.dubbo.qos.command.impl.PublishMetadata;
import org.apache.dubbo.qos.command.impl.PwdTelnet;
import org.apache.dubbo.qos.command.impl.Quit;
import org.apache.dubbo.qos.command.impl.Ready;
import org.apache.dubbo.qos.command.impl.SelectTelnet;
import org.apache.dubbo.qos.command.impl.SerializeCheckStatus;
import org.apache.dubbo.qos.command.impl.SerializeWarnedClasses;
import org.apache.dubbo.qos.command.impl.SetProfilerWarnPercent;
import org.apache.dubbo.qos.command.impl.ShutdownTelnet;
import org.apache.dubbo.qos.command.impl.Startup;
import org.apache.dubbo.qos.command.impl.SwitchLogLevel;
import org.apache.dubbo.qos.command.impl.SwitchLogger;
import org.apache.dubbo.qos.command.impl.Version;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CommandHelperTest {
private CommandHelper commandHelper = new CommandHelper(FrameworkModel.defaultModel());
@Test
void testHasCommand() {
assertTrue(commandHelper.hasCommand("greeting"));
assertFalse(commandHelper.hasCommand("not-exiting"));
}
@Test
void testGetAllCommandClass() {
List<Class<?>> classes = commandHelper.getAllCommandClass();
// update this list when introduce a new command
List<Class<?>> expectedClasses = new LinkedList<>();
expectedClasses.add(GreetingCommand.class);
expectedClasses.add(Help.class);
expectedClasses.add(Live.class);
expectedClasses.add(Ls.class);
expectedClasses.add(Offline.class);
expectedClasses.add(OfflineApp.class);
expectedClasses.add(OfflineInterface.class);
expectedClasses.add(Online.class);
expectedClasses.add(OnlineApp.class);
expectedClasses.add(OnlineInterface.class);
expectedClasses.add(PublishMetadata.class);
expectedClasses.add(Quit.class);
expectedClasses.add(Ready.class);
expectedClasses.add(Startup.class);
expectedClasses.add(Version.class);
expectedClasses.add(ChangeTelnet.class);
expectedClasses.add(CountTelnet.class);
expectedClasses.add(InvokeTelnet.class);
expectedClasses.add(SelectTelnet.class);
expectedClasses.add(PortTelnet.class);
expectedClasses.add(PwdTelnet.class);
expectedClasses.add(ShutdownTelnet.class);
expectedClasses.add(EnableDetailProfiler.class);
expectedClasses.add(DisableDetailProfiler.class);
expectedClasses.add(EnableSimpleProfiler.class);
expectedClasses.add(DisableSimpleProfiler.class);
expectedClasses.add(SetProfilerWarnPercent.class);
expectedClasses.add(GetRouterSnapshot.class);
expectedClasses.add(GetEnabledRouterSnapshot.class);
expectedClasses.add(EnableRouterSnapshot.class);
expectedClasses.add(DisableRouterSnapshot.class);
expectedClasses.add(GetRecentRouterSnapshot.class);
expectedClasses.add(LoggerInfo.class);
expectedClasses.add(SwitchLogger.class);
expectedClasses.add(SwitchLogLevel.class);
expectedClasses.add(SerializeCheckStatus.class);
expectedClasses.add(SerializeWarnedClasses.class);
expectedClasses.add(GetConfig.class);
expectedClasses.add(GetAddress.class);
expectedClasses.add(GracefulShutdown.class);
expectedClasses.add(DefaultMetricsReporterCmd.class);
expectedClasses.add(GetOpenAPI.class);
assertThat(classes, containsInAnyOrder(expectedClasses.toArray(new Class<?>[0])));
}
@Test
void testGetCommandClass() {
assertThat(commandHelper.getCommandClass("greeting"), equalTo(GreetingCommand.class));
assertNull(commandHelper.getCommandClass("not-exiting"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatusTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatusTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.utils.SerializeSecurityManager;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class SerializeCheckStatusTest {
@Test
void testNotify() {
FrameworkModel frameworkModel = new FrameworkModel();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeCheckStatus serializeCheckStatus = new SerializeCheckStatus(frameworkModel);
CommandContext commandContext1 = Mockito.mock(CommandContext.class);
Mockito.when(commandContext1.isHttp()).thenReturn(false);
CommandContext commandContext2 = Mockito.mock(CommandContext.class);
Mockito.when(commandContext2.isHttp()).thenReturn(true);
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext1, null).contains("Test1234"));
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext2, null).contains("Test1234"));
ssm.addToAllowed("Test1234");
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext1, null).contains("Test1234"));
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext2, null).contains("Test1234"));
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext1, null).contains("Test4321"));
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext2, null).contains("Test4321"));
ssm.addToDisAllowed("Test4321");
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext1, null).contains("Test4321"));
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext2, null).contains("Test4321"));
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false"));
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false"));
ssm.setCheckSerializable(false);
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false"));
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false"));
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE"));
Assertions.assertFalse(
serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\""));
ssm.setCheckStatus(org.apache.dubbo.common.utils.SerializeCheckStatus.DISABLE);
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE"));
Assertions.assertTrue(
serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\""));
frameworkModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PublishMetadataTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PublishMetadataTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class PublishMetadataTest {
private FrameworkModel frameworkModel;
@BeforeEach
public void setUp() throws Exception {
frameworkModel = new FrameworkModel();
for (int i = 0; i < 3; i++) {
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("APP_" + i));
}
}
@AfterEach
public void reset() {
frameworkModel.destroy();
}
@Test
void testExecute() {
PublishMetadata publishMetadata = new PublishMetadata(frameworkModel);
String result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[0]);
String expectResult = "publish metadata succeeded. App:APP_0\n" + "publish metadata succeeded. App:APP_1\n"
+ "publish metadata succeeded. App:APP_2\n";
Assertions.assertEquals(result, expectResult);
// delay 5s
result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[] {"5"});
expectResult = "publish task submitted, will publish in 5 seconds. App:APP_0\n"
+ "publish task submitted, will publish in 5 seconds. App:APP_1\n"
+ "publish task submitted, will publish in 5 seconds. App:APP_2\n";
Assertions.assertEquals(result, expectResult);
// wrong delay param
result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[] {"A"});
expectResult = "publishMetadata failed! Wrong delay param!";
Assertions.assertEquals(result, expectResult);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PwdTelnetTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PwdTelnetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.FrameworkModel;
import io.netty.channel.Channel;
import io.netty.util.DefaultAttributeMap;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class PwdTelnetTest {
private static final BaseCommand pwdTelnet = new PwdTelnet();
private Channel mockChannel;
private CommandContext mockCommandContext;
private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap();
@BeforeEach
public void setUp() {
mockChannel = mock(Channel.class);
mockCommandContext = mock(CommandContext.class);
given(mockCommandContext.getRemote()).willReturn(mockChannel);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
}
@AfterEach
public void tearDown() {
FrameworkModel.destroyAll();
mockChannel.close();
reset(mockChannel, mockCommandContext);
}
@Test
void testService() throws RemotingException {
defaultAttributeMap
.attr(ChangeTelnet.SERVICE_KEY)
.set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
String result = pwdTelnet.execute(mockCommandContext, new String[0]);
assertEquals("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService", result);
}
@Test
void testSlash() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null);
String result = pwdTelnet.execute(mockCommandContext, new String[0]);
assertEquals("/", result);
}
@Test
void testMessageError() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null);
String result = pwdTelnet.execute(mockCommandContext, new String[] {"test"});
assertEquals("Unsupported parameter [test] for pwd.", result);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.impl.channel.MockNettyChannel;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.remoting.telnet.support.TelnetUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class CountTelnetTest {
private BaseCommand count;
private MockNettyChannel mockChannel;
private Invoker<DemoService> mockInvoker;
private CommandContext mockCommandContext;
private CountDownLatch latch;
private final URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo?group=g&version=1.0.0");
@BeforeEach
public void setUp() {
count = new CountTelnet(FrameworkModel.defaultModel());
latch = new CountDownLatch(2);
mockInvoker = mock(Invoker.class);
mockCommandContext = mock(CommandContext.class);
mockChannel = new MockNettyChannel(url, latch);
given(mockCommandContext.getRemote()).willReturn(mockChannel);
given(mockInvoker.getInterface()).willReturn(DemoService.class);
given(mockInvoker.getUrl()).willReturn(url);
}
@AfterEach
public void tearDown() {
FrameworkModel.destroyAll();
mockChannel.close();
RpcStatus.removeStatus(url);
reset(mockInvoker, mockCommandContext);
}
@Test
void test() throws Exception {
String methodName = "sayHello";
RpcStatus.removeStatus(url, methodName);
String[] args = new String[] {"org.apache.dubbo.qos.legacy.service.DemoService", "sayHello", "1"};
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
RpcStatus.beginCount(url, methodName);
RpcStatus.endCount(url, methodName, 10L, true);
count.execute(mockCommandContext, args);
latch.await();
StringBuilder sb = new StringBuilder();
for (Object o : mockChannel.getReceivedObjects()) {
sb.append(o.toString());
}
assertThat(sb.toString(), containsString(buildTable(methodName, 10, 10, "1", "0", "0")));
}
@Test
void testCountByServiceKey() throws Exception {
String methodName = "sayHello";
RpcStatus.removeStatus(url, methodName);
String[] args = new String[] {"g/demo:1.0.0", "sayHello", "1"};
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
RpcStatus.beginCount(url, methodName);
RpcStatus.endCount(url, methodName, 10L, true);
count.execute(mockCommandContext, args);
latch.await();
StringBuilder sb = new StringBuilder();
for (Object o : mockChannel.getReceivedObjects()) {
sb.append(o.toString());
}
assertThat(sb.toString(), containsString(buildTable(methodName, 10, 10, "1", "0", "0")));
}
public static String buildTable(
String methodName, long averageElapsed, long maxElapsed, String total, String failed, String active) {
List<String> header = new LinkedList<>();
header.add("method");
header.add("total");
header.add("failed");
header.add("active");
header.add("average");
header.add("max");
List<List<String>> table = new LinkedList<>();
List<String> row = new LinkedList<String>();
row.add(methodName);
row.add(total);
row.add(failed);
row.add(active);
row.add(averageElapsed + "ms");
row.add(maxElapsed + "ms");
table.add(row);
return TelnetUtils.toTable(header, table);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/InvokeTelnetTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/InvokeTelnetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.qos.legacy.service.DemoServiceImpl;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import io.netty.channel.Channel;
import io.netty.util.DefaultAttributeMap;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class InvokeTelnetTest {
private FrameworkModel frameworkModel;
private BaseCommand invoke;
private BaseCommand select;
private Channel mockChannel;
private CommandContext mockCommandContext;
private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap();
private ModuleServiceRepository repository;
@BeforeEach
public void setup() {
DubboBootstrap.reset();
frameworkModel = new FrameworkModel();
invoke = new InvokeTelnet(frameworkModel);
select = new SelectTelnet(frameworkModel);
mockChannel = mock(Channel.class);
mockCommandContext = mock(CommandContext.class);
given(mockCommandContext.getRemote()).willReturn(mockChannel);
ApplicationModel applicationModel = frameworkModel.newApplication();
repository = applicationModel.getDefaultModule().getServiceRepository();
}
@AfterEach
public void after() {
frameworkModel.destroy();
reset(mockChannel, mockCommandContext);
}
@Test
void testInvokeWithoutServicePrefixAndWithoutDefaultService() throws RemotingException {
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = invoke.execute(mockCommandContext, new String[] {"echo(\"ok\")"});
assertTrue(result.contains(
"If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first,"
+ " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]"));
}
@Test
void testInvokeDefaultService() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = invoke.execute(mockCommandContext, new String[] {"echo(\"ok\")"});
assertTrue(result.contains("result: \"ok\""));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testInvokeWithSpecifyService() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null);
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = invoke.execute(mockCommandContext, new String[] {"DemoService.echo(\"ok\")"});
assertTrue(result.contains("result: \"ok\""));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testInvokeByPassingNullValue() {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
try {
invoke.execute(mockCommandContext, new String[] {"sayHello(null)"});
} catch (Exception ex) {
assertTrue(ex instanceof NullPointerException);
}
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testInvokeByPassingEnumValue() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = invoke.execute(mockCommandContext, new String[] {"getType(\"High\")"});
assertTrue(result.contains("result: \"High\""));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testOverriddenMethodWithSpecifyParamType() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = invoke.execute(mockCommandContext, new String[] {
"getPerson({\"name\":\"zhangsan\",\"age\":12,\"class\":\"org.apache.dubbo.qos.legacy.service.Person\"})"
});
assertTrue(result.contains("result: 12"));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testInvokeOverriddenMethodBySelect() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY).set(null);
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY).set(null);
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(null);
defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_METHOD_KEY))
.willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY));
given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY))
.willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY));
given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY))
.willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY));
given(mockChannel.attr(InvokeTelnet.INVOKE_MESSAGE_KEY))
.willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String param = "{\"name\":\"Dubbo\",\"age\":8}";
String result = invoke.execute(mockCommandContext, new String[] {"getPerson(" + param + ")"});
assertTrue(
result.contains("Please use the select command to select the method you want to invoke. eg: select 1"));
result = select.execute(mockCommandContext, new String[] {"1"});
// result dependent on method order.
assertTrue(result.contains("result: 8") || result.contains("result: \"Dubbo\""));
result = select.execute(mockCommandContext, new String[] {"2"});
assertTrue(result.contains("result: 8") || result.contains("result: \"Dubbo\""));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY).remove();
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY).remove();
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove();
defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).remove();
}
@Test
void testInvokeMethodWithMapParameter() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String param = "{1:\"Dubbo\",2:\"test\"}";
String result = invoke.execute(mockCommandContext, new String[] {"getMap(" + param + ")"});
assertTrue(result.contains("result: {1:\"Dubbo\",2:\"test\"}"));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testInvokeMultiJsonParamMethod() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String param = "{\"name\":\"Dubbo\",\"age\":8},{\"name\":\"Apache\",\"age\":20}";
String result = invoke.execute(mockCommandContext, new String[] {"getPerson(" + param + ")"});
assertTrue(result.contains("result: 28"));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testMessageNull() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null);
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
String result = invoke.execute(mockCommandContext, new String[0]);
assertEquals(
"Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})",
result);
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
@Test
void testInvalidMessage() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null);
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
String result = invoke.execute(mockCommandContext, new String[] {"("});
assertEquals("Invalid parameters, format: service.method(args)", result);
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
}
private void registerProvider(String key, Object impl, Class<?> interfaceClass) {
ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass);
repository.registerProvider(key, impl, serviceDescriptor, null, null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ShutdownTelnetTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ShutdownTelnetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.FrameworkModel;
import io.netty.channel.Channel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class ShutdownTelnetTest {
private BaseCommand shutdown;
private Channel mockChannel;
private CommandContext mockCommandContext;
@BeforeEach
public void setUp() {
shutdown = new ShutdownTelnet(FrameworkModel.defaultModel());
mockCommandContext = mock(CommandContext.class);
mockChannel = mock(Channel.class);
given(mockCommandContext.getRemote()).willReturn(mockChannel);
}
@AfterEach
public void after() {
FrameworkModel.destroyAll();
reset(mockChannel, mockCommandContext);
}
@Test
void testInvoke() throws RemotingException {
String result = shutdown.execute(mockCommandContext, new String[0]);
assertTrue(result.contains("Application has shutdown successfully"));
}
@Test
void testInvokeWithTimeParameter() throws RemotingException {
int sleepTime = 2000;
long start = System.currentTimeMillis();
String result = shutdown.execute(mockCommandContext, new String[] {"-t", "" + sleepTime});
long end = System.currentTimeMillis();
assertTrue(result.contains("Application has shutdown successfully"), result);
assertTrue((end - start) >= sleepTime, "sleepTime: " + sleepTime + ", execTime: " + (end - start));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/QuitTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/QuitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.common.QosConstants;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class QuitTest {
@Test
void testExecute() throws Exception {
Quit quit = new Quit();
String output = quit.execute(Mockito.mock(CommandContext.class), null);
assertThat(output, equalTo(QosConstants.CLOSE));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SelectTelnetTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SelectTelnetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.qos.legacy.service.DemoServiceImpl;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import io.netty.channel.Channel;
import io.netty.util.DefaultAttributeMap;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class SelectTelnetTest {
private BaseCommand select;
private Channel mockChannel;
private CommandContext mockCommandContext;
private ModuleServiceRepository repository;
private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap();
private List<Method> methods;
@BeforeEach
public void setup() {
repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository();
select = new SelectTelnet(FrameworkModel.defaultModel());
String methodName = "getPerson";
methods = new ArrayList<>();
for (Method method : DemoService.class.getMethods()) {
if (method.getName().equals(methodName)) {
methods.add(method);
}
}
DubboBootstrap.reset();
mockChannel = mock(Channel.class);
mockCommandContext = mock(CommandContext.class);
given(mockCommandContext.getRemote()).willReturn(mockChannel);
}
@AfterEach
public void after() {
FrameworkModel.destroyAll();
reset(mockChannel, mockCommandContext);
}
@Test
void testInvokeWithoutMethodList() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY))
.willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = select.execute(mockCommandContext, new String[] {"1"});
assertTrue(result.contains("Please use the invoke command first."));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove();
}
@Test
void testInvokeWithIllegalMessage() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(methods);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY))
.willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = select.execute(mockCommandContext, new String[] {"index"});
assertTrue(result.contains("Illegal index ,please input select 1"));
result = select.execute(mockCommandContext, new String[] {"0"});
assertTrue(result.contains("Illegal index ,please input select 1"));
result = select.execute(mockCommandContext, new String[] {"1000"});
assertTrue(result.contains("Illegal index ,please input select 1"));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove();
}
@Test
void testInvokeWithNull() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(methods);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY))
.willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY));
registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class);
String result = select.execute(mockCommandContext, new String[0]);
assertTrue(result.contains("Please input the index of the method you want to invoke"));
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove();
}
private void registerProvider(String key, Object impl, Class<?> interfaceClass) {
ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass);
repository.registerProvider(key, impl, serviceDescriptor, null, null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/GetConfigTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/GetConfigTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class GetConfigTest {
@Test
void testAll() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel1 = frameworkModel.newApplication();
applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1"));
applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345));
applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
applicationModel1
.getApplicationConfigManager()
.addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181"));
ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
configCenterConfig.setAddress("zookeeper://127.0.0.1:2181");
applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig);
applicationModel1.getApplicationConfigManager().setMetrics(new MetricsConfig());
applicationModel1.getApplicationConfigManager().setMonitor(new MonitorConfig());
applicationModel1.getApplicationConfigManager().setSsl(new SslConfig());
ModuleModel moduleModel = applicationModel1.newModule();
moduleModel.getConfigManager().setModule(new ModuleConfig());
moduleModel.getConfigManager().addConsumer(new ConsumerConfig());
moduleModel.getConfigManager().addProvider(new ProviderConfig());
ReferenceConfig<Object> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addReference(referenceConfig);
ServiceConfig<Object> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addService(serviceConfig);
CommandContext commandContext = new CommandContext("getConfig");
commandContext.setHttp(true);
Assertions.assertNotNull(new GetConfig(frameworkModel).execute(commandContext, null));
}
@Test
void testEmptyId() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel1 = frameworkModel.newApplication();
applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1"));
ModuleModel moduleModel = applicationModel1.newModule();
ProviderConfig providerConfig1 = new ProviderConfig();
providerConfig1.setThreadname("test");
moduleModel.getConfigManager().addProvider(providerConfig1);
CommandContext commandContext = new CommandContext("getConfig");
commandContext.setHttp(true);
Assertions.assertNotNull(new GetConfig(frameworkModel).execute(commandContext, null));
}
@Test
void testFilter1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel1 = frameworkModel.newApplication();
applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1"));
applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345));
applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
applicationModel1
.getApplicationConfigManager()
.addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181"));
ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
configCenterConfig.setAddress("zookeeper://127.0.0.1:2181");
applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig);
applicationModel1.getApplicationConfigManager().setMetrics(new MetricsConfig());
applicationModel1.getApplicationConfigManager().setMonitor(new MonitorConfig());
applicationModel1.getApplicationConfigManager().setSsl(new SslConfig());
ModuleModel moduleModel = applicationModel1.newModule();
moduleModel.getConfigManager().setModule(new ModuleConfig());
moduleModel.getConfigManager().addConsumer(new ConsumerConfig());
moduleModel.getConfigManager().addProvider(new ProviderConfig());
ReferenceConfig<Object> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addReference(referenceConfig);
ServiceConfig<Object> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addService(serviceConfig);
CommandContext commandContext = new CommandContext("getConfig");
commandContext.setHttp(true);
Assertions.assertNotNull(
new GetConfig(frameworkModel).execute(commandContext, new String[] {"ApplicationConfig"}));
}
@Test
void testFilter2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel1 = frameworkModel.newApplication();
applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1"));
applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345));
applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
applicationModel1
.getApplicationConfigManager()
.addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181"));
ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
configCenterConfig.setAddress("zookeeper://127.0.0.1:2181");
applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig);
applicationModel1.getApplicationConfigManager().setMetrics(new MetricsConfig());
applicationModel1.getApplicationConfigManager().setMonitor(new MonitorConfig());
applicationModel1.getApplicationConfigManager().setSsl(new SslConfig());
ModuleModel moduleModel = applicationModel1.newModule();
moduleModel.getConfigManager().setModule(new ModuleConfig());
moduleModel.getConfigManager().addConsumer(new ConsumerConfig());
moduleModel.getConfigManager().addProvider(new ProviderConfig());
ReferenceConfig<Object> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addReference(referenceConfig);
ServiceConfig<Object> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addService(serviceConfig);
CommandContext commandContext = new CommandContext("getConfig");
commandContext.setHttp(true);
Assertions.assertNotNull(
new GetConfig(frameworkModel).execute(commandContext, new String[] {"ProtocolConfig", "dubbo"}));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ReadyTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ReadyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.probe.ReadinessProbe;
import org.apache.dubbo.qos.probe.impl.DeployerReadinessProbe;
import org.apache.dubbo.qos.probe.impl.ProviderReadinessProbe;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ReadyTest {
private FrameworkModel frameworkModel;
private ModuleDeployer moduleDeployer;
private FrameworkServiceRepository frameworkServiceRepository;
@BeforeEach
public void setUp() {
frameworkModel = Mockito.mock(FrameworkModel.class);
frameworkServiceRepository = Mockito.mock(FrameworkServiceRepository.class);
ConfigManager manager = Mockito.mock(ConfigManager.class);
Mockito.when(manager.getApplication()).thenReturn(Optional.of(new ApplicationConfig("ReadyTest")));
ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class);
ModuleModel moduleModel = Mockito.mock(ModuleModel.class);
moduleDeployer = Mockito.mock(ModuleDeployer.class);
Mockito.when(frameworkServiceRepository.allProviderModels()).thenReturn(Collections.emptyList());
Mockito.when(frameworkModel.newApplication()).thenReturn(applicationModel);
Mockito.when(frameworkModel.getApplicationModels()).thenReturn(Arrays.asList(applicationModel));
Mockito.when(frameworkModel.getServiceRepository()).thenReturn(frameworkServiceRepository);
Mockito.when(applicationModel.getModuleModels()).thenReturn(Arrays.asList(moduleModel));
Mockito.when(applicationModel.getApplicationConfigManager()).thenReturn(manager);
Mockito.when(moduleModel.getDeployer()).thenReturn(moduleDeployer);
Mockito.when(moduleDeployer.isCompletion()).thenReturn(true);
ExtensionLoader loader = Mockito.mock(ExtensionLoader.class);
Mockito.when(frameworkModel.getExtensionLoader(ReadinessProbe.class)).thenReturn(loader);
URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_READY_PROBE_EXTENSION, "");
List<ReadinessProbe> readinessProbes =
Arrays.asList(new DeployerReadinessProbe(frameworkModel), new ProviderReadinessProbe(frameworkModel));
Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_READY_PROBE_EXTENSION))
.thenReturn(readinessProbes);
}
@Test
void testExecute() {
Ready ready = new Ready(frameworkModel);
CommandContext commandContext = new CommandContext("ready");
String result = ready.execute(commandContext, new String[0]);
Assertions.assertEquals("true", result);
Assertions.assertEquals(commandContext.getHttpCode(), 200);
Mockito.when(moduleDeployer.isCompletion()).thenReturn(false);
result = ready.execute(commandContext, new String[0]);
Assertions.assertEquals("false", result);
Assertions.assertEquals(commandContext.getHttpCode(), 503);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/HelpTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/HelpTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
class HelpTest {
@Test
void testMainHelp() {
Help help = new Help(FrameworkModel.defaultModel());
String output = help.execute(Mockito.mock(CommandContext.class), null);
assertThat(output, containsString("greeting"));
assertThat(output, containsString("help"));
assertThat(output, containsString("ls"));
assertThat(output, containsString("online"));
assertThat(output, containsString("offline"));
assertThat(output, containsString("quit"));
}
@Test
void testGreeting() {
Help help = new Help(FrameworkModel.defaultModel());
String output = help.execute(Mockito.mock(CommandContext.class), new String[] {"greeting"});
assertThat(output, containsString("COMMAND NAME"));
assertThat(output, containsString("greeting"));
assertThat(output, containsString("EXAMPLE"));
assertThat(output, containsString("greeting dubbo"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestInterface2.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestInterface2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
public interface TestInterface2 {
String sayHello();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.utils.SerializeSecurityManager;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class SerializeWarnedClassesTest {
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeWarnedClasses serializeWarnedClasses = new SerializeWarnedClasses(frameworkModel);
CommandContext commandContext1 = Mockito.mock(CommandContext.class);
Mockito.when(commandContext1.isHttp()).thenReturn(false);
CommandContext commandContext2 = Mockito.mock(CommandContext.class);
Mockito.when(commandContext2.isHttp()).thenReturn(true);
Assertions.assertFalse(
serializeWarnedClasses.execute(commandContext1, null).contains("Test1234"));
Assertions.assertFalse(
serializeWarnedClasses.execute(commandContext2, null).contains("Test1234"));
ssm.getWarnedClasses().add("Test1234");
Assertions.assertTrue(
serializeWarnedClasses.execute(commandContext1, null).contains("Test1234"));
Assertions.assertTrue(
serializeWarnedClasses.execute(commandContext2, null).contains("Test1234"));
Assertions.assertFalse(
serializeWarnedClasses.execute(commandContext1, null).contains("Test4321"));
Assertions.assertFalse(
serializeWarnedClasses.execute(commandContext2, null).contains("Test4321"));
ssm.getWarnedClasses().add("Test4321");
Assertions.assertTrue(
serializeWarnedClasses.execute(commandContext1, null).contains("Test4321"));
Assertions.assertTrue(
serializeWarnedClasses.execute(commandContext2, null).contains("Test4321"));
frameworkModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.qos.DemoService;
import org.apache.dubbo.qos.DemoServiceImpl;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.AsyncMethodInfo;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class LsTest {
private static final Logger logger = LoggerFactory.getLogger(LsTest.class);
private FrameworkModel frameworkModel;
private ModuleServiceRepository repository;
@BeforeEach
public void setUp() {
frameworkModel = new FrameworkModel();
repository = frameworkModel.newApplication().getDefaultModule().getServiceRepository();
registerProvider();
registerConsumer();
}
@AfterEach
public void reset() {
frameworkModel.destroy();
}
@Test
void testExecute() {
Ls ls = new Ls(frameworkModel);
String result = ls.execute(Mockito.mock(CommandContext.class), new String[0]);
logger.info(result);
/**
* As Provider side:
* +--------------------------------+---+
* | Provider Service Name |PUB|
* +--------------------------------+---+
* |org.apache.dubbo.qos.DemoService| N |
* +--------------------------------+---+
* As Consumer side:
* +--------------------------------+---+
* | Consumer Service Name |NUM|
* +--------------------------------+---+
* |org.apache.dubbo.qos.DemoService| 0 |
* +--------------------------------+---+
*/
}
private void registerProvider() {
ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class);
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setServiceKey(DemoService.class.getName());
ProviderModel providerModel = new ProviderModel(
DemoService.class.getName(),
new DemoServiceImpl(),
serviceDescriptor,
null,
serviceMetadata,
ClassUtils.getClassLoader(DemoService.class));
repository.registerProvider(providerModel);
}
private void registerConsumer() {
ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class);
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setInterface(DemoService.class);
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setServiceKey(DemoService.class.getName());
Map<String, AsyncMethodInfo> methodConfigs = new HashMap<>();
ConsumerModel consumerModel = new ConsumerModel(
serviceMetadata.getServiceKey(),
null,
serviceDescriptor,
serviceMetadata,
methodConfigs,
referenceConfig.getInterfaceClassLoader());
repository.registerConsumer(consumerModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestRegistryFactory.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestRegistryFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
public class TestRegistryFactory implements RegistryFactory {
static Registry registry;
@Override
public Registry getRegistry(URL url) {
return registry;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/StartupTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/StartupTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.probe.StartupProbe;
import org.apache.dubbo.qos.probe.impl.DeployerStartupProbe;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class StartupTest {
private FrameworkModel frameworkModel;
private ModuleDeployer moduleDeployer;
@BeforeEach
public void setUp() {
frameworkModel = Mockito.mock(FrameworkModel.class);
ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class);
ModuleModel moduleModel = Mockito.mock(ModuleModel.class);
ConfigManager manager = Mockito.mock(ConfigManager.class);
Mockito.when(manager.getApplication()).thenReturn(Optional.of(new ApplicationConfig("ReadyTest")));
moduleDeployer = Mockito.mock(ModuleDeployer.class);
Mockito.when(frameworkModel.newApplication()).thenReturn(applicationModel);
Mockito.when(frameworkModel.getApplicationModels()).thenReturn(Arrays.asList(applicationModel));
Mockito.when(applicationModel.getModuleModels()).thenReturn(Arrays.asList(moduleModel));
Mockito.when(applicationModel.getApplicationConfigManager()).thenReturn(manager);
Mockito.when(moduleModel.getDeployer()).thenReturn(moduleDeployer);
Mockito.when(moduleDeployer.isRunning()).thenReturn(true);
ExtensionLoader loader = Mockito.mock(ExtensionLoader.class);
Mockito.when(frameworkModel.getExtensionLoader(StartupProbe.class)).thenReturn(loader);
URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, "");
List<StartupProbe> readinessProbes = Arrays.asList(new DeployerStartupProbe(frameworkModel));
Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION))
.thenReturn(readinessProbes);
}
@Test
void testExecute() {
Startup startup = new Startup(frameworkModel);
CommandContext commandContext = new CommandContext("startup");
String result = startup.execute(commandContext, new String[0]);
Assertions.assertEquals("true", result);
Assertions.assertEquals(commandContext.getHttpCode(), 200);
Mockito.when(moduleDeployer.isRunning()).thenReturn(false);
result = startup.execute(commandContext, new String[0]);
Assertions.assertEquals("false", result);
Assertions.assertEquals(commandContext.getHttpCode(), 503);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/MockLivenessProbe.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/MockLivenessProbe.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.qos.probe.LivenessProbe;
@Activate
public class MockLivenessProbe implements LivenessProbe {
private static boolean checkReturnValue = false;
@Override
public boolean check() {
return checkReturnValue;
}
public static void setCheckReturnValue(boolean checkReturnValue) {
MockLivenessProbe.checkReturnValue = checkReturnValue;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LiveTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LiveTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class LiveTest {
private FrameworkModel frameworkModel;
@BeforeEach
public void setUp() {
frameworkModel = new FrameworkModel();
}
@AfterEach
public void reset() {
frameworkModel.destroy();
MockLivenessProbe.setCheckReturnValue(false);
}
@Test
void testExecute() {
Live live = new Live(frameworkModel);
CommandContext commandContext = new CommandContext("live");
String result = live.execute(commandContext, new String[0]);
Assertions.assertEquals(result, "false");
Assertions.assertEquals(commandContext.getHttpCode(), 503);
MockLivenessProbe.setCheckReturnValue(true);
result = live.execute(commandContext, new String[0]);
Assertions.assertEquals(result, "true");
Assertions.assertEquals(commandContext.getHttpCode(), 200);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.qos.DemoService;
import org.apache.dubbo.qos.DemoServiceImpl;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE;
import static org.mockito.Mockito.mock;
/**
* {@link BaseOffline}
* {@link Offline}
* {@link OfflineApp}
* {@link OfflineInterface}
*/
class OfflineTest {
private FrameworkModel frameworkModel;
private ModuleServiceRepository repository;
private ProviderModel.RegisterStatedURL registerStatedURL;
@BeforeEach
public void setUp() {
frameworkModel = new FrameworkModel();
repository = frameworkModel.newApplication().getDefaultModule().getServiceRepository();
registerProvider();
}
@AfterEach
public void reset() {
frameworkModel.destroy();
}
@Test
void testExecute() {
Offline offline = new Offline(frameworkModel);
String result = offline.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()});
Assertions.assertEquals(result, "OK");
Assertions.assertFalse(registerStatedURL.isRegistered());
OfflineInterface offlineInterface = new OfflineInterface(frameworkModel);
registerStatedURL.setRegistered(true);
result = offlineInterface.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()});
Assertions.assertEquals(result, "OK");
Assertions.assertFalse(registerStatedURL.isRegistered());
registerStatedURL.setRegistered(true);
registerStatedURL.setRegistryUrl(URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName())
.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE));
OfflineApp offlineApp = new OfflineApp(frameworkModel);
result = offlineApp.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()});
Assertions.assertEquals(result, "OK");
Assertions.assertFalse(registerStatedURL.isRegistered());
}
private void registerProvider() {
ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class);
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setServiceKey(DemoService.class.getName());
ProviderModel providerModel = new ProviderModel(
DemoService.class.getName(),
new DemoServiceImpl(),
serviceDescriptor,
serviceMetadata,
ClassUtils.getClassLoader(DemoService.class));
registerStatedURL = new ProviderModel.RegisterStatedURL(
URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()),
URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()),
true);
providerModel.addStatedUrl(registerStatedURL);
repository.registerProvider(providerModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import io.netty.channel.Channel;
import io.netty.util.DefaultAttributeMap;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class ChangeTelnetTest {
private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap();
private BaseCommand change;
private Channel mockChannel;
private CommandContext mockCommandContext;
private Invoker<DemoService> mockInvoker;
@AfterAll
public static void tearDown() {
FrameworkModel.destroyAll();
}
@BeforeAll
public static void setUp() {
FrameworkModel.destroyAll();
}
@SuppressWarnings("unchecked")
@BeforeEach
public void beforeEach() {
change = new ChangeTelnet(FrameworkModel.defaultModel());
mockCommandContext = mock(CommandContext.class);
mockChannel = mock(Channel.class);
mockInvoker = mock(Invoker.class);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
mockChannel.attr(ChangeTelnet.SERVICE_KEY).set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
given(mockCommandContext.getRemote()).willReturn(mockChannel);
given(mockInvoker.getInterface()).willReturn(DemoService.class);
given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo?group=g&version=1.0.0"));
}
@AfterEach
public void afterEach() {
FrameworkModel.destroyAll();
reset(mockCommandContext, mockChannel, mockInvoker);
}
@Test
void testChangeSimpleName() {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result = change.execute(mockCommandContext, new String[] {"DemoService"});
assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
void testChangeName() {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result =
change.execute(mockCommandContext, new String[] {"org.apache.dubbo.qos.legacy.service.DemoService"});
assertEquals(
"Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /",
result);
}
@Test
void testChangePath() {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result = change.execute(mockCommandContext, new String[] {"demo"});
assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
void testChangeServiceKey() {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result = change.execute(mockCommandContext, new String[] {"g/demo:1.0.0"});
assertEquals("Used the g/demo:1.0.0 as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
void testChangeMessageNull() {
String result = change.execute(mockCommandContext, null);
assertEquals("Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService", result);
}
@Test
void testChangeServiceNotExport() {
String result = change.execute(mockCommandContext, new String[] {"demo"});
assertEquals("No such service demo", result);
}
@Test
void testChangeCancel() {
String result = change.execute(mockCommandContext, new String[] {".."});
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
@Test
void testChangeCancel2() {
String result = change.execute(mockCommandContext, new String[] {"/"});
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.qos.DemoService;
import org.apache.dubbo.qos.DemoServiceImpl;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE;
import static org.mockito.Mockito.mock;
/**
* {@link BaseOnline}
* {@link Online}
* {@link OnlineApp}
* {@link OnlineInterface}
*/
class OnlineTest {
private FrameworkModel frameworkModel;
private ModuleServiceRepository repository;
private ProviderModel.RegisterStatedURL registerStatedURL;
@BeforeEach
public void setUp() {
frameworkModel = new FrameworkModel();
repository = frameworkModel.newApplication().getDefaultModule().getServiceRepository();
registerProvider();
}
@AfterEach
public void reset() {
frameworkModel.destroy();
}
@Test
void testExecute() {
Online online = new Online(frameworkModel);
String result = online.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()});
Assertions.assertEquals(result, "OK");
Assertions.assertTrue(registerStatedURL.isRegistered());
OnlineInterface onlineInterface = new OnlineInterface(frameworkModel);
registerStatedURL.setRegistered(false);
result = onlineInterface.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()});
Assertions.assertEquals(result, "OK");
Assertions.assertTrue(registerStatedURL.isRegistered());
registerStatedURL.setRegistered(false);
registerStatedURL.setRegistryUrl(URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName())
.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE));
OnlineApp onlineApp = new OnlineApp(frameworkModel);
result = onlineApp.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()});
Assertions.assertEquals(result, "OK");
Assertions.assertTrue(registerStatedURL.isRegistered());
}
private void registerProvider() {
ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class);
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setServiceKey(DemoService.class.getName());
ProviderModel providerModel = new ProviderModel(
DemoService.class.getName(),
new DemoServiceImpl(),
serviceDescriptor,
serviceMetadata,
ClassUtils.getClassLoader(DemoService.class));
registerStatedURL = new ProviderModel.RegisterStatedURL(
URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()),
URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()),
false);
providerModel.addStatedUrl(registerStatedURL);
repository.registerProvider(providerModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PortTelnetTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PortTelnetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class PortTelnetTest {
private static final Logger logger = LoggerFactory.getLogger(PortTelnetTest.class);
private BaseCommand port;
private Invoker<DemoService> mockInvoker;
private CommandContext mockCommandContext;
private static final int availablePort = NetUtils.getAvailablePort();
@SuppressWarnings("unchecked")
@BeforeEach
public void before() {
FrameworkModel frameworkModel = FrameworkModel.defaultModel();
port = new PortTelnet(frameworkModel);
mockCommandContext = mock(CommandContext.class);
mockInvoker = mock(Invoker.class);
given(mockInvoker.getInterface()).willReturn(DemoService.class);
given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:" + availablePort + "/demo"));
frameworkModel
.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
}
@AfterEach
public void afterEach() {
FrameworkModel.destroyAll();
reset(mockInvoker, mockCommandContext);
}
/**
* In NAT network scenario, server's channel.getRemoteAddress() possibly get the address of network gateway, or
* the address converted by NAT. In this case, check port only.
*/
@Test
void testListClient() throws Exception {
ExchangeClient client1 = Exchangers.connect("dubbo://127.0.0.1:" + availablePort + "/demo");
ExchangeClient client2 = Exchangers.connect("dubbo://127.0.0.1:" + availablePort + "/demo");
Thread.sleep(100);
String result = port.execute(mockCommandContext, new String[] {"-l", availablePort + ""});
String client1Addr = client1.getLocalAddress().toString();
String client2Addr = client2.getLocalAddress().toString();
logger.info("Result: {}}", result);
logger.info("Client 1 Address {}", client1Addr);
logger.info("Client 2 Address {}", client2Addr);
assertTrue(result.contains(String.valueOf(client1.getLocalAddress().getPort())));
assertTrue(result.contains(String.valueOf(client2.getLocalAddress().getPort())));
}
@Test
void testListDetail() throws RemotingException {
String result = port.execute(mockCommandContext, new String[] {"-l"});
assertEquals("dubbo://127.0.0.1:" + availablePort + "", result);
}
@Test
void testListAllPort() throws RemotingException {
String result = port.execute(mockCommandContext, new String[0]);
assertEquals("" + availablePort + "", result);
}
@Test
void testErrorMessage() throws RemotingException {
String result = port.execute(mockCommandContext, new String[] {"a"});
assertEquals("Illegal port a, must be integer.", result);
}
@Test
void testNoPort() throws RemotingException {
String result = port.execute(mockCommandContext, new String[] {"-l", "20880"});
assertEquals("No such port 20880", result);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestInterface.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestInterface.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl;
public interface TestInterface {
String sayHello();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/channel/MockNettyChannel.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/channel/MockNettyChannel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.impl.channel;
import org.apache.dubbo.common.URL;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelProgressivePromise;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.AttributeMap;
import io.netty.util.DefaultAttributeMap;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
public class MockNettyChannel implements Channel {
InetSocketAddress localAddress;
InetSocketAddress remoteAddress;
private URL remoteUrl;
private List<Object> receivedObjects = new LinkedList<>();
public static final String ERROR_WHEN_SEND = "error_when_send";
private CountDownLatch latch;
private AttributeMap attributeMap = new DefaultAttributeMap();
public MockNettyChannel(URL remoteUrl, CountDownLatch latch) {
this.remoteUrl = remoteUrl;
this.latch = latch;
}
@Override
public ChannelFuture writeAndFlush(Object msg) {
receivedObjects.add(msg);
if (latch != null) {
latch.countDown();
}
return newPromise();
}
@Override
public ChannelPromise newPromise() {
return new ChannelPromise() {
@Override
public Channel channel() {
return null;
}
@Override
public ChannelPromise setSuccess(Void result) {
return null;
}
@Override
public ChannelPromise setSuccess() {
return null;
}
@Override
public boolean trySuccess() {
return false;
}
@Override
public ChannelPromise setFailure(Throwable cause) {
return null;
}
@Override
public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
return null;
}
@Override
public ChannelPromise addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
return null;
}
@Override
public ChannelPromise removeListener(GenericFutureListener<? extends Future<? super Void>> listener) {
return null;
}
@Override
public ChannelPromise removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
return null;
}
@Override
public ChannelPromise sync() throws InterruptedException {
return null;
}
@Override
public ChannelPromise syncUninterruptibly() {
return null;
}
@Override
public ChannelPromise await() throws InterruptedException {
return this;
}
@Override
public ChannelPromise awaitUninterruptibly() {
return null;
}
@Override
public ChannelPromise unvoid() {
return null;
}
@Override
public boolean isVoid() {
return false;
}
@Override
public boolean trySuccess(Void result) {
return false;
}
@Override
public boolean tryFailure(Throwable cause) {
return false;
}
@Override
public boolean setUncancellable() {
return false;
}
@Override
public boolean isSuccess() {
return false;
}
@Override
public boolean isCancellable() {
return false;
}
@Override
public Throwable cause() {
return null;
}
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
return true;
}
@Override
public boolean await(long timeoutMillis) throws InterruptedException {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeout, TimeUnit unit) {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeoutMillis) {
return false;
}
@Override
public Void getNow() {
return null;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public Void get() throws InterruptedException, ExecutionException {
return null;
}
@Override
public Void get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
};
}
@Override
public ChannelProgressivePromise newProgressivePromise() {
return null;
}
@Override
public ChannelFuture newSucceededFuture() {
return null;
}
@Override
public ChannelFuture newFailedFuture(Throwable cause) {
return null;
}
@Override
public ChannelPromise voidPromise() {
return null;
}
@Override
public ChannelId id() {
return null;
}
@Override
public EventLoop eventLoop() {
return null;
}
@Override
public Channel parent() {
return null;
}
@Override
public ChannelConfig config() {
return null;
}
@Override
public boolean isOpen() {
return false;
}
@Override
public boolean isRegistered() {
return false;
}
@Override
public boolean isActive() {
return false;
}
@Override
public ChannelMetadata metadata() {
return null;
}
@Override
public SocketAddress localAddress() {
return null;
}
@Override
public SocketAddress remoteAddress() {
return null;
}
@Override
public ChannelFuture closeFuture() {
return null;
}
@Override
public boolean isWritable() {
return false;
}
@Override
public long bytesBeforeUnwritable() {
return 0;
}
@Override
public long bytesBeforeWritable() {
return 0;
}
@Override
public Unsafe unsafe() {
return null;
}
@Override
public ChannelPipeline pipeline() {
return null;
}
@Override
public ByteBufAllocator alloc() {
return null;
}
@Override
public ChannelFuture bind(SocketAddress localAddress) {
return null;
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress) {
return null;
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
return null;
}
@Override
public ChannelFuture disconnect() {
return null;
}
@Override
public ChannelFuture close() {
return null;
}
@Override
public ChannelFuture deregister() {
return null;
}
@Override
public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
return null;
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
return null;
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
return null;
}
@Override
public ChannelFuture disconnect(ChannelPromise promise) {
return null;
}
@Override
public ChannelFuture close(ChannelPromise promise) {
return null;
}
@Override
public ChannelFuture deregister(ChannelPromise promise) {
return null;
}
@Override
public Channel read() {
return null;
}
@Override
public ChannelFuture write(Object msg) {
return null;
}
@Override
public ChannelFuture write(Object msg, ChannelPromise promise) {
return null;
}
@Override
public Channel flush() {
return null;
}
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
return null;
}
@Override
public <T> Attribute<T> attr(AttributeKey<T> key) {
return attributeMap.attr(key);
}
@Override
public <T> boolean hasAttr(AttributeKey<T> key) {
return attributeMap.hasAttr(key);
}
@Override
public int compareTo(Channel o) {
return 0;
}
public List<Object> getReceivedObjects() {
return receivedObjects;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoderTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.decoder;
import org.apache.dubbo.qos.api.CommandContext;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
class TelnetCommandDecoderTest {
@Test
void testDecode() throws Exception {
CommandContext context = TelnetCommandDecoder.decode("test a b");
assertThat(context.getCommandName(), equalTo("test"));
assertThat(context.isHttp(), is(false));
assertThat(context.getArgs(), arrayContaining("a", "b"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoderTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.command.decoder;
import org.apache.dubbo.qos.api.CommandContext;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class HttpCommandDecoderTest {
@Test
void decodeGet() {
HttpRequest request = mock(HttpRequest.class);
when(request.uri()).thenReturn("localhost:80/test");
when(request.method()).thenReturn(HttpMethod.GET);
CommandContext context = HttpCommandDecoder.decode(request);
assertThat(context.getCommandName(), equalTo("test"));
assertThat(context.isHttp(), is(true));
when(request.uri()).thenReturn("localhost:80/test?a=b&c=d");
context = HttpCommandDecoder.decode(request);
assertThat(context.getArgs(), arrayContaining("b", "d"));
}
@Test
void decodePost() {
FullHttpRequest request = mock(FullHttpRequest.class);
when(request.uri()).thenReturn("localhost:80/test");
when(request.method()).thenReturn(HttpMethod.POST);
when(request.headers()).thenReturn(HttpHeaders.EMPTY_HEADERS);
ByteBuf buf = Unpooled.copiedBuffer("a=b&c=d", StandardCharsets.UTF_8);
when(request.content()).thenReturn(buf);
CommandContext context = HttpCommandDecoder.decode(request);
assertThat(context.getCommandName(), equalTo("test"));
assertThat(context.isHttp(), is(true));
assertThat(context.getArgs(), arrayContaining("b", "d"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.