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/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessNettyServer.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessNettyServer.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.CommandExecutor; import com.taobao.arthas.mcp.server.protocol.spec.McpError; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.protocol.spec.McpStatelessServerTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.BiFunction; /** * A Netty-based MCP server implementation that provides access to tools, resources, and prompts. * * @author Yeaury */ public class McpStatelessNettyServer { private static final Logger logger = LoggerFactory.getLogger(McpStatelessNettyServer.class); private final McpStatelessServerTransport mcpTransportProvider; private final ObjectMapper objectMapper; private final McpSchema.ServerCapabilities serverCapabilities; private final McpSchema.Implementation serverInfo; private final String instructions; private final CopyOnWriteArrayList<McpStatelessServerFeatures.ToolSpecification> tools = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<McpSchema.ResourceTemplate> resourceTemplates = new CopyOnWriteArrayList<>(); private final ConcurrentHashMap<String, McpStatelessServerFeatures.ResourceSpecification> resources = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, McpStatelessServerFeatures.PromptSpecification> prompts = new ConcurrentHashMap<>(); private List<String> protocolVersions; public McpStatelessNettyServer( McpStatelessServerTransport mcpTransport, ObjectMapper objectMapper, Duration requestTimeout, McpStatelessServerFeatures.McpServerConfig features, CommandExecutor commandExecutor) { this.mcpTransportProvider = mcpTransport; this.objectMapper = objectMapper; this.serverInfo = features.getServerInfo(); this.serverCapabilities = features.getServerCapabilities(); this.instructions = features.getInstructions(); this.tools.addAll(features.getTools()); this.resources.putAll(features.getResources()); this.resourceTemplates.addAll(features.getResourceTemplates()); this.prompts.putAll(features.getPrompts()); this.protocolVersions = new ArrayList<>(mcpTransport.protocolVersions()); Map<String, McpStatelessRequestHandler<?>> requestHandlers = new HashMap<>(); // Initialize request handlers for standard MCP methods requestHandlers.put(McpSchema.METHOD_INITIALIZE, initializeRequestHandler()); // Ping MUST respond with an empty data, but not NULL response. requestHandlers.put(McpSchema.METHOD_PING, (exchange, commandContext, params) -> CompletableFuture.completedFuture(Collections.emptyMap())); // Add tools API handlers if the tool capability is enabled if (this.serverCapabilities.getTools() != null) { requestHandlers.put(McpSchema.METHOD_TOOLS_LIST, toolsListRequestHandler()); requestHandlers.put(McpSchema.METHOD_TOOLS_CALL, toolsCallRequestHandler()); } // Add resources API handlers if provided if (this.serverCapabilities.getResources() != null) { requestHandlers.put(McpSchema.METHOD_RESOURCES_LIST, resourcesListRequestHandler()); requestHandlers.put(McpSchema.METHOD_RESOURCES_READ, resourcesReadRequestHandler()); requestHandlers.put(McpSchema.METHOD_RESOURCES_TEMPLATES_LIST, resourceTemplateListRequestHandler()); } // Add prompts API handlers if provider exists if (this.serverCapabilities.getPrompts() != null) { requestHandlers.put(McpSchema.METHOD_PROMPT_LIST, promptsListRequestHandler()); requestHandlers.put(McpSchema.METHOD_PROMPT_GET, promptsGetRequestHandler()); } Map<String, McpStatelessNotificationHandler> notificationHandlers = new HashMap<>(); notificationHandlers.put(McpSchema.METHOD_NOTIFICATION_INITIALIZED, (ctx, params) -> CompletableFuture.completedFuture(null)); McpStatelessServerHandler handler = new DefaultMcpStatelessServerHandler(requestHandlers, notificationHandlers, commandExecutor); mcpTransport.setMcpHandler(handler); } // --------------------------------------- // Lifecycle Management // --------------------------------------- private McpStatelessRequestHandler<McpSchema.InitializeResult> initializeRequestHandler() { return (exchange, commandContext, params) -> CompletableFuture.supplyAsync(() -> { McpSchema.InitializeRequest initializeRequest = objectMapper.convertValue(params, McpSchema.InitializeRequest.class); logger.info("Client initialize request - Protocol: {}, Capabilities: {}, Info: {}", initializeRequest.getProtocolVersion(), initializeRequest.getCapabilities(), initializeRequest.getClientInfo()); // The server MUST respond with the highest protocol version it supports // if // it does not support the requested (e.g. Client) version. String serverProtocolVersion = protocolVersions.get(protocolVersions.size() - 1); if (protocolVersions.contains(initializeRequest.getProtocolVersion())) { serverProtocolVersion = initializeRequest.getProtocolVersion(); } else { logger.warn( "Client requested unsupported protocol version: {}, " + "so the server will suggest {} instead", initializeRequest.getProtocolVersion(), serverProtocolVersion); } return new McpSchema.InitializeResult(serverProtocolVersion, serverCapabilities, serverInfo, instructions); }); } public McpSchema.ServerCapabilities getServerCapabilities() { return this.serverCapabilities; } public McpSchema.Implementation getServerInfo() { return this.serverInfo; } public CompletableFuture<Void> closeGracefully() { return this.mcpTransportProvider.closeGracefully(); } public void close() { this.mcpTransportProvider.close(); } private McpNotificationHandler rootsListChangedNotificationHandler( List<BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>>> rootsChangeConsumers) { return (exchange, commandContext, params) -> { CompletableFuture<McpSchema.ListRootsResult> futureRoots = exchange.listRoots(); return futureRoots.thenCompose(listRootsResult -> { List<McpSchema.Root> roots = listRootsResult.getRoots(); List<CompletableFuture<?>> futures = new ArrayList<>(); for (BiFunction<McpNettyServerExchange, List<McpSchema.Root>, CompletableFuture<Void>> consumer : rootsChangeConsumers) { CompletableFuture<Void> future = consumer.apply(exchange, roots).exceptionally(error -> { logger.error("Error handling roots list change notification", error); return null; }); futures.add(future); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); }); }; } // --------------------------------------- // Tool Management // --------------------------------------- public CompletableFuture<Void> addTool(McpStatelessServerFeatures.ToolSpecification toolSpecification) { if (toolSpecification == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool specification must not be null")); return future; } if (toolSpecification.getTool() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool must not be null")); return future; } if (toolSpecification.getCall() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool call handler must not be null")); return future; } if (this.serverCapabilities.getTools() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with tool capabilities")); return future; } return CompletableFuture .runAsync(() -> { if (this.tools.stream().anyMatch(th -> th.getTool().getName().equals(toolSpecification.getTool().getName()))) { throw new CompletionException( new McpError("Tool with name '" + toolSpecification.getTool().getName() + "' already exists")); } this.tools.add(toolSpecification); logger.debug("Added tool handler: {}", toolSpecification.getTool().getName()); }) .exceptionally(ex -> { Throwable cause = ex instanceof CompletionException ? ex.getCause() : ex; logger.error("Error while adding tool", cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> removeTool(String toolName) { if (toolName == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Tool name must not be null")); return future; } if (this.serverCapabilities.getTools() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with tool capabilities")); return future; } return CompletableFuture .runAsync(() -> { boolean removed = this.tools.removeIf( spec -> spec.getTool().getName().equals(toolName)); if (!removed) { throw new CompletionException( new McpError("Tool with name '" + toolName + "' not found")); } logger.debug("Removed tool handler: {}", toolName); }) .exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; logger.error("Error while removing tool '{}'", toolName, cause); throw new CompletionException(cause); }); } private McpStatelessRequestHandler<McpSchema.ListToolsResult> toolsListRequestHandler() { return (exchange, commandContext, params) -> { List<McpSchema.Tool> tools = new ArrayList<>(); for (McpStatelessServerFeatures.ToolSpecification toolSpec : this.tools) { tools.add(toolSpec.getTool()); } return CompletableFuture.completedFuture(new McpSchema.ListToolsResult(tools, null)); }; } private McpStatelessRequestHandler<McpSchema.CallToolResult> toolsCallRequestHandler() { return (context, commandContext, params) -> { McpSchema.CallToolRequest callToolRequest = objectMapper.convertValue(params, new TypeReference<McpSchema.CallToolRequest>() { }); Optional<McpStatelessServerFeatures.ToolSpecification> toolSpecification = this.tools.stream() .filter(tr -> callToolRequest.getName().equals(tr.getTool().getName())) .findAny(); if (!toolSpecification.isPresent()) { CompletableFuture<McpSchema.CallToolResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("no tool found: " + callToolRequest.getName())); return future; } return toolSpecification.get().getCall().apply(context, commandContext, callToolRequest.getArguments()); }; } // --------------------------------------- // Resource Management // --------------------------------------- public CompletableFuture<Void> addResource(McpStatelessServerFeatures.ResourceSpecification resourceSpecification) { if (resourceSpecification == null || resourceSpecification.getResource() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Resource must not be null")); return future; } if (this.serverCapabilities.getResources() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with resource capabilities")); return future; } return CompletableFuture .runAsync(() -> { String uri = resourceSpecification.getResource().getUri(); if (this.resources.putIfAbsent(uri, resourceSpecification) != null) { throw new CompletionException(new McpError("Resource with URI '" + uri + "' already exists")); } logger.debug("Added resource handler: {}", uri); }) .exceptionally(ex -> { Throwable cause = ex instanceof CompletionException ? ex.getCause() : ex; logger.error("Error while adding resource '{}'", resourceSpecification.getResource().getUri(), cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> removeResource(String resourceUri) { if (resourceUri == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Resource URI must not be null")); return future; } if (this.serverCapabilities.getResources() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with resource capabilities")); return future; } return CompletableFuture .runAsync(() -> { McpStatelessServerFeatures.ResourceSpecification removed = this.resources.remove(resourceUri); if (removed == null) { throw new CompletionException(new McpError("Resource with URI '" + resourceUri + "' not found")); } logger.debug("Removed resource handler: {}", resourceUri); }) .exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; logger.error("Error while removing resource '{}'", resourceUri, cause); throw new CompletionException(cause); }); } private McpStatelessRequestHandler<McpSchema.ListResourcesResult> resourcesListRequestHandler() { return (exchange, commandContext, params) -> { List<McpSchema.Resource> resourceList = new ArrayList<>(); for (McpStatelessServerFeatures.ResourceSpecification spec : this.resources.values()) { resourceList.add(spec.getResource()); } return CompletableFuture.completedFuture(new McpSchema.ListResourcesResult(resourceList, null)); }; } private McpStatelessRequestHandler<McpSchema.ListResourceTemplatesResult> resourceTemplateListRequestHandler() { return (context, commandContext, params) -> CompletableFuture .completedFuture(new McpSchema.ListResourceTemplatesResult(this.resourceTemplates, null)); } private McpStatelessRequestHandler<McpSchema.ReadResourceResult> resourcesReadRequestHandler() { return (context, commandContext, params) -> { McpSchema.ReadResourceRequest resourceRequest = objectMapper.convertValue(params, new TypeReference<McpSchema.ReadResourceRequest>() { }); String resourceUri = resourceRequest.getUri(); McpStatelessServerFeatures.ResourceSpecification specification = this.resources.get(resourceUri); if (specification != null) { return specification.getReadHandler().apply(context, resourceRequest); } CompletableFuture<McpSchema.ReadResourceResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Resource not found: " + resourceUri)); return future; }; } // --------------------------------------- // Prompt Management // --------------------------------------- public CompletableFuture<Void> addPrompt(McpStatelessServerFeatures.PromptSpecification promptSpecification) { if (promptSpecification == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Prompt specification must not be null")); return future; } if (this.serverCapabilities.getPrompts() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with prompt capabilities")); return future; } return CompletableFuture .runAsync(() -> { String name = promptSpecification.getPrompt().getName(); McpStatelessServerFeatures.PromptSpecification existing = this.prompts.putIfAbsent(name, promptSpecification); if (existing != null) { throw new CompletionException(new McpError("Prompt with name '" + name + "' already exists")); } logger.debug("Added prompt handler: {}", name); }) .exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; String name = promptSpecification.getPrompt().getName(); logger.error("Error while adding prompt '{}'", name, cause); throw new CompletionException(cause); }); } public CompletableFuture<Void> removePrompt(String promptName) { if (promptName == null || promptName.isEmpty()) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Prompt name must not be null or empty")); return future; } if (this.serverCapabilities.getPrompts() == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Server must be configured with prompt capabilities")); return future; } return CompletableFuture .runAsync(() -> { McpStatelessServerFeatures.PromptSpecification removed = this.prompts.remove(promptName); if (removed == null) { throw new CompletionException(new McpError("Prompt with name '" + promptName + "' not found")); } logger.debug("Removed prompt handler: {}", promptName); }) .exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; logger.error("Error while removing prompt '{}'", promptName, cause); throw new CompletionException(cause); }); } private McpStatelessRequestHandler<McpSchema.ListPromptsResult> promptsListRequestHandler() { return (exchange, commandContext, params) -> { List<McpSchema.Prompt> promptList = new ArrayList<>(); for (McpStatelessServerFeatures.PromptSpecification promptSpec : this.prompts.values()) { promptList.add(promptSpec.getPrompt()); } return CompletableFuture.completedFuture(new McpSchema.ListPromptsResult(promptList, null)); }; } private McpStatelessRequestHandler<McpSchema.GetPromptResult> promptsGetRequestHandler() { return (context, commandContext, params) -> { McpSchema.GetPromptRequest promptRequest = objectMapper.convertValue(params, new TypeReference<McpSchema.GetPromptRequest>() { }); McpStatelessServerFeatures.PromptSpecification specification = this.prompts.get(promptRequest.getName()); if (specification != null) { return specification.getPromptHandler().apply(context, promptRequest); } CompletableFuture<McpSchema.GetPromptResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Prompt not found: " + promptRequest.getName())); return future; }; } // --------------------------------------- // Sampling // --------------------------------------- public void setProtocolVersions(List<String> protocolVersions) { this.protocolVersions = protocolVersions; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessRequestHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpStatelessRequestHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import java.util.concurrent.CompletableFuture; /** * Handler for MCP requests in a stateless server. */ public interface McpStatelessRequestHandler<R> { /** * Handle the request and complete with a result. * @param transportContext {@link McpTransportContext} associated with the transport * @param params the payload of the MCP request * @return Mono which completes with the response object */ CompletableFuture<R> handle(McpTransportContext transportContext, ArthasCommandContext arthasCommandContext, Object params); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpRequestHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpRequestHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import java.util.concurrent.CompletableFuture; /** * Handles MCP requests from clients using CompletableFuture for async operations. * This is the Netty-specific version that doesn't depend on Reactor. */ public interface McpRequestHandler<T> { /** * Handles a request from the client. * @param exchange the exchange associated with the client that allows calling back to * the connected client or inspecting its capabilities. * @param params the parameters of the request. * @return a CompletableFuture that will emit the response to the request. */ CompletableFuture<T> handle(McpNettyServerExchange exchange, ArthasCommandContext arthasCommandContext, Object params); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpTransportContext.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpTransportContext.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; public interface McpTransportContext { String KEY = "MCP_TRANSPORT_CONTEXT"; McpTransportContext EMPTY = new DefaultMcpTransportContext(); Object get(String key); void put(String key, Object value); McpTransportContext copy(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpNettyServerExchange.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpNettyServerExchange.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.fasterxml.jackson.core.type.TypeReference; import com.taobao.arthas.mcp.server.protocol.spec.McpError; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema.LoggingLevel; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema.LoggingMessageNotification; import com.taobao.arthas.mcp.server.protocol.spec.McpSession; import com.taobao.arthas.mcp.server.util.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; /** * Represents the interaction between MCP server and client. Provides methods for communication, logging, and context management. * This class is focused only on MCP protocol communication and does not handle command execution directly. * * <p> * McpNettyServerExchange provides various methods for communicating with the client, including: * <ul> * <li>Sending requests and notifications * <li>Getting client capabilities and information * <li>Handling logging notifications * <li>Creating client messages * <li>Managing root directories * <li>Streamable task management * </ul> * <p> * Each exchange object is associated with a specific client session, providing context and capabilities for that session. */ public class McpNettyServerExchange { private static final Logger logger = LoggerFactory.getLogger(McpNettyServerExchange.class); private final String sessionId; private final McpSession session; private final McpSchema.ClientCapabilities clientCapabilities; private final McpSchema.Implementation clientInfo; private final McpTransportContext transportContext; private volatile LoggingLevel minLoggingLevel = LoggingLevel.INFO; private static final TypeReference<McpSchema.CreateMessageResult> CREATE_MESSAGE_RESULT_TYPE_REF = new TypeReference<McpSchema.CreateMessageResult>() { }; private static final TypeReference<McpSchema.ListRootsResult> LIST_ROOTS_RESULT_TYPE_REF = new TypeReference<McpSchema.ListRootsResult>() { }; private static final TypeReference<McpSchema.ElicitResult> ELICIT_USER_INPUT_RESULT_TYPE_REF = new TypeReference<McpSchema.ElicitResult>() { }; public static final TypeReference<Object> OBJECT_TYPE_REF = new TypeReference<Object>() { }; public McpNettyServerExchange(String sessionId, McpSession session, McpSchema.ClientCapabilities clientCapabilities, McpSchema.Implementation clientInfo, McpTransportContext transportContext) { this.sessionId = sessionId; this.session = session; this.clientCapabilities = clientCapabilities; this.clientInfo = clientInfo; this.transportContext = transportContext; } /** * Get client capabilities. * @return Client capabilities */ public McpSchema.ClientCapabilities getClientCapabilities() { return this.clientCapabilities; } /** * Get client information. * @return Client information */ public McpSchema.Implementation getClientInfo() { return this.clientInfo; } /** * Get the MCP server session associated with this exchange. * @return The MCP server session */ public McpSession getSession() { return this.session; } /** * Get the transport context associated with this exchange. * @return The transport context */ public McpTransportContext getTransportContext() { return this.transportContext; } /** * Create a new message using client sampling capability. MCP provides a standardized way for servers to request * LLM sampling ("completion" or "generation") through the client. This flow allows clients to maintain control * over model access, selection, and permissions while enabling servers to leverage AI capabilities—without server * API keys. Servers can request text or image-based interactions and can optionally include context from the MCP * server in their prompts. * @param createMessageRequest Request to create a new message * @return A CompletableFuture that completes when the message is created */ public CompletableFuture<McpSchema.CreateMessageResult> createMessage( McpSchema.CreateMessageRequest createMessageRequest) { if (this.clientCapabilities == null) { logger.error("Client not initialized, cannot create message"); CompletableFuture<McpSchema.CreateMessageResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Client must be initialized first. Please call initialize method!")); return future; } if (this.clientCapabilities.getSampling() == null) { logger.error("Client not configured with sampling capability, cannot create message"); CompletableFuture<McpSchema.CreateMessageResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Client must be configured with sampling capability")); return future; } logger.debug("Creating client message, session ID: {}", this.sessionId); return this.session .sendRequest(McpSchema.METHOD_SAMPLING_CREATE_MESSAGE, createMessageRequest, CREATE_MESSAGE_RESULT_TYPE_REF) .whenComplete((result, error) -> { if (error != null) { logger.error("Failed to create message, session ID: {}, error: {}", this.sessionId, error.getMessage()); } else { logger.debug("Message created successfully, session ID: {}", this.sessionId); } }); } /** * Get a list of all root directories provided by the client. * @return Sends out the CompletableFuture of the root list result */ public CompletableFuture<McpSchema.ListRootsResult> listRoots() { return this.listRoots(null); } /** * Get the client-provided list of pagination roots. * Optional pagination cursor @param cursor for the previous list request * @return Emits a CompletableFuture containing the results of the root list */ public CompletableFuture<McpSchema.ListRootsResult> listRoots(String cursor) { logger.debug("Requesting root list, session ID: {}, cursor: {}", this.sessionId, cursor); return this.session .sendRequest(McpSchema.METHOD_ROOTS_LIST, new McpSchema.PaginatedRequest(cursor), LIST_ROOTS_RESULT_TYPE_REF) .whenComplete((result, error) -> { if (error != null) { logger.error("Failed to get root list, session ID: {}, error: {}", this.sessionId, error.getMessage()); } else { logger.debug("Root list retrieved successfully, session ID: {}", this.sessionId); } }); } public CompletableFuture<Void> loggingNotification(LoggingMessageNotification loggingMessageNotification) { if (loggingMessageNotification == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("log messages cannot be empty")); return future; } if (this.isNotificationForLevelAllowed(loggingMessageNotification.getLevel())) { return this.session.sendNotification(McpSchema.METHOD_NOTIFICATION_MESSAGE, loggingMessageNotification) .whenComplete((result, error) -> { if (error != null) { logger.error("Failed to send logging notification, level: {}, session ID: {}, error: {}", loggingMessageNotification.getLevel(), this.sessionId, error.getMessage()); } }); } return CompletableFuture.completedFuture(null); } public CompletableFuture<Object> ping() { return this.session.sendRequest(McpSchema.METHOD_PING, null, OBJECT_TYPE_REF); } public CompletableFuture<McpSchema.ElicitResult> createElicitation(McpSchema.ElicitRequest request) { if (request == null) { CompletableFuture<McpSchema.ElicitResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("elicit request cannot be null")); return future; } if (this.clientCapabilities == null) { CompletableFuture<McpSchema.ElicitResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Client must be initialized. Call the initialize method first!")); return future; } if (this.clientCapabilities.getElicitation() == null) { CompletableFuture<McpSchema.ElicitResult> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("Client must be configured with elicitation capabilities")); return future; } return this.session .sendRequest(McpSchema.METHOD_ELICITATION_CREATE, request, ELICIT_USER_INPUT_RESULT_TYPE_REF) .whenComplete((result, error) -> { if (error != null) { logger.error("Failed to elicit user input, session ID: {}, error: {}", this.sessionId, error.getMessage()); } else { logger.debug("User input elicitation completed, session ID: {}", this.sessionId); } }); } public void setMinLoggingLevel(LoggingLevel minLoggingLevel) { Assert.notNull(minLoggingLevel, "the minimum log level cannot be empty"); logger.debug("Setting minimum logging level: {}, session ID: {}", minLoggingLevel, this.sessionId); this.minLoggingLevel = minLoggingLevel; } private boolean isNotificationForLevelAllowed(LoggingLevel loggingLevel) { return loggingLevel.level() >= this.minLoggingLevel.level(); } public CompletableFuture<Void> progressNotification(McpSchema.ProgressNotification progressNotification) { if (progressNotification == null) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new McpError("progress notifications cannot be empty")); return future; } return this.session .sendNotification(McpSchema.METHOD_NOTIFICATION_PROGRESS, progressNotification) .whenComplete((result, error) -> { if (error != null) { logger.error("Failed to send progress notification, session ID: {}, error: {}", this.sessionId, error.getMessage()); } else { logger.debug("Progress notification sent successfully, session ID: {}", this.sessionId); } }); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpTransportContextExtractor.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/McpTransportContextExtractor.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; /** * Interface for extracting transport context from server requests. * This allows inspection of HTTP transport level metadata during request processing. * * @param <T> the type of server request */ @FunctionalInterface public interface McpTransportContextExtractor<T> { /** * Extract transport context from the server request. * * @param serverRequest the server request to extract context from * @param context the base context to fill in * @return the updated context with extracted information */ McpTransportContext extract(T serverRequest, McpTransportContext context); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/DefaultMcpStatelessServerHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/DefaultMcpStatelessServerHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server; import com.taobao.arthas.mcp.server.CommandExecutor; import com.taobao.arthas.mcp.server.protocol.spec.McpError; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import com.taobao.arthas.mcp.server.session.ArthasCommandSessionManager; import com.taobao.arthas.mcp.server.util.McpAuthExtractor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; class DefaultMcpStatelessServerHandler implements McpStatelessServerHandler { private static final Logger logger = LoggerFactory.getLogger(DefaultMcpStatelessServerHandler.class); Map<String, McpStatelessRequestHandler<?>> requestHandlers; Map<String, McpStatelessNotificationHandler> notificationHandlers; private final CommandExecutor commandExecutor; private final ArthasCommandSessionManager commandSessionManager; public DefaultMcpStatelessServerHandler(Map<String, McpStatelessRequestHandler<?>> requestHandlers, Map<String, McpStatelessNotificationHandler> notificationHandlers, CommandExecutor commandExecutor) { this.requestHandlers = requestHandlers; this.notificationHandlers = notificationHandlers; this.commandExecutor = commandExecutor; this.commandSessionManager = new ArthasCommandSessionManager(commandExecutor); } @Override public CompletableFuture<McpSchema.JSONRPCResponse> handleRequest(McpTransportContext ctx, McpSchema.JSONRPCRequest req) { // Create a temporary session for this request String tempSessionId = UUID.randomUUID().toString(); ArthasCommandSessionManager.CommandSessionBinding binding = commandSessionManager.createCommandSession(tempSessionId); ArthasCommandContext commandContext = new ArthasCommandContext(commandExecutor, binding); // Extract auth subject from transport context and apply to session Object authSubject = ctx.get(McpAuthExtractor.MCP_AUTH_SUBJECT_KEY); if (authSubject != null) { commandExecutor.setSessionAuth(binding.getArthasSessionId(), authSubject); logger.debug("Applied auth subject to stateless session: {}", binding.getArthasSessionId()); } // Extract userId from transport context and apply to session String userId = (String) ctx.get(McpAuthExtractor.MCP_USER_ID_KEY); if (userId != null) { commandExecutor.setSessionUserId(binding.getArthasSessionId(), userId); logger.debug("Applied userId to stateless session: {}", binding.getArthasSessionId()); } McpStatelessRequestHandler<?> handler = requestHandlers.get(req.getMethod()); if (handler == null) { // Clean up session if handler not found closeSession(binding); CompletableFuture<McpSchema.JSONRPCResponse> f = new CompletableFuture<>(); f.completeExceptionally(new McpError("Missing handler for request type: " + req.getMethod())); return f; } try { @SuppressWarnings("unchecked") CompletableFuture<Object> result = (CompletableFuture<Object>) handler .handle(ctx, commandContext, req.getParams()); return result.handle((r, ex) -> { // Clean up session after execution closeSession(binding); if (ex != null) { Throwable cause = ex instanceof CompletionException ? ex.getCause() : ex; return new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, req.getId(), null, new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, cause.getMessage(), null)); } return new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, req.getId(), r, null); }); } catch (Throwable t) { // Clean up session on error closeSession(binding); CompletableFuture<McpSchema.JSONRPCResponse> f = new CompletableFuture<>(); f.completeExceptionally(t); return f; } } private void closeSession(ArthasCommandSessionManager.CommandSessionBinding binding) { try { commandExecutor.closeSession(binding.getArthasSessionId()); } catch (Exception e) { logger.warn("Failed to close temporary session: {}", binding.getArthasSessionId(), e); } } @Override public CompletableFuture<Void> handleNotification(McpTransportContext ctx, McpSchema.JSONRPCNotification note) { McpStatelessNotificationHandler handler = notificationHandlers.get(note.getMethod()); if (handler == null) { logger.warn("Missing handler for notification: {}", note.getMethod()); return CompletableFuture.completedFuture(null); } try { return handler.handle(ctx, note.getParams()); } catch (Throwable t) { CompletableFuture<Void> f = new CompletableFuture<>(); f.completeExceptionally(t); return f; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/store/InMemoryEventStore.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/store/InMemoryEventStore.java
package com.taobao.arthas.mcp.server.protocol.server.store; import com.taobao.arthas.mcp.server.protocol.spec.EventStore; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import java.util.stream.Stream; /** * In-memory implementation of EventStore. * * @author Yeaury */ public class InMemoryEventStore implements EventStore { private static final Logger logger = LoggerFactory.getLogger(InMemoryEventStore.class); /** Global event ID counter */ private final AtomicLong globalEventIdCounter = new AtomicLong(0); /** * Events storage: sessionId -> list of events */ private final Map<String, List<StoredEvent>> sessionEvents = new ConcurrentHashMap<>(); /** * Event ID to session mapping for fast lookup */ private final Map<String, String> eventIdToSession = new ConcurrentHashMap<>(); /** * Maximum events to keep per session (prevent memory leaks) */ private final int maxEventsPerSession; /** * Default retention time in milliseconds (24 hours) */ private final long defaultRetentionMs; public InMemoryEventStore() { this(1000, 24 * 60 * 60 * 1000L); // 1000 events, 24 hours } public InMemoryEventStore(int maxEventsPerSession, long defaultRetentionMs) { this.maxEventsPerSession = maxEventsPerSession; this.defaultRetentionMs = defaultRetentionMs; } @Override public String storeEvent(String sessionId, McpSchema.JSONRPCMessage message) { String eventId = String.valueOf(globalEventIdCounter.incrementAndGet()); Instant timestamp = Instant.now(); StoredEvent event = new StoredEvent(eventId, sessionId, message, timestamp); sessionEvents.computeIfAbsent(sessionId, k -> new ArrayList<>()).add(event); eventIdToSession.put(eventId, sessionId); // Cleanup old events if needed List<StoredEvent> events = sessionEvents.get(sessionId); if (events.size() > maxEventsPerSession) { // Remove oldest events int toRemove = events.size() - maxEventsPerSession; for (int i = 0; i < toRemove; i++) { StoredEvent removedEvent = events.remove(0); eventIdToSession.remove(removedEvent.getEventId()); } logger.debug("Cleaned up {} old events for session {}", toRemove, sessionId); } logger.trace("Stored event {} for session {}", eventId, sessionId); return eventId; } @Override public Stream<StoredEvent> getEventsForSession(String sessionId, String fromEventId) { List<StoredEvent> events = sessionEvents.get(sessionId); if (events == null || events.isEmpty()) { return Stream.empty(); } if (fromEventId == null) { return Stream.empty(); } boolean foundStartEvent = false; List<StoredEvent> result = new ArrayList<>(); for (StoredEvent event : events) { if (!foundStartEvent) { if (event.getEventId().equals(fromEventId)) { foundStartEvent = true; result.add(event); // clear the replayed events events.remove(event); eventIdToSession.remove(event.getEventId()); } continue; } result.add(event); } return result.stream(); } @Override public void cleanupOldEvents(String sessionId, long maxAge) { List<StoredEvent> events = sessionEvents.get(sessionId); if (events == null || events.isEmpty()) { return; } Instant cutoff = Instant.now().minusMillis(maxAge); List<StoredEvent> toRemove = events.stream() .filter(event -> event.getTimestamp().isBefore(cutoff)) .collect(Collectors.toList()); for (StoredEvent event : toRemove) { events.remove(event); eventIdToSession.remove(event.getEventId()); } if (!toRemove.isEmpty()) { logger.debug("Cleaned up {} old events for session {}", toRemove.size(), sessionId); } } @Override public void removeSessionEvents(String sessionId) { List<StoredEvent> events = sessionEvents.remove(sessionId); if (events != null) { for (StoredEvent event : events) { eventIdToSession.remove(event.getEventId()); } logger.debug("Removed {} events for session {}", events.size(), sessionId); } } public void cleanupExpiredEvents() { for (String sessionId : sessionEvents.keySet()) { cleanupOldEvents(sessionId, defaultRetentionMs); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/transport/NettyStreamableServerTransportProvider.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/transport/NettyStreamableServerTransportProvider.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server.transport; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContextExtractor; import com.taobao.arthas.mcp.server.protocol.server.handler.McpStreamableHttpRequestHandler; import com.taobao.arthas.mcp.server.protocol.spec.McpStreamableServerSession; import com.taobao.arthas.mcp.server.protocol.spec.McpStreamableServerTransportProvider; import com.taobao.arthas.mcp.server.protocol.spec.ProtocolVersions; import com.taobao.arthas.mcp.server.util.Assert; import io.netty.handler.codec.http.FullHttpRequest; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; /** * Server-side implementation of the Model Context Protocol (MCP) streamable transport * layer using HTTP with Server-Sent Events (SSE) through Netty. This implementation * provides a bridge between Netty operations and the MCP transport interface. * * @see McpStreamableServerTransportProvider */ public class NettyStreamableServerTransportProvider implements McpStreamableServerTransportProvider { public static final String DEFAULT_MCP_ENDPOINT = "/mcp"; private final McpStreamableHttpRequestHandler requestHandler; /** * Constructs a new NettyStreamableServerTransportProvider instance. * * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization * of messages. * @param mcpEndpoint The endpoint URI where clients should send their JSON-RPC * messages via HTTP. * @param disallowDelete Whether to disallow DELETE requests on the endpoint. * @param contextExtractor The extractor for transport context from the request. * @param keepAliveInterval Interval for keep-alive pings (null to disable) * @throws IllegalArgumentException if any parameter is null */ private NettyStreamableServerTransportProvider(ObjectMapper objectMapper, String mcpEndpoint, boolean disallowDelete, McpTransportContextExtractor<FullHttpRequest> contextExtractor, Duration keepAliveInterval) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); Assert.notNull(mcpEndpoint, "MCP endpoint must not be null"); Assert.notNull(contextExtractor, "Context extractor must not be null"); this.requestHandler = new McpStreamableHttpRequestHandler(objectMapper, mcpEndpoint, disallowDelete, contextExtractor, keepAliveInterval); } @Override public List<String> protocolVersions() { return Arrays.asList(ProtocolVersions.MCP_2024_11_05, ProtocolVersions.MCP_2025_03_26, ProtocolVersions.MCP_2025_06_18); } @Override public void setSessionFactory(McpStreamableServerSession.Factory sessionFactory) { requestHandler.setSessionFactory(sessionFactory); } /** * Broadcasts a notification to all connected clients through their SSE connections. * * @param method The method name for the notification * @param params The parameters for the notification * @return A CompletableFuture that completes when the broadcast attempt is finished */ @Override public CompletableFuture<Void> notifyClients(String method, Object params) { return requestHandler.notifyClients(method, params); } /** * Initiates a graceful shutdown of the transport. * * @return A CompletableFuture that completes when all cleanup operations are finished */ @Override public CompletableFuture<Void> closeGracefully() { return requestHandler.closeGracefully(); } @Override public McpStreamableHttpRequestHandler getMcpRequestHandler() { if (this.requestHandler != null) { return this.requestHandler; } throw new UnsupportedOperationException("Streamable transport provider does not support legacy SSE request handler"); } public static Builder builder() { return new Builder(); } /** * Builder for creating instances of {@link NettyStreamableServerTransportProvider}. */ public static class Builder { private ObjectMapper objectMapper; private String mcpEndpoint = DEFAULT_MCP_ENDPOINT; private boolean disallowDelete = false; private McpTransportContextExtractor<FullHttpRequest> contextExtractor = (serverRequest, context) -> context; private Duration keepAliveInterval; public Builder objectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; return this; } public Builder mcpEndpoint(String mcpEndpoint) { Assert.notNull(mcpEndpoint, "MCP endpoint must not be null"); this.mcpEndpoint = mcpEndpoint; return this; } public Builder disallowDelete(boolean disallowDelete) { this.disallowDelete = disallowDelete; return this; } public Builder contextExtractor(McpTransportContextExtractor<FullHttpRequest> contextExtractor) { Assert.notNull(contextExtractor, "Context extractor must not be null"); this.contextExtractor = contextExtractor; return this; } public Builder keepAliveInterval(Duration keepAliveInterval) { this.keepAliveInterval = keepAliveInterval; return this; } public NettyStreamableServerTransportProvider build() { Assert.notNull(this.objectMapper, "ObjectMapper must be set"); Assert.notNull(this.mcpEndpoint, "MCP endpoint must be set"); return new NettyStreamableServerTransportProvider(this.objectMapper, this.mcpEndpoint, this.disallowDelete, this.contextExtractor, this.keepAliveInterval); } } // Placeholder interface for KeepAliveScheduler if not already implemented private interface KeepAliveScheduler { void shutdown(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/transport/NettyStatelessServerTransport.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/transport/NettyStatelessServerTransport.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server.transport; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.protocol.server.McpStatelessServerHandler; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContextExtractor; import com.taobao.arthas.mcp.server.protocol.server.handler.McpStatelessHttpRequestHandler; import com.taobao.arthas.mcp.server.protocol.spec.McpStatelessServerTransport; import com.taobao.arthas.mcp.server.util.Assert; import io.netty.handler.codec.http.FullHttpRequest; import java.util.concurrent.CompletableFuture; /** * Server-side implementation of the Model Context Protocol (MCP) stateless transport * layer using HTTP through Netty. This implementation provides a bridge between * Netty operations and the MCP transport interface for stateless operations. * * @see McpStatelessServerTransport */ public class NettyStatelessServerTransport implements McpStatelessServerTransport { public static final String DEFAULT_MCP_ENDPOINT = "/mcp"; private final McpStatelessHttpRequestHandler requestHandler; /** * Constructs a new NettyStatelessServerTransportProvider instance. * * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization * of messages. * @param mcpEndpoint The endpoint URI where clients should send their JSON-RPC * messages via HTTP. * @param contextExtractor The extractor for transport context from the request. * @throws IllegalArgumentException if any parameter is null */ private NettyStatelessServerTransport(ObjectMapper objectMapper, String mcpEndpoint, McpTransportContextExtractor<FullHttpRequest> contextExtractor) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); Assert.notNull(mcpEndpoint, "MCP endpoint must not be null"); Assert.notNull(contextExtractor, "Context extractor must not be null"); this.requestHandler = new McpStatelessHttpRequestHandler(objectMapper, mcpEndpoint, contextExtractor); } @Override public void setMcpHandler(McpStatelessServerHandler mcpHandler) { requestHandler.setMcpHandler(mcpHandler); } /** * Initiates a graceful shutdown of the transport. * * @return A CompletableFuture that completes when all cleanup operations are finished */ @Override public CompletableFuture<Void> closeGracefully() { return requestHandler.closeGracefully(); } /** * Gets the underlying HTTP request handler. * * @return The McpStatelessHttpRequestHandler instance */ public McpStatelessHttpRequestHandler getMcpRequestHandler() { if (this.requestHandler != null) { return this.requestHandler; } throw new UnsupportedOperationException("Stateless transport provider does not support request handler"); } public static Builder builder() { return new Builder(); } /** * Builder for creating instances of {@link NettyStatelessServerTransport}. */ public static class Builder { private ObjectMapper objectMapper; private String mcpEndpoint = DEFAULT_MCP_ENDPOINT; private McpTransportContextExtractor<FullHttpRequest> contextExtractor = (serverRequest, context) -> context; public Builder objectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; return this; } public Builder mcpEndpoint(String mcpEndpoint) { Assert.notNull(mcpEndpoint, "MCP endpoint must not be null"); this.mcpEndpoint = mcpEndpoint; return this; } public Builder contextExtractor(McpTransportContextExtractor<FullHttpRequest> contextExtractor) { Assert.notNull(contextExtractor, "Context extractor must not be null"); this.contextExtractor = contextExtractor; return this; } public NettyStatelessServerTransport build() { Assert.notNull(this.objectMapper, "ObjectMapper must be set"); Assert.notNull(this.mcpEndpoint, "MCP endpoint must be set"); return new NettyStatelessServerTransport(this.objectMapper, this.mcpEndpoint, this.contextExtractor); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/handler/McpStreamableHttpRequestHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/handler/McpStreamableHttpRequestHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server.handler; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.util.McpAuthExtractor; import com.taobao.arthas.mcp.server.protocol.server.DefaultMcpTransportContext; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContext; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContextExtractor; import com.taobao.arthas.mcp.server.protocol.spec.HttpHeaders; import com.taobao.arthas.mcp.server.protocol.spec.*; import com.taobao.arthas.mcp.server.util.Assert; import com.taobao.arthas.mcp.server.util.KeepAliveScheduler; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import static com.taobao.arthas.mcp.server.util.McpAuthExtractor.MCP_AUTH_SUBJECT_KEY; /** * Server-side implementation of the Model Context Protocol (MCP) streamable transport * layer using HTTP with Server-Sent Events (SSE) through Netty. This implementation * provides a bridge between Netty operations and the MCP transport interface. * * @see McpStreamableServerTransportProvider */ public class McpStreamableHttpRequestHandler { private static final Logger logger = LoggerFactory.getLogger(McpStreamableHttpRequestHandler.class); /** * Event type for JSON-RPC messages sent through the SSE connection. */ public static final String MESSAGE_EVENT_TYPE = "message"; /** * Header name for the response media types accepted by the requester. */ private static final String ACCEPT = "Accept"; public static final String UTF_8 = "UTF-8"; public static final String APPLICATION_JSON = "application/json"; public static final String TEXT_EVENT_STREAM = "text/event-stream"; private static final String FAILED_TO_SEND_ERROR_RESPONSE = "Failed to send error response: {}"; /** * The endpoint URI where clients should send their JSON-RPC messages. Defaults to * "/mcp". */ private final String mcpEndpoint; /** * Flag indicating whether DELETE requests are disallowed on the endpoint. */ private final boolean disallowDelete; private final ObjectMapper objectMapper; private McpStreamableServerSession.Factory sessionFactory; /** * Map of active client sessions, keyed by mcp-session-id. */ private final ConcurrentHashMap<String, McpStreamableServerSession> sessions = new ConcurrentHashMap<>(); private McpTransportContextExtractor<FullHttpRequest> contextExtractor; /** * Flag indicating if the transport is shutting down. */ private final AtomicBoolean isClosing = new AtomicBoolean(false); /** * Keep-alive scheduler for managing session pings. Activated if keepAliveInterval is * set. Disabled by default. */ private KeepAliveScheduler keepAliveScheduler; /** * Constructs a new NettyStreamableServerTransportProvider instance. * * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization * of messages. * @param mcpEndpoint The endpoint URI where clients should send their JSON-RPC * messages via HTTP. * @param disallowDelete Whether to disallow DELETE requests on the endpoint. * @param contextExtractor The extractor for transport context from the request. * @param keepAliveInterval Interval for keep-alive pings (null to disable) * @throws IllegalArgumentException if any parameter is null */ public McpStreamableHttpRequestHandler(ObjectMapper objectMapper, String mcpEndpoint, boolean disallowDelete, McpTransportContextExtractor<FullHttpRequest> contextExtractor, Duration keepAliveInterval) { this.objectMapper = objectMapper; this.mcpEndpoint = mcpEndpoint; this.disallowDelete = disallowDelete; this.contextExtractor = contextExtractor; if (keepAliveInterval != null) { this.keepAliveScheduler = KeepAliveScheduler .builder(() -> this.isClosing.get() ? Collections.emptyList() : this.sessions.values()) .initialDelay(keepAliveInterval) .interval(keepAliveInterval) .build(); this.keepAliveScheduler.start(); logger.debug("Keep-alive scheduler started with interval: {}ms", keepAliveInterval.toMillis()); } } public void setSessionFactory(McpStreamableServerSession.Factory sessionFactory) { this.sessionFactory = sessionFactory; } public CompletableFuture<Void> notifyClients(String method, Object params) { if (this.sessions.isEmpty()) { logger.debug("No active sessions to broadcast message to"); return CompletableFuture.completedFuture(null); } logger.debug("Attempting to broadcast message to {} active sessions", this.sessions.size()); return CompletableFuture.runAsync(() -> { this.sessions.values().parallelStream().forEach(session -> { try { session.sendNotification(method, params); } catch (Exception e) { logger.error("Failed to send message to session {}: {}", session.getId(), e.getMessage()); } }); }); } public CompletableFuture<Void> closeGracefully() { return CompletableFuture.runAsync(() -> { this.isClosing.set(true); logger.debug("Initiating graceful shutdown with {} active sessions", this.sessions.size()); this.sessions.values().parallelStream().forEach(session -> { try { session.closeGracefully(); } catch (Exception e) { logger.error("Failed to close session {}: {}", session.getId(), e.getMessage()); } }); this.sessions.clear(); logger.debug("Graceful shutdown completed"); if (this.keepAliveScheduler != null) { this.keepAliveScheduler.shutdown(); } }); } protected void handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { String uri = request.uri(); if (!uri.endsWith(mcpEndpoint)) { sendError(ctx, HttpResponseStatus.NOT_FOUND, new McpError("Endpoint not found")); return; } if (isClosing.get()) { sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE, new McpError("Server is shutting down")); return; } HttpMethod method = request.method(); if (method == HttpMethod.GET) { handleGetRequest(ctx, request); } else if (method == HttpMethod.POST) { handlePostRequest(ctx, request); } else if (method == HttpMethod.DELETE) { handleDeleteRequest(ctx, request); } else { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, new McpError("Method not allowed")); } } /** * Handles GET requests to establish SSE connections and message replay. */ private void handleGetRequest(ChannelHandlerContext ctx, FullHttpRequest request) { // TODO support last-event-id #3118 // MCP 客户端在 SSE 断线重连时,可能会带上 last-event-id 尝试做消息回放。 // Arthas MCP Server 不支持基于 last-event-id 的恢复逻辑:直接返回 404, // 让客户端触发完整重置并重新走 Initialize 握手申请新的会话。 if (request.headers().get(HttpHeaders.LAST_EVENT_ID) != null) { sendError(ctx, HttpResponseStatus.NOT_FOUND, new McpError("Session not found, please re-initialize")); return; } List<String> badRequestErrors = new ArrayList<>(); String accept = request.headers().get(ACCEPT); if (accept == null || !accept.contains(TEXT_EVENT_STREAM)) { badRequestErrors.add("text/event-stream required in Accept header"); } String sessionId = request.headers().get(HttpHeaders.MCP_SESSION_ID); if (sessionId == null || sessionId.trim().isEmpty()) { badRequestErrors.add("Session ID required in mcp-session-id header"); } if (!badRequestErrors.isEmpty()) { String combinedMessage = String.join("; ", badRequestErrors); sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError(combinedMessage)); return; } McpStreamableServerSession session = this.sessions.get(sessionId); if (session == null) { sendError(ctx, HttpResponseStatus.NOT_FOUND, new McpError("Session not found")); return; } logger.debug("Handling GET request for session: {}", sessionId); McpTransportContext transportContext = this.contextExtractor.extract(request, new DefaultMcpTransportContext()); Object authSubject = McpAuthExtractor.extractAuthSubjectFromContext(ctx); transportContext.put(McpAuthExtractor.MCP_AUTH_SUBJECT_KEY, authSubject); // 从 HTTP header 中提取 User ID String userId = McpAuthExtractor.extractUserIdFromRequest(request); transportContext.put(McpAuthExtractor.MCP_USER_ID_KEY, userId); try { // Set up SSE response headers HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaderNames.CONTENT_TYPE, TEXT_EVENT_STREAM); response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache"); response.headers().set(HttpHeaderNames.CONNECTION, "keep-alive"); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); ctx.writeAndFlush(response); NettyStreamableMcpSessionTransport sessionTransport = new NettyStreamableMcpSessionTransport( sessionId, ctx); // Check if this is a replay request String lastEventId = request.headers().get(HttpHeaders.LAST_EVENT_ID); if (lastEventId != null) { try { // Replay messages from the last event ID try { session.replay(lastEventId).forEach(message -> { try { sessionTransport.sendMessage(message).join(); } catch (Exception e) { logger.error("Failed to replay message: {}", e.getMessage()); ctx.close(); } }); } catch (Exception e) { logger.error("Failed to replay messages: {}", e.getMessage()); ctx.close(); } } catch (Exception e) { logger.error("Failed to replay messages: {}", e.getMessage()); ctx.close(); } } else { // Establish new listening stream McpStreamableServerSession.McpStreamableServerSessionStream listeningStream = session .listeningStream(sessionTransport); // Handle channel closure ctx.channel().closeFuture().addListener(future -> { logger.debug("SSE connection closed for session: {}", sessionId); listeningStream.close(); }); } } catch (Exception e) { logger.error("Failed to handle GET request for session {}: {}", sessionId, e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Internal server error")); } } /** * Handles POST requests for incoming JSON-RPC messages from clients. */ private void handlePostRequest(ChannelHandlerContext ctx, FullHttpRequest request) { List<String> badRequestErrors = new ArrayList<>(); String accept = request.headers().get(ACCEPT); if (accept == null || !accept.contains(TEXT_EVENT_STREAM)) { badRequestErrors.add("text/event-stream required in Accept header"); } if (accept == null || !accept.contains(APPLICATION_JSON)) { badRequestErrors.add("application/json required in Accept header"); } McpTransportContext transportContext = this.contextExtractor.extract(request, new DefaultMcpTransportContext()); Object authSubject = McpAuthExtractor.extractAuthSubjectFromContext(ctx); transportContext.put(MCP_AUTH_SUBJECT_KEY, authSubject); // 从 HTTP header 中提取 User ID String userId = McpAuthExtractor.extractUserIdFromRequest(request); transportContext.put(McpAuthExtractor.MCP_USER_ID_KEY, userId); try { ByteBuf content = request.content(); String body = content.toString(CharsetUtil.UTF_8); McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper, body); // Handle initialization request if (message instanceof McpSchema.JSONRPCRequest) { McpSchema.JSONRPCRequest jsonrpcRequest = (McpSchema.JSONRPCRequest) message; if (jsonrpcRequest.getMethod().equals(McpSchema.METHOD_INITIALIZE)) { if (!badRequestErrors.isEmpty()) { String combinedMessage = String.join("; ", badRequestErrors); sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError(combinedMessage)); return; } McpSchema.InitializeRequest initializeRequest = objectMapper.convertValue(jsonrpcRequest.getParams(), new TypeReference<McpSchema.InitializeRequest>() { }); McpStreamableServerSession.McpStreamableServerSessionInit init = this.sessionFactory .startSession(initializeRequest); this.sessions.put(init.session().getId(), init.session()); try { init.initResult() .thenAccept(initResult -> { try { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(objectMapper.writeValueAsString( new McpSchema.JSONRPCResponse( McpSchema.JSONRPC_VERSION, jsonrpcRequest.getId(), initResult, null)), CharsetUtil.UTF_8) ); response.headers().set(HttpHeaderNames.CONTENT_TYPE, APPLICATION_JSON); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(HttpHeaders.MCP_SESSION_ID, init.session().getId()); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { logger.error("Failed to serialize init response: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to serialize response")); } }) .exceptionally(e -> { logger.error("Failed to initialize session: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to initialize session: " + e.getMessage())); return null; }); return; } catch (Exception e) { logger.error("Failed to initialize session: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to initialize session: " + e.getMessage())); return; } } } String sessionId = request.headers().get(HttpHeaders.MCP_SESSION_ID); if (sessionId == null || sessionId.trim().isEmpty()) { badRequestErrors.add("Session ID required in mcp-session-id header"); } if (!badRequestErrors.isEmpty()) { String combinedMessage = String.join("; ", badRequestErrors); sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError(combinedMessage)); return; } McpStreamableServerSession session = this.sessions.get(sessionId); if (session == null) { sendError(ctx, HttpResponseStatus.NOT_FOUND, new McpError("Session not found: " + sessionId)); return; } if (message instanceof McpSchema.JSONRPCResponse) { McpSchema.JSONRPCResponse jsonrpcResponse = (McpSchema.JSONRPCResponse) message; session.accept(jsonrpcResponse) .thenRun(() -> { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED ); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }) .exceptionally(e -> { logger.error("Failed to accept response: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to accept response")); return null; }); } else if (message instanceof McpSchema.JSONRPCNotification) { McpSchema.JSONRPCNotification jsonrpcNotification = (McpSchema.JSONRPCNotification) message; session.accept(jsonrpcNotification, transportContext) .thenRun(() -> { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED ); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }) .exceptionally(e -> { logger.error("Failed to accept notification: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to accept notification")); return null; }); } else if (message instanceof McpSchema.JSONRPCRequest) { McpSchema.JSONRPCRequest jsonrpcRequest = (McpSchema.JSONRPCRequest) message; // For streaming responses, we need to return SSE HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaderNames.CONTENT_TYPE, TEXT_EVENT_STREAM); response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache"); response.headers().set(HttpHeaderNames.CONNECTION, "keep-alive"); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); ctx.writeAndFlush(response); NettyStreamableMcpSessionTransport sessionTransport = new NettyStreamableMcpSessionTransport( sessionId, ctx); try { session.responseStream(jsonrpcRequest, sessionTransport, transportContext) .whenComplete((result, e) -> { if (e != null) { logger.error("Failed to handle request stream: {}", e.getMessage()); sessionTransport.close(); } }); } catch (Exception e) { logger.error("Failed to handle request stream: {}", e.getMessage()); sessionTransport.close(); } } else { sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Unknown message type")); } } catch (IllegalArgumentException | IOException e) { logger.error("Failed to deserialize message: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError("Invalid message format: " + e.getMessage())); } catch (Exception e) { logger.error("Error handling message: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Error processing message: " + e.getMessage())); } } /** * Handles DELETE requests for session deletion. */ private void handleDeleteRequest(ChannelHandlerContext ctx, FullHttpRequest request) { if (this.disallowDelete) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, new McpError("DELETE method not allowed")); return; } McpTransportContext transportContext = this.contextExtractor.extract(request, new DefaultMcpTransportContext()); String sessionId = request.headers().get(HttpHeaders.MCP_SESSION_ID); if (sessionId == null) { sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError("Session ID required in mcp-session-id header")); return; } McpStreamableServerSession session = this.sessions.get(sessionId); if (session == null) { sendError(ctx, HttpResponseStatus.NOT_FOUND, new McpError("Session not found")); return; } try { session.delete() .thenRun(() -> { this.sessions.remove(sessionId); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK ); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response); }) .exceptionally(e -> { logger.error("Failed to delete session {}: {}", sessionId, e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError(e.getMessage())); return null; }); } catch (Exception e) { logger.error("Failed to delete session {}: {}", sessionId, e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Error deleting session")); } } /** * Sends an error response to the client. */ private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, McpError mcpError) { try { String jsonError = objectMapper.writeValueAsString(mcpError); ByteBuf content = Unpooled.copiedBuffer(jsonError, CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, content ); response.headers().set(HttpHeaderNames.CONTENT_TYPE, APPLICATION_JSON); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { logger.error(FAILED_TO_SEND_ERROR_RESPONSE, e.getMessage()); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR ); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } // Implementation of McpStreamableServerTransport for Netty SSE sessions private class NettyStreamableMcpSessionTransport implements McpStreamableServerTransport { private final String sessionId; private final ChannelHandlerContext ctx; private final AtomicBoolean closed = new AtomicBoolean(false); private final ReentrantLock lock = new ReentrantLock(); NettyStreamableMcpSessionTransport(String sessionId, ChannelHandlerContext ctx) { this.sessionId = sessionId; this.ctx = ctx; logger.debug("Streamable session transport {} initialized", sessionId); } @Override public CompletableFuture<Void> sendMessage(McpSchema.JSONRPCMessage message) { return sendMessage(message, null); } @Override public CompletableFuture<Void> sendMessage(McpSchema.JSONRPCMessage message, String messageId) { return CompletableFuture.runAsync(() -> { if (this.closed.get()) { logger.warn("Attempted to send message to closed session: {}", this.sessionId); return; } // Check if channel is still active if (!this.ctx.channel().isActive()) { logger.warn("Channel for session {} is not active, message will not be sent", this.sessionId); return; } lock.lock(); try { if (this.closed.get()) { logger.debug("Session {} was closed during message send attempt", this.sessionId); return; } String jsonText = objectMapper.writeValueAsString(message); logger.debug("Sending SSE message to session {}: {}", this.sessionId, jsonText.length() > 200 ? jsonText.substring(0, 200) + "..." : jsonText); sendSseEvent(MESSAGE_EVENT_TYPE, jsonText, messageId != null ? messageId : this.sessionId); logger.debug("Message sent to session {} with ID {}", this.sessionId, messageId); } catch (Exception e) { logger.error("Failed to send message to session {}: {}", this.sessionId, e.getMessage()); this.ctx.close(); } finally { lock.unlock(); } }); } @Override public <T> T unmarshalFrom(Object data, TypeReference<T> typeRef) { return objectMapper.convertValue(data, typeRef); } @Override public CompletableFuture<Void> closeGracefully() { return CompletableFuture.runAsync(this::close); } @Override public void close() { lock.lock(); try { if (this.closed.get()) { logger.debug("Session transport {} already closed", this.sessionId); return; } this.closed.set(true); if (ctx.channel().isActive()) { ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); } logger.debug("Successfully closed session transport {}", sessionId); } catch (Exception e) { logger.warn("Failed to close session transport {}: {}", sessionId, e.getMessage()); } finally { lock.unlock(); } } @Override public Channel getChannel() { return ctx.channel(); } private void sendSseEvent(String eventType, String data, String id) { StringBuilder sseData = new StringBuilder(); if (id != null) { sseData.append("id: ").append(id).append("\n"); } sseData.append("event: ").append(eventType).append("\n"); sseData.append("data: ").append(data).append("\n\n"); ByteBuf buffer = Unpooled.copiedBuffer(sseData.toString(), CharsetUtil.UTF_8); this.ctx.writeAndFlush(new DefaultHttpContent(buffer)); logger.debug("SSE event sent - Type: {}, ID: {}, Data length: {}", eventType, id, data != null ? data.length() : 0); } } public static Builder builder() { return new Builder(); } /** * Builder for creating instances of {@link McpStreamableHttpRequestHandler}. */ public static class Builder { private ObjectMapper objectMapper; private String mcpEndpoint = "/mcp"; private boolean disallowDelete = false; private McpTransportContextExtractor<FullHttpRequest> contextExtractor = (serverRequest, context) -> context; private Duration keepAliveInterval; public Builder objectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; return this; } public Builder mcpEndpoint(String mcpEndpoint) { Assert.notNull(mcpEndpoint, "MCP endpoint must not be null"); this.mcpEndpoint = mcpEndpoint; return this; } public Builder disallowDelete(boolean disallowDelete) { this.disallowDelete = disallowDelete; return this; } public Builder contextExtractor(McpTransportContextExtractor<FullHttpRequest> contextExtractor) { Assert.notNull(contextExtractor, "Context extractor must not be null"); this.contextExtractor = contextExtractor; return this; } public Builder keepAliveInterval(Duration keepAliveInterval) { this.keepAliveInterval = keepAliveInterval; return this; } public McpStreamableHttpRequestHandler build() { Assert.notNull(this.objectMapper, "ObjectMapper must be set");
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
true
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/handler/McpHttpRequestHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/handler/McpHttpRequestHandler.java
package com.taobao.arthas.mcp.server.protocol.server.handler; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.protocol.config.McpServerProperties.ServerProtocol; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContextExtractor; import com.taobao.arthas.mcp.server.protocol.spec.McpError; import com.taobao.arthas.mcp.server.util.Assert; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; /** * MCP HTTP请求处理器,分发请求到无状态或流式处理器。 * * @author Yeaury */ public class McpHttpRequestHandler { private static final Logger logger = LoggerFactory.getLogger(McpHttpRequestHandler.class); public static final String APPLICATION_JSON = "application/json"; public static final String TEXT_EVENT_STREAM = "text/event-stream"; private static final String ACCEPT_HEADER = "Accept"; private final String mcpEndpoint; private final ObjectMapper objectMapper; private final McpTransportContextExtractor<FullHttpRequest> contextExtractor; private final AtomicBoolean isClosing = new AtomicBoolean(false); private McpStatelessHttpRequestHandler statelessHandler; private McpStreamableHttpRequestHandler streamableHandler; private ServerProtocol protocol; public McpHttpRequestHandler(String mcpEndpoint, ObjectMapper objectMapper, McpTransportContextExtractor<FullHttpRequest> contextExtractor) { Assert.notNull(mcpEndpoint, "mcpEndpoint must not be null"); Assert.notNull(objectMapper, "objectMapper must not be null"); Assert.notNull(contextExtractor, "contextExtractor must not be null"); this.mcpEndpoint = mcpEndpoint; this.objectMapper = objectMapper; this.contextExtractor = contextExtractor; } public void setProtocol(ServerProtocol protocol) { this.protocol = protocol; } public void setStatelessHandler(McpStatelessHttpRequestHandler statelessHandler) { this.statelessHandler = statelessHandler; } public void setStreamableHandler(McpStreamableHttpRequestHandler streamableHandler) { this.streamableHandler = streamableHandler; } public void handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { String uri = request.uri(); if (!uri.endsWith(mcpEndpoint)) { sendError(ctx, HttpResponseStatus.NOT_FOUND, new McpError("Endpoint not found")); return; } if (isClosing.get()) { sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE, new McpError("Server is shutting down")); return; } logger.debug("Request {} {} -> using {} transport", request.method(), request.uri(), protocol); try { if (protocol == ServerProtocol.STREAMABLE) { if (streamableHandler == null) { sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE, new McpError("Streamable transport handler not available")); return; } streamableHandler.handle(ctx, request); } else { if (statelessHandler == null) { sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE, new McpError("Stateless transport handler not available")); return; } statelessHandler.handle(ctx, request); } } catch (Exception e) { logger.error("Error handling request: {}", e.getMessage(), e); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Error processing request: " + e.getMessage())); } } public CompletableFuture<Void> closeGracefully() { return CompletableFuture.runAsync(() -> { this.isClosing.set(true); logger.debug("Initiating graceful shutdown of MCP handler"); CompletableFuture<Void> statelessClose = CompletableFuture.completedFuture(null); CompletableFuture<Void> streamableClose = CompletableFuture.completedFuture(null); if (statelessHandler != null) { statelessClose = statelessHandler.closeGracefully(); } if (streamableHandler != null) { streamableClose = streamableHandler.closeGracefully(); } CompletableFuture.allOf(statelessClose, streamableClose).join(); logger.debug("Graceful shutdown completed"); }); } private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, McpError mcpError) { try { String jsonError = objectMapper.writeValueAsString(mcpError); ByteBuf content = Unpooled.copiedBuffer(jsonError, CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, content ); response.headers().set(HttpHeaderNames.CONTENT_TYPE, APPLICATION_JSON); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { logger.error("Failed to send error response: {}", e.getMessage()); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR ); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } public String getMcpEndpoint() { return mcpEndpoint; } public static Builder builder() { return new Builder(); } public static class Builder { private String mcpEndpoint = "/mcp"; private ObjectMapper objectMapper; private McpTransportContextExtractor<FullHttpRequest> contextExtractor = (request, context) -> context; private ServerProtocol protocol; public Builder mcpEndpoint(String mcpEndpoint) { Assert.notNull(mcpEndpoint, "MCP endpoint must not be null"); this.mcpEndpoint = mcpEndpoint; return this; } public Builder objectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; return this; } public Builder contextExtractor(McpTransportContextExtractor<FullHttpRequest> contextExtractor) { Assert.notNull(contextExtractor, "Context extractor must not be null"); this.contextExtractor = contextExtractor; return this; } public Builder protocol(ServerProtocol protocol) { this.protocol = protocol; return this; } public McpHttpRequestHandler build() { Assert.notNull(this.objectMapper, "ObjectMapper must be set"); Assert.notNull(this.mcpEndpoint, "MCP endpoint must be set"); if (this.protocol == null) { this.protocol = ServerProtocol.STREAMABLE; } McpHttpRequestHandler handler = new McpHttpRequestHandler(this.mcpEndpoint, this.objectMapper, this.contextExtractor); handler.setProtocol(this.protocol); return handler; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/handler/McpStatelessHttpRequestHandler.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/server/handler/McpStatelessHttpRequestHandler.java
/* * Copyright 2024-2024 the original author or authors. */ package com.taobao.arthas.mcp.server.protocol.server.handler; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.util.McpAuthExtractor; import com.taobao.arthas.mcp.server.protocol.server.DefaultMcpTransportContext; import com.taobao.arthas.mcp.server.protocol.server.McpStatelessServerHandler; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContext; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContextExtractor; import com.taobao.arthas.mcp.server.protocol.spec.McpError; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.util.Assert; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; /** * Server-side HTTP request handler for stateless MCP transport. * This handler processes HTTP requests without maintaining client sessions. * */ public class McpStatelessHttpRequestHandler { private static final Logger logger = LoggerFactory.getLogger(McpStatelessHttpRequestHandler.class); public static final String UTF_8 = "UTF-8"; public static final String APPLICATION_JSON = "application/json"; public static final String TEXT_EVENT_STREAM = "text/event-stream"; public static final String ACCEPT = "Accept"; private static final String FAILED_TO_SEND_ERROR_RESPONSE = "Failed to send error response: {}"; private final ObjectMapper objectMapper; private final String mcpEndpoint; private McpStatelessServerHandler mcpHandler; private final McpTransportContextExtractor<FullHttpRequest> contextExtractor; private final AtomicBoolean isClosing = new AtomicBoolean(false); /** * Constructs a new McpStatelessHttpRequestHandler instance. * * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization * @param mcpEndpoint The endpoint URI where clients should send their JSON-RPC messages * @param contextExtractor The extractor for transport context from the request */ public McpStatelessHttpRequestHandler(ObjectMapper objectMapper, String mcpEndpoint, McpTransportContextExtractor<FullHttpRequest> contextExtractor) { Assert.notNull(objectMapper, "objectMapper must not be null"); Assert.notNull(mcpEndpoint, "mcpEndpoint must not be null"); Assert.notNull(contextExtractor, "contextExtractor must not be null"); this.objectMapper = objectMapper; this.mcpEndpoint = mcpEndpoint; this.contextExtractor = contextExtractor; } public void setMcpHandler(McpStatelessServerHandler mcpHandler) { this.mcpHandler = mcpHandler; } /** * Initiates a graceful shutdown of the handler. * * @return A CompletableFuture that completes when shutdown is initiated */ public CompletableFuture<Void> closeGracefully() { return CompletableFuture.supplyAsync(() -> { this.isClosing.set(true); return null; }); } protected void handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { String uri = request.uri(); if (!uri.endsWith(mcpEndpoint)) { sendError(ctx, HttpResponseStatus.NOT_FOUND, new McpError("Endpoint not found")); return; } if (isClosing.get()) { sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE, new McpError("Server is shutting down")); return; } HttpMethod method = request.method(); if (method == HttpMethod.GET) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, new McpError("GET method not allowed for stateless transport")); } else if (method == HttpMethod.POST) { handlePostRequest(ctx, request); } else { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, new McpError("Only POST method is supported")); } } /** * Handles POST requests for incoming JSON-RPC messages from clients. */ private void handlePostRequest(ChannelHandlerContext ctx, FullHttpRequest request) { McpTransportContext transportContext = this.contextExtractor.extract(request, new DefaultMcpTransportContext()); Object authSubject = McpAuthExtractor.extractAuthSubjectFromContext(ctx); transportContext.put(McpAuthExtractor.MCP_AUTH_SUBJECT_KEY, authSubject); // 从 HTTP header 中提取 User ID String userId = McpAuthExtractor.extractUserIdFromRequest(request); transportContext.put(McpAuthExtractor.MCP_USER_ID_KEY, userId); String accept = request.headers().get(ACCEPT); if (accept == null || !(accept.contains(APPLICATION_JSON) && accept.contains(TEXT_EVENT_STREAM))) { sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError("Both application/json and text/event-stream required in Accept header")); return; } try { ByteBuf content = request.content(); String body = content.toString(CharsetUtil.UTF_8); McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper, body); if (message instanceof McpSchema.JSONRPCRequest) { McpSchema.JSONRPCRequest jsonrpcRequest = (McpSchema.JSONRPCRequest) message; try { this.mcpHandler.handleRequest(transportContext, jsonrpcRequest) .thenAccept(jsonrpcResponse -> { try { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(objectMapper.writeValueAsString(jsonrpcResponse), CharsetUtil.UTF_8) ); response.headers().set(HttpHeaderNames.CONTENT_TYPE, APPLICATION_JSON); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { logger.error("Failed to serialize response: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to serialize response: " + e.getMessage())); } }) .exceptionally(e -> { logger.error("Failed to handle request: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to handle request: " + e.getMessage())); return null; }); } catch (Exception e) { logger.error("Failed to handle request: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to handle request: " + e.getMessage())); } } else if (message instanceof McpSchema.JSONRPCNotification) { McpSchema.JSONRPCNotification jsonrpcNotification = (McpSchema.JSONRPCNotification) message; try { this.mcpHandler.handleNotification(transportContext, jsonrpcNotification) .thenRun(() -> { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED ); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }) .exceptionally(e -> { logger.error("Failed to handle notification: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to handle notification: " + e.getMessage())); return null; }); } catch (Exception e) { logger.error("Failed to handle notification: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Failed to handle notification: " + e.getMessage())); } } else { sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError("The server accepts either requests or notifications")); } } catch (IllegalArgumentException | IOException e) { logger.error("Failed to deserialize message: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.BAD_REQUEST, new McpError("Invalid message format")); } catch (Exception e) { logger.error("Unexpected error handling message: {}", e.getMessage()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, new McpError("Unexpected error: " + e.getMessage())); } } /** * Sends an error response to the client. */ private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, McpError mcpError) { try { String jsonError = objectMapper.writeValueAsString(mcpError); ByteBuf content = Unpooled.copiedBuffer(jsonError, CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, content ); response.headers().set(HttpHeaderNames.CONTENT_TYPE, APPLICATION_JSON); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { logger.error(FAILED_TO_SEND_ERROR_RESPONSE, e.getMessage()); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR ); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/config/McpServerProperties.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/protocol/config/McpServerProperties.java
package com.taobao.arthas.mcp.server.protocol.config; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** * MCP Server Configuration Properties * Used to manage all configuration items for MCP server. * * @author Yeaury */ public class McpServerProperties { /** * Server basic information */ private final String name; private final String version; private final String instructions; /** * Server capability configuration */ private final boolean toolChangeNotification; private final boolean resourceChangeNotification; private final boolean promptChangeNotification; private final boolean resourceSubscribe; private final String mcpEndpoint; /** * Timeout configuration */ private final Duration requestTimeout; private final Duration initializationTimeout; private final ObjectMapper objectMapper; private final ServerProtocol protocol; /** * (Optional) response MIME type per tool name. */ private Map<String, String> toolResponseMimeType = new HashMap<>(); /** * Private constructor, can only be created through Builder */ private McpServerProperties(Builder builder) { this.name = builder.name; this.version = builder.version; this.instructions = builder.instructions; this.toolChangeNotification = builder.toolChangeNotification; this.resourceChangeNotification = builder.resourceChangeNotification; this.promptChangeNotification = builder.promptChangeNotification; this.resourceSubscribe = builder.resourceSubscribe; this.mcpEndpoint = builder.mcpEndpoint; this.requestTimeout = builder.requestTimeout; this.initializationTimeout = builder.initializationTimeout; this.objectMapper = builder.objectMapper; this.protocol = builder.protocol; } /** * Create Builder with default configuration */ public static Builder builder() { return new Builder(); } public enum ServerProtocol { STREAMABLE, STATELESS } /** * Get server name * @return Server name */ public String getName() { return name; } /** * Get server version * @return Server version */ public String getVersion() { return version; } /** * Get server instructions * @return Server instructions */ public String getInstructions() { return instructions; } /** * Get tool change notification * @return Tool change notification */ public boolean isToolChangeNotification() { return toolChangeNotification; } /** * Get resource change notification * @return Resource change notification */ public boolean isResourceChangeNotification() { return resourceChangeNotification; } /** * Get prompt change notification * @return Prompt change notification */ public boolean isPromptChangeNotification() { return promptChangeNotification; } /** * Get resource subscribe * @return Resource subscribe */ public boolean isResourceSubscribe() { return resourceSubscribe; } /** * Get SSE endpoint * @return SSE endpoint */ public String getMcpEndpoint() { return mcpEndpoint; } /** * Get request timeout * @return Request timeout */ public Duration getRequestTimeout() { return requestTimeout; } /** * Get initialization timeout * @return Initialization timeout */ public Duration getInitializationTimeout() { return initializationTimeout; } /** * Get object mapper * @return Object mapper */ public ObjectMapper getObjectMapper() { return objectMapper; } public ServerProtocol getProtocol() { return protocol; } public Map<String, String> getToolResponseMimeType() { return toolResponseMimeType; } public void setToolResponseMimeType(Map<String, String> toolResponseMimeType) { this.toolResponseMimeType = toolResponseMimeType; } /** * Builder class for McpServerProperties */ public static class Builder { // Default values private String name = "mcp-server"; private String version = "1.0.0"; private String instructions; private boolean toolChangeNotification = true; private boolean resourceChangeNotification = false; private boolean promptChangeNotification = false; private boolean resourceSubscribe = false; private String bindAddress = "localhost"; private int port = 8080; private String mcpEndpoint = "/mcp"; private Duration requestTimeout = Duration.ofSeconds(10); private Duration initializationTimeout = Duration.ofSeconds(30); private ObjectMapper objectMapper; private ServerProtocol protocol = ServerProtocol.STREAMABLE; public Builder() { // Private constructor to prevent direct instantiation } public Builder name(String name) { this.name = name; return this; } public Builder version(String version) { this.version = version; return this; } public Builder instructions(String instructions) { this.instructions = instructions; return this; } public Builder toolChangeNotification(boolean toolChangeNotification) { this.toolChangeNotification = toolChangeNotification; return this; } public Builder resourceChangeNotification(boolean resourceChangeNotification) { this.resourceChangeNotification = resourceChangeNotification; return this; } public Builder promptChangeNotification(boolean promptChangeNotification) { this.promptChangeNotification = promptChangeNotification; return this; } public Builder resourceSubscribe(boolean resourceSubscribe) { this.resourceSubscribe = resourceSubscribe; return this; } public Builder mcpEndpoint(String mcpEndpoint) { this.mcpEndpoint = mcpEndpoint; return this; } public Builder requestTimeout(Duration requestTimeout) { this.requestTimeout = requestTimeout; return this; } public Builder initializationTimeout(Duration initializationTimeout) { this.initializationTimeout = initializationTimeout; return this; } public Builder objectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } public Builder protocol(ServerProtocol protocol) { this.protocol = protocol; return this; } /** * Build McpServerProperties instance */ public McpServerProperties build() { return new McpServerProperties(this); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/DefaultToolCallbackProvider.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/DefaultToolCallbackProvider.java
package com.taobao.arthas.mcp.server.tool; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.definition.ToolDefinition; import com.taobao.arthas.mcp.server.tool.definition.ToolDefinitions; import com.taobao.arthas.mcp.server.tool.execution.DefaultToolCallResultConverter; import com.taobao.arthas.mcp.server.tool.execution.ToolCallResultConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Default tool callback provider implementation * <p> * Scan methods with @Tool annotations in the classpath and register them as tool callbacks. * <p> * Users must call {@link #setToolBasePackage(String)} to configure the package to scan before calling * {@link #getToolCallbacks()}. */ public class DefaultToolCallbackProvider implements ToolCallbackProvider { private static final Logger logger = LoggerFactory.getLogger(DefaultToolCallbackProvider.class); private final ToolCallResultConverter toolCallResultConverter; private ToolCallback[] toolCallbacks; private String toolBasePackage; public DefaultToolCallbackProvider() { this.toolCallResultConverter = new DefaultToolCallResultConverter(); } public void setToolBasePackage(String toolBasePackage) { this.toolBasePackage = toolBasePackage; } @Override public ToolCallback[] getToolCallbacks() { if (toolCallbacks == null) { synchronized (this) { if (toolCallbacks == null) { toolCallbacks = scanForToolCallbacks(); } } } return toolCallbacks; } private ToolCallback[] scanForToolCallbacks() { List<ToolCallback> callbacks = new ArrayList<>(); try { logger.info("Starting to scan for tool callbacks in package: {}", toolBasePackage); scanPackageForToolMethods(toolBasePackage, callbacks); logger.info("Found {} tool callbacks", callbacks.size()); } catch (Exception e) { logger.error("Failed to scan for tool callbacks: {}", e.getMessage(), e); } return callbacks.toArray(new ToolCallback[0]); } private void scanPackageForToolMethods(String packageName, List<ToolCallback> callbacks) throws IOException { String packageDirName = packageName.replace('.', '/'); ClassLoader classLoader = DefaultToolCallbackProvider.class.getClassLoader(); logger.info("Using classloader: {} for scanning package: {}", classLoader, packageName); Enumeration<URL> resources = classLoader.getResources(packageDirName); if (!resources.hasMoreElements()) { logger.warn("No resources found for package: {}", packageName); return; } while (resources.hasMoreElements()) { URL resource = resources.nextElement(); String protocol = resource.getProtocol(); logger.info("Found resource: {} with protocol: {}", resource, protocol); if ("file".equals(protocol)) { String filePath = URLDecoder.decode(resource.getFile(), StandardCharsets.UTF_8.name()); logger.info("Scanning directory: {}", filePath); scanDirectory(new File(filePath), packageName, callbacks); } else if ("jar".equals(protocol)) { JarURLConnection jarConn = (JarURLConnection) resource.openConnection(); try (JarFile jarFile = jarConn.getJarFile()) { logger.info("Scanning jar file: {}", jarFile.getName()); scanJarEntries(jarFile, packageDirName, callbacks); } } else { logger.warn("Unsupported protocol: {} for resource: {}", protocol, resource); } } } private void scanDirectory(File directory, String packageName, List<ToolCallback> callbacks) { if (!directory.exists() || !directory.isDirectory()) { logger.warn("Directory does not exist or is not a directory: {}", directory); return; } File[] files = directory.listFiles(); if (files == null) { logger.warn("Failed to list files in directory: {}", directory); return; } for (File file : files) { if (file.isDirectory()) { scanDirectory(file, packageName + "." + file.getName(), callbacks); } else if (file.getName().endsWith(".class")) { String className = packageName + "." + file.getName().substring(0, file.getName().length() - 6); logger.debug("Processing class: {}", className); processClass(className, callbacks); } } } private void scanJarEntries(JarFile jarFile, String packageDirName, List<ToolCallback> callbacks) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.startsWith(packageDirName) && name.endsWith(".class")) { String className = name.substring(0, name.length() - 6).replace('/', '.'); logger.debug("Processing jar entry: {}", className); processClass(className, callbacks); } } } private void processClass(String className, List<ToolCallback> callbacks) { try { Class<?> clazz = Class.forName(className, false, DefaultToolCallbackProvider.class.getClassLoader()); if (clazz.isInterface() || clazz.isEnum() || clazz.isAnnotation()) { return; } for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(Tool.class)) { registerToolMethod(clazz, method, callbacks); } } } catch (Throwable t) { logger.warn("Error loading class {}: {}", className, t.getMessage(), t); } } private void registerToolMethod(Class<?> clazz, Method method, List<ToolCallback> callbacks) { try { ToolDefinition toolDefinition = ToolDefinitions.from(method); Object toolObject = Modifier.isStatic(method.getModifiers()) ? null : clazz.getDeclaredConstructor().newInstance(); ToolCallback callback = DefaultToolCallback.builder() .toolDefinition(toolDefinition) .toolMethod(method) .toolObject(toolObject) .toolCallResultConverter(toolCallResultConverter) .build(); callbacks.add(callback); logger.info("Registered tool: {} from class: {}", toolDefinition.getName(), clazz.getName()); } catch (Exception e) { logger.error("Failed to register tool {}.{}, error: {}", clazz.getName(), method.getName(), e.getMessage(), e); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/ToolCallback.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/ToolCallback.java
package com.taobao.arthas.mcp.server.tool; import com.taobao.arthas.mcp.server.tool.definition.ToolDefinition; /** * Define the basic behavior of the tool */ public interface ToolCallback { ToolDefinition getToolDefinition(); String call(String toolInput); String call(String toolInput, ToolContext toolContext); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/DefaultToolCallback.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/DefaultToolCallback.java
package com.taobao.arthas.mcp.server.tool; import com.fasterxml.jackson.core.type.TypeReference; import com.taobao.arthas.mcp.server.tool.definition.ToolDefinition; import com.taobao.arthas.mcp.server.tool.execution.ToolCallResultConverter; import com.taobao.arthas.mcp.server.tool.execution.ToolExecutionException; import com.taobao.arthas.mcp.server.util.Assert; import com.taobao.arthas.mcp.server.util.JsonParser; import com.taobao.arthas.mcp.server.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Map; import java.util.stream.Stream; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class DefaultToolCallback implements ToolCallback { private static final Logger logger = LoggerFactory.getLogger(DefaultToolCallback.class); private final ToolDefinition toolDefinition; private final Method toolMethod; private final Object toolObject; private final ToolCallResultConverter toolCallResultConverter; public DefaultToolCallback(ToolDefinition toolDefinition, Method toolMethod, Object toolObject, ToolCallResultConverter toolCallResultConverter) { Assert.notNull(toolDefinition, "toolDefinition cannot be null"); Assert.notNull(toolMethod, "toolMethod cannot be null"); Assert.isTrue(Modifier.isStatic(toolMethod.getModifiers()) || toolObject != null, "toolObject cannot be null for non-static methods"); this.toolDefinition = toolDefinition; this.toolMethod = toolMethod; this.toolObject = toolObject; this.toolCallResultConverter = toolCallResultConverter; } @Override public ToolDefinition getToolDefinition() { return this.toolDefinition; } @Override public String call(String toolInput) { return call(toolInput, null); } @Override public String call(String toolInput, ToolContext toolContext) { Assert.hasText(toolInput, "toolInput cannot be null or empty"); logger.debug("Starting execution of tool: {}", this.toolDefinition.getName()); validateToolContextSupport(toolContext); Map<String, Object> toolArguments = extractToolArguments(toolInput); validateRequiredParameters(toolArguments); Object[] methodArguments = buildMethodArguments(toolArguments, toolContext); Object result = callMethod(methodArguments); logger.debug("Successful execution of tool: {}", this.toolDefinition.getName()); Type returnType = this.toolMethod.getGenericReturnType(); return this.toolCallResultConverter.convert(result, returnType); } private void validateToolContextSupport(ToolContext toolContext) { boolean isNonEmptyToolContextProvided = toolContext != null && !Utils.isEmpty(toolContext.getContext()); boolean isToolContextAcceptedByMethod = Arrays.stream(this.toolMethod.getParameterTypes()) .anyMatch(type -> Utils.isAssignable(type, ToolContext.class)); if (isToolContextAcceptedByMethod && !isNonEmptyToolContextProvided) { throw new IllegalArgumentException("ToolContext is required by the method as an argument"); } } /** * validate the required parameters */ private void validateRequiredParameters(Map<String, Object> toolArguments) { Parameter[] parameters = this.toolMethod.getParameters(); for (Parameter parameter : parameters) { if (parameter.getType().isAssignableFrom(ToolContext.class)) { continue; } ToolParam toolParam = parameter.getAnnotation(ToolParam.class); if (toolParam != null && toolParam.required()) { String paramName = parameter.getName(); Object paramValue = toolArguments.get(paramName); // check if the parameter is empty or an empty string if (paramValue == null) { throw new IllegalArgumentException("Required parameter '" + paramName + "' is missing"); } if (paramValue instanceof String && ((String) paramValue).trim().isEmpty()) { throw new IllegalArgumentException("Required parameter '" + paramName + "' cannot be empty"); } } } } private Map<String, Object> extractToolArguments(String toolInput) { return JsonParser.fromJson(toolInput, new TypeReference<Map<String, Object>>() { }); } private Object[] buildMethodArguments(Map<String, Object> toolInputArguments, ToolContext toolContext) { return Stream.of(this.toolMethod.getParameters()).map(parameter -> { if (parameter.getType().isAssignableFrom(ToolContext.class)) { return toolContext; } Object rawArgument = toolInputArguments.get(parameter.getName()); return buildTypedArgument(rawArgument, parameter.getParameterizedType()); }).toArray(); } private Object buildTypedArgument(Object value, Type type) { if (value == null) { return null; } if (type instanceof Class<?>) { return JsonParser.toTypedObject(value, (Class<?>) type); } String json = JsonParser.toJson(value); return JsonParser.fromJson(json, type); } private Object callMethod(Object[] methodArguments) { if (isObjectNotPublic() || isMethodNotPublic()) { this.toolMethod.setAccessible(true); } Object result; try { result = this.toolMethod.invoke(this.toolObject, methodArguments); } catch (IllegalAccessException ex) { throw new IllegalStateException("Could not access method: " + ex.getMessage(), ex); } catch (InvocationTargetException ex) { throw new ToolExecutionException(this.toolDefinition, ex.getCause()); } return result; } private boolean isObjectNotPublic() { return this.toolObject != null && !Modifier.isPublic(this.toolObject.getClass().getModifiers()); } private boolean isMethodNotPublic() { return !Modifier.isPublic(this.toolMethod.getModifiers()); } @Override public String toString() { return "MethodToolCallback{" + "toolDefinition=" + this.toolDefinition + '}'; } public static Builder builder() { return new Builder(); } public static final class Builder { private ToolDefinition toolDefinition; private Method toolMethod; private Object toolObject; private ToolCallResultConverter toolCallResultConverter; private Builder() { } public Builder toolDefinition(ToolDefinition toolDefinition) { this.toolDefinition = toolDefinition; return this; } public Builder toolMethod(Method toolMethod) { this.toolMethod = toolMethod; return this; } public Builder toolObject(Object toolObject) { this.toolObject = toolObject; return this; } public Builder toolCallResultConverter(ToolCallResultConverter toolCallResultConverter) { this.toolCallResultConverter = toolCallResultConverter; return this; } public DefaultToolCallback build() { return new DefaultToolCallback(this.toolDefinition, this.toolMethod, this.toolObject, this.toolCallResultConverter); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/ToolContext.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/ToolContext.java
package com.taobao.arthas.mcp.server.tool; import java.util.Collections; import java.util.Map; public final class ToolContext { private final Map<String, Object> context; public ToolContext(Map<String, Object> context) { this.context = Collections.unmodifiableMap(context); } public Map<String, Object> getContext() { return this.context; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/ToolCallbackProvider.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/ToolCallbackProvider.java
package com.taobao.arthas.mcp.server.tool; public interface ToolCallbackProvider { ToolCallback[] getToolCallbacks(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/util/JsonSchemaGenerator.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/util/JsonSchemaGenerator.java
package com.taobao.arthas.mcp.server.tool.util; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; import com.taobao.arthas.mcp.server.util.Assert; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Simple JsonSchema generator * JsonSchema definitions for generating method parameters */ public final class JsonSchemaGenerator { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final boolean PROPERTY_REQUIRED_BY_DEFAULT = true; private JsonSchemaGenerator() { } /** * Generate JsonSchema for method parameters * @param method target method * @return JsonSchema object */ public static McpSchema.JsonSchema generateForMethodInput(Method method) { Assert.notNull(method, "method cannot be null"); ObjectNode schema = OBJECT_MAPPER.createObjectNode(); schema.put("type", "object"); ObjectNode properties = schema.putObject("properties"); List<String> required = new ArrayList<>(); Parameter[] parameters = method.getParameters(); for (Parameter parameter : parameters) { ToolParam toolParam = parameter.getAnnotation(ToolParam.class); if (toolParam == null) { continue; } String paramName = getParameterName(parameter); Class<?> paramType = parameter.getType(); boolean isRequired = isParameterRequired(parameter); if (isRequired) { required.add(paramName); } ObjectNode paramProperties = generateParameterProperties(paramType); String description = getParameterDescription(parameter); if (description != null) { paramProperties.put("description", description); } properties.set(paramName, paramProperties); } if (!required.isEmpty()) { ArrayNode requiredArray = schema.putArray("required"); for (String req : required) { requiredArray.add(req); } } schema.put("additionalProperties", false); return new McpSchema.JsonSchema("object", convertToMap(properties), required, false); } private static String getParameterName(Parameter parameter) { JsonProperty jsonProperty = parameter.getAnnotation(JsonProperty.class); if (jsonProperty != null && !jsonProperty.value().isEmpty()) { return jsonProperty.value(); } return parameter.getName(); } private static ObjectNode generateParameterProperties(Class<?> paramType) { ObjectNode properties = OBJECT_MAPPER.createObjectNode(); if (paramType == String.class) { properties.put("type", "string"); } else if (paramType == int.class || paramType == Integer.class || paramType == long.class || paramType == Long.class) { properties.put("type", "integer"); } else if (paramType == double.class || paramType == Double.class || paramType == float.class || paramType == Float.class) { properties.put("type", "number"); } else if (paramType == boolean.class || paramType == Boolean.class) { properties.put("type", "boolean"); } else if (paramType.isArray()) { properties.put("type", "array"); ObjectNode items = properties.putObject("items"); Class<?> componentType = paramType.getComponentType(); if (componentType == String.class) { items.put("type", "string"); } else if (componentType == int.class || componentType == Integer.class || componentType == long.class || componentType == Long.class) { items.put("type", "integer"); } else if (componentType == double.class || componentType == Double.class || componentType == float.class || componentType == Float.class) { items.put("type", "number"); } else if (componentType == boolean.class || componentType == Boolean.class) { items.put("type", "boolean"); } else { items.put("type", "object"); } } else { properties.put("type", "object"); } return properties; } private static boolean isParameterRequired(Parameter parameter) { ToolParam toolParam = parameter.getAnnotation(ToolParam.class); if (toolParam != null) { return toolParam.required(); } JsonProperty jsonProperty = parameter.getAnnotation(JsonProperty.class); if (jsonProperty != null) { return jsonProperty.required(); } return PROPERTY_REQUIRED_BY_DEFAULT; } private static String getParameterDescription(Parameter parameter) { ToolParam toolParam = parameter.getAnnotation(ToolParam.class); if (toolParam != null && toolParam.description() != null && !toolParam.description().isEmpty()) { return toolParam.description(); } JsonPropertyDescription jsonPropertyDescription = parameter.getAnnotation(JsonPropertyDescription.class); if (jsonPropertyDescription != null && !jsonPropertyDescription.value().isEmpty()) { return jsonPropertyDescription.value(); } return null; } private static Map<String, Object> convertToMap(ObjectNode node) { Map<String, Object> result = new HashMap<>(); node.fields().forEachRemaining(entry -> { JsonNode value = entry.getValue(); if (value.isObject()) { result.put(entry.getKey(), convertToMap((ObjectNode) value)); } else if (value.isArray()) { List<Object> array = new ArrayList<>(); value.elements().forEachRemaining(element -> { if (element.isObject()) { array.add(convertToMap((ObjectNode) element)); } else { array.add(element.asText()); } }); result.put(entry.getKey(), array); } else { result.put(entry.getKey(), value.asText()); } }); 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-server/src/main/java/com/taobao/arthas/mcp/server/tool/definition/ToolDefinitions.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/definition/ToolDefinitions.java
package com.taobao.arthas.mcp.server.tool.definition; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.util.JsonSchemaGenerator; import com.taobao.arthas.mcp.server.util.Assert; import java.lang.reflect.Method; public class ToolDefinitions { public static ToolDefinition.Builder builder(Method method) { Assert.notNull(method, "method cannot be null"); return ToolDefinition.builder() .name(getToolName(method)) .description(getToolDescription(method)) .inputSchema(JsonSchemaGenerator.generateForMethodInput(method)) .streamable(isStreamable(method)); } public static ToolDefinition from(Method method) { return builder(method).build(); } public static String getToolName(Method method) { Assert.notNull(method, "method cannot be null"); Tool tool = method.getAnnotation(Tool.class); if (tool == null) { return method.getName(); } return tool.name() != null ? tool.name() : method.getName(); } public static String getToolDescription(Method method) { Assert.notNull(method, "method cannot be null"); Tool tool = method.getAnnotation(Tool.class); if (tool == null) { return method.getName(); } return tool.description() != null ? tool.description() : method.getName(); } public static boolean isStreamable(Method method) { Assert.notNull(method, "method cannot be null"); Tool tool = method.getAnnotation(Tool.class); if (tool == null) { return false; } return tool.streamable(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/definition/ToolDefinition.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/definition/ToolDefinition.java
package com.taobao.arthas.mcp.server.tool.definition; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; public class ToolDefinition { private String name; private String description; private McpSchema.JsonSchema inputSchema; private boolean streamable; public ToolDefinition(String name, String description, McpSchema.JsonSchema inputSchema, boolean streamable) { this.name = name; this.description = description; this.inputSchema = inputSchema; this.streamable = streamable; } public String getName() { return name; } public String getDescription() { return description; } public McpSchema.JsonSchema getInputSchema() { return inputSchema; } public boolean isStreamable() { return streamable; } public static Builder builder() { return new Builder(); } public static final class Builder { private String name; private String description; private McpSchema.JsonSchema inputSchema; private boolean streamable; private Builder() { } public Builder name(String name) { this.name = name; return this; } public Builder description(String description) { this.description = description; return this; } public Builder inputSchema(McpSchema.JsonSchema inputSchema) { this.inputSchema = inputSchema; return this; } public Builder streamable(boolean streamable) { this.streamable = streamable; return this; } public ToolDefinition build() { return new ToolDefinition(this.name, this.description, this.inputSchema, this.streamable); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/DefaultToolCallResultConverter.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/DefaultToolCallResultConverter.java
package com.taobao.arthas.mcp.server.tool.execution; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.util.JsonParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.imageio.ImageIO; import java.awt.image.RenderedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Type; import java.util.Base64; import java.util.HashMap; import java.util.Map; /** * A default implementation of {@link ToolCallResultConverter}. */ public final class DefaultToolCallResultConverter implements ToolCallResultConverter { private static final Logger logger = LoggerFactory.getLogger(DefaultToolCallResultConverter.class); private static final ObjectMapper OBJECT_MAPPER = JsonParser.getObjectMapper(); @Override public String convert(Object result, Type returnType) { if (returnType == Void.TYPE) { logger.debug("The tool has no return type. Converting to conventional response."); return JsonParser.toJson("Done"); } if (result instanceof RenderedImage) { final ByteArrayOutputStream buf = new ByteArrayOutputStream(1024 * 4); try { ImageIO.write((RenderedImage) result, "PNG", buf); } catch (IOException e) { return "Failed to convert tool result to a base64 image: " + e.getMessage(); } final String imgB64 = Base64.getEncoder().encodeToString(buf.toByteArray()); Map<String, String> imageData = new HashMap<>(); imageData.put("mimeType", "image/png"); imageData.put("data", imgB64); return JsonParser.toJson(imageData); } else if (result instanceof String) { String stringResult = (String) result; if (isValidJson(stringResult)) { logger.debug("Result is already valid JSON, returning as is."); return stringResult; } else { logger.debug("Converting string result to JSON."); return JsonParser.toJson(result); } } else { logger.debug("Converting tool result to JSON."); return JsonParser.toJson(result); } } private boolean isValidJson(String jsonString) { if (jsonString == null || jsonString.trim().isEmpty()) { return false; } try { OBJECT_MAPPER.readTree(jsonString); return true; } catch (JsonProcessingException e) { return false; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/DefaultToolExecutionExceptionProcessor.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/DefaultToolExecutionExceptionProcessor.java
package com.taobao.arthas.mcp.server.tool.execution; import com.taobao.arthas.mcp.server.util.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation of {@link ToolExecutionExceptionProcessor}. */ public class DefaultToolExecutionExceptionProcessor implements ToolExecutionExceptionProcessor { private final static Logger logger = LoggerFactory.getLogger(DefaultToolExecutionExceptionProcessor.class); private static final boolean DEFAULT_ALWAYS_THROW = false; private final boolean alwaysThrow; public DefaultToolExecutionExceptionProcessor(boolean alwaysThrow) { this.alwaysThrow = alwaysThrow; } @Override public String process(ToolExecutionException exception) { Assert.notNull(exception, "exception cannot be null"); if (this.alwaysThrow) { throw exception; } logger.debug("Exception thrown by tool: {}. Message: {}", exception.getToolDefinition().getName(), exception.getMessage()); return exception.getMessage(); } public static Builder builder() { return new Builder(); } public static class Builder { private boolean alwaysThrow = DEFAULT_ALWAYS_THROW; public Builder alwaysThrow(boolean alwaysThrow) { this.alwaysThrow = alwaysThrow; return this; } public DefaultToolExecutionExceptionProcessor build() { return new DefaultToolExecutionExceptionProcessor(this.alwaysThrow); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/ToolExecutionException.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/ToolExecutionException.java
package com.taobao.arthas.mcp.server.tool.execution; import com.taobao.arthas.mcp.server.tool.definition.ToolDefinition; /** * An exception thrown when a tool execution fails. */ public class ToolExecutionException extends RuntimeException { private final ToolDefinition toolDefinition; public ToolExecutionException(ToolDefinition toolDefinition, Throwable cause) { super(cause.getMessage(), cause); this.toolDefinition = toolDefinition; } public ToolDefinition getToolDefinition() { return this.toolDefinition; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/ToolExecutionExceptionProcessor.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/ToolExecutionExceptionProcessor.java
package com.taobao.arthas.mcp.server.tool.execution; /** * A functional interface to process a {@link ToolExecutionException} by either converting * the error message to a String that can be sent back to the AI model or throwing an * exception to be handled by the caller. */ @FunctionalInterface public interface ToolExecutionExceptionProcessor { /** * Convert an exception thrown by a tool to a String that can be sent back to the AI * model or throw an exception to be handled by the caller. */ String process(ToolExecutionException exception); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/ToolCallResultConverter.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/execution/ToolCallResultConverter.java
package com.taobao.arthas.mcp.server.tool.execution; import java.lang.reflect.Type; /** * A functional interface to convert tool call results to a String that can be sent back * to the AI model. */ @FunctionalInterface public interface ToolCallResultConverter { /** * Given an Object returned by a tool, convert it to a String compatible with the * given class type. */ String convert(Object result, Type returnType); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/annotation/ToolParam.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/annotation/ToolParam.java
package com.taobao.arthas.mcp.server.tool.annotation; import java.lang.annotation.*; @Target({ ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ToolParam { /** * Whether the tool argument is required. */ boolean required() default true; /** * The description of the tool argument. */ String description() default ""; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/annotation/Tool.java
arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/annotation/Tool.java
package com.taobao.arthas.mcp.server.tool.annotation; import java.lang.annotation.*; @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Tool { String name() default ""; String description() default ""; boolean streamable() default false; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/test/java/com/alibaba/arthas/tunnel/server/URITest.java
tunnel-server/src/test/java/com/alibaba/arthas/tunnel/server/URITest.java
package com.alibaba.arthas.tunnel.server; import java.net.URI; import java.net.URISyntaxException; import org.assertj.core.api.Assertions; import org.junit.Test; import org.springframework.web.util.UriComponentsBuilder; import com.alibaba.arthas.tunnel.common.MethodConstants; import com.alibaba.arthas.tunnel.common.URIConstans; /** * * @author hengyunabc 2020-10-22 * */ public class URITest { @Test public void test() throws URISyntaxException { String id = "xxx"; URI responseUri = new URI("response", null, "/", "method=" + MethodConstants.AGENT_REGISTER + "&id=" + id, null); String string = responseUri.toString(); String uriString = UriComponentsBuilder.newInstance().scheme("response").path("/") .queryParam("method", MethodConstants.AGENT_REGISTER).queryParam("id", id).build().toUriString(); Assertions.assertThat(string).isEqualTo(uriString).isEqualTo("response:/?method=agentRegister&id=xxx"); } @Test public void testEncode() throws URISyntaxException { String id = "xxx/%ff#ff"; URI responseUri = new URI("response", null, "/", "method=" + MethodConstants.AGENT_REGISTER + "&id=" + id, null); String string = responseUri.toString(); String uriString = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/") .queryParam(URIConstans.METHOD, MethodConstants.AGENT_REGISTER).queryParam(URIConstans.ID, id).build() .encode().toUriString(); Assertions.assertThat(string).isEqualTo(uriString) .isEqualTo("response:/?method=agentRegister&id=xxx/%25ff%23ff"); } @Test public void test3() throws URISyntaxException { String agentId = "ffff"; String clientConnectionId = "ccccc"; URI uri = new URI("response", null, "/", "method=" + MethodConstants.START_TUNNEL + "&id=" + agentId + "&clientConnectionId=" + clientConnectionId, null); String string = uri.toString(); String uriString = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/") .queryParam(URIConstans.METHOD, MethodConstants.START_TUNNEL).queryParam(URIConstans.ID, agentId) .queryParam(URIConstans.CLIENT_CONNECTION_ID, clientConnectionId).build().toUriString(); System.err.println(string); Assertions.assertThat(string).isEqualTo(uriString) .isEqualTo("response:/?method=startTunnel&id=ffff&clientConnectionId=ccccc"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/test/java/com/alibaba/arthas/tunnel/server/app/ArthasTunnelApplicationTest.java
tunnel-server/src/test/java/com/alibaba/arthas/tunnel/server/app/ArthasTunnelApplicationTest.java
package com.alibaba.arthas.tunnel.server.app; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * * @author hengyunabc 2021-07-12 * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { ArthasTunnelApplication.class }) public class ArthasTunnelApplicationTest { @Test public void contextLoads() { System.out.println("hello"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/test/java/com/alibaba/arthas/tunnel/server/utils/HttpUtilsTest.java
tunnel-server/src/test/java/com/alibaba/arthas/tunnel/server/utils/HttpUtilsTest.java
package com.alibaba.arthas.tunnel.server.utils; import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.Mockito; import io.netty.handler.codec.http.HttpHeaders; /** * * @author hengyunabc 2021-02-26 * */ public class HttpUtilsTest { @Test public void test1() { HttpHeaders headers = Mockito.mock(HttpHeaders.class); Mockito.when(headers.get("X-Forwarded-For")).thenReturn("30.25.233.172, 11.162.179.161"); String ip = HttpUtils.findClientIP(headers); Assertions.assertThat(ip).isEqualTo("30.25.233.172"); } @Test public void test2() { HttpHeaders headers = Mockito.mock(HttpHeaders.class); Mockito.when(headers.get("X-Forwarded-For")).thenReturn("30.25.233.172"); String ip = HttpUtils.findClientIP(headers); Assertions.assertThat(ip).isEqualTo("30.25.233.172"); } @Test public void test3() { HttpHeaders headers = Mockito.mock(HttpHeaders.class); Mockito.when(headers.get("X-Forwarded-For")).thenReturn(null); String ip = HttpUtils.findClientIP(headers); Assertions.assertThat(ip).isEqualTo(null); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/TunnelSocketServerInitializer.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/TunnelSocketServerInitializer.java
package com.alibaba.arthas.tunnel.server; import com.taobao.arthas.common.ArthasConstants; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.timeout.IdleStateHandler; /** * * @author hengyunabc 2019-08-27 * */ public class TunnelSocketServerInitializer extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; private TunnelServer tunnelServer; public TunnelSocketServerInitializer(TunnelServer tunnelServer, SslContext sslCtx) { this.sslCtx = sslCtx; this.tunnelServer = tunnelServer; } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslCtx != null) { pipeline.addLast(sslCtx.newHandler(ch.alloc())); } pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH)); pipeline.addLast(new WebSocketServerCompressionHandler()); pipeline.addLast(new WebSocketServerProtocolHandler(tunnelServer.getPath(), null, true, ArthasConstants.MAX_HTTP_CONTENT_LENGTH, false, true, 10000L)); pipeline.addLast(new IdleStateHandler(0, 0, ArthasConstants.WEBSOCKET_IDLE_SECONDS)); pipeline.addLast(new TunnelSocketFrameHandler(tunnelServer)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/RelayHandler.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/RelayHandler.java
package com.alibaba.arthas.tunnel.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; 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()) { relayChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.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-server/src/main/java/com/alibaba/arthas/tunnel/server/TunnelServer.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/TunnelServer.java
package com.alibaba.arthas.tunnel.server; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.arthas.tunnel.common.SimpleHttpResponse; import com.alibaba.arthas.tunnel.server.cluster.TunnelClusterStore; import com.taobao.arthas.common.ArthasConstants; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Promise; /** * * @author hengyunabc 2019-08-09 * */ public class TunnelServer { private final static Logger logger = LoggerFactory.getLogger(TunnelServer.class); private boolean ssl; private String host; private int port; private String path = ArthasConstants.DEFAULT_WEBSOCKET_PATH; private Map<String, AgentInfo> agentInfoMap = new ConcurrentHashMap<>(); private Map<String, ClientConnectionInfo> clientConnectionInfoMap = new ConcurrentHashMap<>(); /** * 记录 proxy request */ private Map<String, Promise<SimpleHttpResponse>> proxyRequestPromiseMap = new ConcurrentHashMap<>(); private EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("arthas-TunnelServer-boss", true)); private EventLoopGroup workerGroup = new NioEventLoopGroup(new DefaultThreadFactory("arthas-TunnelServer-worker", true)); private Channel channel; /** * 在集群部署时,保存agentId和host关系 */ private TunnelClusterStore tunnelClusterStore; /** * 集群部署时外部连接的host */ private String clientConnectHost; public void start() throws Exception { // Configure SSL. final SslContext sslCtx; if (ssl) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new TunnelSocketServerInitializer(this, sslCtx)); if (StringUtils.isBlank(host)) { channel = b.bind(port).sync().channel(); } else { channel = b.bind(host, port).sync().channel(); } logger.info("Tunnel server listen at {}:{}", host, port); workerGroup.scheduleWithFixedDelay(new Runnable() { @Override public void run() { agentInfoMap.entrySet().removeIf(e -> !e.getValue().getChannelHandlerContext().channel().isActive()); clientConnectionInfoMap.entrySet() .removeIf(e -> !e.getValue().getChannelHandlerContext().channel().isActive()); // 更新集群key信息 if (tunnelClusterStore != null && clientConnectHost != null) { try { for (Entry<String, AgentInfo> entry : agentInfoMap.entrySet()) { tunnelClusterStore.addAgent(entry.getKey(), new AgentClusterInfo(entry.getValue(), clientConnectHost, port), 60 * 60, TimeUnit.SECONDS); } } catch (Throwable t) { logger.error("update tunnel info error", t); } } } }, 60, 60, TimeUnit.SECONDS); } public void stop() { if (channel != null) { channel.close(); } bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } public Optional<AgentInfo> findAgent(String id) { return Optional.ofNullable(this.agentInfoMap.get(id)); } public void addAgent(String id, AgentInfo agentInfo) { agentInfoMap.put(id, agentInfo); if (this.tunnelClusterStore != null) { this.tunnelClusterStore.addAgent(id, new AgentClusterInfo(agentInfo, clientConnectHost, port), 60 * 60, TimeUnit.SECONDS); } } public AgentInfo removeAgent(String id) { AgentInfo agentInfo = agentInfoMap.remove(id); if (this.tunnelClusterStore != null) { this.tunnelClusterStore.removeAgent(id); } return agentInfo; } public Optional<ClientConnectionInfo> findClientConnection(String id) { return Optional.ofNullable(this.clientConnectionInfoMap.get(id)); } public void addClientConnectionInfo(String id, ClientConnectionInfo clientConnectionInfo) { clientConnectionInfoMap.put(id, clientConnectionInfo); } public ClientConnectionInfo removeClientConnectionInfo(String id) { return this.clientConnectionInfoMap.remove(id); } public void addProxyRequestPromise(String requestId, Promise<SimpleHttpResponse> promise) { this.proxyRequestPromiseMap.put(requestId, promise); // 把过期的proxy 请求删掉 workerGroup.schedule(new Runnable() { @Override public void run() { removeProxyRequestPromise(requestId); } }, 60, TimeUnit.SECONDS); } public void removeProxyRequestPromise(String requestId) { this.proxyRequestPromiseMap.remove(requestId); } public Promise<SimpleHttpResponse> findProxyRequestPromise(String requestId) { return this.proxyRequestPromiseMap.get(requestId); } public boolean isSsl() { return ssl; } public void setSsl(boolean ssl) { this.ssl = ssl; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public Map<String, AgentInfo> getAgentInfoMap() { return agentInfoMap; } public void setAgentInfoMap(Map<String, AgentInfo> agentInfoMap) { this.agentInfoMap = agentInfoMap; } public Map<String, ClientConnectionInfo> getClientConnectionInfoMap() { return clientConnectionInfoMap; } public void setClientConnectionInfoMap(Map<String, ClientConnectionInfo> clientConnectionInfoMap) { this.clientConnectionInfoMap = clientConnectionInfoMap; } public TunnelClusterStore getTunnelClusterStore() { return tunnelClusterStore; } public void setTunnelClusterStore(TunnelClusterStore tunnelClusterStore) { this.tunnelClusterStore = tunnelClusterStore; } public String getClientConnectHost() { return clientConnectHost; } public void setClientConnectHost(String clientConnectHost) { this.clientConnectHost = clientConnectHost; } public String getPath() { return path; } public void setPath(String path) { path = path.trim(); if (!path.startsWith("/")) { logger.warn("tunnel server path should start with / ! path: {}, try to auto add / .", path); path = "/" + path; } this.path = path; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/ClientConnectionInfo.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/ClientConnectionInfo.java
package com.alibaba.arthas.tunnel.server; import com.fasterxml.jackson.annotation.JsonIgnore; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.Promise; /** * * @author hengyunabc 2019-08-27 * */ public class ClientConnectionInfo { @JsonIgnore private ChannelHandlerContext channelHandlerContext; private String host; private int port; /** * wait for agent connect */ @JsonIgnore private Promise<Channel> promise; public ChannelHandlerContext getChannelHandlerContext() { return channelHandlerContext; } public void setChannelHandlerContext(ChannelHandlerContext channelHandlerContext) { this.channelHandlerContext = channelHandlerContext; } public Promise<Channel> getPromise() { return promise; } public void setPromise(Promise<Channel> promise) { this.promise = promise; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/ChannelUtils.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/ChannelUtils.java
package com.alibaba.arthas.tunnel.server; 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-server/src/main/java/com/alibaba/arthas/tunnel/server/TunnelSocketFrameHandler.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/TunnelSocketFrameHandler.java
package com.alibaba.arthas.tunnel.server; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.RandomStringUtils; import org.apache.tomcat.util.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import com.alibaba.arthas.tunnel.common.MethodConstants; import com.alibaba.arthas.tunnel.common.SimpleHttpResponse; import com.alibaba.arthas.tunnel.common.URIConstans; import com.alibaba.arthas.tunnel.server.utils.HttpUtils; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; 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.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; /** * * @author hengyunabc 2019-08-27 * */ public class TunnelSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> { private final static Logger logger = LoggerFactory.getLogger(TunnelSocketFrameHandler.class); private TunnelServer tunnelServer; public TunnelSocketFrameHandler(TunnelServer tunnelServer) { this.tunnelServer = tunnelServer; } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof HandshakeComplete) { HandshakeComplete handshake = (HandshakeComplete) evt; // http request uri String uri = handshake.requestUri(); logger.info("websocket handshake complete, uri: {}", uri); MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(uri).build().getQueryParams(); String method = parameters.getFirst(URIConstans.METHOD); if (MethodConstants.CONNECT_ARTHAS.equals(method)) { // form browser connectArthas(ctx, parameters); } else if (MethodConstants.AGENT_REGISTER.equals(method)) { // form arthas agent, register agentRegister(ctx, handshake, uri); } if (MethodConstants.OPEN_TUNNEL.equals(method)) { // from arthas agent open tunnel String clientConnectionId = parameters.getFirst(URIConstans.CLIENT_CONNECTION_ID); openTunnel(ctx, clientConnectionId); } } else if (evt instanceof IdleStateEvent) { ctx.writeAndFlush(new PingWebSocketFrame()); } else { ctx.fireUserEventTriggered(evt); } } @Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { // 只有 arthas agent register建立的 channel 才可能有数据到这里 if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; String text = textFrame.text(); MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(text).build() .getQueryParams(); String method = parameters.getFirst(URIConstans.METHOD); /** * <pre> * 1. 之前http proxy请求已发送到 tunnel cleint,这里接收到 tunnel client的结果,并解析出SimpleHttpResponse * 2. 需要据 URIConstans.PROXY_REQUEST_ID 取出当时的 Promise,再设置SimpleHttpResponse进去 * </pre> */ if (MethodConstants.HTTP_PROXY.equals(method)) { final String requestIdRaw = parameters.getFirst(URIConstans.PROXY_REQUEST_ID); final String requestId; if (requestIdRaw != null) { requestId = URLDecoder.decode(requestIdRaw, "utf-8"); } else { requestId = null; } if (requestId == null) { logger.error("error, need {}, text: {}", URIConstans.PROXY_REQUEST_ID, text); return; } logger.info("received http proxy response, requestId: {}", requestId); Promise<SimpleHttpResponse> promise = tunnelServer.findProxyRequestPromise(requestId); final String dataRaw = parameters.getFirst(URIConstans.PROXY_RESPONSE_DATA); final String data; if (dataRaw != null) { data = URLDecoder.decode(dataRaw, "utf-8"); byte[] bytes = Base64.decodeBase64(data); SimpleHttpResponse simpleHttpResponse = SimpleHttpResponse.fromBytes(bytes); promise.setSuccess(simpleHttpResponse); } else { data = null; promise.setFailure(new Exception(URIConstans.PROXY_RESPONSE_DATA + " is null! reuqestId: " + requestId)); } } } } private void connectArthas(ChannelHandlerContext tunnelSocketCtx, MultiValueMap<String, String> parameters) throws URISyntaxException { List<String> agentId = parameters.getOrDefault("id", Collections.emptyList()); if (agentId.isEmpty()) { logger.error("arthas agent id can not be null, parameters: {}", parameters); throw new IllegalArgumentException("arthas agent id can not be null"); } logger.info("try to connect to arthas agent, id: " + agentId.get(0)); Optional<AgentInfo> findAgent = tunnelServer.findAgent(agentId.get(0)); if (findAgent.isPresent()) { ChannelHandlerContext agentCtx = findAgent.get().getChannelHandlerContext(); String clientConnectionId = RandomStringUtils.random(20, true, true).toUpperCase(); logger.info("random clientConnectionId: " + clientConnectionId); // URI uri = new URI("response", null, "/", // "method=" + MethodConstants.START_TUNNEL + "&id=" + agentId.get(0) + "&clientConnectionId=" + clientConnectionId, null); URI uri = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/") .queryParam(URIConstans.METHOD, MethodConstants.START_TUNNEL).queryParam(URIConstans.ID, agentId) .queryParam(URIConstans.CLIENT_CONNECTION_ID, clientConnectionId).build().toUri(); logger.info("startTunnel response: " + uri); ClientConnectionInfo clientConnectionInfo = new ClientConnectionInfo(); SocketAddress remoteAddress = tunnelSocketCtx.channel().remoteAddress(); if (remoteAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress; clientConnectionInfo.setHost(inetSocketAddress.getHostString()); clientConnectionInfo.setPort(inetSocketAddress.getPort()); } clientConnectionInfo.setChannelHandlerContext(tunnelSocketCtx); // when the agent open tunnel success, will set result into the promise Promise<Channel> promise = GlobalEventExecutor.INSTANCE.newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { tunnelSocketCtx.pipeline().remove(TunnelSocketFrameHandler.this); // outboundChannel is form arthas agent outboundChannel.pipeline().removeLast(); outboundChannel.pipeline().addLast(new RelayHandler(tunnelSocketCtx.channel())); tunnelSocketCtx.pipeline().addLast(new RelayHandler(outboundChannel)); } else { logger.error("wait for agent connect error. agentId: {}, clientConnectionId: {}", agentId, clientConnectionId); ChannelUtils.closeOnFlush(agentCtx.channel()); } } }); clientConnectionInfo.setPromise(promise); this.tunnelServer.addClientConnectionInfo(clientConnectionId, clientConnectionInfo); tunnelSocketCtx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { tunnelServer.removeClientConnectionInfo(clientConnectionId); } }); agentCtx.channel().writeAndFlush(new TextWebSocketFrame(uri.toString())); logger.info("browser connect waitting for arthas agent open tunnel"); boolean watiResult = promise.awaitUninterruptibly(20, TimeUnit.SECONDS); if (watiResult) { logger.info( "browser connect wait for arthas agent open tunnel success, agentId: {}, clientConnectionId: {}", agentId, clientConnectionId); } else { logger.error( "browser connect wait for arthas agent open tunnel timeout, agentId: {}, clientConnectionId: {}", agentId, clientConnectionId); tunnelSocketCtx.close(); } } else { tunnelSocketCtx.channel().writeAndFlush(new CloseWebSocketFrame(2000, "Can not find arthas agent by id: "+ agentId)); logger.error("Can not find arthas agent by id: {}", agentId); throw new IllegalArgumentException("Can not find arthas agent by id: " + agentId); } } private void agentRegister(ChannelHandlerContext ctx, HandshakeComplete handshake, String requestUri) throws URISyntaxException { QueryStringDecoder queryDecoder = new QueryStringDecoder(requestUri); Map<String, List<String>> parameters = queryDecoder.parameters(); String appName = null; List<String> appNameList = parameters.get(URIConstans.APP_NAME); if (appNameList != null && !appNameList.isEmpty()) { appName = appNameList.get(0); } // generate a random agent id String id = null; if (appName != null) { // 如果有传 app name,则生成带 app name前缀的id,方便管理 id = appName + "_" + RandomStringUtils.random(20, true, true).toUpperCase(); } else { id = RandomStringUtils.random(20, true, true).toUpperCase(); } // agent传过来,则优先用 agent的 List<String> idList = parameters.get(URIConstans.ID); if (idList != null && !idList.isEmpty()) { id = idList.get(0); } String arthasVersion = null; List<String> arthasVersionList = parameters.get(URIConstans.ARTHAS_VERSION); if (arthasVersionList != null && !arthasVersionList.isEmpty()) { arthasVersion = arthasVersionList.get(0); } final String finalId = id; // URI responseUri = new URI("response", null, "/", "method=" + MethodConstants.AGENT_REGISTER + "&id=" + id, null); URI responseUri = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/") .queryParam(URIConstans.METHOD, MethodConstants.AGENT_REGISTER).queryParam(URIConstans.ID, id).build() .encode().toUri(); AgentInfo info = new AgentInfo(); // 前面可能有nginx代理 HttpHeaders headers = handshake.requestHeaders(); String host = HttpUtils.findClientIP(headers); if (host == null) { SocketAddress remoteAddress = ctx.channel().remoteAddress(); if (remoteAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress; info.setHost(inetSocketAddress.getHostString()); info.setPort(inetSocketAddress.getPort()); } } else { info.setHost(host); Integer port = HttpUtils.findClientPort(headers); if (port != null) { info.setPort(port); } } info.setChannelHandlerContext(ctx); if (arthasVersion != null) { info.setArthasVersion(arthasVersion); } tunnelServer.addAgent(id, info); ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { tunnelServer.removeAgent(finalId); } }); ctx.channel().writeAndFlush(new TextWebSocketFrame(responseUri.toString())); } private void openTunnel(ChannelHandlerContext ctx, String clientConnectionId) { Optional<ClientConnectionInfo> infoOptional = this.tunnelServer.findClientConnection(clientConnectionId); if (infoOptional.isPresent()) { ClientConnectionInfo info = infoOptional.get(); logger.info("openTunnel clientConnectionId:" + clientConnectionId); Promise<Channel> promise = info.getPromise(); promise.setSuccess(ctx.channel()); } else { logger.error("Can not find client connection by id: {}", clientConnectionId); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/AgentInfo.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/AgentInfo.java
package com.alibaba.arthas.tunnel.server; import com.fasterxml.jackson.annotation.JsonIgnore; import io.netty.channel.ChannelHandlerContext; /** * * @author hengyunabc 2019-08-27 * */ public class AgentInfo { @JsonIgnore private ChannelHandlerContext channelHandlerContext; private String host; private int port; private String arthasVersion; public ChannelHandlerContext getChannelHandlerContext() { return channelHandlerContext; } public void setChannelHandlerContext(ChannelHandlerContext channelHandlerContext) { this.channelHandlerContext = channelHandlerContext; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getArthasVersion() { return arthasVersion; } public void setArthasVersion(String arthasVersion) { this.arthasVersion = arthasVersion; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/AgentClusterInfo.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/AgentClusterInfo.java
package com.alibaba.arthas.tunnel.server; /** * @author hengyunabc 2020-10-30 * */ public class AgentClusterInfo { /** * agent本身以哪个ip连接到 tunnel server */ private String host; private int port; private String arthasVersion; /** * agent 连接到的 tunnel server 的ip 和 port */ private String clientConnectHost; private int clientConnectTunnelPort; public AgentClusterInfo() { } public AgentClusterInfo(AgentInfo agentInfo, String clientConnectHost, int clientConnectTunnelPort) { this.host = agentInfo.getHost(); this.port = agentInfo.getPort(); this.arthasVersion = agentInfo.getArthasVersion(); this.clientConnectHost = clientConnectHost; this.clientConnectTunnelPort = clientConnectTunnelPort; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getArthasVersion() { return arthasVersion; } public void setArthasVersion(String arthasVersion) { this.arthasVersion = arthasVersion; } public String getClientConnectHost() { return clientConnectHost; } public void setClientConnectHost(String clientConnectHost) { this.clientConnectHost = clientConnectHost; } public int getClientConnectTunnelPort() { return clientConnectTunnelPort; } public void setClientConnectTunnelPort(int clientConnectTunnelPort) { this.clientConnectTunnelPort = clientConnectTunnelPort; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/WebSecurityConfig.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/WebSecurityConfig.java
package com.alibaba.arthas.tunnel.server.app; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import com.alibaba.arthas.tunnel.server.app.configuration.ArthasProperties; /** * * @author hengyunabc 2021-08-11 * */ @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired ArthasProperties arthasProperties; @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint()).authenticated().anyRequest() .permitAll().and().formLogin(); // allow iframe if (arthasProperties.isEnableIframeSupport()) { httpSecurity.headers().frameOptions().disable(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/ArthasTunnelApplication.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/ArthasTunnelApplication.java
package com.alibaba.arthas.tunnel.server.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication(scanBasePackages = { "com.alibaba.arthas.tunnel.server.app", "com.alibaba.arthas.tunnel.server.endpoint" }) @EnableCaching public class ArthasTunnelApplication { public static void main(String[] args) { SpringApplication.run(ArthasTunnelApplication.class, args); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/ArthasProperties.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/ArthasProperties.java
package com.alibaba.arthas.tunnel.server.app.configuration; import java.util.ArrayList; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import com.alibaba.arthas.tunnel.server.utils.InetAddressUtil; import com.taobao.arthas.common.ArthasConstants; /** * * @author hengyunabc 2019-08-29 * */ @Component @ConfigurationProperties(prefix = "arthas") public class ArthasProperties { private Server server; private EmbeddedRedis embeddedRedis; /** * supoort apps.html/agents.html */ private boolean enableDetailPages = false; private boolean enableIframeSupport = true; public Server getServer() { return server; } public void setServer(Server server) { this.server = server; } public EmbeddedRedis getEmbeddedRedis() { return embeddedRedis; } public void setEmbeddedRedis(EmbeddedRedis embeddedRedis) { this.embeddedRedis = embeddedRedis; } public boolean isEnableDetailPages() { return enableDetailPages; } public void setEnableDetailPages(boolean enableDetailPages) { this.enableDetailPages = enableDetailPages; } public boolean isEnableIframeSupport() { return enableIframeSupport; } public void setEnableIframeSupport(boolean enableIframeSupport) { this.enableIframeSupport = enableIframeSupport; } public static class Server { /** * tunnel server listen host */ private String host; private int port; private boolean ssl; private String path = ArthasConstants.DEFAULT_WEBSOCKET_PATH; /** * 客户端连接的地址。也用于保存到redis里,当部署tunnel server集群里需要。不配置则会自动获取 */ private String clientConnectHost = InetAddressUtil.getInetAddress(); public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public boolean isSsl() { return ssl; } public void setSsl(boolean ssl) { this.ssl = ssl; } public String getClientConnectHost() { return clientConnectHost; } public void setClientConnectHost(String clientConnectHost) { this.clientConnectHost = clientConnectHost; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } } /** * for test * * @author hengyunabc 2020-11-03 * */ public static class EmbeddedRedis { private boolean enabled = false; private String host = "127.0.0.1"; private int port = 6379; private List<String> settings = new ArrayList<String>(); public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public List<String> getSettings() { return settings; } public void setSettings(List<String> settings) { this.settings = settings; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/TunnelClusterStoreConfiguration.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/TunnelClusterStoreConfiguration.java
package com.alibaba.arthas.tunnel.server.app.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.redis.core.StringRedisTemplate; import com.alibaba.arthas.tunnel.server.app.configuration.TunnelClusterStoreConfiguration.RedisTunnelClusterStoreConfiguration; import com.alibaba.arthas.tunnel.server.cluster.InMemoryClusterStore; import com.alibaba.arthas.tunnel.server.cluster.RedisTunnelClusterStore; import com.alibaba.arthas.tunnel.server.cluster.TunnelClusterStore; /** * * @author hengyunabc 2020-10-29 * */ @Configuration @AutoConfigureAfter(value = { RedisAutoConfiguration.class, CacheAutoConfiguration.class }) @Import(RedisTunnelClusterStoreConfiguration.class) public class TunnelClusterStoreConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnProperty(name = "spring.cache.type", havingValue = "caffeine") public TunnelClusterStore tunnelClusterStore(@Autowired CacheManager cacheManager) { Cache inMemoryClusterCache = cacheManager.getCache("inMemoryClusterCache"); InMemoryClusterStore inMemoryClusterStore = new InMemoryClusterStore(); inMemoryClusterStore.setCache(inMemoryClusterCache); return inMemoryClusterStore; } static class RedisTunnelClusterStoreConfiguration { @Bean // @ConditionalOnBean(StringRedisTemplate.class) @ConditionalOnClass(StringRedisTemplate.class) @ConditionalOnProperty("spring.redis.host") @ConditionalOnMissingBean public TunnelClusterStore tunnelClusterStore(@Autowired StringRedisTemplate redisTemplate) { RedisTunnelClusterStore redisTunnelClusterStore = new RedisTunnelClusterStore(); redisTunnelClusterStore.setRedisTemplate(redisTemplate); return redisTunnelClusterStore; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/EmbeddedRedisConfiguration.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/EmbeddedRedisConfiguration.java
package com.alibaba.arthas.tunnel.server.app.configuration; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.arthas.tunnel.server.app.configuration.ArthasProperties.EmbeddedRedis; import redis.embedded.RedisServer; import redis.embedded.RedisServerBuilder; /** * * @author hengyunabc 2020-11-03 * */ @Configuration @AutoConfigureBefore(TunnelClusterStoreConfiguration.class) public class EmbeddedRedisConfiguration { @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "arthas", name = { "embedded-redis.enabled" }) public RedisServer embeddedRedisServer(ArthasProperties arthasProperties) { EmbeddedRedis embeddedRedis = arthasProperties.getEmbeddedRedis(); RedisServerBuilder builder = RedisServer.builder().port(embeddedRedis.getPort()).bind(embeddedRedis.getHost()); for (String setting : embeddedRedis.getSettings()) { builder.setting(setting); } RedisServer redisServer = builder.build(); return redisServer; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/TunnelServerConfiguration.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/configuration/TunnelServerConfiguration.java
package com.alibaba.arthas.tunnel.server.app.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.arthas.tunnel.server.TunnelServer; import com.alibaba.arthas.tunnel.server.cluster.TunnelClusterStore; /** * * @author hengyunabc 2020-10-27 * */ @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class TunnelServerConfiguration { @Autowired ArthasProperties arthasProperties; @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean public TunnelServer tunnelServer(@Autowired(required = false) TunnelClusterStore tunnelClusterStore) { TunnelServer tunnelServer = new TunnelServer(); tunnelServer.setHost(arthasProperties.getServer().getHost()); tunnelServer.setPort(arthasProperties.getServer().getPort()); tunnelServer.setSsl(arthasProperties.getServer().isSsl()); tunnelServer.setPath(arthasProperties.getServer().getPath()); tunnelServer.setClientConnectHost(arthasProperties.getServer().getClientConnectHost()); if (tunnelClusterStore != null) { tunnelServer.setTunnelClusterStore(tunnelClusterStore); } return tunnelServer; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/DetailAPIController.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/DetailAPIController.java
package com.alibaba.arthas.tunnel.server.app.web; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.arthas.tunnel.server.AgentClusterInfo; import com.alibaba.arthas.tunnel.server.app.configuration.ArthasProperties; import com.alibaba.arthas.tunnel.server.cluster.TunnelClusterStore; /** * * @author hengyunabc 2020-11-03 * */ @Controller public class DetailAPIController { private final static Logger logger = LoggerFactory.getLogger(DetailAPIController.class); @Autowired ArthasProperties arthasProperties; @Autowired(required = false) private TunnelClusterStore tunnelClusterStore; @RequestMapping("/api/tunnelApps") @ResponseBody public Set<String> tunnelApps(HttpServletRequest request, Model model) { if (!arthasProperties.isEnableDetailPages()) { throw new IllegalAccessError("not allow"); } Set<String> result = new HashSet<String>(); if (tunnelClusterStore != null) { Collection<String> agentIds = tunnelClusterStore.allAgentIds(); for (String id : agentIds) { String appName = findAppNameFromAgentId(id); if (appName != null) { result.add(appName); } else { logger.warn("illegal agentId: " + id); } } } return result; } @RequestMapping("/api/tunnelAgentInfo") @ResponseBody public Map<String, AgentClusterInfo> tunnelAgentIds(@RequestParam(value = "app", required = true) String appName, HttpServletRequest request, Model model) { if (!arthasProperties.isEnableDetailPages()) { throw new IllegalAccessError("not allow"); } if (tunnelClusterStore != null) { Map<String, AgentClusterInfo> agentInfos = tunnelClusterStore.agentInfo(appName); return agentInfos; } return Collections.emptyMap(); } /** * check if agentId exists * @param agentId * @return */ @RequestMapping("/api/tunnelAgents") @ResponseBody public Map<String, Object> tunnelAgentIds(@RequestParam(value = "agentId", required = true) String agentId) { Map<String, Object> result = new HashMap<String, Object>(); boolean success = false; try { AgentClusterInfo info = tunnelClusterStore.findAgent(agentId); if (info != null) { success = true; } } catch (Throwable e) { logger.error("try to find agentId error, id: {}", agentId, e); } result.put("success", success); return result; } private static String findAppNameFromAgentId(String id) { int index = id.indexOf('_'); if (index < 0 || index >= id.length()) { return null; } return id.substring(0, index); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/ProxyController.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/ProxyController.java
package com.alibaba.arthas.tunnel.server.app.web; import java.net.URI; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity.BodyBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.util.UriComponentsBuilder; import com.alibaba.arthas.tunnel.common.MethodConstants; import com.alibaba.arthas.tunnel.common.SimpleHttpResponse; import com.alibaba.arthas.tunnel.common.URIConstans; import com.alibaba.arthas.tunnel.server.AgentInfo; import com.alibaba.arthas.tunnel.server.TunnelServer; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; /** * 代理http请求到具体的 arthas agent里 * * @author hengyunabc 2020-10-22 * */ @Controller public class ProxyController { private final static Logger logger = LoggerFactory.getLogger(ProxyController.class); @Autowired TunnelServer tunnelServer; @RequestMapping(value = "/proxy/{agentId}/**") @ResponseBody public ResponseEntity<?> execute(@PathVariable(name = "agentId", required = true) String agentId, HttpServletRequest request) throws InterruptedException, ExecutionException, TimeoutException { String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String targetUrl = fullPath.substring("/proxy/".length() + agentId.length()); logger.info("http proxy, agentId: {}, targetUrl: {}", agentId, targetUrl); Optional<AgentInfo> findAgent = tunnelServer.findAgent(agentId); if (findAgent.isPresent()) { String requestId = RandomStringUtils.random(20, true, true).toUpperCase(); ChannelHandlerContext agentCtx = findAgent.get().getChannelHandlerContext(); Promise<SimpleHttpResponse> httpResponsePromise = GlobalEventExecutor.INSTANCE.newPromise(); tunnelServer.addProxyRequestPromise(requestId, httpResponsePromise); URI uri = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/") .queryParam(URIConstans.METHOD, MethodConstants.HTTP_PROXY).queryParam(URIConstans.ID, agentId) .queryParam(URIConstans.TARGET_URL, targetUrl).queryParam(URIConstans.PROXY_REQUEST_ID, requestId) .build().toUri(); agentCtx.channel().writeAndFlush(new TextWebSocketFrame(uri.toString())); logger.info("waitting for arthas agent http proxy, agentId: {}, targetUrl: {}", agentId, targetUrl); SimpleHttpResponse simpleHttpResponse = httpResponsePromise.get(15, TimeUnit.SECONDS); BodyBuilder bodyBuilder = ResponseEntity.status(simpleHttpResponse.getStatus()); for (Entry<String, String> entry : simpleHttpResponse.getHeaders().entrySet()) { bodyBuilder.header(entry.getKey(), entry.getValue()); } ResponseEntity<byte[]> responseEntity = bodyBuilder.body(simpleHttpResponse.getContent()); return responseEntity; } else { logger.error("can not find agent by agentId: {}", agentId); } return ResponseEntity.notFound().build(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/StatController.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/StatController.java
package com.alibaba.arthas.tunnel.server.app.web; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * arthas agent数据回报的演示接口 * @author hengyunabc 2019-09-24 * */ @Controller public class StatController { private final static Logger logger = LoggerFactory.getLogger(StatController.class); @RequestMapping(value = "/api/stat") @ResponseBody public Map<String, Object> execute(@RequestParam(value = "ip", required = true) String ip, @RequestParam(value = "version", required = true) String version, @RequestParam(value = "agentId", required = false) String agentId, @RequestParam(value = "command", required = true) String command, @RequestParam(value = "arguments", required = false, defaultValue = "") String arguments) { logger.info("arthas stat, ip: {}, version: {}, agentId: {}, command: {}, arguments: {}", ip, version, agentId, command, arguments); Map<String, Object> result = new HashMap<>(); result.put("success", true); return result; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/ClusterController.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/app/web/ClusterController.java
package com.alibaba.arthas.tunnel.server.app.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.arthas.tunnel.server.AgentClusterInfo; import com.alibaba.arthas.tunnel.server.TunnelServer; import com.alibaba.arthas.tunnel.server.cluster.TunnelClusterStore; /** * * @author hengyunabc 2020-10-27 * */ @Controller public class ClusterController { private final static Logger logger = LoggerFactory.getLogger(ClusterController.class); @Autowired TunnelServer tunnelServer; @RequestMapping(value = "/api/cluster/findHost") @ResponseBody public String execute(@RequestParam(value = "agentId", required = true) String agentId) { TunnelClusterStore tunnelClusterStore = tunnelServer.getTunnelClusterStore(); String host = null; if (tunnelClusterStore != null) { AgentClusterInfo info = tunnelClusterStore.findAgent(agentId); host = info.getClientConnectHost(); } if (host == null) { host = ""; } logger.info("arthas cluster findHost, agentId: {}, host: {}", agentId, host); return host; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/utils/HttpUtils.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/utils/HttpUtils.java
package com.alibaba.arthas.tunnel.server.utils; import io.netty.handler.codec.http.HttpHeaders; /** * * @author hengyunabc 2021-02-26 * */ public class HttpUtils { public static String findClientIP(HttpHeaders headers) { String hostStr = headers.get("X-Forwarded-For"); if (hostStr == null) { return null; } int index = hostStr.indexOf(','); if (index > 0) { hostStr = hostStr.substring(0, index); } return hostStr; } public static Integer findClientPort(HttpHeaders headers) { String portStr = headers.get("X-Real-Port"); if (portStr != null) { return Integer.parseInt(portStr); } return null; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/utils/InetAddressUtil.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/utils/InetAddressUtil.java
package com.alibaba.arthas.tunnel.server.utils; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author hengyunabc 2020-10-27 * */ public class InetAddressUtil { private final static Logger logger = LoggerFactory.getLogger(InetAddressUtil.class); /** * 获得本机IP。 * <p> * 在超过一块网卡时会有问题,因为这里每次都只是取了第一块网卡绑定的IP地址 */ public static String getInetAddress() { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); InetAddress address = null; while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { address = addresses.nextElement(); if (isValidAddress(address)) { return address.getHostAddress(); } } } logger.warn("Can not get the server IP address"); return null; } catch (Throwable t) { logger.error("Can not get the server IP address", t); return null; } } public static boolean isValidAddress(InetAddress address) { return address != null && !address.isLoopbackAddress() // filter 127.x.x.x && !address.isAnyLocalAddress() // filter 0.0.0.0 && !address.isLinkLocalAddress() // filter 169.254.0.0/16 && !address.getHostAddress().contains(":");// filter IPv6 } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/cluster/InMemoryClusterStore.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/cluster/InMemoryClusterStore.java
package com.alibaba.arthas.tunnel.server.cluster; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.Cache; import org.springframework.cache.Cache.ValueWrapper; import org.springframework.cache.caffeine.CaffeineCache; import com.alibaba.arthas.tunnel.server.AgentClusterInfo; /** * * @author hengyunabc 2020-12-02 * */ public class InMemoryClusterStore implements TunnelClusterStore { private final static Logger logger = LoggerFactory.getLogger(InMemoryClusterStore.class); private Cache cache; @Override public AgentClusterInfo findAgent(String agentId) { ValueWrapper valueWrapper = cache.get(agentId); if (valueWrapper == null) { return null; } AgentClusterInfo info = (AgentClusterInfo) valueWrapper.get(); return info; } @Override public void removeAgent(String agentId) { cache.evict(agentId); } @Override public void addAgent(String agentId, AgentClusterInfo info, long timeout, TimeUnit timeUnit) { cache.put(agentId, info); } @Override public Collection<String> allAgentIds() { CaffeineCache caffeineCache = (CaffeineCache) cache; com.github.benmanes.caffeine.cache.Cache<Object, Object> nativeCache = caffeineCache.getNativeCache(); return (Collection<String>) (Collection<?>) nativeCache.asMap().keySet(); } @Override public Map<String, AgentClusterInfo> agentInfo(String appName) { CaffeineCache caffeineCache = (CaffeineCache) cache; com.github.benmanes.caffeine.cache.Cache<Object, Object> nativeCache = caffeineCache.getNativeCache(); ConcurrentMap<String, AgentClusterInfo> map = (ConcurrentMap<String, AgentClusterInfo>) (ConcurrentMap<?, ?>) nativeCache .asMap(); Map<String, AgentClusterInfo> result = new HashMap<String, AgentClusterInfo>(); String prefix = appName + "_"; for (Entry<String, AgentClusterInfo> entry : map.entrySet()) { String agentId = entry.getKey(); if (agentId.startsWith(prefix)) { result.put(agentId, entry.getValue()); } } return result; } public Cache getCache() { return cache; } public void setCache(Cache cache) { this.cache = cache; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/cluster/TunnelClusterStore.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/cluster/TunnelClusterStore.java
package com.alibaba.arthas.tunnel.server.cluster; import java.util.Collection; import java.util.Map; import java.util.concurrent.TimeUnit; import com.alibaba.arthas.tunnel.server.AgentClusterInfo; /** * 保存agentId连接到哪个具体的 tunnel server,集群部署时使用 * * @author hengyunabc 2020-10-27 * */ public interface TunnelClusterStore { public void addAgent(String agentId, AgentClusterInfo info, long expire, TimeUnit timeUnit); public AgentClusterInfo findAgent(String agentId); public void removeAgent(String agentId); public Collection<String> allAgentIds(); public Map<String, AgentClusterInfo> agentInfo(String appName); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/cluster/RedisTunnelClusterStore.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/cluster/RedisTunnelClusterStore.java
package com.alibaba.arthas.tunnel.server.cluster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import com.alibaba.arthas.tunnel.server.AgentClusterInfo; import com.fasterxml.jackson.databind.ObjectMapper; /** * * @author hengyunabc 2020-10-27 * */ public class RedisTunnelClusterStore implements TunnelClusterStore { private final static Logger logger = LoggerFactory.getLogger(RedisTunnelClusterStore.class); // 定义jackson对象 private static final ObjectMapper MAPPER = new ObjectMapper(); private String prefix = "arthas-tunnel-agent-"; private StringRedisTemplate redisTemplate; @Override public AgentClusterInfo findAgent(String agentId) { try { ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); String infoStr = opsForValue.get(prefix + agentId); if (infoStr == null) { throw new IllegalArgumentException("can not find info for agentId: " + agentId); } AgentClusterInfo info = MAPPER.readValue(infoStr, AgentClusterInfo.class); return info; } catch (Throwable e) { logger.error("try to read agentInfo error. agentId:{}", agentId, e); throw new RuntimeException(e); } } @Override public void removeAgent(String agentId) { ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); opsForValue.getOperations().delete(prefix + agentId); } @Override public void addAgent(String agentId, AgentClusterInfo info, long timeout, TimeUnit timeUnit) { try { ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); String infoStr = MAPPER.writeValueAsString(info); opsForValue.set(prefix + agentId, infoStr, timeout, timeUnit); } catch (Throwable e) { logger.error("try to add agentInfo error. agentId:{}", agentId, e); throw new RuntimeException(e); } } public StringRedisTemplate getRedisTemplate() { return redisTemplate; } public void setRedisTemplate(StringRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } @Override public Collection<String> allAgentIds() { ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); int length = prefix.length(); final Set<String> redisValues = opsForValue.getOperations().keys(prefix + "*"); if (redisValues != null) { final ArrayList<String> result = new ArrayList<>(redisValues.size()); for (String value : redisValues) { result.add(value.substring(length)); } return result; } else { logger.error("try to get allAgentIds error. redis returned null."); return Collections.emptyList(); } } @Override public Map<String, AgentClusterInfo> agentInfo(String appName) { try { ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); String prefixWithAppName = prefix + appName + "_"; ArrayList<String> keys = new ArrayList<>(opsForValue.getOperations().keys(prefixWithAppName + "*")); List<String> values = opsForValue.getOperations().opsForValue().multiGet(keys); Map<String, AgentClusterInfo> result = new HashMap<>(); Iterator<String> iterator = values.iterator(); for (String key : keys) { String infoStr = iterator.next(); AgentClusterInfo info = MAPPER.readValue(infoStr, AgentClusterInfo.class); String agentId = key.substring(prefix.length()); result.put(agentId, info); } return result; } catch (Throwable e) { logger.error("try to query agentInfo error. appName:{}", appName, e); throw new RuntimeException(e); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/endpoint/ArthasEndPointAutoconfiguration.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/endpoint/ArthasEndPointAutoconfiguration.java
package com.alibaba.arthas.tunnel.server.endpoint; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.arthas.tunnel.server.app.configuration.ArthasProperties; @EnableConfigurationProperties(ArthasProperties.class) @Configuration public class ArthasEndPointAutoconfiguration { @ConditionalOnMissingBean @Bean @ConditionalOnAvailableEndpoint public ArthasEndpoint arthasEndPoint() { return new ArthasEndpoint(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/endpoint/ArthasEndpoint.java
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/endpoint/ArthasEndpoint.java
package com.alibaba.arthas.tunnel.server.endpoint; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import com.alibaba.arthas.tunnel.server.TunnelServer; import com.alibaba.arthas.tunnel.server.app.configuration.ArthasProperties; @Endpoint(id = "arthas") public class ArthasEndpoint { @Autowired ArthasProperties arthasProperties; @Autowired TunnelServer tunnelServer; @ReadOperation public Map<String, Object> invoke() { Map<String, Object> result = new HashMap<>(4); result.put("version", this.getClass().getPackage().getImplementationVersion()); result.put("properties", arthasProperties); result.put("agents", tunnelServer.getAgentInfoMap()); result.put("clientConnections", tunnelServer.getClientConnectionInfoMap()); return result; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/test/java/com/alibaba/arthas/spring/StringUtilsTest.java
arthas-spring-boot-starter/src/test/java/com/alibaba/arthas/spring/StringUtilsTest.java
package com.alibaba.arthas.spring; import java.util.HashMap; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** * * @author hengyunabc 2020-06-24 * */ public class StringUtilsTest { @Test public void test() { Map<String, String> map = new HashMap<String, String>(); map.put("telnet-port", "" + 9999); map.put("aaa--bbb", "fff"); map.put("123", "123"); map.put("123-", "123"); map.put("123-abc", "123"); map.put("xxx-", "xxx"); map = StringUtils.removeDashKey(map); Assertions.assertThat(map).containsEntry("telnetPort", "" + 9999); Assertions.assertThat(map).containsEntry("aaa-Bbb", "fff"); Assertions.assertThat(map).containsEntry("123", "123"); Assertions.assertThat(map).containsEntry("123-", "123"); Assertions.assertThat(map).containsEntry("123Abc", "123"); Assertions.assertThat(map).containsEntry("xxx-", "xxx"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/it/arthas-spring-boot3-starter-example/src/test/java/com/example/arthasspringboot3starterexample/ArthasSpringBoot3StarterExampleApplicationTests.java
arthas-spring-boot-starter/src/it/arthas-spring-boot3-starter-example/src/test/java/com/example/arthasspringboot3starterexample/ArthasSpringBoot3StarterExampleApplicationTests.java
package com.example.arthasspringbootstarterexample3; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ArthasSpringBoot3StarterExampleApplicationTests { @Test void contextLoads() { } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/it/arthas-spring-boot3-starter-example/src/main/java/com/example/arthasspringboot3starterexample/ArthasSpringBoot3StarterExampleApplication.java
arthas-spring-boot-starter/src/it/arthas-spring-boot3-starter-example/src/main/java/com/example/arthasspringboot3starterexample/ArthasSpringBoot3StarterExampleApplication.java
package com.example.arthasspringboot3starterexample; import java.util.concurrent.TimeUnit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ArthasSpringBoot3StarterExampleApplication { public static void main(String[] args) throws InterruptedException { SpringApplication.run(ArthasSpringBoot3StarterExampleApplication.class, args); System.out.println("xxxxxxxxxxxxxxxxxx"); TimeUnit.SECONDS.sleep(3); System.exit(0); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/it/arthas-spring-boot-starter-example/src/test/java/com/example/arthasspringbootstarterexample/ArthasSpringBootStarterExampleApplicationTests.java
arthas-spring-boot-starter/src/it/arthas-spring-boot-starter-example/src/test/java/com/example/arthasspringbootstarterexample/ArthasSpringBootStarterExampleApplicationTests.java
package com.example.arthasspringbootstarterexample; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ArthasSpringBootStarterExampleApplicationTests { @Test void contextLoads() { } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/it/arthas-spring-boot-starter-example/src/main/java/com/example/arthasspringbootstarterexample/ArthasSpringBootStarterExampleApplication.java
arthas-spring-boot-starter/src/it/arthas-spring-boot-starter-example/src/main/java/com/example/arthasspringbootstarterexample/ArthasSpringBootStarterExampleApplication.java
package com.example.arthasspringbootstarterexample; import java.util.concurrent.TimeUnit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ArthasSpringBootStarterExampleApplication { public static void main(String[] args) throws InterruptedException { SpringApplication.run(ArthasSpringBootStarterExampleApplication.class, args); System.out.println("xxxxxxxxxxxxxxxxxx"); TimeUnit.SECONDS.sleep(3); System.exit(0); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/StringUtils.java
arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/StringUtils.java
package com.alibaba.arthas.spring; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * * @author hengyunabc 2020-06-24 * */ public class StringUtils { public static Map<String, String> removeDashKey(Map<String, String> map) { Map<String, String> result = new HashMap<String, String>(map.size()); for (Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); if (key.contains("-")) { StringBuilder sb = new StringBuilder(key.length()); for (int i = 0; i < key.length(); i++) { if (key.charAt(i) == '-' && (i + 1 < key.length()) && Character.isAlphabetic(key.charAt(i + 1))) { ++i; char upperChar = Character.toUpperCase(key.charAt(i)); sb.append(upperChar); } else { sb.append(key.charAt(i)); } } key = sb.toString(); } result.put(key, entry.getValue()); } return result; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/ArthasProperties.java
arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/ArthasProperties.java
package com.alibaba.arthas.spring; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; /** * * @author hengyunabc 2020-06-23 * */ @ConfigurationProperties(prefix = "arthas") public class ArthasProperties { private String ip; private int telnetPort; private int httpPort; private String tunnelServer; private String agentId; private String appName; /** * report executed command */ private String statUrl; /** * session timeout seconds */ private long sessionTimeout; private String username; private String password; private String home; /** * when arthas agent init error will throw exception by default. */ private boolean slientInit = false; /** * disabled commands,default disable stop command */ private String disabledCommands; private static final String DEFAULT_DISABLEDCOMMANDS = "stop"; /** * 因为 arthasConfigMap 只注入了用户配置的值,没有默认值,因些统一处理补全 */ public static void updateArthasConfigMapDefaultValue(Map<String, String> arthasConfigMap) { if (!arthasConfigMap.containsKey("disabledCommands")) { arthasConfigMap.put("disabledCommands", DEFAULT_DISABLEDCOMMANDS); } } public String getHome() { return home; } public void setHome(String home) { this.home = home; } public boolean isSlientInit() { return slientInit; } public void setSlientInit(boolean slientInit) { this.slientInit = slientInit; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getTelnetPort() { return telnetPort; } public void setTelnetPort(int telnetPort) { this.telnetPort = telnetPort; } public int getHttpPort() { return httpPort; } public void setHttpPort(int httpPort) { this.httpPort = httpPort; } public String getTunnelServer() { return tunnelServer; } public void setTunnelServer(String tunnelServer) { this.tunnelServer = tunnelServer; } public String getAgentId() { return agentId; } public void setAgentId(String agentId) { this.agentId = agentId; } public String getStatUrl() { return statUrl; } public void setStatUrl(String statUrl) { this.statUrl = statUrl; } public long getSessionTimeout() { return sessionTimeout; } public void setSessionTimeout(long sessionTimeout) { this.sessionTimeout = sessionTimeout; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getDisabledCommands() { return disabledCommands; } public void setDisabledCommands(String disabledCommands) { this.disabledCommands = disabledCommands; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/ArthasConfiguration.java
arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/ArthasConfiguration.java
package com.alibaba.arthas.spring; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.core.env.ConfigurableEnvironment; import com.taobao.arthas.agent.attach.ArthasAgent; /** * * @author hengyunabc 2020-06-22 * */ @ConditionalOnProperty(name = "spring.arthas.enabled", matchIfMissing = true) @EnableConfigurationProperties({ ArthasProperties.class }) public class ArthasConfiguration { private static final Logger logger = LoggerFactory.getLogger(ArthasConfiguration.class); @Autowired ConfigurableEnvironment environment; /** * <pre> * 1. 提取所有以 arthas.* 开头的配置项,再统一转换为Arthas配置 * 2. 避免某些配置在新版本里支持,但在ArthasProperties里没有配置的情况。 * </pre> */ @ConfigurationProperties(prefix = "arthas") @ConditionalOnMissingBean(name="arthasConfigMap") @Bean public HashMap<String, String> arthasConfigMap() { return new HashMap<String, String>(); } @ConditionalOnMissingBean @Bean public ArthasAgent arthasAgent(@Autowired @Qualifier("arthasConfigMap") Map<String, String> arthasConfigMap, @Autowired ArthasProperties arthasProperties) throws Throwable { arthasConfigMap = StringUtils.removeDashKey(arthasConfigMap); ArthasProperties.updateArthasConfigMapDefaultValue(arthasConfigMap); /** * @see org.springframework.boot.context.ContextIdApplicationContextInitializer#getApplicationId(ConfigurableEnvironment) */ String appName = environment.getProperty("spring.application.name"); if (arthasConfigMap.get("appName") == null && appName != null) { arthasConfigMap.put("appName", appName); } // 给配置全加上前缀 Map<String, String> mapWithPrefix = new HashMap<String, String>(arthasConfigMap.size()); for (Entry<String, String> entry : arthasConfigMap.entrySet()) { mapWithPrefix.put("arthas." + entry.getKey(), entry.getValue()); } final ArthasAgent arthasAgent = new ArthasAgent(mapWithPrefix, arthasProperties.getHome(), arthasProperties.isSlientInit(), null); arthasAgent.init(); logger.info("Arthas agent start success."); return arthasAgent; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/endpoints/ArthasEndPointAutoConfiguration.java
arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/endpoints/ArthasEndPointAutoConfiguration.java
package com.alibaba.arthas.spring.endpoints; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; /** * * @author hengyunabc 2020-06-24 * */ @ConditionalOnProperty(name = "spring.arthas.enabled", matchIfMissing = true) public class ArthasEndPointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint public ArthasEndPoint arthasEndPoint() { return new ArthasEndPoint(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/endpoints/ArthasEndPoint.java
arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/endpoints/ArthasEndPoint.java
package com.alibaba.arthas.spring.endpoints; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import com.taobao.arthas.agent.attach.ArthasAgent; /** * * @author hengyunabc 2020-06-24 * */ @Endpoint(id = "arthas") public class ArthasEndPoint { @Autowired(required = false) private ArthasAgent arthasAgent; @Autowired(required = false) private HashMap<String, String> arthasConfigMap; @ReadOperation public Map<String, Object> invoke() { Map<String, Object> result = new HashMap<String, Object>(); if (arthasConfigMap != null) { result.put("arthasConfigMap", arthasConfigMap); } String errorMessage = arthasAgent.getErrorMessage(); if (errorMessage != null) { result.put("errorMessage", errorMessage); } return result; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/ExecutingCommand.java
common/src/main/java/com/taobao/arthas/common/ExecutingCommand.java
package com.taobao.arthas.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A class for executing on the command line and returning the result of * execution. * * @author alessandro[at]perucchi[dot]org */ public class ExecutingCommand { private ExecutingCommand() { } /** * Executes a command on the native command line and returns the result. * * @param cmdToRun * Command to run * @return A list of Strings representing the result of the command, or empty * string if the command failed */ public static List<String> runNative(String cmdToRun) { String[] cmd = cmdToRun.split(" "); return runNative(cmd); } /** * Executes a command on the native command line and returns the result line by * line. * * @param cmdToRunWithArgs * Command to run and args, in an array * @return A list of Strings representing the result of the command, or empty * string if the command failed */ public static List<String> runNative(String[] cmdToRunWithArgs) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRunWithArgs); } catch (SecurityException e) { AnsiLog.trace("Couldn't run command {}:", Arrays.toString(cmdToRunWithArgs)); AnsiLog.trace(e); return new ArrayList<String>(0); } catch (IOException e) { AnsiLog.trace("Couldn't run command {}:", Arrays.toString(cmdToRunWithArgs)); AnsiLog.trace(e); return new ArrayList<String>(0); } ArrayList<String> sa = new ArrayList<String>(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); try { String line; while ((line = reader.readLine()) != null) { sa.add(line); } p.waitFor(); } catch (IOException e) { AnsiLog.trace("Problem reading output from {}:", Arrays.toString(cmdToRunWithArgs)); AnsiLog.trace(e); return new ArrayList<String>(0); } catch (InterruptedException ie) { AnsiLog.trace("Problem reading output from {}:", Arrays.toString(cmdToRunWithArgs)); AnsiLog.trace(ie); Thread.currentThread().interrupt(); } finally { IOUtils.close(reader); } return sa; } /** * Return first line of response for selected command. * * @param cmd2launch * String command to be launched * @return String or empty string if command failed */ public static String getFirstAnswer(String cmd2launch) { return getAnswerAt(cmd2launch, 0); } /** * Return response on selected line index (0-based) after running selected * command. * * @param cmd2launch * String command to be launched * @param answerIdx * int index of line in response of the command * @return String whole line in response or empty string if invalid index or * running of command fails */ public static String getAnswerAt(String cmd2launch, int answerIdx) { List<String> sa = ExecutingCommand.runNative(cmd2launch); if (answerIdx >= 0 && answerIdx < sa.size()) { return sa.get(answerIdx); } return ""; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/ArthasConstants.java
common/src/main/java/com/taobao/arthas/common/ArthasConstants.java
package com.taobao.arthas.common; /** * * @author hengyunabc 2020-09-02 * */ public class ArthasConstants { /** * local address in VM communication * * @see io.netty.channel.local.LocalAddress * @see io.netty.channel.local.LocalChannel */ public static final String NETTY_LOCAL_ADDRESS = "arthas-netty-LocalAddress"; public static final int MAX_HTTP_CONTENT_LENGTH = 1024 * 1024 * 10; public static final String ARTHAS_OUTPUT = "arthas-output"; public static final String APP_NAME = "app-name"; public static final String PROJECT_NAME = "project.name"; public static final String SPRING_APPLICATION_NAME = "spring.application.name"; public static final int TELNET_PORT = 3658; public static final String DEFAULT_WEBSOCKET_PATH = "/ws"; public static final int WEBSOCKET_IDLE_SECONDS = 10; /** * HTTP cookie id */ public static final String ASESSION_KEY = "asession"; public static final String DEFAULT_USERNAME = "arthas"; public static final String SUBJECT_KEY = "subject"; public static final String AUTH = "auth"; public static final String USERNAME_KEY = "username"; public static final String PASSWORD_KEY = "password"; public static final String USER_ID_KEY = "userId"; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/ReflectUtils.java
common/src/main/java/com/taobao/arthas/common/ReflectUtils.java
package com.taobao.arthas.common; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * from spring * @version $Id: ReflectUtils.java,v 1.30 2009/01/11 19:47:49 herbyderby Exp $ */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class ReflectUtils { private ReflectUtils() { } private static final Map primitives = new HashMap(8); private static final Map transforms = new HashMap(8); private static final ClassLoader defaultLoader = ReflectUtils.class.getClassLoader(); // SPRING PATCH BEGIN private static final Method privateLookupInMethod; private static final Method lookupDefineClassMethod; private static final Method classLoaderDefineClassMethod; private static final ProtectionDomain PROTECTION_DOMAIN; private static final Throwable THROWABLE; private static final List<Method> OBJECT_METHODS = new ArrayList<Method>(); static { Method privateLookupIn; Method lookupDefineClass; Method classLoaderDefineClass; ProtectionDomain protectionDomain; Throwable throwable = null; try { privateLookupIn = (Method) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { try { return MethodHandles.class.getMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class); } catch (NoSuchMethodException ex) { return null; } } }); lookupDefineClass = (Method) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { try { return MethodHandles.Lookup.class.getMethod("defineClass", byte[].class); } catch (NoSuchMethodException ex) { return null; } } }); classLoaderDefineClass = (Method) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { return ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE, ProtectionDomain.class); } }); protectionDomain = getProtectionDomain(ReflectUtils.class); AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { Method[] methods = Object.class.getDeclaredMethods(); for (Method method : methods) { if ("finalize".equals(method.getName()) || (method.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) > 0) { continue; } OBJECT_METHODS.add(method); } return null; } }); } catch (Throwable t) { privateLookupIn = null; lookupDefineClass = null; classLoaderDefineClass = null; protectionDomain = null; throwable = t; } privateLookupInMethod = privateLookupIn; lookupDefineClassMethod = lookupDefineClass; classLoaderDefineClassMethod = classLoaderDefineClass; PROTECTION_DOMAIN = protectionDomain; THROWABLE = throwable; } // SPRING PATCH END private static final String[] CGLIB_PACKAGES = { "java.lang", }; static { primitives.put("byte", Byte.TYPE); primitives.put("char", Character.TYPE); primitives.put("double", Double.TYPE); primitives.put("float", Float.TYPE); primitives.put("int", Integer.TYPE); primitives.put("long", Long.TYPE); primitives.put("short", Short.TYPE); primitives.put("boolean", Boolean.TYPE); transforms.put("byte", "B"); transforms.put("char", "C"); transforms.put("double", "D"); transforms.put("float", "F"); transforms.put("int", "I"); transforms.put("long", "J"); transforms.put("short", "S"); transforms.put("boolean", "Z"); } public static ProtectionDomain getProtectionDomain(final Class source) { if (source == null) { return null; } return (ProtectionDomain) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return source.getProtectionDomain(); } }); } public static Constructor findConstructor(String desc) { return findConstructor(desc, defaultLoader); } public static Constructor findConstructor(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); String className = desc.substring(0, lparen).trim(); return getClass(className, loader).getConstructor(parseTypes(desc, loader)); } catch (ClassNotFoundException ex) { throw new ReflectException(ex); } catch (NoSuchMethodException ex) { throw new ReflectException(ex); } } public static Method findMethod(String desc) { return findMethod(desc, defaultLoader); } public static Method findMethod(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); int dot = desc.lastIndexOf('.', lparen); String className = desc.substring(0, dot).trim(); String methodName = desc.substring(dot + 1, lparen).trim(); return getClass(className, loader).getDeclaredMethod(methodName, parseTypes(desc, loader)); } catch (ClassNotFoundException ex) { throw new ReflectException(ex); } catch (NoSuchMethodException ex) { throw new ReflectException(ex); } } private static Class[] parseTypes(String desc, ClassLoader loader) throws ClassNotFoundException { int lparen = desc.indexOf('('); int rparen = desc.indexOf(')', lparen); List params = new ArrayList(); int start = lparen + 1; for (;;) { int comma = desc.indexOf(',', start); if (comma < 0) { break; } params.add(desc.substring(start, comma).trim()); start = comma + 1; } if (start < rparen) { params.add(desc.substring(start, rparen).trim()); } Class[] types = new Class[params.size()]; for (int i = 0; i < types.length; i++) { types[i] = getClass((String) params.get(i), loader); } return types; } private static Class getClass(String className, ClassLoader loader) throws ClassNotFoundException { return getClass(className, loader, CGLIB_PACKAGES); } private static Class getClass(String className, ClassLoader loader, String[] packages) throws ClassNotFoundException { String save = className; int dimensions = 0; int index = 0; while ((index = className.indexOf("[]", index) + 1) > 0) { dimensions++; } StringBuilder brackets = new StringBuilder(className.length() - dimensions); for (int i = 0; i < dimensions; i++) { brackets.append('['); } className = className.substring(0, className.length() - 2 * dimensions); String prefix = (dimensions > 0) ? brackets + "L" : ""; String suffix = (dimensions > 0) ? ";" : ""; try { return Class.forName(prefix + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } for (int i = 0; i < packages.length; i++) { try { return Class.forName(prefix + packages[i] + '.' + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } } if (dimensions == 0) { Class c = (Class) primitives.get(className); if (c != null) { return c; } } else { String transform = (String) transforms.get(className); if (transform != null) { try { return Class.forName(brackets + transform, false, loader); } catch (ClassNotFoundException ignore) { } } } throw new ClassNotFoundException(save); } public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; public static Object newInstance(Class type) { return newInstance(type, EMPTY_CLASS_ARRAY, null); } public static Object newInstance(Class type, Class[] parameterTypes, Object[] args) { return newInstance(getConstructor(type, parameterTypes), args); } public static Object newInstance(final Constructor cstruct, final Object[] args) { boolean flag = cstruct.isAccessible(); try { if (!flag) { cstruct.setAccessible(true); } Object result = cstruct.newInstance(args); return result; } catch (InstantiationException e) { throw new ReflectException(e); } catch (IllegalAccessException e) { throw new ReflectException(e); } catch (InvocationTargetException e) { throw new ReflectException(e.getTargetException()); } finally { if (!flag) { cstruct.setAccessible(flag); } } } public static Constructor getConstructor(Class type, Class[] parameterTypes) { try { Constructor constructor = type.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { throw new ReflectException(e); } } public static String[] getNames(Class[] classes) { if (classes == null) return null; String[] names = new String[classes.length]; for (int i = 0; i < names.length; i++) { names[i] = classes[i].getName(); } return names; } public static Class[] getClasses(Object[] objects) { Class[] classes = new Class[objects.length]; for (int i = 0; i < objects.length; i++) { classes[i] = objects[i].getClass(); } return classes; } public static Method findNewInstance(Class iface) { Method m = findInterfaceMethod(iface); if (!m.getName().equals("newInstance")) { throw new IllegalArgumentException(iface + " missing newInstance method"); } return m; } public static Method[] getPropertyMethods(PropertyDescriptor[] properties, boolean read, boolean write) { Set methods = new HashSet(); for (int i = 0; i < properties.length; i++) { PropertyDescriptor pd = properties[i]; if (read) { methods.add(pd.getReadMethod()); } if (write) { methods.add(pd.getWriteMethod()); } } methods.remove(null); return (Method[]) methods.toArray(new Method[methods.size()]); } public static PropertyDescriptor[] getBeanProperties(Class type) { return getPropertiesHelper(type, true, true); } public static PropertyDescriptor[] getBeanGetters(Class type) { return getPropertiesHelper(type, true, false); } public static PropertyDescriptor[] getBeanSetters(Class type) { return getPropertiesHelper(type, false, true); } private static PropertyDescriptor[] getPropertiesHelper(Class type, boolean read, boolean write) { try { BeanInfo info = Introspector.getBeanInfo(type, Object.class); PropertyDescriptor[] all = info.getPropertyDescriptors(); if (read && write) { return all; } List properties = new ArrayList(all.length); for (int i = 0; i < all.length; i++) { PropertyDescriptor pd = all[i]; if ((read && pd.getReadMethod() != null) || (write && pd.getWriteMethod() != null)) { properties.add(pd); } } return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[properties.size()]); } catch (IntrospectionException e) { throw new ReflectException(e); } } public static Method findDeclaredMethod(final Class type, final String methodName, final Class[] parameterTypes) throws NoSuchMethodException { Class cl = type; while (cl != null) { try { return cl.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { cl = cl.getSuperclass(); } } throw new NoSuchMethodException(methodName); } public static List addAllMethods(final Class type, final List list) { if (type == Object.class) { list.addAll(OBJECT_METHODS); } else list.addAll(java.util.Arrays.asList(type.getDeclaredMethods())); Class superclass = type.getSuperclass(); if (superclass != null) { addAllMethods(superclass, list); } Class[] interfaces = type.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { addAllMethods(interfaces[i], list); } return list; } public static List addAllInterfaces(Class type, List list) { Class superclass = type.getSuperclass(); if (superclass != null) { list.addAll(Arrays.asList(type.getInterfaces())); addAllInterfaces(superclass, list); } return list; } public static Method findInterfaceMethod(Class iface) { if (!iface.isInterface()) { throw new IllegalArgumentException(iface + " is not an interface"); } Method[] methods = iface.getDeclaredMethods(); if (methods.length != 1) { throw new IllegalArgumentException("expecting exactly 1 method in " + iface); } return methods[0]; } // SPRING PATCH BEGIN public static Class defineClass(String className, byte[] b, ClassLoader loader) throws Exception { return defineClass(className, b, loader, null, null); } public static Class defineClass(String className, byte[] b, ClassLoader loader, ProtectionDomain protectionDomain) throws Exception { return defineClass(className, b, loader, protectionDomain, null); } public static Class defineClass(String className, byte[] b, ClassLoader loader, ProtectionDomain protectionDomain, Class<?> contextClass) throws Exception { Class c = null; // 在 jdk 17之后,需要hack方式来调用 #2659 if (c == null && classLoaderDefineClassMethod != null) { Lookup implLookup = UnsafeUtils.implLookup(); MethodHandle unreflect = implLookup.unreflect(classLoaderDefineClassMethod); if (protectionDomain == null) { protectionDomain = PROTECTION_DOMAIN; } try { c = (Class) unreflect.invoke(loader, className, b, 0, b.length, protectionDomain); } catch (InvocationTargetException ex) { throw new ReflectException(ex.getTargetException()); } catch (Throwable ex) { // Fall through if setAccessible fails with InaccessibleObjectException on JDK // 9+ // (on the module path and/or with a JVM bootstrapped with // --illegal-access=deny) if (!ex.getClass().getName().endsWith("InaccessibleObjectException")) { throw new ReflectException(ex); } } } // Preferred option: JDK 9+ Lookup.defineClass API if ClassLoader matches if (contextClass != null && contextClass.getClassLoader() == loader && privateLookupInMethod != null && lookupDefineClassMethod != null) { try { MethodHandles.Lookup lookup = (MethodHandles.Lookup) privateLookupInMethod.invoke(null, contextClass, MethodHandles.lookup()); c = (Class) lookupDefineClassMethod.invoke(lookup, b); } catch (InvocationTargetException ex) { Throwable target = ex.getTargetException(); if (target.getClass() != LinkageError.class && target.getClass() != IllegalArgumentException.class) { throw new ReflectException(target); } // in case of plain LinkageError (class already defined) // or IllegalArgumentException (class in different package): // fall through to traditional ClassLoader.defineClass below } catch (Throwable ex) { throw new ReflectException(ex); } } // Classic option: protected ClassLoader.defineClass method if (c == null && classLoaderDefineClassMethod != null) { if (protectionDomain == null) { protectionDomain = PROTECTION_DOMAIN; } Object[] args = new Object[] { className, b, 0, b.length, protectionDomain }; try { if (!classLoaderDefineClassMethod.isAccessible()) { classLoaderDefineClassMethod.setAccessible(true); } c = (Class) classLoaderDefineClassMethod.invoke(loader, args); } catch (InvocationTargetException ex) { throw new ReflectException(ex.getTargetException()); } catch (Throwable ex) { // Fall through if setAccessible fails with InaccessibleObjectException on JDK // 9+ // (on the module path and/or with a JVM bootstrapped with // --illegal-access=deny) if (!ex.getClass().getName().endsWith("InaccessibleObjectException")) { throw new ReflectException(ex); } } } // Fallback option: JDK 9+ Lookup.defineClass API even if ClassLoader does not // match if (c == null && contextClass != null && contextClass.getClassLoader() != loader && privateLookupInMethod != null && lookupDefineClassMethod != null) { try { MethodHandles.Lookup lookup = (MethodHandles.Lookup) privateLookupInMethod.invoke(null, contextClass, MethodHandles.lookup()); c = (Class) lookupDefineClassMethod.invoke(lookup, b); } catch (InvocationTargetException ex) { throw new ReflectException(ex.getTargetException()); } catch (Throwable ex) { throw new ReflectException(ex); } } // No defineClass variant available at all? if (c == null) { throw new ReflectException(THROWABLE); } // Force static initializers to run. Class.forName(className, true, loader); return c; } // SPRING PATCH END public static int findPackageProtected(Class[] classes) { for (int i = 0; i < classes.length; i++) { if (!Modifier.isPublic(classes[i].getModifiers())) { return i; } } return 0; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/OSUtils.java
common/src/main/java/com/taobao/arthas/common/OSUtils.java
package com.taobao.arthas.common; import java.io.File; import java.util.Locale; /** * * @author hengyunabc 2018-11-08 * */ public class OSUtils { private static final String OPERATING_SYSTEM_NAME = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); private static final String OPERATING_SYSTEM_ARCH = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); private static final String UNKNOWN = "unknown"; static PlatformEnum platform; static String arch; static { if (OPERATING_SYSTEM_NAME.startsWith("linux")) { platform = PlatformEnum.LINUX; } else if (OPERATING_SYSTEM_NAME.startsWith("mac") || OPERATING_SYSTEM_NAME.startsWith("darwin")) { platform = PlatformEnum.MACOSX; } else if (OPERATING_SYSTEM_NAME.startsWith("windows")) { platform = PlatformEnum.WINDOWS; } else { platform = PlatformEnum.UNKNOWN; } arch = normalizeArch(OPERATING_SYSTEM_ARCH); } private OSUtils() { } public static boolean isWindows() { return platform == PlatformEnum.WINDOWS; } public static boolean isLinux() { return platform == PlatformEnum.LINUX; } public static boolean isMac() { return platform == PlatformEnum.MACOSX; } public static boolean isCygwinOrMinGW() { if (isWindows()) { if ((System.getenv("MSYSTEM") != null && System.getenv("MSYSTEM").startsWith("MINGW")) || "/bin/bash".equals(System.getenv("SHELL"))) { return true; } } return false; } public static String arch() { return arch; } public static boolean isArm32() { return "arm_32".equals(arch); } public static boolean isArm64() { return "aarch_64".equals(arch); } public static boolean isX86() { return "x86_32".equals(arch); } public static boolean isX86_64() { return "x86_64".equals(arch); } private static String normalizeArch(String value) { value = normalize(value); if (value.matches("^(x8664|amd64|ia32e|em64t|x64)$")) { return "x86_64"; } if (value.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) { return "x86_32"; } if (value.matches("^(ia64w?|itanium64)$")) { return "itanium_64"; } if ("ia64n".equals(value)) { return "itanium_32"; } if (value.matches("^(sparc|sparc32)$")) { return "sparc_32"; } if (value.matches("^(sparcv9|sparc64)$")) { return "sparc_64"; } if (value.matches("^(arm|arm32)$")) { return "arm_32"; } if ("aarch64".equals(value)) { return "aarch_64"; } if (value.matches("^(mips|mips32)$")) { return "mips_32"; } if (value.matches("^(mipsel|mips32el)$")) { return "mipsel_32"; } if ("mips64".equals(value)) { return "mips_64"; } if ("mips64el".equals(value)) { return "mipsel_64"; } if (value.matches("^(ppc|ppc32)$")) { return "ppc_32"; } if (value.matches("^(ppcle|ppc32le)$")) { return "ppcle_32"; } if ("ppc64".equals(value)) { return "ppc_64"; } if ("ppc64le".equals(value)) { return "ppcle_64"; } if ("s390".equals(value)) { return "s390_32"; } if ("s390x".equals(value)) { return "s390_64"; } return value; } public static boolean isMuslLibc() { File ld_musl_x86_64_file = new File("/lib/ld-musl-x86_64.so.1"); File ld_musl_aarch64_file = new File("/lib/ld-musl-aarch64.so.1"); if(ld_musl_x86_64_file.exists() || ld_musl_aarch64_file.exists()){ return true; } return false; } private static String normalize(String value) { if (value == null) { return ""; } return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", ""); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/FileUtils.java
common/src/main/java/com/taobao/arthas/common/FileUtils.java
package com.taobao.arthas.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * * @see org.apache.commons.io.FileUtils * @author hengyunabc 2020-05-03 * */ public class FileUtils { public static File getTempDirectory() { return new File(System.getProperty("java.io.tmpdir")); } /** * Writes a byte array to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created if * they do not exist. * * @param file the file to write to * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 1.1 */ public static void writeByteArrayToFile(final File file, final byte[] data) throws IOException { writeByteArrayToFile(file, data, false); } /** * Writes a byte array to a file creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param append if {@code true}, then bytes will be added to the end of the * file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeByteArrayToFile(final File file, final byte[] data, final boolean append) throws IOException { writeByteArrayToFile(file, data, 0, data.length, append); } /** * Writes {@code len} bytes from the specified byte array starting at offset * {@code off} to a file, creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param off the start offset in the data * @param len the number of bytes to write * @throws IOException in case of an I/O error * @since 2.5 */ public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len) throws IOException { writeByteArrayToFile(file, data, off, len, false); } /** * Writes {@code len} bytes from the specified byte array starting at offset * {@code off} to a file, creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param off the start offset in the data * @param len the number of bytes to write * @param append if {@code true}, then bytes will be added to the end of the * file rather than overwriting * @throws IOException in case of an I/O error * @since 2.5 */ public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len, final boolean append) throws IOException { FileOutputStream out = null; try { out = openOutputStream(file, append); out.write(data, off, len); } finally { IOUtils.close(out); } } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * At the end of the method either the stream will be successfully opened, or an * exception will have been thrown. * <p> * The parent directory will be created if it does not exist. The file will be * created if it does not exist. An exception is thrown if the file object * exists but is a directory. An exception is thrown if the file exists but * cannot be written to. An exception is thrown if the parent directory cannot * be created. * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the end of the * file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws IOException if the file object is a directory * @throws IOException if the file cannot be written to * @throws IOException if a parent directory needs creating but that fails * @since 2.1 */ public static FileOutputStream openOutputStream(final File file, final boolean append) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (!file.canWrite()) { throw new IOException("File '" + file + "' cannot be written to"); } } else { final File parent = file.getParentFile(); if (parent != null) { if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory '" + parent + "' could not be created"); } } } return new FileOutputStream(file, append); } /** * Reads the contents of a file into a byte array. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws IOException in case of an I/O error * @since 1.1 */ public static byte[] readFileToByteArray(final File file) throws IOException { InputStream in = null; try { in = new FileInputStream(file); return IOUtils.getBytes(in); } finally { IOUtils.close(in); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/IOUtils.java
common/src/main/java/com/taobao/arthas/common/IOUtils.java
package com.taobao.arthas.common; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * * @author hengyunabc 2018-11-06 * */ public class IOUtils { private IOUtils() { } public static String toString(InputStream inputStream) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString("UTF-8"); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } /** * @return a byte[] containing the information contained in the specified * InputStream. * @throws java.io.IOException */ public static byte[] getBytes(InputStream input) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); copy(input, result); result.close(); return result.toByteArray(); } public static IOException close(InputStream input) { return close((Closeable) input); } public static IOException close(OutputStream output) { return close((Closeable) output); } public static IOException close(final Reader input) { return close((Closeable) input); } public static IOException close(final Writer output) { return close((Closeable) output); } public static IOException close(final Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (final IOException ioe) { return ioe; } return null; } // support jdk6 public static IOException close(final ZipFile zip) { try { if (zip != null) { zip.close(); } } catch (final IOException ioe) { return ioe; } return null; } public static boolean isSubFile(File parent, File child) throws IOException { return child.getCanonicalPath().startsWith(parent.getCanonicalPath() + File.separator); } public static boolean isSubFile(String parent, String child) throws IOException { return isSubFile(new File(parent), new File(child)); } public static void unzip(String zipFile, String extractFolder) throws IOException { File file = new File(zipFile); ZipFile zip = null; try { int BUFFER = 1024 * 8; zip = new ZipFile(file); File newPath = new File(extractFolder); newPath.mkdirs(); Enumeration<? extends ZipEntry> zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); if (!isSubFile(newPath, destFile)) { throw new IOException("Bad zip entry: " + currentEntry); } // destFile = new File(newPath, destFile.getName()); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = null; BufferedOutputStream dest = null; try { is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); } finally { close(dest); close(is); } } } } finally { close(zip); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/PidUtils.java
common/src/main/java/com/taobao/arthas/common/PidUtils.java
package com.taobao.arthas.common; import java.lang.management.ManagementFactory; /** * * @author hengyunabc 2019-02-16 * */ public class PidUtils { private static String PID = "-1"; private static long pid = -1; private static String MAIN_CLASS = ""; static { // https://stackoverflow.com/a/7690178 try { String jvmName = ManagementFactory.getRuntimeMXBean().getName(); int index = jvmName.indexOf('@'); if (index > 0) { PID = Long.toString(Long.parseLong(jvmName.substring(0, index))); pid = Long.parseLong(PID); } } catch (Throwable e) { // ignore } try { MAIN_CLASS = System.getProperty("sun.java.command", ""); } catch (Throwable e) { // ignore } } private PidUtils() { } public static String currentPid() { return PID; } public static long currentLongPid() { return pid; } public static String mainClass() { return MAIN_CLASS; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/UnsafeUtils.java
common/src/main/java/com/taobao/arthas/common/UnsafeUtils.java
package com.taobao.arthas.common; import java.lang.invoke.MethodHandles; import java.lang.reflect.Field; import sun.misc.Unsafe; /** * * @author hengyunabc 2023-09-21 * */ public class UnsafeUtils { public static final Unsafe UNSAFE; private static MethodHandles.Lookup IMPL_LOOKUP; static { Unsafe unsafe = null; try { Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeField.setAccessible(true); unsafe = (Unsafe) theUnsafeField.get(null); } catch (Throwable ignored) { // ignored } UNSAFE = unsafe; } public static MethodHandles.Lookup implLookup() { if (IMPL_LOOKUP == null) { Class<MethodHandles.Lookup> lookupClass = MethodHandles.Lookup.class; try { Field implLookupField = lookupClass.getDeclaredField("IMPL_LOOKUP"); long offset = UNSAFE.staticFieldOffset(implLookupField); IMPL_LOOKUP = (MethodHandles.Lookup) UNSAFE.getObject(UNSAFE.staticFieldBase(implLookupField), offset); } catch (Throwable e) { // ignored } } return IMPL_LOOKUP; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/JavaVersionUtils.java
common/src/main/java/com/taobao/arthas/common/JavaVersionUtils.java
package com.taobao.arthas.common; import java.util.Properties; /** * * @author hengyunabc 2018-11-21 * */ public class JavaVersionUtils { private static final String VERSION_PROP_NAME = "java.specification.version"; private static final String JAVA_VERSION_STR = System.getProperty(VERSION_PROP_NAME); private static final float JAVA_VERSION = Float.parseFloat(JAVA_VERSION_STR); private JavaVersionUtils() { } public static String javaVersionStr() { return JAVA_VERSION_STR; } public static String javaVersionStr(Properties props) { return (null != props) ? props.getProperty(VERSION_PROP_NAME): null; } public static float javaVersion() { return JAVA_VERSION; } public static boolean isJava6() { return "1.6".equals(JAVA_VERSION_STR); } public static boolean isJava7() { return "1.7".equals(JAVA_VERSION_STR); } public static boolean isJava8() { return "1.8".equals(JAVA_VERSION_STR); } public static boolean isJava9() { return "9".equals(JAVA_VERSION_STR); } public static boolean isLessThanJava9() { return JAVA_VERSION < 9.0f; } public static boolean isGreaterThanJava7() { return JAVA_VERSION > 1.7f; } public static boolean isGreaterThanJava8() { return JAVA_VERSION > 1.8f; } public static boolean isGreaterThanJava11() { return JAVA_VERSION > 11.0f; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/PlatformEnum.java
common/src/main/java/com/taobao/arthas/common/PlatformEnum.java
package com.taobao.arthas.common; /** * Enum of supported operating systems. * */ public enum PlatformEnum { /** * Microsoft Windows */ WINDOWS, /** * A flavor of Linux */ LINUX, /** * macOS (OS X) */ MACOSX, UNKNOWN }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/VmToolUtils.java
common/src/main/java/com/taobao/arthas/common/VmToolUtils.java
package com.taobao.arthas.common; /** * * @author hengyunabc 2021-04-27 * */ public class VmToolUtils { private static String libName = null; static { if (OSUtils.isMac()) { libName = "libArthasJniLibrary.dylib"; } if (OSUtils.isLinux()) { if (OSUtils.isArm32()) { libName = "libArthasJniLibrary-arm.so"; } else if (OSUtils.isArm64()) { libName = "libArthasJniLibrary-aarch64.so"; } else if (OSUtils.isX86_64()) { libName = "libArthasJniLibrary-x64.so"; }else { libName = "libArthasJniLibrary-" + OSUtils.arch() + ".so"; } } if (OSUtils.isWindows()) { libName = "libArthasJniLibrary-x64.dll"; if (OSUtils.isX86()) { libName = "libArthasJniLibrary-x86.dll"; } } } public static String detectLibName() { return libName; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/Pair.java
common/src/main/java/com/taobao/arthas/common/Pair.java
package com.taobao.arthas.common; public class Pair<X, Y> { private final X x; private final Y y; public Pair(X x, Y y) { this.x = x; this.y = y; } public X getFirst() { return x; } public Y getSecond() { return y; } public static <A, B> Pair<A, B> make(A a, B b) { return new Pair<A, B>(a, b); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; Pair other = (Pair) o; if (x == null) { if (other.x != null) return false; } else { if (!x.equals(other.x)) return false; } if (y == null) { if (other.y != null) return false; } else { if (!y.equals(other.y)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; if (x != null) hashCode = x.hashCode(); if (y != null) hashCode = (hashCode * 31) + y.hashCode(); return hashCode; } @Override public String toString() { return "P[" + x + "," + y + "]"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/UsageRender.java
common/src/main/java/com/taobao/arthas/common/UsageRender.java
package com.taobao.arthas.common; /** * * @author hengyunabc 2018-11-22 * */ public class UsageRender { private UsageRender() { } public static String render(String usage) { if (AnsiLog.enableColor()) { StringBuilder sb = new StringBuilder(1024); String lines[] = usage.split("\\r?\\n"); for (String line : lines) { if (line.startsWith("Usage: ")) { sb.append(AnsiLog.green("Usage: ")); sb.append(line.substring("Usage: ".length())); } else if (!line.startsWith(" ") && line.endsWith(":")) { sb.append(AnsiLog.green(line)); } else { sb.append(line); } sb.append('\n'); } return sb.toString(); } else { return usage; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/SocketUtils.java
common/src/main/java/com/taobao/arthas/common/SocketUtils.java
package com.taobao.arthas.common; import java.net.InetAddress; import java.net.ServerSocket; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.net.ServerSocketFactory; /** * * @author hengyunabc 2018-11-07 * */ public class SocketUtils { /** * The default minimum value for port ranges used when finding an available * socket port. */ public static final int PORT_RANGE_MIN = 1024; /** * The default maximum value for port ranges used when finding an available * socket port. */ public static final int PORT_RANGE_MAX = 65535; private static final Random random = new Random(System.currentTimeMillis()); private SocketUtils() { } public static long findTcpListenProcess(int port) { // Add a timeout of 5 seconds to prevent blocking final int TIMEOUT_SECONDS = 5; ExecutorService executor = Executors.newSingleThreadExecutor(); try { Future<Long> future = executor.submit(new Callable<Long>() { @Override public Long call() throws Exception { return doFindTcpListenProcess(port); } }); try { return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (TimeoutException e) { future.cancel(true); return -1; } catch (Exception e) { return -1; } } finally { executor.shutdownNow(); } } private static long doFindTcpListenProcess(int port) { try { if (OSUtils.isWindows()) { return findTcpListenProcessOnWindows(port); } if (OSUtils.isLinux() || OSUtils.isMac()) { return findTcpListenProcessOnUnix(port); } } catch (Throwable e) { // ignore } return -1; } private static long findTcpListenProcessOnWindows(int port) { String[] command = { "netstat", "-ano", "-p", "TCP" }; List<String> lines = ExecutingCommand.runNative(command); for (String line : lines) { if (line.contains("LISTENING")) { // TCP 0.0.0.0:49168 0.0.0.0:0 LISTENING 476 String[] strings = line.trim().split("\\s+"); if (strings.length == 5) { if (strings[1].endsWith(":" + port)) { return Long.parseLong(strings[4]); } } } } return -1; } private static long findTcpListenProcessOnUnix(int port) { String pid = ExecutingCommand.getFirstAnswer("lsof -t -s TCP:LISTEN -i TCP:" + port); if (pid != null && !pid.trim().isEmpty()) { try { return Long.parseLong(pid.trim()); } catch (NumberFormatException e) { // ignore } } return -1; } public static boolean isTcpPortAvailable(int port) { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName("localhost")); serverSocket.close(); return true; } catch (Exception ex) { return false; } } /** * Find an available TCP port randomly selected from the range * [{@value #PORT_RANGE_MIN}, {@value #PORT_RANGE_MAX}]. * * @return an available TCP port number * @throws IllegalStateException if no available port could be found */ public static int findAvailableTcpPort() { return findAvailableTcpPort(PORT_RANGE_MIN); } /** * Find an available TCP port randomly selected from the range [{@code minPort}, * {@value #PORT_RANGE_MAX}]. * * @param minPort the minimum port number * @return an available TCP port number * @throws IllegalStateException if no available port could be found */ public static int findAvailableTcpPort(int minPort) { return findAvailableTcpPort(minPort, PORT_RANGE_MAX); } /** * Find an available TCP port randomly selected from the range [{@code minPort}, * {@code maxPort}]. * * @param minPort the minimum port number * @param maxPort the maximum port number * @return an available TCP port number * @throws IllegalStateException if no available port could be found */ public static int findAvailableTcpPort(int minPort, int maxPort) { return findAvailablePort(minPort, maxPort); } /** * Find an available port for this {@code SocketType}, randomly selected from * the range [{@code minPort}, {@code maxPort}]. * * @param minPort the minimum port number * @param maxPort the maximum port number * @return an available port number for this socket type * @throws IllegalStateException if no available port could be found */ private static int findAvailablePort(int minPort, int maxPort) { int portRange = maxPort - minPort; int candidatePort; int searchCounter = 0; do { if (searchCounter > portRange) { throw new IllegalStateException( String.format("Could not find an available tcp port in the range [%d, %d] after %d attempts", minPort, maxPort, searchCounter)); } candidatePort = findRandomPort(minPort, maxPort); searchCounter++; } while (!isTcpPortAvailable(candidatePort)); return candidatePort; } /** * Find a pseudo-random port number within the range [{@code minPort}, * {@code maxPort}]. * * @param minPort the minimum port number * @param maxPort the maximum port number * @return a random port number within the specified range */ private static int findRandomPort(int minPort, int maxPort) { int portRange = maxPort - minPort; return minPort + random.nextInt(portRange + 1); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/AnsiLog.java
common/src/main/java/com/taobao/arthas/common/AnsiLog.java
package com.taobao.arthas.common; import java.util.logging.Level; import java.util.regex.Matcher; /** * * <pre> * FINEST -> TRACE * FINER -> DEBUG * FINE -> DEBUG * CONFIG -> INFO * INFO -> INFO * WARNING -> WARN * SEVERE -> ERROR * </pre> * * @see org.slf4j.bridge.SLF4JBridgeHandler * @author hengyunabc 2017-05-03 * */ public abstract class AnsiLog { static boolean enableColor; public static java.util.logging.Level LEVEL = java.util.logging.Level.CONFIG; private static final String RESET = "\033[0m"; private static final int DEFAULT = 39; private static final int BLACK = 30; private static final int RED = 31; private static final int GREEN = 32; private static final int YELLOW = 33; private static final int BLUE = 34; private static final int MAGENTA = 35; private static final int CYAN = 36; private static final int WHITE = 37; private static final String TRACE_PREFIX = "[TRACE] "; private static final String TRACE_COLOR_PREFIX = "[" + colorStr("TRACE", GREEN) + "] "; private static final String DEBUG_PREFIX = "[DEBUG] "; private static final String DEBUG_COLOR_PREFIX = "[" + colorStr("DEBUG", GREEN) + "] "; private static final String INFO_PREFIX = "[INFO] "; private static final String INFO_COLOR_PREFIX = "[" + colorStr("INFO", GREEN) + "] "; private static final String WARN_PREFIX = "[WARN] "; private static final String WARN_COLOR_PREFIX = "[" + colorStr("WARN", YELLOW) + "] "; private static final String ERROR_PREFIX = "[ERROR] "; private static final String ERROR_COLOR_PREFIX = "[" + colorStr("ERROR", RED) + "] "; static { try { if (System.console() != null) { enableColor = true; // windows dos, do not support color if (OSUtils.isWindows()) { enableColor = false; } } // cygwin and mingw support color if (OSUtils.isCygwinOrMinGW()) { enableColor = true; } } catch (Throwable t) { // ignore } } private AnsiLog() { } public static boolean enableColor() { return enableColor; } /** * set logger Level * * @see java.util.logging.Level * @param level * @return */ public static Level level(Level level) { Level old = LEVEL; LEVEL = level; return old; } /** * get current logger Level * * @return */ public static Level level() { return LEVEL; } public static String black(String msg) { if (enableColor) { return colorStr(msg, BLACK); } else { return msg; } } public static String red(String msg) { if (enableColor) { return colorStr(msg, RED); } else { return msg; } } public static String green(String msg) { if (enableColor) { return colorStr(msg, GREEN); } else { return msg; } } public static String yellow(String msg) { if (enableColor) { return colorStr(msg, YELLOW); } else { return msg; } } public static String blue(String msg) { if (enableColor) { return colorStr(msg, BLUE); } else { return msg; } } public static String magenta(String msg) { if (enableColor) { return colorStr(msg, MAGENTA); } else { return msg; } } public static String cyan(String msg) { if (enableColor) { return colorStr(msg, CYAN); } else { return msg; } } public static String white(String msg) { if (enableColor) { return colorStr(msg, WHITE); } else { return msg; } } private static String colorStr(String msg, int colorCode) { return "\033[" + colorCode + "m" + msg + RESET; } public static void trace(String msg) { if (canLog(Level.FINEST)) { if (enableColor) { System.out.println(TRACE_COLOR_PREFIX + msg); } else { System.out.println(TRACE_PREFIX + msg); } } } public static void trace(String format, Object... arguments) { if (canLog(Level.FINEST)) { trace(format(format, arguments)); } } public static void trace(Throwable t) { if (canLog(Level.FINEST)) { t.printStackTrace(System.out); } } public static void debug(String msg) { if (canLog(Level.FINER)) { if (enableColor) { System.out.println(DEBUG_COLOR_PREFIX + msg); } else { System.out.println(DEBUG_PREFIX + msg); } } } public static void debug(String format, Object... arguments) { if (canLog(Level.FINER)) { debug(format(format, arguments)); } } public static void debug(Throwable t) { if (canLog(Level.FINER)) { t.printStackTrace(System.out); } } public static void info(String msg) { if (canLog(Level.CONFIG)) { if (enableColor) { System.out.println(INFO_COLOR_PREFIX + msg); } else { System.out.println(INFO_PREFIX + msg); } } } public static void info(String format, Object... arguments) { if (canLog(Level.CONFIG)) { info(format(format, arguments)); } } public static void info(Throwable t) { if (canLog(Level.CONFIG)) { t.printStackTrace(System.out); } } public static void warn(String msg) { if (canLog(Level.WARNING)) { if (enableColor) { System.out.println(WARN_COLOR_PREFIX + msg); } else { System.out.println(WARN_PREFIX + msg); } } } public static void warn(String format, Object... arguments) { if (canLog(Level.WARNING)) { warn(format(format, arguments)); } } public static void warn(Throwable t) { if (canLog(Level.WARNING)) { t.printStackTrace(System.out); } } public static void error(String msg) { if (canLog(Level.SEVERE)) { if (enableColor) { System.out.println(ERROR_COLOR_PREFIX + msg); } else { System.out.println(ERROR_PREFIX + msg); } } } public static void error(String format, Object... arguments) { if (canLog(Level.SEVERE)) { error(format(format, arguments)); } } public static void error(Throwable t) { if (canLog(Level.SEVERE)) { t.printStackTrace(System.out); } } private static String format(String from, Object... arguments) { if (from != null) { String computed = from; if (arguments != null && arguments.length != 0) { for (Object argument : arguments) { computed = computed.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(argument))); } } return computed; } return null; } private static boolean canLog(Level level) { return level.intValue() >= LEVEL.intValue(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/ReflectException.java
common/src/main/java/com/taobao/arthas/common/ReflectException.java
package com.taobao.arthas.common; public class ReflectException extends RuntimeException { private static final long serialVersionUID = 1L; private Throwable cause; public ReflectException(Throwable cause) { super(cause != null ? cause.getClass().getName() + "-->" + cause.getMessage() : ""); this.cause = cause; } public Throwable getCause() { return this.cause; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
/* * Copyright 2012 The Netty Project * * The Netty Project 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. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package com.taobao.arthas.common.concurrent; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; /** * An alternative weak-key {@link ConcurrentMap} which is similar to * {@link ConcurrentHashMap}. * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values */ public final class ConcurrentWeakKeyHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> { /* * The basic strategy is to subdivide the table among Segments, * each of which itself is a concurrently readable hash table. */ /** * The default initial capacity for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The default load factor for this table, used when not otherwise specified * in a constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The default concurrency level for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * The maximum capacity, used if a higher value is implicitly specified by * either of the constructors with arguments. MUST be a power of two * &lt;= 1&lt;&lt;30 to ensure that entries are indexable using integers. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The maximum number of segments to allow; used to bound constructor * arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** * Number of unsynchronized retries in size and containsValue methods before * resorting to locking. This is used to avoid unbounded retries if tables * undergo continuous modification which would make it impossible to obtain * an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** * Mask value for indexing into segments. The upper bits of a key's hash * code are used to choose the segment. */ final int segmentMask; /** * Shift value for indexing within segments. */ final int segmentShift; /** * The segments, each of which is a specialized hash table */ final Segment<K, V>[] segments; Set<K> keySet; Set<Map.Entry<K, V>> entrySet; Collection<V> values; /* ---------------- Small Utilities -------------- */ /** * Applies a supplemental hash function to a given hashCode, which defends * against poor quality hash functions. This is critical because * ConcurrentReferenceHashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ in lower * or upper bits. */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += h << 15 ^ 0xffffcd7d; h ^= h >>> 10; h += h << 3; h ^= h >>> 6; h += (h << 2) + (h << 14); return h ^ h >>> 16; } /** * Returns the segment that should be used for key with given hash. * * @param hash the hash code for the key * @return the segment */ Segment<K, V> segmentFor(int hash) { return segments[hash >>> segmentShift & segmentMask]; } private static int hashOf(Object key) { return hash(key.hashCode()); } /* ---------------- Inner Classes -------------- */ /** * A weak-key reference which stores the key hash needed for reclamation. */ static final class WeakKeyReference<K> extends WeakReference<K> { final int hash; WeakKeyReference(K key, int hash, ReferenceQueue<Object> refQueue) { super(key, refQueue); this.hash = hash; } public int keyHash() { return hash; } public Object keyRef() { return this; } } /** * ConcurrentReferenceHashMap list entry. Note that this is never exported * out as a user-visible Map.Entry. * * Because the value field is volatile, not final, it is legal wrt * the Java Memory Model for an unsynchronized reader to see null * instead of initial value when read via a data race. Although a * reordering leading to this is not likely to ever actually * occur, the Segment.readValueUnderLock method is used as a * backup in case a null (pre-initialized) value is ever seen in * an unsynchronized access method. */ static final class HashEntry<K, V> { final Object keyRef; final int hash; volatile Object valueRef; final HashEntry<K, V> next; HashEntry( K key, int hash, HashEntry<K, V> next, V value, ReferenceQueue<Object> refQueue) { this.hash = hash; this.next = next; keyRef = new WeakKeyReference<K>(key, hash, refQueue); valueRef = value; } @SuppressWarnings("unchecked") K key() { return ((Reference<K>) keyRef).get(); } V value() { return dereferenceValue(valueRef); } @SuppressWarnings("unchecked") V dereferenceValue(Object value) { if (value instanceof WeakKeyReference) { return ((Reference<V>) value).get(); } return (V) value; } void setValue(V value) { valueRef = value; } @SuppressWarnings("unchecked") static <K, V> HashEntry<K, V>[] newArray(int i) { return new HashEntry[i]; } } /** * Segments are specialized versions of hash tables. This subclasses from * ReentrantLock opportunistically, just to simplify some locking and avoid * separate construction. */ static final class Segment<K, V> extends ReentrantLock { /* * Segments maintain a table of entry lists that are ALWAYS kept in a * consistent state, so can be read without locking. Next fields of * nodes are immutable (final). All list additions are performed at the * front of each bin. This makes it easy to check changes, and also fast * to traverse. When nodes would otherwise be changed, new nodes are * created to replace them. This works well for hash tables since the * bin lists tend to be short. (The average length is less than two for * the default load factor threshold.) * * Read operations can thus proceed without locking, but rely on * selected uses of volatiles to ensure that completed write operations * performed by other threads are noticed. For most purposes, the * "count" field, tracking the number of elements, serves as that * volatile variable ensuring visibility. This is convenient because * this field needs to be read in many read operations anyway: * * - All (unsynchronized) read operations must first read the * "count" field, and should not look at table entries if * it is 0. * * - All (synchronized) write operations should write to * the "count" field after structurally changing any bin. * The operations must not take any action that could even * momentarily cause a concurrent read operation to see * inconsistent data. This is made easier by the nature of * the read operations in Map. For example, no operation * can reveal that the table has grown but the threshold * has not yet been updated, so there are no atomicity * requirements for this with respect to reads. * * As a guide, all critical volatile reads and writes to the count field * are marked in code comments. */ private static final long serialVersionUID = -8328104880676891126L; /** * The number of elements in this segment's region. */ transient volatile int count; /** * Number of updates that alter the size of the table. This is used * during bulk-read methods to make sure they see a consistent snapshot: * If modCounts change during a traversal of segments computing size or * checking containsValue, then we might have an inconsistent view of * state so (usually) must retry. */ int modCount; /** * The table is rehashed when its size exceeds this threshold. * (The value of this field is always <tt>(capacity * loadFactor)</tt>.) */ int threshold; /** * The per-segment table. */ transient volatile HashEntry<K, V>[] table; /** * The load factor for the hash table. Even though this value is same * for all segments, it is replicated to avoid needing links to outer * object. */ final float loadFactor; /** * The collected weak-key reference queue for this segment. This should * be (re)initialized whenever table is assigned, */ transient volatile ReferenceQueue<Object> refQueue; Segment(int initialCapacity, float lf) { loadFactor = lf; setTable(HashEntry.<K, V>newArray(initialCapacity)); } @SuppressWarnings("unchecked") static <K, V> Segment<K, V>[] newArray(int i) { return new Segment[i]; } private static boolean keyEq(Object src, Object dest) { return src.equals(dest); } /** * Sets table to new HashEntry array. Call only while holding lock or in * constructor. */ void setTable(HashEntry<K, V>[] newTable) { threshold = (int) (newTable.length * loadFactor); table = newTable; refQueue = new ReferenceQueue<Object>(); } /** * Returns properly casted first entry of bin for given hash. */ HashEntry<K, V> getFirst(int hash) { HashEntry<K, V>[] tab = table; return tab[hash & tab.length - 1]; } HashEntry<K, V> newHashEntry( K key, int hash, HashEntry<K, V> next, V value) { return new HashEntry<K, V>( key, hash, next, value, refQueue); } /** * Reads value field of an entry under lock. Called if value field ever * appears to be null. This is possible only if a compiler happens to * reorder a HashEntry initialization with its table assignment, which * is legal under memory model but is not known to ever occur. */ V readValueUnderLock(HashEntry<K, V> e) { lock(); try { removeStale(); return e.value(); } finally { unlock(); } } /* Specialized implementations of map methods */ V get(Object key, int hash) { if (count != 0) { // read-volatile HashEntry<K, V> e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { Object opaque = e.valueRef; if (opaque != null) { return e.dereferenceValue(opaque); } return readValueUnderLock(e); // recheck } e = e.next; } } return null; } boolean containsKey(Object key, int hash) { if (count != 0) { // read-volatile HashEntry<K, V> e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { return true; } e = e.next; } } return false; } boolean containsValue(Object value) { if (count != 0) { // read-volatile for (HashEntry<K, V> e: table) { for (; e != null; e = e.next) { Object opaque = e.valueRef; V v; if (opaque == null) { v = readValueUnderLock(e); // recheck } else { v = e.dereferenceValue(opaque); } if (value.equals(v)) { return true; } } } } return false; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { removeStale(); HashEntry<K, V> e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } boolean replaced = false; if (e != null && oldValue.equals(e.value())) { replaced = true; e.setValue(newValue); } return replaced; } finally { unlock(); } } V replace(K key, int hash, V newValue) { lock(); try { removeStale(); HashEntry<K, V> e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { oldValue = e.value(); e.setValue(newValue); } return oldValue; } finally { unlock(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { removeStale(); int c = count; if (c ++ > threshold) { // ensure capacity int reduced = rehash(); if (reduced > 0) { count = (c -= reduced) - 1; // write-volatile } } HashEntry<K, V>[] tab = table; int index = hash & tab.length - 1; HashEntry<K, V> first = tab[index]; HashEntry<K, V> e = first; while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue; if (e != null) { oldValue = e.value(); if (!onlyIfAbsent) { e.setValue(value); } } else { oldValue = null; ++ modCount; tab[index] = newHashEntry(key, hash, first, value); count = c; // write-volatile } return oldValue; } finally { unlock(); } } int rehash() { HashEntry<K, V>[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) { return 0; } /* * Reclassify nodes in each list to new Map. Because we are using * power-of-two expansion, the elements from each bin must either * stay at same index, or move with a power of two offset. We * eliminate unnecessary node creation by catching cases where old * nodes can be reused because their next fields won't change. * Statistically, at the default threshold, only about one-sixth of * them need cloning when a table doubles. The nodes they replace * will be garbage collectable as soon as they are no longer * referenced by any reader thread that may be in the midst of * traversing table right now. */ HashEntry<K, V>[] newTable = HashEntry.newArray(oldCapacity << 1); threshold = (int) (newTable.length * loadFactor); int sizeMask = newTable.length - 1; int reduce = 0; for (HashEntry<K, V> e: oldTable) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. if (e != null) { HashEntry<K, V> next = e.next; int idx = e.hash & sizeMask; // Single node on list if (next == null) { newTable[idx] = e; } else { // Reuse trailing consecutive sequence at same slot HashEntry<K, V> lastRun = e; int lastIdx = idx; for (HashEntry<K, V> last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (HashEntry<K, V> p = e; p != lastRun; p = p.next) { // Skip GC'd weak references K key = p.key(); if (key == null) { reduce++; continue; } int k = p.hash & sizeMask; HashEntry<K, V> n = newTable[k]; newTable[k] = newHashEntry(key, p.hash, n, p.value()); } } } } table = newTable; return reduce; } /** * Remove; match on key only if value null, else match both. */ V remove(Object key, int hash, Object value, boolean refRemove) { lock(); try { if (!refRemove) { removeStale(); } int c = count - 1; HashEntry<K, V>[] tab = table; int index = hash & tab.length - 1; HashEntry<K, V> first = tab[index]; HashEntry<K, V> e = first; // a reference remove operation compares the Reference instance while (e != null && key != e.keyRef && (refRemove || hash != e.hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { V v = e.value(); if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay in list, // but all preceding ones need to be cloned. ++ modCount; HashEntry<K, V> newFirst = e.next; for (HashEntry<K, V> p = first; p != e; p = p.next) { K pKey = p.key(); if (pKey == null) { // Skip GC'd keys c --; continue; } newFirst = newHashEntry( pKey, p.hash, newFirst, p.value()); } tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } } @SuppressWarnings("rawtypes") void removeStale() { WeakKeyReference ref; while ((ref = (WeakKeyReference) refQueue.poll()) != null) { remove(ref.keyRef(), ref.keyHash(), null, true); } } void clear() { if (count != 0) { lock(); try { Arrays.fill(table, null); ++ modCount; // replace the reference queue to avoid unnecessary stale // cleanups refQueue = new ReferenceQueue<Object>(); count = 0; // write-volatile } finally { unlock(); } } } } /* ---------------- Public operations -------------- */ /** * Creates a new, empty map with the specified initial capacity, load factor * and concurrency level. * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently updating * threads. The implementation performs internal * sizing to try to accommodate this many threads. * @throws IllegalArgumentException if the initial capacity is negative or * the load factor or concurrencyLevel are * nonpositive. */ public ConcurrentWeakKeyHashMap( int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) { throw new IllegalArgumentException(); } if (concurrencyLevel > MAX_SEGMENTS) { concurrencyLevel = MAX_SEGMENTS; } // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; while (ssize < concurrencyLevel) { ++ sshift; ssize <<= 1; } segmentShift = 32 - sshift; segmentMask = ssize - 1; segments = Segment.newArray(ssize); if (initialCapacity > MAXIMUM_CAPACITY) { initialCapacity = MAXIMUM_CAPACITY; } int c = initialCapacity / ssize; if (c * ssize < initialCapacity) { ++ c; } int cap = 1; while (cap < c) { cap <<= 1; } for (int i = 0; i < segments.length; ++ i) { segments[i] = new Segment<K, V>(cap, loadFactor); } } /** * Creates a new, empty map with the specified initial capacity and load * factor and with the default reference types (weak keys, strong values), * and concurrencyLevel (16). * * @param initialCapacity The implementation performs internal sizing to * accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @throws IllegalArgumentException if the initial capacity of elements is * negative or the load factor is * nonpositive */ public ConcurrentWeakKeyHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with the specified initial capacity, and with * default reference types (weak keys, strong values), load factor (0.75) * and concurrencyLevel (16). * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @throws IllegalArgumentException if the initial capacity of elements is * negative. */ public ConcurrentWeakKeyHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with a default initial capacity (16), reference * types (weak keys, strong values), default load factor (0.75) and * concurrencyLevel (16). */ public ConcurrentWeakKeyHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new map with the same mappings as the given map. The map is * created with a capacity of 1.5 times the number of mappings in the given * map or 16 (whichever is greater), and a default load factor (0.75) and * concurrencyLevel (16). * * @param m the map */ public ConcurrentWeakKeyHashMap(Map<? extends K, ? extends V> m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); putAll(m); } /** * Returns <tt>true</tt> if this map contains no key-value mappings. * * @return <tt>true</tt> if this map contains no key-value mappings */ @Override public boolean isEmpty() { final Segment<K, V>[] segments = this.segments; /* * We keep track of per-segment modCounts to avoid ABA problems in which * an element in one segment was added and in another removed during * traversal, in which case the table was never actually empty at any * point. Note the similar use of modCounts in the size() and * containsValue() methods, which are the only other methods also * susceptible to ABA problems. */ int[] mc = new int[segments.length]; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0) { return false; } else { mcsum += mc[i] = segments[i].modCount; } } // If mcsum happens to be zero, then we know we got a snapshot before // any modifications at all were made. This is probably common enough // to bother tracking. if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0 || mc[i] != segments[i].modCount) { return false; } } } return true; } /** * Returns the number of key-value mappings in this map. If the map contains * more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * * @return the number of key-value mappings in this map */ @Override public int size() { final Segment<K, V>[] segments = this.segments; long sum = 0; long check = 0; int[] mc = new int[segments.length]; // Try a few times to get accurate count. On failure due to continuous // async changes in table, resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { check = 0; sum = 0; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; mcsum += mc[i] = segments[i].modCount; } if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { check += segments[i].count; if (mc[i] != segments[i].modCount) { check = -1; // force retry break; } } } if (check == sum) { break; } } if (check != sum) { // Resort to locking all segments sum = 0; for (Segment<K, V> segment: segments) { segment.lock(); } for (Segment<K, V> segment: segments) { sum += segment.count; } for (Segment<K, V> segment: segments) { segment.unlock(); } } if (sum > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) sum; } } /** * Returns the value to which the specified key is mapped, or {@code null} * if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key {@code k} to * a value {@code v} such that {@code key.equals(k)}, then this method * returns {@code v}; otherwise it returns {@code null}. (There can be at * most one such mapping.) * * @throws NullPointerException if the specified key is null */ @Override public V get(Object key) { int hash = hashOf(key); return segmentFor(hash).get(key, hash); } /** * Tests if the specified object is a key in this table. * * @param key possible key * @return <tt>true</tt> if and only if the specified object is a key in * this table, as determined by the <tt>equals</tt> method; * <tt>false</tt> otherwise. * @throws NullPointerException if the specified key is null */ @Override public boolean containsKey(Object key) { int hash = hashOf(key); return segmentFor(hash).containsKey(key, hash); } /** * Returns <tt>true</tt> if this map maps one or more keys to the specified * value. Note: This method requires a full internal traversal of the hash * table, and so is much slower than method <tt>containsKey</tt>. * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the specified * value * @throws NullPointerException if the specified value is null */ @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } // See explanation of modCount use above final Segment<K, V>[] segments = this.segments; int[] mc = new int[segments.length]; // Try a few times without locking for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { mcsum += mc[i] = segments[i].modCount; if (segments[i].containsValue(value)) { return true; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
true
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/common/src/main/java/com/taobao/arthas/common/concurrent/ReusableIterator.java
common/src/main/java/com/taobao/arthas/common/concurrent/ReusableIterator.java
/* * Copyright 2012 The Netty Project * * The Netty Project 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 com.taobao.arthas.common.concurrent; import java.util.Iterator; public interface ReusableIterator<E> extends Iterator<E> { void rewind(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/spy/src/main/java/java/arthas/SpyAPI.java
spy/src/main/java/java/arthas/SpyAPI.java
package java.arthas; /** * <pre> * 一个adviceId 是什么呢? 就是一个trace/monitor/watch命令能对应上的一个id,比如一个类某个函数,它的 enter/end/exception 统一是一个id,分配完了就不会再分配。 * * 同样一个method,如果它trace之后,也会有一个 adviceId, 这个method里的所有invoke都是统一处理,认为是一个 adviceId 。 但如果有匹配到不同的 invoke的怎么分配?? * 好像有点难了。。 * * 其实就是把所有可以插入的地方都分类好,那么怎么分类呢?? 或者是叫同一种匹配,就是同一种的 adviceId? * * 比如入参是有 class , method ,是固定的 , 某个行号,或者 某个 * * aop插入的叫 adviceId , command插入的叫 ListenerId? * * * * </pre> * * @author hengyunabc * */ public class SpyAPI { public static final AbstractSpy NOPSPY = new NopSpy(); private static volatile AbstractSpy spyInstance = NOPSPY; public static volatile boolean INITED; public static AbstractSpy getSpy() { return spyInstance; } public static void setSpy(AbstractSpy spy) { spyInstance = spy; } public static void setNopSpy() { setSpy(NOPSPY); } public static boolean isNopSpy() { return NOPSPY == spyInstance; } public static void init() { INITED = true; } public static boolean isInited() { return INITED; } public static void destroy() { setNopSpy(); INITED = false; } public static void atEnter(Class<?> clazz, String methodInfo, Object target, Object[] args) { spyInstance.atEnter(clazz, methodInfo, target, args); } public static void atExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Object returnObject) { spyInstance.atExit(clazz, methodInfo, target, args, returnObject); } public static void atExceptionExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Throwable throwable) { spyInstance.atExceptionExit(clazz, methodInfo, target, args, throwable); } public static void atBeforeInvoke(Class<?> clazz, String invokeInfo, Object target) { spyInstance.atBeforeInvoke(clazz, invokeInfo, target); } public static void atAfterInvoke(Class<?> clazz, String invokeInfo, Object target) { spyInstance.atAfterInvoke(clazz, invokeInfo, target); } public static void atInvokeException(Class<?> clazz, String invokeInfo, Object target, Throwable throwable) { spyInstance.atInvokeException(clazz, invokeInfo, target, throwable); } public static abstract class AbstractSpy { public abstract void atEnter(Class<?> clazz, String methodInfo, Object target, Object[] args); public abstract void atExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Object returnObject); public abstract void atExceptionExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Throwable throwable); public abstract void atBeforeInvoke(Class<?> clazz, String invokeInfo, Object target); public abstract void atAfterInvoke(Class<?> clazz, String invokeInfo, Object target); public abstract void atInvokeException(Class<?> clazz, String invokeInfo, Object target, Throwable throwable); } static class NopSpy extends AbstractSpy { @Override public void atEnter(Class<?> clazz, String methodInfo, Object target, Object[] args) { } @Override public void atExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Object returnObject) { } @Override public void atExceptionExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Throwable throwable) { } @Override public void atBeforeInvoke(Class<?> clazz, String invokeInfo, Object target) { } @Override public void atAfterInvoke(Class<?> clazz, String invokeInfo, Object target) { } @Override public void atInvokeException(Class<?> clazz, String invokeInfo, Object target, Throwable throwable) { } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/boot/src/test/java/com/taobao/arthas/boot/DownloadUtilsTest.java
boot/src/test/java/com/taobao/arthas/boot/DownloadUtilsTest.java
package com.taobao.arthas.boot; import java.io.File; import java.io.IOException; import java.util.List; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class DownloadUtilsTest { @Rule public TemporaryFolder rootFolder = new TemporaryFolder(); @Test public void testReadReleaseVersion() { String releaseVersion = DownloadUtils.readLatestReleaseVersion(); Assert.assertNotNull(releaseVersion); Assert.assertNotEquals("releaseVersion is empty", "", releaseVersion.trim()); System.err.println(releaseVersion); } @Test public void testReadAllVersions() { List<String> versions = DownloadUtils.readRemoteVersions(); Assert.assertEquals("", true, versions.contains("3.1.7")); } @Test public void testAliyunDownload() throws IOException { // fix travis-ci failed problem if (TimeUnit.MILLISECONDS.toHours(TimeZone.getDefault().getOffset(System.currentTimeMillis())) == 8) { String version = "3.3.7"; File folder = rootFolder.newFolder(); System.err.println(folder.getAbsolutePath()); DownloadUtils.downArthasPackaging("aliyun", false, version, folder.getAbsolutePath()); File as = new File(folder, version + File.separator + "arthas" + File.separator + "as.sh"); Assert.assertTrue(as.exists()); } } @Test public void testCenterDownload() throws IOException { String version = "3.1.7"; File folder = rootFolder.newFolder(); System.err.println(folder.getAbsolutePath()); DownloadUtils.downArthasPackaging("center", false, version, folder.getAbsolutePath()); File as = new File(folder, version + File.separator + "arthas" + File.separator + "as.sh"); Assert.assertTrue(as.exists()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/boot/src/main/java/com/taobao/arthas/boot/Bootstrap.java
boot/src/main/java/com/taobao/arthas/boot/Bootstrap.java
package com.taobao.arthas.boot; import static com.taobao.arthas.boot.ProcessUtils.STATUS_EXEC_ERROR; import static com.taobao.arthas.boot.ProcessUtils.STATUS_EXEC_TIMEOUT; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.InputMismatchException; import java.util.List; import java.util.Scanner; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import com.taobao.arthas.common.AnsiLog; import com.taobao.arthas.common.JavaVersionUtils; import com.taobao.arthas.common.SocketUtils; import com.taobao.arthas.common.UsageRender; import com.taobao.middleware.cli.CLI; import com.taobao.middleware.cli.CommandLine; import com.taobao.middleware.cli.UsageMessageFormatter; import com.taobao.middleware.cli.annotations.Argument; import com.taobao.middleware.cli.annotations.CLIConfigurator; import com.taobao.middleware.cli.annotations.Description; import com.taobao.middleware.cli.annotations.Name; import com.taobao.middleware.cli.annotations.Option; import com.taobao.middleware.cli.annotations.Summary; /** * @author hengyunabc 2018-10-26 * */ @Name("arthas-boot") @Summary("Bootstrap Arthas") @Description("NOTE: Arthas 4 supports JDK 8+. If you need to diagnose applications running on JDK 6/7, you can use Arthas 3.\n\n" +"EXAMPLES:\n" + " java -jar arthas-boot.jar <pid>\n" + " java -jar arthas-boot.jar --telnet-port 9999 --http-port -1\n" + " java -jar arthas-boot.jar --username admin --password <password>\n" + " java -jar arthas-boot.jar --tunnel-server 'ws://192.168.10.11:7777/ws' --app-name demoapp\n" + " java -jar arthas-boot.jar --tunnel-server 'ws://192.168.10.11:7777/ws' --agent-id bvDOe8XbTM2pQWjF4cfw\n" + " java -jar arthas-boot.jar --stat-url 'http://192.168.10.11:8080/api/stat'\n" + " java -jar arthas-boot.jar -c 'sysprop; thread' <pid>\n" + " java -jar arthas-boot.jar -f batch.as <pid>\n" + " java -jar arthas-boot.jar --use-version 4.1.4\n" + " java -jar arthas-boot.jar --versions\n" + " java -jar arthas-boot.jar --select math-game\n" + " java -jar arthas-boot.jar --session-timeout 3600\n" + " java -jar arthas-boot.jar --attach-only\n" + " java -jar arthas-boot.jar --disabled-commands stop,dump\n" + " java -jar arthas-boot.jar --repo-mirror aliyun --use-http\n" + "WIKI:\n" + " https://arthas.aliyun.com/doc\n") public class Bootstrap { private static final int DEFAULT_TELNET_PORT = 3658; private static final int DEFAULT_HTTP_PORT = 8563; private static final String DEFAULT_TARGET_IP = "127.0.0.1"; private static File ARTHAS_LIB_DIR; private boolean help = false; private long pid = -1; private String targetIp; private Integer telnetPort; private Integer httpPort; /** * @see com.taobao.arthas.core.config.Configure#DEFAULT_SESSION_TIMEOUT_SECONDS */ private Long sessionTimeout; private Integer height = null; private Integer width = null; private boolean verbose = false; /** * <pre> * The directory contains arthas-core.jar/arthas-client.jar/arthas-spy.jar. * 1. When use-version is not empty, try to find arthas home under ~/.arthas/lib * 2. Try set the directory where arthas-boot.jar is located to arthas home * 3. Try to download from remote repo * </pre> */ private String arthasHome; /** * under ~/.arthas/lib */ private String useVersion; /** * list local and remote versions */ private boolean versions; /** * download from remo repository. if timezone is +0800, default value is 'aliyun', else is 'center'. */ private String repoMirror; /** * enforce use http to download arthas. default use https */ private boolean useHttp = false; private boolean attachOnly = false; private String command; private String batchFile; private String tunnelServer; private String agentId; private String appName; private String username; private String password; private String statUrl; private String select; private String disabledCommands; static { String arthasLibDirEnv = System.getenv("ARTHAS_LIB_DIR"); if (arthasLibDirEnv != null) { ARTHAS_LIB_DIR = new File(arthasLibDirEnv); AnsiLog.info("ARTHAS_LIB_DIR: " + arthasLibDirEnv); } else { ARTHAS_LIB_DIR = new File( System.getProperty("user.home") + File.separator + ".arthas" + File.separator + "lib"); } try { ARTHAS_LIB_DIR.mkdirs(); } catch (Throwable t) { //ignore } if (!ARTHAS_LIB_DIR.exists()) { // try to set a temp directory ARTHAS_LIB_DIR = new File(System.getProperty("java.io.tmpdir") + File.separator + ".arthas" + File.separator + "lib"); try { ARTHAS_LIB_DIR.mkdirs(); } catch (Throwable e) { // ignore } } if (!ARTHAS_LIB_DIR.exists()) { System.err.println("Can not find directory to save arthas lib. please try to set user home by -Duser.home="); } } @Argument(argName = "pid", index = 0, required = false) @Description("Target pid") public void setPid(long pid) { this.pid = pid; } @Option(shortName = "h", longName = "help", flag = true) @Description("Print usage") public void setHelp(boolean help) { this.help = help; } @Option(longName = "target-ip") @Description("The target jvm listen ip, default 127.0.0.1") public void setTargetIp(String targetIp) { this.targetIp = targetIp; } @Option(longName = "telnet-port") @Description("The target jvm listen telnet port, default 3658") public void setTelnetPort(int telnetPort) { this.telnetPort = telnetPort; } @Option(longName = "http-port") @Description("The target jvm listen http port, default 8563") public void setHttpPort(int httpPort) { this.httpPort = httpPort; } @Option(longName = "session-timeout") @Description("The session timeout seconds, default 1800 (30min)") public void setSessionTimeout(Long sessionTimeout) { this.sessionTimeout = sessionTimeout; } @Option(longName = "arthas-home") @Description("The arthas home") public void setArthasHome(String arthasHome) { this.arthasHome = arthasHome; } @Option(longName = "use-version") @Description("Use special version arthas") public void setUseVersion(String useVersion) { this.useVersion = useVersion; } @Option(longName = "repo-mirror") @Description("Use special remote repository mirror, value is center/aliyun or http repo url.") public void setRepoMirror(String repoMirror) { this.repoMirror = repoMirror; } @Option(longName = "versions", flag = true) @Description("List local and remote arthas versions") public void setVersions(boolean versions) { this.versions = versions; } @Option(longName = "use-http", flag = true) @Description("Enforce use http to download, default use https") public void setuseHttp(boolean useHttp) { this.useHttp = useHttp; } @Option(longName = "attach-only", flag = true) @Description("Attach target process only, do not connect") public void setAttachOnly(boolean attachOnly) { this.attachOnly = attachOnly; } @Option(shortName = "c", longName = "command") @Description("Command to execute, multiple commands separated by ;") public void setCommand(String command) { this.command = command; } @Option(shortName = "f", longName = "batch-file") @Description("The batch file to execute") public void setBatchFile(String batchFile) { this.batchFile = batchFile; } @Option(longName = "height") @Description("arthas-client terminal height") public void setHeight(int height) { this.height = height; } @Option(longName = "width") @Description("arthas-client terminal width") public void setWidth(int width) { this.width = width; } @Option(shortName = "v", longName = "verbose", flag = true) @Description("Verbose, print debug info.") public void setVerbose(boolean verbose) { this.verbose = verbose; } @Option(longName = "tunnel-server") @Description("The tunnel server url") public void setTunnelServer(String tunnelServer) { this.tunnelServer = tunnelServer; } @Option(longName = "agent-id") @Description("The agent id register to tunnel server") public void setAgentId(String agentId) { this.agentId = agentId; } @Option(longName = "app-name") @Description("The app name") public void setAppName(String appName) { this.appName = appName; } @Option(longName = "username") @Description("The username") public void setUsername(String username) { this.username = username; } @Option(longName = "password") @Description("The password") public void setPassword(String password) { this.password = password; } @Option(longName = "stat-url") @Description("The report stat url") public void setStatUrl(String statUrl) { this.statUrl = statUrl; } @Option(longName = "select") @Description("select target process by classname or JARfilename") public void setSelect(String select) { this.select = select; } @Option(longName = "disabled-commands") @Description("disable some commands ") public void setDisabledCommands(String disabledCommands) { this.disabledCommands = disabledCommands; } public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String javaHome = System.getProperty("java.home"); if (javaHome != null) { AnsiLog.info("JAVA_HOME: " + javaHome); } Package bootstrapPackage = Bootstrap.class.getPackage(); if (bootstrapPackage != null) { String arthasBootVersion = bootstrapPackage.getImplementationVersion(); if (arthasBootVersion != null) { AnsiLog.info("arthas-boot version: " + arthasBootVersion); } } try { String javaToolOptions = System.getenv("JAVA_TOOL_OPTIONS"); if (javaToolOptions != null && !javaToolOptions.trim().isEmpty()) { AnsiLog.info("JAVA_TOOL_OPTIONS: " + javaToolOptions); } } catch (Throwable e) { // ignore } Bootstrap bootstrap = new Bootstrap(); CLI cli = CLIConfigurator.define(Bootstrap.class); CommandLine commandLine = cli.parse(Arrays.asList(args)); try { CLIConfigurator.inject(commandLine, bootstrap); } catch (Throwable e) { e.printStackTrace(); System.out.println(usage(cli)); System.exit(1); } if (bootstrap.isVerbose()) { AnsiLog.level(Level.ALL); } if (bootstrap.isHelp()) { System.out.println(usage(cli)); System.exit(0); } if (bootstrap.getRepoMirror() == null || bootstrap.getRepoMirror().trim().isEmpty()) { bootstrap.setRepoMirror("center"); // if timezone is +0800, default repo mirror is aliyun if (TimeUnit.MILLISECONDS.toHours(TimeZone.getDefault().getOffset(System.currentTimeMillis())) == 8) { bootstrap.setRepoMirror("aliyun"); } } AnsiLog.debug("Repo mirror:" + bootstrap.getRepoMirror()); if (bootstrap.isVersions()) { System.out.println(UsageRender.render(listVersions())); System.exit(0); } if (JavaVersionUtils.isJava6() || JavaVersionUtils.isJava7()) { bootstrap.setuseHttp(true); AnsiLog.debug("Java version is {}, only support http, set useHttp to true.", JavaVersionUtils.javaVersionStr()); } // check telnet/http port long telnetPortPid = -1; long httpPortPid = -1; if (bootstrap.getTelnetPortOrDefault() > 0) { telnetPortPid = SocketUtils.findTcpListenProcess(bootstrap.getTelnetPortOrDefault()); if (telnetPortPid > 0) { AnsiLog.info("Process {} already using port {}", telnetPortPid, bootstrap.getTelnetPortOrDefault()); } } if (bootstrap.getHttpPortOrDefault() > 0) { httpPortPid = SocketUtils.findTcpListenProcess(bootstrap.getHttpPortOrDefault()); if (httpPortPid > 0) { AnsiLog.info("Process {} already using port {}", httpPortPid, bootstrap.getHttpPortOrDefault()); } } long pid = bootstrap.getPid(); // select pid if (pid < 0) { try { pid = ProcessUtils.select(bootstrap.isVerbose(), telnetPortPid, bootstrap.getSelect()); } catch (InputMismatchException e) { System.out.println("Please input an integer to select pid."); System.exit(1); } if (pid < 0) { System.out.println("Please select an available pid."); System.exit(1); } } checkTelnetPortPid(bootstrap, telnetPortPid, pid); if (httpPortPid > 0 && pid != httpPortPid) { AnsiLog.error("Target process {} is not the process using port {}, you will connect to an unexpected process.", pid, bootstrap.getHttpPortOrDefault()); AnsiLog.error("1. Try to restart arthas-boot, select process {}, shutdown it first with running the 'stop' command.", httpPortPid); AnsiLog.error("2. Or try to use different http port, for example: java -jar arthas-boot.jar --telnet-port 9998 --http-port 9999"); System.exit(1); } // find arthas home File arthasHomeDir = null; if (bootstrap.getArthasHome() != null) { verifyArthasHome(bootstrap.getArthasHome()); arthasHomeDir = new File(bootstrap.getArthasHome()); } if (arthasHomeDir == null && bootstrap.getUseVersion() != null) { // try to find from ~/.arthas/lib File specialVersionDir = new File(System.getProperty("user.home"), ".arthas" + File.separator + "lib" + File.separator + bootstrap.getUseVersion() + File.separator + "arthas"); if (!specialVersionDir.exists()) { // try to download arthas from remote server. DownloadUtils.downArthasPackaging(bootstrap.getRepoMirror(), bootstrap.isUseHttp(), bootstrap.getUseVersion(), ARTHAS_LIB_DIR.getAbsolutePath()); } verifyArthasHome(specialVersionDir.getAbsolutePath()); arthasHomeDir = specialVersionDir; } // Try set the directory where arthas-boot.jar is located to arthas home if (arthasHomeDir == null) { CodeSource codeSource = Bootstrap.class.getProtectionDomain().getCodeSource(); if (codeSource != null) { try { // https://stackoverflow.com/a/17870390 File bootJarPath = new File(codeSource.getLocation().toURI().getSchemeSpecificPart()); verifyArthasHome(bootJarPath.getParent()); arthasHomeDir = bootJarPath.getParentFile(); } catch (Throwable e) { // ignore } } } // try to download from remote server if (arthasHomeDir == null) { boolean checkFile = ARTHAS_LIB_DIR.exists() || ARTHAS_LIB_DIR.mkdirs(); if(!checkFile){ AnsiLog.error("cannot create directory {}: maybe permission denied", ARTHAS_LIB_DIR.getAbsolutePath()); System.exit(1); } /** * <pre> * 1. get local latest version * 2. get remote latest version * 3. compare two version * </pre> */ List<String> versionList = listNames(ARTHAS_LIB_DIR); Collections.sort(versionList); String localLatestVersion = null; if (!versionList.isEmpty()) { localLatestVersion = versionList.get(versionList.size() - 1); } String remoteLatestVersion = DownloadUtils.readLatestReleaseVersion(); boolean needDownload = false; if (localLatestVersion == null) { if (remoteLatestVersion == null) { // exit AnsiLog.error("Can not find Arthas under local: {} and remote repo mirror: {}", ARTHAS_LIB_DIR, bootstrap.getRepoMirror()); AnsiLog.error( "Unable to download arthas from remote server, please download the full package according to wiki: https://github.com/alibaba/arthas"); System.exit(1); } else { needDownload = true; } } else { if (remoteLatestVersion != null) { if (localLatestVersion.compareTo(remoteLatestVersion) < 0) { AnsiLog.info("local latest version: {}, remote latest version: {}, try to download from remote.", localLatestVersion, remoteLatestVersion); needDownload = true; } } } if (needDownload) { // try to download arthas from remote server. DownloadUtils.downArthasPackaging(bootstrap.getRepoMirror(), bootstrap.isUseHttp(), remoteLatestVersion, ARTHAS_LIB_DIR.getAbsolutePath()); localLatestVersion = remoteLatestVersion; } // get the latest version arthasHomeDir = new File(ARTHAS_LIB_DIR, localLatestVersion + File.separator + "arthas"); } verifyArthasHome(arthasHomeDir.getAbsolutePath()); AnsiLog.info("arthas home: " + arthasHomeDir); if (telnetPortPid > 0 && pid == telnetPortPid) { AnsiLog.info("The target process already listen port {}, skip attach.", bootstrap.getTelnetPortOrDefault()); } else { //double check telnet port and pid before attach telnetPortPid = findProcessByTelnetClient(arthasHomeDir.getAbsolutePath(), bootstrap.getTelnetPortOrDefault()); checkTelnetPortPid(bootstrap, telnetPortPid, pid); if (telnetPortPid > 0 && pid == telnetPortPid) { AnsiLog.info("The target process already listen port {}, skip attach.", bootstrap.getTelnetPortOrDefault()); } else { // start arthas-core.jar List<String> attachArgs = new ArrayList<String>(); attachArgs.add("-jar"); attachArgs.add(new File(arthasHomeDir, "arthas-core.jar").getAbsolutePath()); attachArgs.add("-pid"); attachArgs.add("" + pid); if (bootstrap.getTargetIp() != null) { attachArgs.add("-target-ip"); attachArgs.add(bootstrap.getTargetIp()); } if (bootstrap.getTelnetPort() != null) { attachArgs.add("-telnet-port"); attachArgs.add("" + bootstrap.getTelnetPort()); } if (bootstrap.getHttpPort() != null) { attachArgs.add("-http-port"); attachArgs.add("" + bootstrap.getHttpPort()); } attachArgs.add("-core"); attachArgs.add(new File(arthasHomeDir, "arthas-core.jar").getAbsolutePath()); attachArgs.add("-agent"); attachArgs.add(new File(arthasHomeDir, "arthas-agent.jar").getAbsolutePath()); if (bootstrap.getSessionTimeout() != null) { attachArgs.add("-session-timeout"); attachArgs.add("" + bootstrap.getSessionTimeout()); } if (bootstrap.getAppName() != null) { attachArgs.add("-app-name"); attachArgs.add(bootstrap.getAppName()); } if (bootstrap.getUsername() != null) { attachArgs.add("-username"); attachArgs.add(bootstrap.getUsername()); } if (bootstrap.getPassword() != null) { attachArgs.add("-password"); attachArgs.add(bootstrap.getPassword()); } if (bootstrap.getTunnelServer() != null) { attachArgs.add("-tunnel-server"); attachArgs.add(bootstrap.getTunnelServer()); } if (bootstrap.getAgentId() != null) { attachArgs.add("-agent-id"); attachArgs.add(bootstrap.getAgentId()); } if (bootstrap.getStatUrl() != null) { attachArgs.add("-stat-url"); attachArgs.add(bootstrap.getStatUrl()); } if (bootstrap.getDisabledCommands() != null) { attachArgs.add("-disabled-commands"); attachArgs.add(bootstrap.getDisabledCommands()); } AnsiLog.info("Try to attach process " + pid); AnsiLog.debug("Start arthas-core.jar args: " + attachArgs); ProcessUtils.startArthasCore(pid, attachArgs); AnsiLog.info("Attach process {} success.", pid); } } if (bootstrap.isAttachOnly()) { System.exit(0); } // start java telnet client // find arthas-client.jar URLClassLoader classLoader = new URLClassLoader( new URL[] { new File(arthasHomeDir, "arthas-client.jar").toURI().toURL() }); Class<?> telnetConsoleClas = classLoader.loadClass("com.taobao.arthas.client.TelnetConsole"); Method mainMethod = telnetConsoleClas.getMethod("main", String[].class); List<String> telnetArgs = new ArrayList<String>(); if (bootstrap.getCommand() != null) { telnetArgs.add("-c"); telnetArgs.add(bootstrap.getCommand()); } if (bootstrap.getBatchFile() != null) { telnetArgs.add("-f"); telnetArgs.add(bootstrap.getBatchFile()); } if (bootstrap.getHeight() != null) { telnetArgs.add("--height"); telnetArgs.add("" + bootstrap.getHeight()); } if (bootstrap.getWidth() != null) { telnetArgs.add("--width"); telnetArgs.add("" + bootstrap.getWidth()); } // telnet port ,ip telnetArgs.add(bootstrap.getTargetIpOrDefault()); telnetArgs.add("" + bootstrap.getTelnetPortOrDefault()); AnsiLog.info("arthas-client connect {} {}", bootstrap.getTargetIpOrDefault(), bootstrap.getTelnetPortOrDefault()); AnsiLog.debug("Start arthas-client.jar args: " + telnetArgs); // fix https://github.com/alibaba/arthas/issues/833 Thread.currentThread().setContextClassLoader(classLoader); mainMethod.invoke(null, new Object[] { telnetArgs.toArray(new String[0]) }); } private static void checkTelnetPortPid(Bootstrap bootstrap, long telnetPortPid, long targetPid) { if (telnetPortPid > 0 && targetPid != telnetPortPid) { AnsiLog.error("The telnet port {} is used by process {} instead of target process {}, you will connect to an unexpected process.", bootstrap.getTelnetPortOrDefault(), telnetPortPid, targetPid); AnsiLog.error("1. Try to restart arthas-boot, select process {}, shutdown it first with running the 'stop' command.", telnetPortPid); AnsiLog.error("2. Or try to stop the existing arthas instance: java -jar arthas-client.jar 127.0.0.1 {} -c \"stop\"", bootstrap.getTelnetPortOrDefault()); AnsiLog.error("3. Or try to use different telnet port, for example: java -jar arthas-boot.jar --telnet-port 9998 --http-port -1"); System.exit(1); } } private static long findProcessByTelnetClient(String arthasHomeDir, int telnetPort) { // start java telnet client List<String> telnetArgs = new ArrayList<String>(); telnetArgs.add("-c"); telnetArgs.add("session"); telnetArgs.add("--execution-timeout"); telnetArgs.add("2000"); // telnet port ,ip telnetArgs.add("127.0.0.1"); telnetArgs.add("" + telnetPort); try { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); String error = null; int status = ProcessUtils.startArthasClient(arthasHomeDir, telnetArgs, out); if (status == STATUS_EXEC_TIMEOUT) { error = "detection timeout"; } else if (status == STATUS_EXEC_ERROR) { error = "detection error"; AnsiLog.error("process status: {}", status); AnsiLog.error("process output: {}", out.toString()); } else { // ignore connect error } if (error != null) { AnsiLog.error("The telnet port {} is used, but process {}, you will connect to an unexpected process.", telnetPort, error); AnsiLog.error("Try to use a different telnet port, for example: java -jar arthas-boot.jar --telnet-port 9998 --http-port -1"); System.exit(1); } //parse output, find java pid String output = out.toString("UTF-8"); String javaPidLine = null; Scanner scanner = new Scanner(output); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("JAVA_PID")) { javaPidLine = line; break; } } if (javaPidLine != null) { // JAVA_PID 10473 try { String[] strs = javaPidLine.split("JAVA_PID"); if (strs.length > 1) { return Long.parseLong(strs[strs.length - 1].trim()); } } catch (NumberFormatException e) { // ignore } } } catch (Throwable ex) { AnsiLog.error("Detection telnet port error"); AnsiLog.error(ex); } return -1; } private static String listVersions() { StringBuilder result = new StringBuilder(1024); List<String> versionList = listNames(ARTHAS_LIB_DIR); Collections.sort(versionList); result.append("Local versions:\n"); for (String version : versionList) { result.append(" ").append(version).append('\n'); } result.append("Remote versions:\n"); List<String> remoteVersions = DownloadUtils.readRemoteVersions(); if (remoteVersions != null) { Collections.reverse(remoteVersions); for (String version : remoteVersions) { result.append(" " + version).append('\n'); } } else { result.append(" unknown\n"); } return result.toString(); } private static List<String> listNames(File dir) { List<String> names = new ArrayList<String>(); if (!dir.exists()) { return names; } File[] files = dir.listFiles(); if (files == null) { return names; } for (File file : files) { String name = file.getName(); if (name.startsWith(".") || file.isFile()) { continue; } names.add(name); } return names; } private static void verifyArthasHome(String arthasHome) { File home = new File(arthasHome); if (home.isDirectory()) { String[] fileList = { "arthas-core.jar", "arthas-agent.jar", "arthas-spy.jar" }; for (String fileName : fileList) { if (!new File(home, fileName).exists()) { throw new IllegalArgumentException( fileName + " do not exist, arthas home: " + home.getAbsolutePath()); } } return; } throw new IllegalArgumentException("illegal arthas home: " + home.getAbsolutePath()); } private static String usage(CLI cli) { StringBuilder usageStringBuilder = new StringBuilder(); UsageMessageFormatter usageMessageFormatter = new UsageMessageFormatter(); usageMessageFormatter.setOptionComparator(null); cli.usage(usageStringBuilder, usageMessageFormatter); return UsageRender.render(usageStringBuilder.toString()); } public String getArthasHome() { return arthasHome; } public String getUseVersion() { return useVersion; } public String getRepoMirror() { return repoMirror; } public boolean isUseHttp() { return useHttp; } public String getTargetIp() { return targetIp; } public String getTargetIpOrDefault() { if (this.targetIp == null) { return DEFAULT_TARGET_IP; } else { return this.targetIp; } } public Integer getTelnetPort() { return telnetPort; } public int getTelnetPortOrDefault() { if (this.telnetPort == null) { return DEFAULT_TELNET_PORT; } else { return this.telnetPort; } } public Integer getHttpPort() { return httpPort; } public int getHttpPortOrDefault() { if (this.httpPort == null) { return DEFAULT_HTTP_PORT; } else { return this.httpPort; } } public String getCommand() { return command; } public String getBatchFile() { return batchFile; } public boolean isAttachOnly() { return attachOnly; } public long getPid() { return pid; } public boolean isHelp() { return help; } public Long getSessionTimeout() { return sessionTimeout; } public boolean isVerbose() { return verbose; } public boolean isVersions() { return versions; } public Integer getHeight() { return height; } public Integer getWidth() { return width; } public String getTunnelServer() { return tunnelServer; } public String getAgentId() { return agentId; } public String getAppName() { return appName; } public String getStatUrl() { return statUrl; } public String getSelect() { return select; } public String getUsername() { return username; } public String getPassword() { return password; } public String getDisabledCommands() { return disabledCommands; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/boot/src/main/java/com/taobao/arthas/boot/ProcessUtils.java
boot/src/main/java/com/taobao/arthas/boot/ProcessUtils.java
package com.taobao.arthas.boot; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.InputMismatchException; import com.taobao.arthas.common.AnsiLog; import com.taobao.arthas.common.ExecutingCommand; import com.taobao.arthas.common.IOUtils; import com.taobao.arthas.common.JavaVersionUtils; import com.taobao.arthas.common.PidUtils; /** * * @author hengyunabc 2018-11-06 * */ public class ProcessUtils { private static String FOUND_JAVA_HOME = null; //status code from com.taobao.arthas.client.TelnetConsole /** * Process success */ public static final int STATUS_OK = 0; /** * Generic error */ public static final int STATUS_ERROR = 1; /** * Execute commands timeout */ public static final int STATUS_EXEC_TIMEOUT = 100; /** * Execute commands error */ public static final int STATUS_EXEC_ERROR = 101; @SuppressWarnings("resource") public static long select(boolean v, long telnetPortPid, String select) throws InputMismatchException { Map<Long, String> processMap = listProcessByJps(v); if (processMap.isEmpty()) { processMap = listProcessByJcmd(); if (processMap.isEmpty()) { AnsiLog.error("Cannot find java process. Try to run `jps` or `jcmd` commands to list the instrumented Java HotSpot VMs on the target system."); return -1; } } // Put the port that is already listening at the first if (telnetPortPid > 0 && processMap.containsKey(telnetPortPid)) { String telnetPortProcess = processMap.get(telnetPortPid); processMap.remove(telnetPortPid); Map<Long, String> newProcessMap = new LinkedHashMap<Long, String>(); newProcessMap.put(telnetPortPid, telnetPortProcess); newProcessMap.putAll(processMap); processMap = newProcessMap; } // select target process by the '--select' option when match only one process if (select != null && !select.trim().isEmpty()) { int matchedSelectCount = 0; Long matchedPid = null; for (Entry<Long, String> entry : processMap.entrySet()) { if (entry.getValue().contains(select)) { matchedSelectCount++; matchedPid = entry.getKey(); } } if (matchedSelectCount == 1) { return matchedPid; } } AnsiLog.info("Found existing java process, please choose one and input the serial number of the process, eg : 1. Then hit ENTER."); // print list int count = 1; for (String process : processMap.values()) { if (count == 1) { System.out.println("* [" + count + "]: " + process); } else { System.out.println(" [" + count + "]: " + process); } count++; } // read choice String line = new Scanner(System.in).nextLine(); if (line.trim().isEmpty()) { // get the first process id return processMap.keySet().iterator().next(); } int choice = new Scanner(line).nextInt(); if (choice <= 0 || choice > processMap.size()) { return -1; } Iterator<Long> idIter = processMap.keySet().iterator(); for (int i = 1; i <= choice; ++i) { if (i == choice) { return idIter.next(); } idIter.next(); } return -1; } private static Map<Long, String> listProcessByJcmd() { Map<Long, String> result = new LinkedHashMap<>(); String jcmd = "jcmd"; File jcmdFile = findJcmd(); if (jcmdFile != null) { jcmd = jcmdFile.getAbsolutePath(); } AnsiLog.debug("Try use jcmd to list java process, jcmd: " + jcmd); String[] command = new String[] { jcmd, "-l" }; List<String> lines = ExecutingCommand.runNative(command); AnsiLog.debug("jcmd result: " + lines); long currentPid = Long.parseLong(PidUtils.currentPid()); for (String line : lines) { String[] strings = line.trim().split("\\s+"); if (strings.length < 1) { continue; } try { long pid = Long.parseLong(strings[0]); if (pid == currentPid) { continue; } if (strings.length >= 2 && isJcmdProcess(strings[1])) { // skip jcmd continue; } result.put(pid, line); } catch (Throwable e) { // https://github.com/alibaba/arthas/issues/970 // ignore } } return result; } /** * @deprecated {@link #listProcessByJcmd()} */ @Deprecated private static Map<Long, String> listProcessByJps(boolean v) { Map<Long, String> result = new LinkedHashMap<Long, String>(); String jps = "jps"; File jpsFile = findJps(); if (jpsFile != null) { jps = jpsFile.getAbsolutePath(); } AnsiLog.debug("Try use jps to list java process, jps: " + jps); String[] command = null; if (v) { command = new String[] { jps, "-v", "-l" }; } else { command = new String[] { jps, "-l" }; } List<String> lines = ExecutingCommand.runNative(command); AnsiLog.debug("jps result: " + lines); long currentPid = Long.parseLong(PidUtils.currentPid()); for (String line : lines) { String[] strings = line.trim().split("\\s+"); if (strings.length < 1) { continue; } try { long pid = Long.parseLong(strings[0]); if (pid == currentPid) { continue; } if (strings.length >= 2 && isJpsProcess(strings[1])) { // skip jps continue; } result.put(pid, line); } catch (Throwable e) { // https://github.com/alibaba/arthas/issues/970 // ignore } } return result; } /** * <pre> * 1. Try to find java home from System Property java.home * 2. If jdk > 8, FOUND_JAVA_HOME set to java.home * 3. If jdk <= 8, try to find tools.jar under java.home * 4. If tools.jar do not exists under java.home, try to find System env JAVA_HOME * 5. If jdk <= 8 and tools.jar do not exists under JAVA_HOME, throw IllegalArgumentException * </pre> * * @return */ public static String findJavaHome() { if (FOUND_JAVA_HOME != null) { return FOUND_JAVA_HOME; } String javaHome = System.getProperty("java.home"); if (JavaVersionUtils.isLessThanJava9()) { File toolsJar = new File(javaHome, "lib/tools.jar"); if (!toolsJar.exists()) { toolsJar = new File(javaHome, "../lib/tools.jar"); } if (!toolsJar.exists()) { // maybe jre toolsJar = new File(javaHome, "../../lib/tools.jar"); } if (toolsJar.exists()) { FOUND_JAVA_HOME = javaHome; return FOUND_JAVA_HOME; } if (!toolsJar.exists()) { AnsiLog.debug("Can not find tools.jar under java.home: " + javaHome); String javaHomeEnv = System.getenv("JAVA_HOME"); if (javaHomeEnv != null && !javaHomeEnv.isEmpty()) { AnsiLog.debug("Try to find tools.jar in System Env JAVA_HOME: " + javaHomeEnv); // $JAVA_HOME/lib/tools.jar toolsJar = new File(javaHomeEnv, "lib/tools.jar"); if (!toolsJar.exists()) { // maybe jre toolsJar = new File(javaHomeEnv, "../lib/tools.jar"); } } if (toolsJar.exists()) { AnsiLog.info("Found java home from System Env JAVA_HOME: " + javaHomeEnv); FOUND_JAVA_HOME = javaHomeEnv; return FOUND_JAVA_HOME; } throw new IllegalArgumentException("Can not find tools.jar under java home: " + javaHome + ", please try to start arthas-boot with full path java. Such as /opt/jdk/bin/java -jar arthas-boot.jar"); } } else { FOUND_JAVA_HOME = javaHome; } return FOUND_JAVA_HOME; } public static void startArthasCore(long targetPid, List<String> attachArgs) { // find java/java.exe, then try to find tools.jar String javaHome = findJavaHome(); // find java/java.exe File javaPath = findJava(javaHome); if (javaPath == null) { throw new IllegalArgumentException( "Can not find java/java.exe executable file under java home: " + javaHome); } File toolsJar = findToolsJar(javaHome); if (JavaVersionUtils.isLessThanJava9()) { if (toolsJar == null || !toolsJar.exists()) { throw new IllegalArgumentException("Can not find tools.jar under java home: " + javaHome); } } List<String> command = new ArrayList<String>(); command.add(javaPath.getAbsolutePath()); if (toolsJar != null && toolsJar.exists()) { command.add("-Xbootclasspath/a:" + toolsJar.getAbsolutePath()); } command.addAll(attachArgs); // "${JAVA_HOME}"/bin/java \ // ${opts} \ // -jar "${arthas_lib_dir}/arthas-core.jar" \ // -pid ${TARGET_PID} \ // -target-ip ${TARGET_IP} \ // -telnet-port ${TELNET_PORT} \ // -http-port ${HTTP_PORT} \ // -core "${arthas_lib_dir}/arthas-core.jar" \ // -agent "${arthas_lib_dir}/arthas-agent.jar" ProcessBuilder pb = new ProcessBuilder(command); // https://github.com/alibaba/arthas/issues/2166 pb.environment().put("JAVA_TOOL_OPTIONS", ""); try { final Process proc = pb.start(); Thread redirectStdout = new Thread(new Runnable() { @Override public void run() { InputStream inputStream = proc.getInputStream(); try { IOUtils.copy(inputStream, System.out); } catch (IOException e) { IOUtils.close(inputStream); } } }); Thread redirectStderr = new Thread(new Runnable() { @Override public void run() { InputStream inputStream = proc.getErrorStream(); try { IOUtils.copy(inputStream, System.err); } catch (IOException e) { IOUtils.close(inputStream); } } }); redirectStdout.start(); redirectStderr.start(); redirectStdout.join(); redirectStderr.join(); int exitValue = proc.exitValue(); if (exitValue != 0) { AnsiLog.error("attach fail, targetPid: " + targetPid); System.exit(1); } } catch (Throwable e) { // ignore } } public static int startArthasClient(String arthasHomeDir, List<String> telnetArgs, OutputStream out) throws Throwable { // start java telnet client // find arthas-client.jar URLClassLoader classLoader = new URLClassLoader( new URL[]{new File(arthasHomeDir, "arthas-client.jar").toURI().toURL()}); Class<?> telnetConsoleClass = classLoader.loadClass("com.taobao.arthas.client.TelnetConsole"); Method processMethod = telnetConsoleClass.getMethod("process", String[].class); //redirect System.out/System.err PrintStream originSysOut = System.out; PrintStream originSysErr = System.err; PrintStream newOut = new PrintStream(out); PrintStream newErr = new PrintStream(out); // call TelnetConsole.process() // fix https://github.com/alibaba/arthas/issues/833 ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { System.setOut(newOut); System.setErr(newErr); Thread.currentThread().setContextClassLoader(classLoader); return (Integer) processMethod.invoke(null, new Object[]{telnetArgs.toArray(new String[0])}); } catch (Throwable e) { //java.lang.reflect.InvocationTargetException : java.net.ConnectException e = e.getCause(); if (e instanceof IOException || e instanceof InterruptedException) { // ignore connection error and interrupted error return STATUS_ERROR; } else { // process error AnsiLog.error("process error: {}", e.toString()); AnsiLog.error(e); return STATUS_EXEC_ERROR; } } finally { Thread.currentThread().setContextClassLoader(tccl); //reset System.out/System.err System.setOut(originSysOut); System.setErr(originSysErr); //flush output newOut.flush(); newErr.flush(); } } private static File findJava(String javaHome) { String[] paths = { "bin/java", "bin/java.exe", "../bin/java", "../bin/java.exe" }; List<File> javaList = new ArrayList<File>(); for (String path : paths) { File javaFile = new File(javaHome, path); if (javaFile.exists()) { AnsiLog.debug("Found java: " + javaFile.getAbsolutePath()); javaList.add(javaFile); } } if (javaList.isEmpty()) { AnsiLog.debug("Can not find java/java.exe under current java home: " + javaHome); return null; } // find the shortest path, jre path longer than jdk path if (javaList.size() > 1) { Collections.sort(javaList, new Comparator<File>() { @Override public int compare(File file1, File file2) { try { return file1.getCanonicalPath().length() - file2.getCanonicalPath().length(); } catch (IOException e) { // ignore } return -1; } }); } return javaList.get(0); } private static File findToolsJar(String javaHome) { if (JavaVersionUtils.isGreaterThanJava8()) { return null; } File toolsJar = new File(javaHome, "lib/tools.jar"); if (!toolsJar.exists()) { toolsJar = new File(javaHome, "../lib/tools.jar"); } if (!toolsJar.exists()) { // maybe jre toolsJar = new File(javaHome, "../../lib/tools.jar"); } if (!toolsJar.exists()) { throw new IllegalArgumentException("Can not find tools.jar under java home: " + javaHome); } AnsiLog.debug("Found tools.jar: " + toolsJar.getAbsolutePath()); return toolsJar; } private static File findJcmd() { // Try to find jcmd under java.home and System env JAVA_HOME String javaHome = System.getProperty("java.home"); String[] paths = { "bin/jcmd", "bin/jcmd.exe", "../bin/jcmd", "../bin/jcmd.exe" }; List<File> jcmdList = new ArrayList<>(); for (String path : paths) { File jcmdFile = new File(javaHome, path); if (jcmdFile.exists()) { AnsiLog.debug("Found jcmd: " + jcmdFile.getAbsolutePath()); jcmdList.add(jcmdFile); } } if (jcmdList.isEmpty()) { AnsiLog.debug("Can not find jcmd under :" + javaHome); String javaHomeEnv = System.getenv("JAVA_HOME"); AnsiLog.debug("Try to find jcmd under env JAVA_HOME :" + javaHomeEnv); if (javaHomeEnv != null) { for (String path : paths) { File jcmdFile = new File(javaHomeEnv, path); if (jcmdFile.exists()) { AnsiLog.debug("Found jcmd: " + jcmdFile.getAbsolutePath()); jcmdList.add(jcmdFile); } } } else { AnsiLog.debug("JAVA_HOME environment variable is not set."); } } if (jcmdList.isEmpty()) { AnsiLog.debug("Can not find jcmd under current java home: " + javaHome); return null; } // find the shortest path, jre path longer than jdk path if (jcmdList.size() > 1) { jcmdList.sort((file1, file2) -> { try { return file1.getCanonicalPath().length() - file2.getCanonicalPath().length(); } catch (IOException e) { // ignore // fallback to absolute path length comparison return file1.getAbsolutePath().length() - file2.getAbsolutePath().length(); } }); } return jcmdList.get(0); } private static boolean isJcmdProcess(String mainClassName) { // Java 8 or Java 9+ return "sun.tools.jcmd.JCmd".equals(mainClassName) || "jdk.jcmd/sun.tools.jcmd.JCmd".equals(mainClassName); } /** * @deprecated {@link #findJcmd()} */ @Deprecated private static File findJps() { // Try to find jps under java.home and System env JAVA_HOME String javaHome = System.getProperty("java.home"); String[] paths = { "bin/jps", "bin/jps.exe", "../bin/jps", "../bin/jps.exe" }; List<File> jpsList = new ArrayList<File>(); for (String path : paths) { File jpsFile = new File(javaHome, path); if (jpsFile.exists()) { AnsiLog.debug("Found jps: " + jpsFile.getAbsolutePath()); jpsList.add(jpsFile); } } if (jpsList.isEmpty()) { AnsiLog.debug("Can not find jps under :" + javaHome); String javaHomeEnv = System.getenv("JAVA_HOME"); AnsiLog.debug("Try to find jps under env JAVA_HOME :" + javaHomeEnv); for (String path : paths) { File jpsFile = new File(javaHomeEnv, path); if (jpsFile.exists()) { AnsiLog.debug("Found jps: " + jpsFile.getAbsolutePath()); jpsList.add(jpsFile); } } } if (jpsList.isEmpty()) { AnsiLog.debug("Can not find jps under current java home: " + javaHome); return null; } // find the shortest path, jre path longer than jdk path if (jpsList.size() > 1) { Collections.sort(jpsList, new Comparator<File>() { @Override public int compare(File file1, File file2) { try { return file1.getCanonicalPath().length() - file2.getCanonicalPath().length(); } catch (IOException e) { // ignore } return -1; } }); } return jpsList.get(0); } /** * @deprecated {@link #isJcmdProcess(String)} */ @Deprecated private static boolean isJpsProcess(String mainClassName) { return "sun.tools.jps.Jps".equals(mainClassName) || "jdk.jcmd/sun.tools.jps.Jps".equals(mainClassName); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/boot/src/main/java/com/taobao/arthas/boot/DownloadUtils.java
boot/src/main/java/com/taobao/arthas/boot/DownloadUtils.java
package com.taobao.arthas.boot; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import com.taobao.arthas.common.AnsiLog; import com.taobao.arthas.common.IOUtils; /** * * @author hengyunabc 2018-11-06 * */ public class DownloadUtils { private static final String ARTHAS_VERSIONS_URL = "https://arthas.aliyun.com/api/versions"; private static final String ARTHAS_LATEST_VERSIONS_URL = "https://arthas.aliyun.com/api/latest_version"; private static final String ARTHAS_DOWNLOAD_URL = "https://arthas.aliyun.com/download/${VERSION}?mirror=${REPO}"; private static final int CONNECTION_TIMEOUT = 3000; public static String readLatestReleaseVersion() { InputStream inputStream = null; try { URLConnection connection = openURLConnection(ARTHAS_LATEST_VERSIONS_URL); inputStream = connection.getInputStream(); return IOUtils.toString(inputStream).trim(); } catch (Throwable t) { AnsiLog.error("Can not read arthas version from: " + ARTHAS_LATEST_VERSIONS_URL); AnsiLog.debug(t); } finally { IOUtils.close(inputStream); } return null; } public static List<String> readRemoteVersions() { InputStream inputStream = null; try { URLConnection connection = openURLConnection(ARTHAS_VERSIONS_URL); inputStream = connection.getInputStream(); String versionsStr = IOUtils.toString(inputStream); String[] versions = versionsStr.split("\r\n"); ArrayList<String> result = new ArrayList<String>(); for (String version : versions) { result.add(version.trim()); } return result; } catch (Throwable t) { AnsiLog.error("Can not read arthas versions from: " + ARTHAS_VERSIONS_URL); AnsiLog.debug(t); } finally { IOUtils.close(inputStream); } return null; } private static String getRepoUrl(String repoUrl, boolean http) { if (repoUrl.endsWith("/")) { repoUrl = repoUrl.substring(0, repoUrl.length() - 1); } if (http && repoUrl.startsWith("https")) { repoUrl = "http" + repoUrl.substring("https".length()); } return repoUrl; } public static void downArthasPackaging(String repoMirror, boolean http, String arthasVersion, String savePath) throws IOException { String repoUrl = getRepoUrl(ARTHAS_DOWNLOAD_URL, http); File unzipDir = new File(savePath, arthasVersion + File.separator + "arthas"); File tempFile = File.createTempFile("arthas", "arthas"); AnsiLog.debug("Arthas download temp file: " + tempFile.getAbsolutePath()); String remoteDownloadUrl = repoUrl.replace("${REPO}", repoMirror).replace("${VERSION}", arthasVersion); AnsiLog.info("Start download arthas from remote server: " + remoteDownloadUrl); saveUrl(tempFile.getAbsolutePath(), remoteDownloadUrl, true); AnsiLog.info("Download arthas success."); IOUtils.unzip(tempFile.getAbsolutePath(), unzipDir.getAbsolutePath()); } private static void saveUrl(final String filename, final String urlString, boolean printProgress) throws IOException { BufferedInputStream in = null; FileOutputStream fout = null; try { URLConnection connection = openURLConnection(urlString); in = new BufferedInputStream(connection.getInputStream()); List<String> values = connection.getHeaderFields().get("Content-Length"); int fileSize = 0; if (values != null && !values.isEmpty()) { String contentLength = values.get(0); if (contentLength != null) { // parse the length into an integer... fileSize = Integer.parseInt(contentLength); } } fout = new FileOutputStream(filename); final byte[] data = new byte[1024 * 1024]; int totalCount = 0; int count; long lastPrintTime = System.currentTimeMillis(); while ((count = in.read(data, 0, data.length)) != -1) { totalCount += count; if (printProgress) { long now = System.currentTimeMillis(); if (now - lastPrintTime > 1000) { AnsiLog.info("File size: {}, downloaded size: {}, downloading ...", formatFileSize(fileSize), formatFileSize(totalCount)); lastPrintTime = now; } } fout.write(data, 0, count); } } catch (javax.net.ssl.SSLException e) { AnsiLog.error("TLS connect error, please try to add --use-http argument."); AnsiLog.error("URL: " + urlString); AnsiLog.error(e); } finally { IOUtils.close(in); IOUtils.close(fout); } } /** * support redirect * * @param url * @return * @throws MalformedURLException * @throws IOException */ private static URLConnection openURLConnection(String url) throws MalformedURLException, IOException { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { connection.setConnectTimeout(CONNECTION_TIMEOUT); // normally, 3xx is redirect int status = ((HttpURLConnection) connection).getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { String newUrl = connection.getHeaderField("Location"); AnsiLog.debug("Try to open url: {}, redirect to: {}", url, newUrl); return openURLConnection(newUrl); } } } return connection; } private static String formatFileSize(long size) { String hrSize; double b = size; double k = size / 1024.0; double m = ((size / 1024.0) / 1024.0); double g = (((size / 1024.0) / 1024.0) / 1024.0); double t = ((((size / 1024.0) / 1024.0) / 1024.0) / 1024.0); DecimalFormat dec = new DecimalFormat("0.00"); if (t > 1) { hrSize = dec.format(t).concat(" TB"); } else if (g > 1) { hrSize = dec.format(g).concat(" GB"); } else if (m > 1) { hrSize = dec.format(m).concat(" MB"); } else if (k > 1) { hrSize = dec.format(k).concat(" KB"); } else { hrSize = dec.format(b).concat(" Bytes"); } return hrSize; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/GlobalOptionsTest.java
core/src/test/java/com/taobao/arthas/core/GlobalOptionsTest.java
package com.taobao.arthas.core; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import ognl.OgnlRuntime; class GlobalOptionsTest { @Test void test() { GlobalOptions.updateOnglStrict(true); Assertions.assertThat(OgnlRuntime.getUseStricterInvocationValue()).isTrue(); GlobalOptions.updateOnglStrict(false); Assertions.assertThat(OgnlRuntime.getUseStricterInvocationValue()).isFalse(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/ArthasCheckUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/ArthasCheckUtilsTest.java
package com.taobao.arthas.core.util; import org.junit.Assert; import org.junit.Test; /** * @author earayu */ public class ArthasCheckUtilsTest { @Test public void testIsIn(){ Assert.assertTrue(ArthasCheckUtils.isIn(1,1,2,3)); Assert.assertFalse(ArthasCheckUtils.isIn(1,2,3,4)); Assert.assertTrue(ArthasCheckUtils.isIn(null,1,null,2)); Assert.assertFalse(ArthasCheckUtils.isIn(1,null)); Assert.assertTrue(ArthasCheckUtils.isIn(1L,1L,2L,3L)); Assert.assertFalse(ArthasCheckUtils.isIn(1L,2L,3L,4L)); Assert.assertTrue(ArthasCheckUtils.isIn("foo","foo","bar")); Assert.assertFalse(ArthasCheckUtils.isIn("foo","bar","goo")); } @Test public void testIsEquals(){ Assert.assertTrue(ArthasCheckUtils.isEquals(1,1)); Assert.assertTrue(ArthasCheckUtils.isEquals(1L,1L)); Assert.assertTrue(ArthasCheckUtils.isEquals("foo","foo")); Assert.assertFalse(ArthasCheckUtils.isEquals(1,2)); Assert.assertFalse(ArthasCheckUtils.isEquals("foo","bar")); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/DateUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/DateUtilsTest.java
package com.taobao.arthas.core.util; import org.junit.Assert; import org.junit.Test; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * * @author brijeshprasad89 * */ public class DateUtilsTest { @Test public void testFormatDateTimeWithCorrectFormat() { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); // supported date format LocalDateTime dateTime = LocalDateTime.now(); Assert.assertEquals(DateUtils.formatDateTime(dateTime), dateTimeFormatter.format(dateTime)); } @Test public void testFormatDateTimeWithInCorrectFormat() { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); // Not supported Date format LocalDateTime dateTime = LocalDateTime.now(); Assert.assertNotEquals(DateUtils.formatDateTime(dateTime), dateTimeFormatter.format(dateTime)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/TypeRenderUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/TypeRenderUtilsTest.java
package com.taobao.arthas.core.util; import org.assertj.core.api.Assertions; import org.junit.Test; import com.taobao.arthas.common.JavaVersionUtils; import java.io.Serializable; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class TypeRenderUtilsTest { public class TestClass implements Serializable { private int testField; public char anotherTestField; public int testMethod(int i, boolean b) { return 0; } public void anotherTestMethod() throws NullPointerException { } } @Test public void testDrawInterface() { if (JavaVersionUtils.isGreaterThanJava11()) { Assertions.assertThat(TypeRenderUtils.drawInterface(String.class)).isEqualTo( "java.io.Serializable,java.lang.Comparable,java.lang.CharSequence,java.lang.constant.Constable,java.lang.constant.ConstantDesc"); } else { Assertions.assertThat(TypeRenderUtils.drawInterface(String.class)) .isEqualTo("java.io.Serializable,java.lang.Comparable,java.lang.CharSequence"); } assertThat(TypeRenderUtils.drawInterface(TestClass.class), is(equalTo("java.io.Serializable"))); assertThat(TypeRenderUtils.drawInterface(Serializable.class), is(equalTo(""))); } @Test public void testDrawParametersForMethod() throws NoSuchMethodException { Class[] classesOfParameters = new Class[2]; classesOfParameters[0] = int.class; classesOfParameters[1] = boolean.class; assertThat(TypeRenderUtils.drawParameters(TestClass.class.getMethod("testMethod", classesOfParameters)), is(equalTo("int\nboolean"))); assertThat(TypeRenderUtils.drawParameters(TestClass.class.getMethod("anotherTestMethod")), is(equalTo(""))); assertThat(TypeRenderUtils.drawParameters(String.class.getMethod("charAt", int.class)), is(equalTo("int"))); assertThat(TypeRenderUtils.drawParameters(String.class.getMethod("isEmpty")), is(equalTo(""))); } @Test(expected = NoSuchMethodException.class) public void testDrawParametersForMethodThrowsException() throws NoSuchMethodException { assertThat(TypeRenderUtils.drawParameters(TestClass.class.getMethod("method")), is(equalTo(""))); } @Test public void testDrawParametersForConstructor() throws NoSuchMethodException { Class[] classesOfParameters = new Class[3]; classesOfParameters[0] = char[].class; classesOfParameters[1] = int.class; classesOfParameters[2] = int.class; assertThat(TypeRenderUtils.drawParameters(String.class.getConstructor(classesOfParameters)), is(equalTo("[]\nint\nint"))); assertThat(TypeRenderUtils.drawParameters(String.class.getConstructor()), is(equalTo(""))); } @Test(expected = NoSuchMethodException.class) public void testDrawParametersForConstructorThrowsException() throws NoSuchMethodException { assertThat(TypeRenderUtils.drawParameters(TestClass.class.getConstructor()), is(equalTo(""))); } @Test public void testDrawReturn() throws NoSuchMethodException { Class[] classesOfParameters = new Class[2]; classesOfParameters[0] = int.class; classesOfParameters[1] = boolean.class; assertThat(TypeRenderUtils.drawReturn(TestClass.class.getMethod("testMethod", classesOfParameters)), is(equalTo("int"))); assertThat(TypeRenderUtils.drawReturn(TestClass.class.getMethod("anotherTestMethod")), is(equalTo("void"))); assertThat(TypeRenderUtils.drawReturn(String.class.getMethod("isEmpty")), is(equalTo("boolean"))); } @Test(expected = NoSuchMethodException.class) public void testDrawReturnThrowsException() throws NoSuchMethodException { assertThat(TypeRenderUtils.drawReturn(TestClass.class.getMethod("method")), is(equalTo(""))); } @Test public void testDrawExceptionsForMethod() throws NoSuchMethodException { Class[] classesOfParameters = new Class[2]; classesOfParameters[0] = int.class; classesOfParameters[1] = boolean.class; assertThat(TypeRenderUtils.drawExceptions(TestClass.class.getMethod("testMethod", classesOfParameters)), is(equalTo(""))); assertThat(TypeRenderUtils.drawExceptions(TestClass.class.getMethod("anotherTestMethod")), is(equalTo("java.lang.NullPointerException"))); assertThat(TypeRenderUtils.drawExceptions(String.class.getMethod("getBytes", String.class)), is(equalTo("java.io.UnsupportedEncodingException"))); } @Test(expected = NoSuchMethodException.class) public void testDrawExceptionsForMethodThrowsException() throws NoSuchMethodException { assertThat(TypeRenderUtils.drawExceptions(TestClass.class.getMethod("method")), is(equalTo(""))); } @Test public void testDrawExceptionsForConstructor() throws NoSuchMethodException { Class[] classesOfConstructorParameters = new Class[2]; classesOfConstructorParameters[0] = byte[].class; classesOfConstructorParameters[1] = String.class; assertThat(TypeRenderUtils.drawExceptions(String.class.getConstructor()), is(equalTo(""))); assertThat(TypeRenderUtils.drawExceptions(String.class.getConstructor(classesOfConstructorParameters)), is(equalTo("java.io.UnsupportedEncodingException"))); } @Test(expected = NoSuchMethodException.class) public void testDrawExceptionsForConstructorThrowsException() throws NoSuchMethodException { assertThat(TypeRenderUtils.drawExceptions(TestClass.class.getConstructor()), is(equalTo(""))); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/FileUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/FileUtilsTest.java
package com.taobao.arthas.core.util; import com.taobao.arthas.core.testtool.TestUtils; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.startsWith; public class FileUtilsTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); private File getTestDirectory() { return temporaryFolder.getRoot(); } @Test public void testGetTestDirectory(){ Assert.assertNotNull(getTestDirectory()); } @Test public void testOpenOutputStreamIsDirectory() throws IOException { thrown.expectMessage(allOf(startsWith("File '") ,endsWith("' exists but is a directory"))); FileUtils.openOutputStream(getTestDirectory(), true); thrown.expectMessage(allOf(startsWith("File '") ,endsWith("' exists but is a directory"))); FileUtils.openOutputStream(getTestDirectory(), false); } @Test public void testOpenOutputStreamCannotWrite() throws IOException { thrown.expectMessage(allOf(startsWith("File '") ,endsWith("' cannot be written to"))); File targetFile = temporaryFolder.newFile("cannotWrite.txt"); targetFile.setWritable(false); FileUtils.openOutputStream(targetFile, true); } @Test public void testOpenOutputStream() throws IOException { File targetFile = temporaryFolder.newFile("targetFile.txt"); FileOutputStream outputStream = FileUtils.openOutputStream(targetFile, true); Assert.assertNotNull(outputStream); outputStream.close(); } @Test public void testWriteByteArrayToFile() throws IOException { String data = "test data"; File targetFile = temporaryFolder.newFile("targetFile.txt"); FileUtils.writeByteArrayToFile(targetFile, data.getBytes()); TestUtils.assertEqualContent(data.getBytes(), targetFile); } @Test public void testWriteByteArrayToFileWithAppend() throws IOException { String data = "test data"; File targetFile = temporaryFolder.newFile("targetFile.txt"); FileUtils.writeByteArrayToFile(targetFile, data.getBytes(), true); TestUtils.assertEqualContent(data.getBytes(), targetFile); } @Test public void testReadFileToString() throws IOException { String data = "test data"; File targetFile = temporaryFolder.newFile("targetFile.txt"); FileUtils.writeByteArrayToFile(targetFile, data.getBytes(), true); String content = FileUtils.readFileToString(targetFile, Charset.defaultCharset()); TestUtils.assertEqualContent(content.getBytes(), targetFile); } @Test public void testSaveCommandHistory() throws IOException { //cls int[] command1 = new int[]{99,108,115}; File targetFile = temporaryFolder.newFile("targetFile.txt"); FileUtils.saveCommandHistory(TestUtils.newArrayList(command1), targetFile); TestUtils.assertEqualContent("cls\n".getBytes(), targetFile); } @Test public void testLoadCommandHistory() throws IOException { //cls int[] command1 = new int[]{99,108,115}; File targetFile = temporaryFolder.newFile("targetFile.txt"); FileUtils.saveCommandHistory(TestUtils.newArrayList(command1), targetFile); List<int[]> content = FileUtils.loadCommandHistory(targetFile); Assert.assertArrayEquals(command1, content.get(0)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/ArrayUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/ArrayUtilsTest.java
package com.taobao.arthas.core.util; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * @author earayu */ public class ArrayUtilsTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testEmptyLongArray() { Assert.assertArrayEquals(ArrayUtils.EMPTY_LONG_ARRAY, new long[0]); } @Test public void testToPrimitive() { Assert.assertArrayEquals(ArrayUtils.toPrimitive(null), null); Assert.assertArrayEquals(ArrayUtils.toPrimitive(new Long[0]), new long[0]); Assert.assertArrayEquals( ArrayUtils.toPrimitive(new Long[]{ 1L, 1763L, 54769975464L }), new long[]{ 1L, 1763L, 54769975464L }); //throws NullPointerException if array content is null thrown.expect(NullPointerException.class); Assert.assertArrayEquals(ArrayUtils.toPrimitive(new Long[]{null}), new long[]{1L}); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/StringUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/StringUtilsTest.java
package com.taobao.arthas.core.util; import org.junit.Assert; import org.junit.rules.ExpectedException; import org.junit.Rule; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.TreeMap; import java.util.TreeSet; import java.util.Properties; /** * @author bohrqiu 2018-09-21 01:01 * @author paulkennethkent 2019-04-08 10:29 */ public class StringUtilsTest { @Rule public final ExpectedException thrown = ExpectedException.none(); @Test public void testHumanReadableByteCount() { Assert.assertEquals(StringUtils.humanReadableByteCount(1023L), "1023 B"); Assert.assertEquals(StringUtils.humanReadableByteCount(1024L), "1.0 KiB"); Assert.assertEquals(StringUtils.humanReadableByteCount(1024L * 1024L), "1.0 MiB"); Assert.assertEquals(StringUtils.humanReadableByteCount(1024L * 1024L - 100), "1023.9 KiB"); Assert.assertEquals(StringUtils.humanReadableByteCount(1024L * 1024 * 1024L), "1.0 GiB"); Assert.assertEquals(StringUtils.humanReadableByteCount(1024L * 1024 * 1024 * 1024L), "1.0 TiB"); Assert.assertEquals(StringUtils.humanReadableByteCount(1024L * 1024 * 1024 * 1024 * 1024), "1.0 PiB"); } @Test public void testCause() { Assert.assertNull(StringUtils.cause(new Throwable(null, null))); final Throwable t2 = new Throwable("error message", new Throwable("error message", null)); Assert.assertEquals(t2.getMessage(), StringUtils.cause(t2)); } @Test public void testCommaDelimitedListToSet() { TreeSet set = new TreeSet(); set.add("foo"); Assert.assertEquals(set, StringUtils.commaDelimitedListToSet("foo")); } @Test public void testCommaDelimitedListToStringArray() { Assert.assertArrayEquals(new String[] {}, StringUtils.commaDelimitedListToStringArray(null)); Assert.assertArrayEquals(new String[] {}, StringUtils.commaDelimitedListToStringArray("")); Assert.assertArrayEquals(new String[] {"/////"}, StringUtils.commaDelimitedListToStringArray("/////")); Assert.assertArrayEquals(new String[] {"foo", "bar", "baz"}, StringUtils.commaDelimitedListToStringArray("foo,bar,baz")); } @Test public void testContainsWhitespaceInputNotNullOutputTrue() { Assert.assertTrue(StringUtils.containsWhitespace("foo ")); Assert.assertTrue(StringUtils.containsWhitespace(" ")); Assert.assertFalse(StringUtils.containsWhitespace("!")); Assert.assertFalse(StringUtils.containsWhitespace("")); Assert.assertFalse(StringUtils.containsWhitespace(null)); } @Test public void testCountOccurrencesOf() { Assert.assertEquals(0, StringUtils.countOccurrencesOf("44444444", "$$$$$$$$")); Assert.assertEquals(0, StringUtils.countOccurrencesOf("$", "")); Assert.assertEquals(0, StringUtils.countOccurrencesOf("", "")); Assert.assertEquals(1, StringUtils.countOccurrencesOf(";;;;;;;:::", ";;;;;;;:")); Assert.assertEquals(3, StringUtils.countOccurrencesOf("foofoofoo", "foo")); } @Test public void testDeleteAny() { Assert.assertEquals("", StringUtils.deleteAny("\"", "\"!!!!!!!! ")); Assert.assertEquals("\"", StringUtils.deleteAny("\"", "$ 00000000")); Assert.assertEquals("!", StringUtils.deleteAny("!", "")); Assert.assertEquals("", StringUtils.deleteAny("", "")); Assert.assertEquals("barbar", StringUtils.deleteAny("foobarfoobar", "foo")); } @Test public void testDelete() { Assert.assertEquals("0", StringUtils.delete("0", "")); Assert.assertEquals("foo", StringUtils.delete("foobar", "bar")); } @Test public void testDelimitedListToStringArray() { Assert.assertArrayEquals(new String[] {}, StringUtils.delimitedListToStringArray("", ">", "")); Assert.assertArrayEquals(new String[] {"r662"}, StringUtils.delimitedListToStringArray("r662", ">>>>", "")); Assert.assertArrayEquals(new String[] {}, StringUtils.delimitedListToStringArray("", "", "")); Assert.assertArrayEquals(new String[] {"foo", "br", "bz"}, StringUtils.delimitedListToStringArray("foo>bar>baz", ">", "a")); } @Test public void testDelimitedListToStringArray2() { Assert.assertArrayEquals(new String[] {}, StringUtils.delimitedListToStringArray(null, "")); Assert.assertArrayEquals(new String[] {"{}~~~~~~"}, StringUtils.delimitedListToStringArray("{}~~~~~~", null)); Assert.assertArrayEquals(new String[] {"{"}, StringUtils.delimitedListToStringArray("{", "")); Assert.assertArrayEquals(new String[] {}, StringUtils.delimitedListToStringArray("", "????")); Assert.assertArrayEquals(new String[] {"V777VVVVV"}, StringUtils.delimitedListToStringArray("V777VVVVV", "77777")); Assert.assertArrayEquals(new String[] {}, StringUtils.delimitedListToStringArray("", "")); Assert.assertArrayEquals(new String[] {"foo", "bar", "baz"}, StringUtils.delimitedListToStringArray("foo-bar-baz", "-")); } @Test public void testEndsWithIgnoreCase() { Assert.assertFalse(StringUtils.endsWithIgnoreCase(null, "")); Assert.assertFalse(StringUtils.endsWithIgnoreCase("QPPQPPP[", "\'g\'&&\'&A&")); Assert.assertTrue(StringUtils.endsWithIgnoreCase("FFFFFFFFF\'", "f\'")); Assert.assertTrue(StringUtils.endsWithIgnoreCase("&&&&&&&&&\'", "&&&&&\'")); } @Test public void testHasLength() { Assert.assertTrue(StringUtils.hasLength(" ")); Assert.assertTrue(StringUtils.hasLength("AAAAAAAA")); Assert.assertFalse(StringUtils.hasLength("")); Assert.assertFalse(StringUtils.hasLength(null)); } @Test public void testHasText() { Assert.assertTrue(StringUtils.hasText(" !")); Assert.assertTrue(StringUtils.hasText("!")); Assert.assertFalse(StringUtils.hasText(" ")); Assert.assertFalse(StringUtils.hasText("")); } @Test public void testIsBlank() { Assert.assertTrue(StringUtils.isBlank("")); Assert.assertTrue(StringUtils.isBlank(" ")); Assert.assertFalse(StringUtils.isBlank(" (!!!!!!!!")); } @Test public void testIsEmpty() { Assert.assertFalse(StringUtils.isEmpty(-2147483647)); Assert.assertFalse(StringUtils.isEmpty("foo")); Assert.assertTrue(StringUtils.isEmpty("")); } @Test public void testJoin() { Assert.assertEquals("7234", StringUtils.join(new Object[] {7, 234}, null)); Assert.assertEquals("11", StringUtils.join(new Object[] {11}, null)); Assert.assertEquals("", StringUtils.join(new Object[] {}, null)); Assert.assertEquals("", StringUtils.join(new Object[] {}, "HH")); Assert.assertEquals("foobarbaz", StringUtils.join(new Object[] {"foo", "bar", "baz"}, "")); } @Test public void testLength() { Assert.assertEquals(0, StringUtils.length(null)); Assert.assertEquals(0, StringUtils.length("")); Assert.assertEquals(3, StringUtils.length("boo")); } @Test public void testNormalizeClassName() { Assert.assertEquals("", StringUtils.normalizeClassName("")); Assert.assertEquals(".", StringUtils.normalizeClassName("/")); Assert.assertEquals("foo.bar.Baz", StringUtils.normalizeClassName("foo/bar/Baz")); Assert.assertEquals("foo.bar.Baz", StringUtils.normalizeClassName("foo.bar.Baz")); } @Test public void testObjectToString() { Assert.assertEquals("1", StringUtils.objectToString(1)); Assert.assertEquals("", StringUtils.objectToString(null)); Assert.assertEquals("{}", StringUtils.objectToString(new TreeMap())); } @Test public void testQuoteIfString() { Assert.assertEquals("\'foo\'", StringUtils.quoteIfString("foo")); Assert.assertEquals(1, StringUtils.quoteIfString(1)); } @Test public void testQuote() { Assert.assertEquals("\'!\'", StringUtils.quote("!")); Assert.assertEquals("\'1234\'", StringUtils.quote("1234")); } @Test public void testRepeat() { Assert.assertNull(StringUtils.repeat(null, -1635778558)); Assert.assertEquals("", StringUtils.repeat("", 3)); Assert.assertEquals("\u0000\u0000", StringUtils.repeat("\u0000", 2)); Assert.assertEquals("\u0000\u0000\u0000\u0000", StringUtils.repeat("\u0000\u0000", 2)); Assert.assertEquals("", StringUtils.repeat("foo", 0)); Assert.assertEquals("foo", StringUtils.repeat("foo", 1)); Assert.assertEquals("foofoofoofoo", StringUtils.repeat("foo", 4)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 8194; i++) sb.append('c'); Assert.assertEquals(sb.toString(), StringUtils.repeat('c', 8194)); thrown.expect(NegativeArraySizeException.class); StringUtils.repeat("\uffff\u2aa0", 1073742337); } @Test public void testReplace() { Assert.assertEquals(" ", StringUtils.replace(" ", "", " ")); Assert.assertEquals("", StringUtils.replace("", "", " ")); Assert.assertEquals("baz", StringUtils.replace("bar", "r", "z")); } @Test public void testSplitArrayElementsIntoProperties() { final String[] array = {}; Assert.assertNull(StringUtils.splitArrayElementsIntoProperties(array, "_", "DEE")); final String[] array2 = {"foo=1", "bar=2"}; final Properties prop = new Properties(); prop.setProperty("foo", "1"); prop.setProperty("bar", "2"); Assert.assertEquals(prop, StringUtils.splitArrayElementsIntoProperties(array2, "=", "")); final String[] array3 = {" foo=1 ", " bar=2 "}; final Properties prop2 = new Properties(); prop2.setProperty("foo", "1"); prop2.setProperty("bar", "2"); Assert.assertEquals(prop2, StringUtils.splitArrayElementsIntoProperties(array3, "=", " ")); } @Test public void testSplit() { Assert.assertNull(StringUtils.split("AAAAAAA@@", "AAAAAAAA")); Assert.assertNull(StringUtils.split("@", "")); Assert.assertNull(StringUtils.split("", "AAAAAAAA")); Assert.assertArrayEquals(new String[] {"", ""}, StringUtils.split("A", "A")); Assert.assertArrayEquals(new String[] {"foo", "foo"}, StringUtils.split("foo,foo", ",")); } @Test public void testStartsWith() { Assert.assertFalse(StringUtils.startsWithIgnoreCase(null, "")); Assert.assertFalse(StringUtils.startsWithIgnoreCase("LHNCC", "TTsVV")); Assert.assertFalse(StringUtils.startsWithIgnoreCase("", "TTTT")); Assert.assertTrue(StringUtils.startsWithIgnoreCase("Foo", "f")); } @Test public void testStripEnd() { Assert.assertEquals("foo", StringUtils.stripEnd("foo!", "!")); Assert.assertEquals(" foo", StringUtils.stripEnd(" foo ", " ")); Assert.assertEquals("!", StringUtils.stripEnd("!", "")); Assert.assertEquals("#", StringUtils.stripEnd("# ", null)); Assert.assertEquals("", StringUtils.stripEnd("", "!!")); Assert.assertEquals("1234", StringUtils.stripEnd("1234.0", ".0")); } @Test public void testSubstringAfter() { Assert.assertEquals("", StringUtils.substringAfter("foo", null)); Assert.assertEquals("!!", StringUtils.substringAfter("!!", "")); Assert.assertEquals("", StringUtils.substringAfter("", "")); Assert.assertEquals("bar", StringUtils.substringAfter("foo=bar", "=")); } @Test public void testSubstringAfterLast() { Assert.assertEquals("bar", StringUtils.substringAfterLast("foo-bar", "-")); Assert.assertEquals("6", StringUtils.substringAfterLast("123456", "12345")); Assert.assertEquals("", StringUtils.substringAfterLast("foo", "foo")); Assert.assertEquals("", StringUtils.substringAfterLast("foo", "")); Assert.assertEquals("", StringUtils.substringAfterLast("", "")); } @Test public void testSubstringBefore() { Assert.assertNull(StringUtils.substringBefore(null, "")); Assert.assertEquals("foo", StringUtils.substringBefore("foo", "-")); Assert.assertEquals("", StringUtils.substringBefore("foo", "foo")); Assert.assertEquals("", StringUtils.substringBefore("?", "")); Assert.assertEquals("foo", StringUtils.substringBefore("foo, bar", ",")); } @Test public void testSubstringBeforeLast() { Assert.assertEquals("foo", StringUtils.substringBeforeLast("foo", ",")); Assert.assertEquals("", StringUtils.substringBeforeLast("foo", "foo")); Assert.assertEquals("", StringUtils.substringBeforeLast("", ",")); Assert.assertEquals("foo,bar", StringUtils.substringBeforeLast("foo,bar,baz", ",")); } @Test public void testSubstringMatch() { Assert.assertFalse(StringUtils.substringMatch("foo", 524290, "o")); Assert.assertFalse(StringUtils.substringMatch(" foo", 2, "@")); Assert.assertTrue(StringUtils.substringMatch("{{", 1, "{")); Assert.assertTrue(StringUtils.substringMatch("foo", 524290, "")); Assert.assertTrue(StringUtils.substringMatch("foobarbaz", 3, "bar")); } @Test public void testTokenizeToStringArray() { Assert.assertNull(StringUtils.tokenizeToStringArray(null, "?", true, false)); Assert.assertArrayEquals(new String[] {}, StringUtils.tokenizeToStringArray("", "\"\"", false, false)); Assert.assertArrayEquals(new String[] {"bar", "baz", "foo "}, StringUtils.tokenizeToStringArray("bar,baz,foo ,,", ",", false, true)); Assert.assertArrayEquals(new String[] {"bar", "baz", "foo "}, StringUtils.tokenizeToStringArray("bar,baz,foo ,,", ",", false, false)); Assert.assertArrayEquals(new String[] {"bar", "baz", "foo"}, StringUtils.tokenizeToStringArray("bar,baz,foo ,,", ",")); } @Test public void testToStringArray() { final Collection<String> collection = null; final ArrayList<String> arrayList = new ArrayList<String>(); final ArrayList<String> arrayList2 = new ArrayList<String>(); arrayList2.add("foo"); Assert.assertNull(StringUtils.toStringArray(collection)); Assert.assertArrayEquals(new String[] {}, StringUtils.toStringArray(arrayList)); Assert.assertArrayEquals(new String[] {"foo"}, StringUtils.toStringArray(arrayList2)); } @Test public void testTrimAllWhitespace() { Assert.assertEquals("", StringUtils.trimAllWhitespace(" ")); Assert.assertEquals("", StringUtils.trimAllWhitespace("")); Assert.assertEquals("foo", StringUtils.trimAllWhitespace("foo")); Assert.assertEquals("foo", StringUtils.trimAllWhitespace(" foo ")); } @Test public void testTrimLeadingCharacter() { Assert.assertEquals("", StringUtils.trimLeadingCharacter("", 'a')); Assert.assertEquals("foo", StringUtils.trimLeadingCharacter("foo", 'a')); Assert.assertEquals("", StringUtils.trimLeadingCharacter("a", 'a')); Assert.assertEquals("foo", StringUtils.trimLeadingCharacter("afoo", 'a')); } @Test public void testTrimLeadingWhitespace() { Assert.assertEquals("", StringUtils.trimLeadingWhitespace("")); Assert.assertEquals("", StringUtils.trimLeadingWhitespace(" ")); Assert.assertEquals("!", StringUtils.trimLeadingWhitespace("!")); Assert.assertEquals("foo ", StringUtils.trimLeadingWhitespace(" foo ")); } @Test public void testTrimTrailingCharacter() { Assert.assertEquals("foo", StringUtils.trimTrailingCharacter("foo!", '!')); Assert.assertEquals("", StringUtils.trimTrailingCharacter("", '!')); Assert.assertEquals("", StringUtils.trimTrailingCharacter("!", '!')); } @Test public void testTrimTrailingWhitespace() { Assert.assertEquals("", StringUtils.trimTrailingWhitespace(" ")); Assert.assertEquals("", StringUtils.trimTrailingWhitespace("")); Assert.assertEquals(" foo", StringUtils.trimTrailingWhitespace(" foo ")); } @Test public void testTrimWhitespace() { Assert.assertEquals("\u6d7c\u1280", StringUtils.trimWhitespace(" \u6d7c\u1280\u1680")); Assert.assertEquals("", StringUtils.trimWhitespace(" ")); Assert.assertEquals("(", StringUtils.trimWhitespace("(")); Assert.assertEquals("", StringUtils.trimWhitespace("")); Assert.assertEquals("foo foo", StringUtils.trimWhitespace(" foo foo ")); } @Test public void testUncapitalize() { Assert.assertEquals("a", StringUtils.uncapitalize("A")); Assert.assertEquals("a", StringUtils.uncapitalize("a")); Assert.assertEquals("", StringUtils.uncapitalize("")); } @Test public void testCapitalize() { Assert.assertEquals("A", StringUtils.capitalize("a")); Assert.assertEquals("A", StringUtils.capitalize("A")); Assert.assertEquals("", StringUtils.capitalize("")); } @Test public void testUnqualify() { Assert.assertEquals("c", StringUtils.unqualify("a.b.c")); Assert.assertEquals("d", StringUtils.unqualify("a!b!c!d", '!')); } @Test public void testWrap() { Assert.assertEquals("\n!", StringUtils.wrap("!", 0)); Assert.assertEquals("", StringUtils.wrap("", 1)); Assert.assertEquals("f\no\no", StringUtils.wrap("foo", 1)); Assert.assertEquals("f\n", StringUtils.wrap("f\n", 1)); Assert.assertEquals("\u0001\n", StringUtils.wrap("\u0001\n", 3)); } @Test public void testClassLoaderHash() { Assert.assertEquals("null", StringUtils.classLoaderHash(null)); } @Test public void testNormalizeNull() { Assert.assertNull(StringUtils.normalizeClassName(null)); } @Test public void testNormalizeNoSlash() { String input = "com.example.Class"; Assert.assertEquals(input, StringUtils.normalizeClassName(input)); } @Test public void testNormalizeWithSlash() { String input = "com/example/Class"; Assert.assertEquals("com.example.Class", StringUtils.normalizeClassName(input)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/DecompilerTest.java
core/src/test/java/com/taobao/arthas/core/util/DecompilerTest.java
package com.taobao.arthas.core.util; import java.io.File; import org.assertj.core.api.Assertions; import org.junit.Test; /** * * @author hengyunabc 2021-02-09 * */ public class DecompilerTest { @Test public void test() { String dir = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); File classFile = new File(dir, this.getClass().getName().replace('.', '/') + ".class"); String code = Decompiler.decompile(classFile.getAbsolutePath(), null, true); System.err.println(code); Assertions.assertThat(code).contains("/*23*/ System.err.println(code);").contains("/*32*/ int i = 0;"); } public void aaa() { int jjj = 0; for (int i = 0; i < 100; ++i) { System.err.println(i); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/IPUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/IPUtilsTest.java
package com.taobao.arthas.core.util; import static org.junit.Assert.assertEquals; import org.junit.Test; public class IPUtilsTest { @Test public void testZeroIPv4() { String zero = "0.0.0.0"; assertEquals(true, IPUtils.isAllZeroIP(zero)); } @Test public void testZeroIPv6() { String zero = "::"; assertEquals(true, IPUtils.isAllZeroIP(zero)); } @Test public void testNormalIPv6() { String ipv6 = "2001:db8:85a3::8a2e:370:7334"; assertEquals(false, IPUtils.isAllZeroIP(ipv6)); } @Test public void testLeadingZerosIPv6() { String ipv6 = "0000::0000:0000"; assertEquals(true, IPUtils.isAllZeroIP(ipv6)); } @Test public void testTrailingZerosIPv6() { String ipv6 = "::0000:0000:0000"; assertEquals(true, IPUtils.isAllZeroIP(ipv6)); } @Test public void testMixedZerosIPv6() { String ipv6 = "0000::0000:0000:0000:0000"; assertEquals(true, IPUtils.isAllZeroIP(ipv6)); } @Test public void testEmptyIPv6() { String empty = ""; assertEquals(false, IPUtils.isAllZeroIP(empty)); } @Test public void testBlankIPv6() { String blank = " "; assertEquals(false, IPUtils.isAllZeroIP(blank)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/TokenUtilsTest.java
core/src/test/java/com/taobao/arthas/core/util/TokenUtilsTest.java
package com.taobao.arthas.core.util; import com.taobao.arthas.core.shell.cli.CliToken; import com.taobao.arthas.core.shell.cli.impl.CliTokenImpl; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author earayu */ public class TokenUtilsTest { private List<CliToken> newCliTokenList(CliToken ... tokens){ List<CliToken> cliTokens = new ArrayList<CliToken>(); if(tokens!=null) { Collections.addAll(cliTokens, tokens); } return cliTokens; } @Test public void testFindFirstTextToken(){ CliToken textCliToken = new CliTokenImpl(true,"textCliToken"); CliToken nonTextCliToken = new CliTokenImpl(false,"nonTextCliToken"); //null list Assert.assertEquals(null, TokenUtils.findFirstTextToken(null)); //empty list Assert.assertEquals(null, TokenUtils.findFirstTextToken(new ArrayList<CliToken>())); //list with null value Assert.assertEquals(null, TokenUtils.findFirstTextToken(newCliTokenList(new CliToken[]{null}))); Assert.assertEquals(textCliToken, TokenUtils.findFirstTextToken(newCliTokenList(new CliToken[]{null, textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findFirstTextToken(newCliTokenList(new CliToken[]{null, nonTextCliToken, textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findFirstTextToken(newCliTokenList(new CliToken[]{nonTextCliToken, null, textCliToken}))); //list with normal inputs Assert.assertEquals(textCliToken, TokenUtils.findFirstTextToken(newCliTokenList(new CliToken[]{textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findFirstTextToken(newCliTokenList(new CliToken[]{nonTextCliToken, textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findFirstTextToken(newCliTokenList(new CliToken[]{textCliToken, nonTextCliToken}))); } @Test public void testFindLastTextToken(){ CliToken textCliToken = new CliTokenImpl(true,"textCliToken"); CliToken nonTextCliToken = new CliTokenImpl(false,"nonTextCliToken"); //null list Assert.assertEquals(null, TokenUtils.findLastTextToken(null)); //empty list Assert.assertEquals(null, TokenUtils.findLastTextToken(new ArrayList<CliToken>())); //list with null value Assert.assertEquals(null, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{null}))); Assert.assertEquals(textCliToken, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{null, textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{null, nonTextCliToken, textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{nonTextCliToken, null, textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{textCliToken, null, nonTextCliToken}))); //list with normal inputs Assert.assertEquals(textCliToken, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{textCliToken}))); Assert.assertEquals(null, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{nonTextCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{nonTextCliToken, textCliToken}))); Assert.assertEquals(textCliToken, TokenUtils.findLastTextToken(newCliTokenList(new CliToken[]{textCliToken, nonTextCliToken}))); } @Test public void testFindSecondTextToken(){ CliToken textCliToken = new CliTokenImpl(true,"textCliToken"); CliToken nonTextCliToken = new CliTokenImpl(false,"nonTextCliToken"); //null list Assert.assertEquals(null, TokenUtils.findSecondTokenText(null)); //empty list Assert.assertEquals(null, TokenUtils.findSecondTokenText(new ArrayList<CliToken>())); //list with null value Assert.assertEquals(null, TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{null}))); Assert.assertEquals(null, TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{null, textCliToken}))); Assert.assertEquals(null, TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{null, nonTextCliToken, textCliToken}))); Assert.assertEquals(textCliToken.value(), TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{null, nonTextCliToken, textCliToken, textCliToken}))); //list with normal inputs Assert.assertEquals(null, TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{textCliToken}))); Assert.assertEquals(null, TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{nonTextCliToken}))); Assert.assertEquals(null, TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{nonTextCliToken, textCliToken}))); Assert.assertEquals(textCliToken.value(), TokenUtils.findSecondTokenText(newCliTokenList(new CliToken[]{textCliToken, nonTextCliToken, textCliToken}))); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false