In Aspectran, an Activity (Activity) is the framework’s core runtime execution engine orchestrating a single request-response lifecycle. Every unit of execution arriving from the external world—an HTTP request from a web browser, a non-blocking network event loop, a background scheduler trigger, an interactive CLI command, or an internal method invocation—is encapsulated and processed within a dedicated Activity instance.
The Activity architecture completely decouples business logic (Actions, Beans) from the underlying execution environment (Servlet, Netty, Undertow, etc.), enforcing a uniform, standard lifecycle for AOP advices, parameter parsing, translet rule evaluation, response rendering, and exception handling pipelines.
1. Division of Roles: Activity vs Translet
To understand Aspectran’s execution model, it is vital to distinguish the distinct responsibilities and interaction between Activity and Translet.
graph LR
subgraph Engine["Runtime Engine"]
Act[Activity / CoreActivity]
Adapters[Request / Response / Session Adapters]
AOP[AOP Advice Executor]
end
subgraph UserSpace["Application Space"]
Tr[Translet Interface]
Actions[Actions / Beans]
Data[ActivityData / ProcessResult]
end
Client[Incoming Request] --> Act
Act -->|Initialize Adapters & Bind Rules| Adapters
Act -->|Expose Translet Instance| Tr
Tr -->|Query Request Data & Store Results| Actions
Actions --> Data
Act -->|Collect Results & Render Views| Client
Activity(Internal Execution Engine):- Serves as the framework-level runtime controller.
- Owns and manages the
ActivityContext, classloader, environment adapters (RequestAdapter,ResponseAdapter,SessionAdapter), AOP advice chains, and exception processors, driving the internal state machine. - Application developers rarely interact with
Activitydirectly; it is created and driven by the service layer.
Translet(Application Space Facade):- Serves as the business-facing medium for application developers.
- Encapsulates the specific translet rule (
TransletRule), execution data (ActivityData), and execution results (ProcessResult) associated with a single request. - Acts as the standard interface injected into action methods or view templates to inspect parameters or set attributes.
2. Hierarchical Class Structure and Core Models
Aspectran’s Activity class hierarchy is meticulously designed around the Single Responsibility Principle and the Template Method pattern.
classDiagram
direction TB
class Activity {
<<interface>>
+getMode() Mode
+getActivityContext() ActivityContext
+getRequestAdapter() RequestAdapter
+getResponseAdapter() ResponseAdapter
+getSessionAdapter() SessionAdapter
+getTranslet() Translet
+perform()
+terminate()
}
class AbstractActivity {
<<abstract>>
-Activity pendingActivity
#saveCurrentActivity()
#removeCurrentActivity()
}
class AdviceActivity {
<<abstract>>
#executeBeforeAdvices()
#executeAfterAdvices()
#executeFinallyAdvices()
}
class CoreActivity {
-CoreTranslet translet
-ActivityData activityData
+prepare(String, MethodType)
+perform()
#adapt()
#parseRequest()
#produce()
#response()
#finish()
}
class DefaultActivity {
}
class InstantActivity {
+perform(InstantAction)
}
class JobActivity {
-JobExecutionContext jobExecutionContext
}
class ProxyActivity {
-Activity actualActivity
}
Activity <|.. AbstractActivity
AbstractActivity <|-- AdviceActivity
AdviceActivity <|-- CoreActivity
AdviceActivity <|-- ProxyActivity
CoreActivity <|-- DefaultActivity
CoreActivity <|-- InstantActivity
CoreActivity <|-- JobActivity
CoreActivity <|-- ServletWebActivity
CoreActivity <|-- NettyActivity
CoreActivity <|-- TowActivity
CoreActivity <|-- ShellActivity
CoreActivity <|-- DaemonActivity
CoreActivity <|-- AspectranActivity
1) Activity.Mode: 6 Runtime Modes
Activity defines enumeration constants representing the runtime characteristics of its host environment:
WEB: Standard servlet or servlet-less HTTP web request processingSHELL: Interactive terminal command-line executionDAEMON: Persistent background OS daemon process executionSCHEDULER: Quartz-based scheduled batch job executionPROXY: IoC container AOP dynamic proxy method interceptionDEFAULT: General-purpose execution mode unbound to a specific service
2) AbstractActivity: ThreadLocal Binding & Nested Stack Management
Safely binds and unbinds the currently active Activity to a ThreadLocal for the current thread.
- Nested Execution (
pendingActivity) Stack: When anInstantActivityorProxyActivityis triggered inside an existing request, the active activity is stored in thependingActivityfield while the new activity takes over the thread context. Once the nested execution completes, the previous activity is restored seamlessly.
3) AdviceActivity: AOP Advice Execution Engine
Directly coupled with Aspectran’s lightweight AOP engine to trigger aspect rules before, after, or upon exception of translet execution:
executeBeforeAdvices(): Executes thebeforeadvice chainexecuteAfterAdvices(): Executes theafteradvice chainexecuteFinallyAdvices(): Executes thefinallyadvice chain regardless of success or failure
4) CoreActivity: 5-Phase Request Processing Pipeline
The core abstract class orchestrating the entire lifecycle: finding translets, parsing parameters, invoking actions, and rendering final responses.
3. End-to-End Request Processing: 5 Deterministic Phases
The request processing pipeline governed by CoreActivity consists of five sequential, deterministic phases.
sequenceDiagram
autonumber
participant Client as Client / Runtime Entry
participant Activity as CoreActivity
participant Adapter as Adapters (Req/Res)
participant AOP as AOP Advice Engine
participant Action as Actions / Content
participant View as Response (View/Transform)
Client->>Activity: prepare(requestName, method)
Note over Activity: 1. Match TransletRule, instantiate CoreTranslet,<br/>validate HTTP method, assemble advice rules
Client->>Activity: adapt() (Subclass Hook)
Note over Activity,Adapter: 2. Wrap native I/O objects into<br/>RequestAdapter and ResponseAdapter
Activity->>Activity: parseRequest()
Note over Activity: 3. Extract path variables, map parameters,<br/>validate mandatory fields, restore FlashMap, resolve locale
Client->>Activity: perform()
Activity->>AOP: executeBeforeAdvices()
Activity->>Action: produce() (Sequential ContentList & ActionList execution)
Action-->>Activity: Accumulate ProcessResult data
Activity->>View: response() (View Dispatch / Transform / Redirect / Forward)
View-->>Client: Stream response body & headers
Activity->>AOP: executeAfterAdvices()
alt Upon Exception
Activity->>AOP: executeThrownAdvices()
Activity->>Activity: processExceptionRules() (Declarative exception mapping)
end
Activity->>AOP: executeFinallyAdvices()
Client->>Activity: finish()
Note over Activity: 5. Flush buffer, clean up resources, unbind ThreadLocal
Phase 1: Preparation (prepare)
- Queries the
TransletRuleRegistryfor a matchingTransletRulebased on the incoming request URI (requestName) and HTTP method (MethodType). - Throws a
TransletNotFoundExceptionif no matching rule is registered. - Instantiates
CoreTransletand validates allowed HTTP methods (RequestMethodNotAllowedException). - Evaluates pointcuts to build the AOP advice rule chain (
prepareAdviceRules) applicable to the target translet.
Phase 2: Environment Adaptation (adapt)
- Specialized
Activitysubclasses (ServletWebActivity,NettyActivity, etc.) wrap native request and response objects into standardizedRequestAdapterandResponseAdaptercontracts. - Beyond this step, all subsequent business logic and framework pipelines operate completely independently of underlying infrastructure.
Phase 3: Request Parsing (parseRequest)
- Normalizes and injects request parameters, character encodings, and session attributes into the execution context:
- Path Variable Extraction: Extracts dynamic tokens from RESTful URI patterns (e.g.,
/users/{id}) into aPathVariableMap. - Declarative Parameter/Attribute Binding: Evaluates default values and ASEL token expressions defined in
RequestRuleand binds them toActivityData. - Mandatory Field Validation: Immediately raises a
MissingMandatoryParametersExceptionif required parameters are missing. - FlashMap & Locale Resolution: Restores transient flash attributes passed from prior redirect requests and resolves the client locale using
LocaleResolver.
- Path Variable Extraction: Extracts dynamic tokens from RESTful URI patterns (e.g.,
Phase 4: Execution & Response (perform)
- The central phase where business actions run and outputs are rendered:
- Before Advices: Starts transactions, performs authentication/authorization checks, and logs audit traces.
- Content Action Execution (
produce): Executes actions (Executable) declared in<content>sections sequentially, collecting return values intoProcessResult. - Response Handling (
response):TransformResponse: Data transformation (JSON, XML, Text, APON).DispatchResponse: View template dispatching (JSP, Thymeleaf, FreeMarker).RedirectResponse: HTTP 302/303 URL redirection.ForwardResponse: Internal delegation to another translet while preserving accumulatedProcessResultdata (forwarding loop).
- After Advices: Post-processing following successful action execution.
- Exception Handling (
processExceptionRules): Catches thrown exceptions, routes them to declarative<exception>rules, and executesThrownadvices to generate error views or error responses. - Finally Advices: Guaranteed cleanup and release of acquired transactional or system resources.
Phase 5: Teardown & Cleanup (finish)
- Flushes and closes response output streams and buffers.
- Removes the
Activityfrom the thread-local storage (removeCurrentActivity()) or restores the priorpendingActivity. - Decrements the active request counter in
ActivityCounter.
4. Specialized Activity Implementations per Runtime
Specialized subclasses extend CoreActivity’s template pipeline to handle the I/O mechanics of each runtime environment.
| Environment | Dedicated Activity Implementation | Bound Native Object | Key Responsibilities & Characteristics |
|---|---|---|---|
| Servlet Web | ServletWebActivity | HttpServletRequest, HttpServletResponse | Combines HttpServletRequestAdapter & HttpServletResponseAdapter, manages servlet session binding and Servlet 3.0+ AsyncContext lifecycles |
| Netty | NettyActivity | ChannelHandlerContext, FullHttpRequest | Directly coupled to non-blocking event loops, streams zero-copy ByteBuf responses, binds servlet-less NettyRequestAdapter & NettyResponseAdapter |
| Undertow | TowActivity | HttpServerExchange | Native Undertow communication, binds TowRequestAdapter & TowResponseAdapter, delivers low-overhead servlet-free streaming |
| Shell | ShellActivity | TransletCommandLine, ShellConsole | JLine3-based interactive terminal I/O, binds ShellRequestAdapter & ShellResponseAdapter, manages ANSI formatting and console output |
| Daemon | DaemonActivity | Internal ParameterMap, Attribute Map | Standalone OS daemon process, binds DaemonRequestAdapter & DaemonResponseAdapter, captures internal memory I/O buffers |
| Embedded | AspectranActivity | In-Memory Parameter / Attribute Maps | Embedded invocations from host Java applications, binds EmbeddedRequestAdapter & EmbeddedResponseAdapter, returns results directly in memory |
5. Special-Purpose Activity Implementations
Beyond standard translet executions, Aspectran provides lightweight and specialized infrastructure Activity implementations:
1) Lightweight Programmatic Execution: InstantActivity
Allows immediate execution of arbitrary Java code blocks (InstantAction<V>) within Aspectran’s managed context (Bean injection, environment variable access, transaction management) without declaring a pre-configured translet rule.
InstantActivity activity = new InstantActivity(activityContext);
Integer count = activity.perform(() -> {
UserService userService = activity.getBean(UserService.class);
return userService.countUsers();
});
2) Quartz Scheduling Execution: JobActivity
Receives schedule metadata (JobRule, Trigger) from Quartz’s JobExecutionContext to execute designated translets in the background, providing scheduled batch jobs with the exact same DI, AOP, and template capabilities as standard web requests.
3) IoC/AOP Proxy Interception: ProxyActivity
A specialized virtual activity created inside dynamic proxies or CGLIB/Javassist proxies to intercept method calls on POJO beans managed by the IoC container. If an active activity already exists (actualActivity), it references and preserves that context.
6. ThreadLocal Management and Context Injection
To ensure thread safety and concurrency isolation in multi-threaded environments, ActivityContext maintains a ThreadLocal<Activity>.
- Active Activity Lookup:
Activity activity = ActivityContext.getCurrentActivity();If no activity is bound to the current thread, a
NoActivityStateExceptionis thrown to prevent invalid asynchronous access. - Dependency Injection Support:
- Beans implementing
CurrentActivityAwarereceive the current activeActivityautomatically upon instantiation or method invocation. CurrentActivityDataFactoryBeancan be used to inject the current request’sActivityDatadirectly into bean properties.
- Beans implementing
🔍 Related Detailed Mechanisms
- For how activities isolate input/output data using adapter interfaces, see Aspectran Adapter Architecture.
- For how the service layer creates and orchestrates activities, see Aspectran Service Architecture.
- For the structural details of translet rules and actions parsed by activities, see Aspectran Rule Architecture.
7. Next Steps: Exploring Detailed Mechanisms
To explore the specific types of business actions (BeanAction, MethodAction, EchoAction, HeaderAction, etc.) and response transformation strategies that run inside the Activity pipeline, continue to the dedicated mechanism documents.
To see how all mechanisms and packages interconnect across the entire framework, refer to the Aspectran Detailed Mechanisms Index.