### Component Setup for Standalone Server Source: https://context7.com/restlet/restlet-framework-java/llms.txt Sets up the main Restlet Component, adds an HTTP server connector, a client connector, and attaches a custom application. This is the entry point for standalone server deployment. ```java import org.restlet.Component; import org.restlet.Server; import org.restlet.data.Protocol; public class Main { public static void main(String[] args) throws Exception { // Create the component Component component = new Component(); // Add an HTTP server connector on port 8182 component.getServers().add(Protocol.HTTP, 8182); // Add an HTTPS client connector so the app can make outbound HTTPS calls component.getClients().add(Protocol.HTTPS); // Attach the application to the default virtual host component.getDefaultHost().attach("/api", new MyApplication()); // Start the component (starts connectors, routers, services) component.start(); // The server is now listening on http://localhost:8182/api/... // Graceful shutdown // component.stop(); } } ``` -------------------------------- ### ServerResource - Annotated HTTP Resource Handler Source: https://context7.com/restlet/restlet-framework-java/llms.txt Demonstrates how to create server-side resources using ServerResource and annotating methods with HTTP verbs like @Get, @Post, @Put, @Delete, and @Options to handle incoming requests. ```APIDOC ## ServerResource — Annotated HTTP Resource Handler `ServerResource` is the base class for server-side resources. Annotate methods with `@Get`, `@Post`, `@Put`, `@Delete`, `@Patch`, or `@Options` to declare HTTP handlers. One instance is created per request, so no thread-safety concerns on instance fields. ```java import org.restlet.data.Status; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; public class UserResource extends ServerResource { // Simulated data store private static final java.util.Map store = new java.util.concurrent.ConcurrentHashMap<>(); @Get("json") // responds to GET, produces JSON public User retrieve() { String userId = getAttribute("userId"); User user = store.get(userId); if (user == null) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); return null; } return user; } @Put("json:json") // consumes JSON, produces JSON public User store(User incoming) { String userId = getAttribute("userId"); store.put(userId, incoming); setStatus(Status.SUCCESS_OK); return incoming; } @Post("json:json") // consumes JSON, produces JSON public User create(User incoming) throws ResourceException { if (incoming == null) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Body required"); } store.put(incoming.getId(), incoming); setStatus(Status.SUCCESS_CREATED); setLocationRef("/users/" + incoming.getId()); return incoming; } @Delete public void remove() { String userId = getAttribute("userId"); if (store.remove(userId) == null) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { setStatus(Status.SUCCESS_NO_CONTENT); } } } ``` ``` -------------------------------- ### Make HTTP GET and POST Requests with ClientResource Source: https://context7.com/restlet/restlet-framework-java/llms.txt Use ClientResource to make direct HTTP calls. Supports GET with JSON media type and POST with a JSON body. Ensure to release the resource after use. ```java import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; public class WeatherClient { public static void main(String[] args) throws Exception { // Simple GET returning text ClientResource cr = new ClientResource("http://api.example.com/weather/london"); try { Representation rep = cr.get(MediaType.APPLICATION_JSON); System.out.println("Weather: " + rep.getText()); System.out.println("Status: " + cr.getStatus()); } catch (ResourceException e) { System.err.println("HTTP error: " + e.getStatus()); } finally { cr.release(); } // POST with a JSON body ClientResource post = new ClientResource("http://api.example.com/alerts"); try { String body = "{\"city\":\"london\",\"threshold\":5}"; Representation result = post.post( new org.restlet.representation.StringRepresentation( body, MediaType.APPLICATION_JSON), MediaType.APPLICATION_JSON); if (Status.SUCCESS_CREATED.equals(post.getStatus())) { System.out.println("Alert created: " + result.getText()); } } finally { post.release(); } } } ``` -------------------------------- ### ServerResource HTTP Handlers with Annotations Source: https://context7.com/restlet/restlet-framework-java/llms.txt Extend ServerResource and annotate methods with @Get, @Post, @Put, @Delete, or @Options to handle specific HTTP methods. One instance is created per request, avoiding thread-safety issues with instance fields. ```java import org.restlet.data.Status; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; public class UserResource extends ServerResource { // Simulated data store private static final java.util.Map store = new java.util.concurrent.ConcurrentHashMap<>(); @Get("json") // responds to GET, produces JSON public User retrieve() { String userId = getAttribute("userId"); User user = store.get(userId); if (user == null) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); return null; } return user; } @Put("json:json") // consumes JSON, produces JSON public User store(User incoming) { String userId = getAttribute("userId"); store.put(userId, incoming); setStatus(Status.SUCCESS_OK); return incoming; } @Post("json:json") // consumes JSON, produces JSON public User create(User incoming) throws ResourceException { if (incoming == null) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Body required"); } store.put(incoming.getId(), incoming); setStatus(Status.SUCCESS_CREATED); setLocationRef("/users/" + incoming.getId()); return incoming; } @Delete public void remove() { String userId = getAttribute("userId"); if (store.remove(userId) == null) { setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { setStatus(Status.SUCCESS_NO_CONTENT); } } } ``` -------------------------------- ### Implement Request/Response Filtering in Java Source: https://context7.com/restlet/restlet-framework-java/llms.txt Create a custom Filter to process requests before they reach the resource and responses after. Control pipeline flow using CONTINUE, SKIP, or STOP. Example shows API key validation and adding a response header. ```java import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.routing.Filter; public class ApiKeyFilter extends Filter { public ApiKeyFilter(Context context) { super(context); } @Override protected int beforeHandle(Request request, Response response) { String apiKey = request.getHeaders().getFirstValue("X-Api-Key"); if (!"secret-key-123".equals(apiKey)) { response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); return STOP; // halt processing, return 401 } return CONTINUE; // pass to next stage } @Override protected void afterHandle(Request request, Response response) { // Add a response header after the resource handled the call response.getHeaders().add("X-Powered-By", "Restlet Framework"); } } // Wire filter into routing inside Application.createInboundRoot(): Router router = new Router(getContext()); router.attach("/secure/data", DataResource.class); ApiKeyFilter filter = new ApiKeyFilter(getContext()); filter.setNext(router); // filter → router → resource return filter; ``` -------------------------------- ### Internal Application-to-Application Calls with RIAP Source: https://context7.com/restlet/restlet-framework-java/llms.txt Use RIAP URIs to call components and applications directly in-process without network overhead. Ensure the component is started before making internal calls. ```java import org.restlet.Application; import org.restlet.Component; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.LocalReference; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; Component component = new Component(); Application backend = new Application() { @Override public Restlet createInboundRoot() { return new Restlet(getContext()) { @Override public void handle(Request req, Response resp) { String name = req.getResourceRef().getRemainingPart().substring(1); resp.setEntity(new StringRepresentation("Hello, " + name + "!")); } }; } }; // Attach backend to the internal (non-network) router component.getInternalRouter().attach("/greet", backend); component.start(); // Call the internal application from anywhere within the same component String riapUri = LocalReference.createRiapReference( LocalReference.RIAP_COMPONENT, "/greet/World").toString(); // riapUri == "riap://component/greet/World" ClientResource internal = new ClientResource(riapUri); internal.setNext(component.getContext().getClientDispatcher()); System.out.println(internal.get().getText()); // "Hello, World!" internal.release(); ``` -------------------------------- ### Static File Serving with Directory Source: https://context7.com/restlet/restlet-framework-java/llms.txt Configure the Directory class to serve static files from a local directory. Enable directory listings and deep accessibility as needed. ```java import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.resource.Directory; import org.restlet.routing.Router; public class StaticApp extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); // Serve files from /var/www/html Directory dir = new Directory(getContext(), "file:///var/www/html"); dir.setListingAllowed(true); // enable directory listings dir.setDeeplyAccessible(true); // allow subdirectory traversal dir.setIndexName("index.html"); // default document router.attach("/static/", dir); router.attach("/api/", ApiResource.class); return router; } } ``` -------------------------------- ### Configure Router for URI Pattern Routing in Java Source: https://context7.com/restlet/restlet-framework-java/llms.txt Set up a Router to dispatch calls based on URI patterns, supporting static paths, template variables, wildcards, and default fallbacks. Use Router.MODE_BEST_MATCH for optimal route selection. ```java import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.routing.Router; public class BookApplication extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); // Use best-match mode (scores all routes, picks highest) router.setDefaultMatchingMode(Router.MODE_BEST_MATCH); // Static path router.attach("/books", BookListResource.class); // Path with URI template variable {isbn} router.attach("/books/{isbn}", BookResource.class); // Wildcard: matches /docs/any/path/below router.attach("/docs/", DirectoryResource.class); // Default fallback route router.attachDefault(NotFoundResource.class); return router; } } // In BookResource, retrieve the URI variable: public class BookResource extends ServerResource { @Get("json") public Book fetch() { String isbn = getAttribute("isbn"); // from /books/{isbn} return BookStore.find(isbn); } } ``` -------------------------------- ### Configure HTTP Basic Authentication in Java Source: https://context7.com/restlet/restlet-framework-java/llms.txt Use ChallengeAuthenticator with MapVerifier for simple in-memory credential checking to secure application resources with HTTP Basic authentication. Set optional to false to always require authentication. ```java import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.routing.Router; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.MapVerifier; public class SecureApp extends Application { @Override public Restlet createInboundRoot() { // Build the inner routing tree Router router = new Router(getContext()); router.attach("/data", DataResource.class); // Set up HTTP BASIC auth with in-memory credentials MapVerifier verifier = new MapVerifier(); verifier.getLocalSecrets().put("alice", "passw0rd".toCharArray()); verifier.getLocalSecrets().put("bob", "s3cret".toCharArray()); ChallengeAuthenticator authenticator = new ChallengeAuthenticator(getContext(), false, // optional=false → always require auth ChallengeScheme.HTTP_BASIC, "My Secure Realm", verifier); authenticator.setNext(router); return authenticator; // authenticator → router → resource } } ``` -------------------------------- ### Set up VirtualHost for Name-based Routing Source: https://context7.com/restlet/restlet-framework-java/llms.txt Configure VirtualHost to route calls based on the requested host name or port. Enables multiple applications to share a single Component on the same port. ```java import org.restlet.Component; import org.restlet.data.Protocol; import org.restlet.routing.VirtualHost; Component component = new Component(); component.getServers().add(Protocol.HTTP, 80); component.getClients().add(Protocol.HTTP); // Virtual host for api.example.com VirtualHost apiHost = new VirtualHost(component.getContext()); apiHost.setHostDomain("api\.example\.com"); // regex apiHost.attach("/v1", new ApiV1Application()); apiHost.attach("/v2", new ApiV2Application()); component.getHosts().add(apiHost); // Virtual host for www.example.com VirtualHost wwwHost = new VirtualHost(component.getContext()); wwwHost.setHostDomain("www\.example\.com"); wwwHost.attach("/", new WebApplication()); component.getHosts().add(wwwHost); // Default host catches everything else component.getDefaultHost().attach("/health", new HealthResource.class); component.start(); ``` -------------------------------- ### Configure Jetty Log Level via Properties File Source: https://github.com/restlet/restlet-framework-java/blob/2.6/org.restlet.java/org.restlet.ext.jetty/README.md Configure the logging level for Jetty and its client to TRACE by creating a `jetty-logging.properties` file. This method is an alternative to programmatic setting. ```properties org.eclipse.jetty.LEVEL=TRACE org.eclipse.jetty.client.LEVEL=TRACE ``` -------------------------------- ### Application Definition with Resource Routing Source: https://context7.com/restlet/restlet-framework-java/llms.txt Defines a custom Restlet Application by subclassing Application and overriding createInboundRoot() to set up URI routing. Enables response compression by default. ```java import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.routing.Router; public class MyApplication extends Application { public MyApplication() { super(); // Enable response compression (disabled by default) getEncoderService().setEnabled(true); } @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); // Attach resources to URI patterns router.attach("/users", UserListResource.class); router.attach("/users/{userId}", UserResource.class); router.attach("/orders/{id}", OrderResource.class); return router; } } ``` -------------------------------- ### Activate JMX Debugging in Jetty Source: https://github.com/restlet/restlet-framework-java/blob/2.6/org.restlet.java/org.restlet.ext.jetty/README.md Integrate JMX for debugging by creating an MBeanContainer and adding it to the Jetty server component. This allows for state tracking and operation management via JMX tools like jconsole. ```java // Create an MBeanContainer with the platform MBeanServer. MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); // Add MBeanContainer to the root component. jettyServer.addBean(mbeanContainer); ``` -------------------------------- ### Maven Dependencies for Restlet Framework Source: https://context7.com/restlet/restlet-framework-java/llms.txt Add these dependencies to your pom.xml for core Restlet functionality, the Jetty connector for standalone operation, and the Jackson extension for automatic JSON conversion. Ensure you have the Maven Central repository configured. ```xml org.restlet org.restlet 2.6.0 org.restlet org.restlet.ext.jetty 2.6.0 org.restlet org.restlet.ext.jackson 2.6.0 org.restlet org.restlet.ext.spring 2.6.0 maven-central https://repo1.maven.org/maven2/ ``` -------------------------------- ### Set Jetty Log Level Programmatically Source: https://github.com/restlet/restlet-framework-java/blob/2.6/org.restlet.java/org.restlet.ext.jetty/README.md Set the global logging level for Jetty to TRACE programmatically. This is useful for detailed debugging. ```java System.setProperty("org.eclipse.jetty.LEVEL", "TRACE"); ``` -------------------------------- ### Configure Redirector for URI Rewriting and Proxying Source: https://context7.com/restlet/restlet-framework-java/llms.txt Use Redirector to rewrite URIs and perform client-side redirects or server-side proxy forwarding. Supports URI template variables like {rr} for remaining path. ```java import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.routing.Redirector; import org.restlet.routing.Router; public class ProxyApp extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); // Permanent 301 redirect: /old-api/... → /api/... Redirector permanentRedirect = new Redirector( getContext(), "/api/{rr}", Redirector.MODE_CLIENT_PERMANENT); router.attach("/old-api/", permanentRedirect); // Transparent reverse-proxy: /proxy/... → http://backend:9090/... Redirector proxy = new Redirector( getContext(), "http://backend:9090/{rr}", Redirector.MODE_SERVER_OUTBOUND); router.attach("/proxy/", proxy); router.attach("/api/", ApiResource.class); return router; } } ``` -------------------------------- ### Wrapping Response Bodies with Representations Source: https://context7.com/restlet/restlet-framework-java/llms.txt Use various Representation subclasses to wrap response entities, including strings, files, streams, and byte arrays. Ensure the correct MediaType and Charset are set. ```java import org.restlet.data.MediaType; import org.restlet.representation.FileRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; import java.io.File; import java.io.InputStream; public class DownloadResource extends ServerResource { @Get("json") public StringRepresentation asJson() { return new StringRepresentation( "{\"status\":\"ok\"}", MediaType.APPLICATION_JSON); } @Get("txt") public StringRepresentation asText() { return new StringRepresentation("Everything is fine.", MediaType.TEXT_PLAIN); } @Get("pdf") public FileRepresentation asPdf() { File report = new File("/var/reports/report.pdf"); return new FileRepresentation(report, MediaType.APPLICATION_PDF); } @Get("octet-stream") public InputRepresentation asStream() { InputStream is = getClass().getResourceAsStream("/data/archive.zip"); return new InputRepresentation(is, MediaType.APPLICATION_ZIP); } } ``` -------------------------------- ### Annotated Resource Interface for Type-Safe REST Source: https://context7.com/restlet/restlet-framework-java/llms.txt Define a shared Java interface with Restlet HTTP annotations for compile-time safety between server implementations and client proxies. This ensures consistency in REST interactions. ```java // -- Shared interface (e.g., in a common module) -- import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Options; import org.restlet.resource.Post; import org.restlet.resource.Put; public interface UserResource01 { @Get User represent(); // GET → returns User (content-negotiated) @Put String store(User user); // PUT → stores user, returns confirmation @Post boolean accept(User user); // POST → submits user, returns success flag @Delete("txt") String remove(); // DELETE → deletes, returns plain-text message @Options("txt") String describe(); // OPTIONS → returns plain-text description } ``` ```java // -- Server implementation -- public class UserServerResource extends ServerResource implements UserResource01 { private User current = new User("alice", "Alice Smith"); public User represent() { return current; } public String store(User u) { current = u; return "Stored"; } public boolean accept(User u) { return u != null; } public String remove() { current = null; return "Deleted"; } public String describe() { return "User resource: GET, PUT, POST, DELETE"; } } ``` ```java // -- Client usage (type-safe proxy) -- import org.restlet.resource.ClientResource; ClientResource cr = new ClientResource("http://localhost:8182/api/users/alice"); UserResource01 proxy = cr.wrap(UserResource01.class); User u = proxy.represent(); // GET /api/users/alice System.out.println(u.getName()); // "Alice Smith" String result = proxy.store(new User("alice", "Alice Updated")); // PUT System.out.println(result); // "Stored" proxy.remove(); // DELETE cr.release(); ``` -------------------------------- ### Annotated Resource Interface - Type-safe Client/Server Contract Source: https://context7.com/restlet/restlet-framework-java/llms.txt Defines a shared Java interface annotated with Restlet HTTP annotations, enabling type-safe REST interactions between clients and servers. ```APIDOC ## Annotated Resource Interface — Type-safe Client/Server Contract Define a shared Java interface annotated with Restlet HTTP annotations. Both the server implementation and the `ClientResource` proxy use the same interface, giving compile-time safety to REST interactions. ```java // -- Shared interface (e.g., in a common module) -- import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Options; import org.restlet.resource.Post; import org.restlet.resource.Put; public interface UserResource01 { @Get User represent(); // GET → returns User (content-negotiated) @Put String store(User user); // PUT → stores user, returns confirmation @Post boolean accept(User user); // POST → submits user, returns success flag @Delete("txt") String remove(); // DELETE → deletes, returns plain-text message @Options("txt") String describe(); // OPTIONS → returns plain-text description } // -- Server implementation -- public class UserServerResource extends ServerResource implements UserResource01 { private User current = new User("alice", "Alice Smith"); public User represent() { return current; } public String store(User u) { current = u; return "Stored"; } public boolean accept(User u) { return u != null; } public String remove() { current = null; return "Deleted"; } public String describe() { return "User resource: GET, PUT, POST, DELETE"; } } // -- Client usage (type-safe proxy) -- import org.restlet.resource.ClientResource; ClientResource cr = new ClientResource("http://localhost:8182/api/users/alice"); UserResource01 proxy = cr.wrap(UserResource01.class); User u = proxy.represent(); // GET /api/users/alice System.out.println(u.getName()); // "Alice Smith" String result = proxy.store(new User("alice", "Alice Updated")); // PUT System.out.println(result); // "Stored" proxy.remove(); // DELETE cr.release(); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.