From 02a8ce37ad5648850d2d5fcb0fdc195b2f18be9e Mon Sep 17 00:00:00 2001 From: Jerome Louvel <374450+jlouvel@users.noreply.github.com> Date: Sun, 27 Oct 2024 23:37:32 -0400 Subject: [PATCH] Removed deprecated code Removed code deprecated in version 2.4, including native Restlet XML configuration mechasism. Please use Spring for an alternative approach if needed. --- changes.md | 2 + .../java/org/restlet/ext/gae/GaeEnroler.java | 34 - .../java/org/restlet/ext/gwt/package.html | 2 +- .../restlet/ext/servlet/ServerServlet.java | 1652 ++++++++--------- .../java/org/restlet/ext/servlet/package.html | 3 +- .../main/java/org/restlet/Application.java | 12 - .../src/main/java/org/restlet/Component.java | 119 -- .../main/java/org/restlet/data/MediaType.java | 7 - .../restlet/engine/adapter/HttpRequest.java | 14 - .../engine/component/ComponentXmlParser.java | 776 -------- .../engine/local/ZipEntryRepresentation.java | 15 - .../restlet/resource/ResourceException.java | 11 - .../main/java/org/restlet/security/Role.java | 51 - .../java/org/restlet/service/LogService.java | 22 - .../org/restlet/service/StatusService.java | 203 +- 15 files changed, 833 insertions(+), 2090 deletions(-) delete mode 100644 org.restlet.java/org.restlet/src/main/java/org/restlet/engine/component/ComponentXmlParser.java diff --git a/changes.md b/changes.md index 4c1c3e4202..13c0ab4c11 100644 --- a/changes.md +++ b/changes.md @@ -20,6 +20,8 @@ Changes log - Removed incubator to rely instead on pull requests. - Renamed extension Inject into Guice as it isn't truly generic. - Updated the links in all Javadocs file for accuracy. + - Removed code deprecated in version 2.4, including native Restlet XML configuration mechasism. + Please use Spring for an alternative approach if needed. - 2.5 Milestone 1 (03/09/2020) - Bugs fixed diff --git a/org.restlet.java/org.restlet.ext.gae/src/main/java/org/restlet/ext/gae/GaeEnroler.java b/org.restlet.java/org.restlet.ext.gae/src/main/java/org/restlet/ext/gae/GaeEnroler.java index 510fec4f51..bf32db6388 100644 --- a/org.restlet.java/org.restlet.ext.gae/src/main/java/org/restlet/ext/gae/GaeEnroler.java +++ b/org.restlet.java/org.restlet.ext.gae/src/main/java/org/restlet/ext/gae/GaeEnroler.java @@ -27,14 +27,6 @@ public class GaeEnroler implements Enroler { /** The Administrator role. */ private Role adminRole; - /** - * Default constructor. It defines an administrator role, which name is - * "admin". - */ - public GaeEnroler() { - this("admin", "Administrator of the current application."); - } - /** * Constructor. * @@ -73,32 +65,6 @@ public GaeEnroler(Role adminRole) { setAdminRole(adminRole); } - /** - * Constructor. - * - * @param adminRoleName - * The name of the administrator role. - * @deprecated Use {@link #GaeEnroler(Application, String)} instead. - */ - @Deprecated - public GaeEnroler(String adminRoleName) { - this(adminRoleName, "Administrator of the current application."); - } - - /** - * Constructor. - * - * @param adminRoleName - * The name of the administrator role. - * @param adminRoleDescription - * The description of the administrator role. - * @deprecated Use {@link #GaeEnroler(Application, String, String)} instead. - */ - @Deprecated - public GaeEnroler(String adminRoleName, String adminRoleDescription) { - this(new Role(adminRoleName, adminRoleDescription)); - } - /** * Adds admin role object if user is an administrator according to Google * App Engine UserService. diff --git a/org.restlet.java/org.restlet.ext.gwt/src/main/java/org/restlet/ext/gwt/package.html b/org.restlet.java/org.restlet.ext.gwt/src/main/java/org/restlet/ext/gwt/package.html index df1e594076..27b35a1f5f 100644 --- a/org.restlet.java/org.restlet.ext.gwt/src/main/java/org/restlet/ext/gwt/package.html +++ b/org.restlet.java/org.restlet.ext.gwt/src/main/java/org/restlet/ext/gwt/package.html @@ -1,6 +1,6 @@ -Server-side integration with GWT @minor-version@. +Server-side integration with GWT. @since Restlet 1.1 @see Google Web Toolkit diff --git a/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/ServerServlet.java b/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/ServerServlet.java index ae9915ef0e..e677e171c5 100644 --- a/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/ServerServlet.java +++ b/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/ServerServlet.java @@ -36,7 +36,6 @@ import org.restlet.engine.component.ComponentContext; import org.restlet.ext.servlet.internal.ServletCall; import org.restlet.ext.servlet.internal.ServletWarClient; -import org.restlet.representation.Representation; import org.restlet.routing.Route; import org.restlet.routing.TemplateRoute; import org.restlet.routing.VirtualHost; @@ -48,9 +47,8 @@ * applications, and declaring client connectors, for example for the CLAP, FILE * or HTTP protocols.
*
- * There are three separate ways to configure the deployment using this Servlet. - * Please note that you can also combine the two first of them whereas the last - * one is a full alternative. They are described below by order of priority: + * There are two separate ways to configure the deployment using this Servlet. + * They are described below by order of priority: * * * @@ -59,22 +57,15 @@ * * * - * - * - * - * * + * combine the definition of your own custom Component subclass and method + * 1. * * - * + * * *
list of supported deployment modes
1A "/WEB-INF/restlet.xml" file exists and contains a valid XML - * configuration as described in the documentation of the {@link Component} - * class. It is used to instantiate and attach the described component, - * contained applications and connectors. Please note that you can combine the - * usage of such configuration file and method 2.
2The "/WEB-INF/web.xml" file contains a parameter named * "org.restlet.component". Its value must be the path of a class that inherits * from {@link Component}. It is used to instantiate and attach the described * component, contained applications and connectors. Please note that you can - * combine the definition of your own custom Component subclass and method 1.
32The "/WEB-INF/web.xml" file contains a parameter named * "org.restlet.application". Its value must be the path of a class that * inherits from {@link Application}. It is used to instantiate the application @@ -82,7 +73,7 @@ *
*
- * In deployment mode 3, you can also add an optional "org.restlet.clients" + * In deployment mode 2, you can also add an optional "org.restlet.clients" * context parameter that contains a space separated list of client protocols * supported by the underlying component. For each one, a new client connector * is added to the implicit {@link Component} instance.
@@ -146,19 +137,19 @@ * <servlet-name>RestletAdapter</servlet-name> * <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class> * - * <!-- Your component class name (Optional - For mode 2) --> + * <!-- Your component class name (Optional - For mode 1) --> * <init-param> * <param-name>org.restlet.component</param-name> * <param-value>test.MyComponent</param-value> * </init-param> * - * <!-- Your application class name (Optional - For mode 3) --> + * <!-- Your application class name (Optional - For mode 2) --> * <init-param> * <param-name>org.restlet.application</param-name> * <param-value>test.MyApplication</param-value> * </init-param> * - * <!-- List of supported client protocols (Optional - Only in mode 3) --> + * <!-- List of supported client protocols (Optional - Only in mode 2) --> * <init-param> * <param-name>org.restlet.clients</param-name> * <param-value>HTTP HTTPS FILE</param-value> @@ -201,12 +192,12 @@ * attaching Restlets to the host. The important conclusion is that both routing * configurations must be consistent in order to work fine.
*
- * In deployment mode 3, the context path of the servlet is automatically added. + * In deployment mode 2, the context path of the servlet is automatically added. * That's what we call the auto-wire feature. This is the default case, and is * equivalent to setting the value "true" for the "org.restlet.autoWire" - * parameter as described above. In modes 1 or 2, if you want to manually - * control the URI wiring, you can disable the auto-wiring by setting the - * property to "false".
+ * parameter as described above. In mode 1, if you want to manually control the + * URI wiring, you can disable the auto-wiring by setting the property to + * "false".
*
* Also, a WAR client connector is automatically attached to the parent Restlet * component. It lets you access to resources inside your WAR using the uniform @@ -225,883 +216,742 @@ * @author Jerome Louvel */ public class ServerServlet extends HttpServlet { - /** - * Name of the attribute key containing a reference to the current - * application. - */ - private static final String APPLICATION_KEY = "org.restlet.application"; - - /** - * The Servlet context initialization parameter's name containing a boolean - * value. "true" indicates that all applications will be attached to the - * Component's virtual hosts with the Servlet Context path value. - */ - private static final String AUTO_WIRE_KEY = "org.restlet.autoWire"; - - /** The default value for the AUTO_WIRE_KEY parameter. */ - private static final String AUTO_WIRE_KEY_DEFAULT = "true"; - - /** - * Name of the attribute key containing a list of supported client - * protocols. - */ - private static final String CLIENTS_KEY = "org.restlet.clients"; - - /** - * Name of the attribute key containing a reference to the current - * component. - */ - private static final String COMPONENT_KEY = "org.restlet.component"; - - /** - * The Servlet context initialization parameter's name containing the name - * of the Servlet context attribute that should be used to store the Restlet - * Application instance. - */ - private static final String NAME_APPLICATION_ATTRIBUTE = "org.restlet.attribute.application"; - - /** The default value for the NAME_APPLICATION_ATTRIBUTE parameter. */ - private static final String NAME_APPLICATION_ATTRIBUTE_DEFAULT = "org.restlet.ext.servlet.ServerServlet.application"; - - /** - * The Servlet context initialization parameter's name containing the name - * of the Servlet context attribute that should be used to store the Restlet - * Component instance. - */ - private static final String NAME_COMPONENT_ATTRIBUTE = "org.restlet.attribute.component"; - - /** The default value for the NAME_COMPONENT_ATTRIBUTE parameter. */ - private static final String NAME_COMPONENT_ATTRIBUTE_DEFAULT = "org.restlet.ext.servlet.ServerServlet.component"; - - /** - * Name of the attribute containing the computed offset path used to attach - * applications when (and only when) the auto-wiring feature is set, is - * added to the component's context. - */ - private static final String NAME_OFFSET_PATH_ATTRIBUTE = "org.restlet.ext.servlet.offsetPath"; - - /** - * The Servlet context initialization parameter's name containing the name - * of the Servlet context attribute that should be used to store the HTTP - * server connector instance. - */ - private static final String NAME_SERVER_ATTRIBUTE = "org.restlet.attribute.server"; - - /** The default value for the NAME_SERVER_ATTRIBUTE parameter. */ - private static final String NAME_SERVER_ATTRIBUTE_DEFAULT = "org.restlet.ext.servlet.ServerServlet.server"; - - /** Serial version identifier. */ - private static final long serialVersionUID = 1L; - - /** The associated Restlet application. */ - private volatile transient Application application; - - /** The associated Restlet component. */ - private volatile transient Component component; - - /** The associated HTTP server helper. */ - private volatile transient HttpServerHelper helper; - - /** - * Constructor. - */ - public ServerServlet() { - this.application = null; - this.component = null; - this.helper = null; - } - - /** - * Creates the single Application used by this Servlet. - * - * @param parentContext - * The parent component context. - * - * @return The newly created Application or null if unable to create - */ - protected Application createApplication(Context parentContext) { - Application application = null; - - // Try to instantiate a new target application - // First, find the application class name - String applicationClassName = getInitParameter(APPLICATION_KEY, null); - - // Load the application class using the given class name - if (applicationClassName != null) { - try { - Class targetClass = loadClass(applicationClassName); - - try { - // Instantiate an application with the default constructor - // then invoke the setContext method. - application = (Application) targetClass.getConstructor() - .newInstance(); - - // Set the context based on the Servlet's context - application.setContext(parentContext.createChildContext()); - } catch (NoSuchMethodException e) { - log("[Restlet] ServerServlet couldn't invoke the constructor of the target class. Please check this class has a constructor without parameter. The constructor with a parameter of type Context will be used instead."); - // The constructor with the Context parameter does not - // exist. Create a new instance of the application class by - // invoking the constructor with the Context parameter. - application = (Application) targetClass.getConstructor( - Context.class).newInstance( - parentContext.createChildContext()); - } - } catch (ClassNotFoundException e) { - log("[Restlet] ServerServlet couldn't find the target class. Please check that your classpath includes " - + applicationClassName, e); - - } catch (InstantiationException e) { - log("[Restlet] ServerServlet couldn't instantiate the target class. Please check this class has an empty constructor " - + applicationClassName, e); - } catch (IllegalAccessException e) { - log("[Restlet] ServerServlet couldn't instantiate the target class. Please check that you have to proper access rights to " - + applicationClassName, e); - } catch (NoSuchMethodException e) { - log("[Restlet] ServerServlet couldn't invoke the constructor of the target class. Please check this class has a constructor with a single parameter of Context " - + applicationClassName, e); - } catch (InvocationTargetException e) { - log("[Restlet] ServerServlet couldn't instantiate the target class. An exception was thrown while creating " - + applicationClassName, e); - } - } - - return application; - } - - /** - * Creates a new Servlet call wrapping a Servlet request/response couple and - * a Server connector. - * - * @param server - * The Server connector. - * @param request - * The Servlet request. - * @param response - * The Servlet response. - * @return The new ServletCall instance. - */ - protected ServerCall createCall(Server server, HttpServletRequest request, - HttpServletResponse response) { - return new ServletCall(server, request, response); - } - - /** - * Creates the single Component used by this Servlet. - * - * @return The newly created Component or null if unable to create. - */ - @SuppressWarnings("deprecation") - protected Component createComponent() { - // Detect customized Component - String componentClassName = getInitParameter(COMPONENT_KEY, null); - Class targetClass = null; - Component component = null; - - if (componentClassName != null) { - try { - targetClass = loadClass(componentClassName); - } catch (ClassNotFoundException e) { - log("[Restlet] ServerServlet couldn't find the target component class. Please check that your classpath includes " - + componentClassName, e); - } - } - log("[Restlet] ServerServlet: component class is " + componentClassName); - - // Detect the configuration of Component using restlet.xml file. - Client warClient = createWarClient(new Context(), getServletConfig()); - Response response = warClient.handle(new Request(Method.GET, - "war:///WEB-INF/restlet.xml")); - - boolean xmlConfiguration = response.getStatus().isSuccess() - && response.isEntityAvailable(); - - if (targetClass != null) { - try { - if (xmlConfiguration) { - @SuppressWarnings("unchecked") - Constructor ctor = ((Class) targetClass) - .getConstructor(Representation.class); - - log("[Restlet] ServerServlet: configuring custom component from war:///WEB-INF/restlet.xml"); - component = (Component) ctor.newInstance(response - .getEntity()); - } else { - @SuppressWarnings("unchecked") - Constructor ctor = ((Class) targetClass) - .getConstructor(); - - log("[Restlet] ServerServlet: instantiating custom component"); - component = (Component) ctor.newInstance(); - } - } catch (IllegalAccessException e) { - log("[Restlet] ServerServlet couldn't instantiate the target class. Please check that you have proper access rights to " - + componentClassName, e); - } catch (InvocationTargetException e) { - log("[Restlet] ServerServlet encountered an exception instantiating the target class " - + componentClassName, e.getTargetException()); - } catch (InstantiationException e) { - log(String.format( - "[Restlet] ServerServlet couldn't instantiate the target class. Please check that %s has %s.", - componentClassName, - ((xmlConfiguration) ? "a constructor taking a Representation as single parameter" - : "an empty constructor")), e); - } catch (NoSuchMethodException e) { - log(String.format( - "[Restlet] ServerServlet couldn't instantiate the target class. Please check that %s has %s.", - componentClassName, - ((xmlConfiguration) ? "a constructor taking Representation as single parameter" - : "an empty constructor")), e); - } - } else if (xmlConfiguration) { - log("[Restlet] ServerServlet: configuring component from war:///WEB-INF/restlet.xml"); - component = new Component(response.getEntity()); - } - - // Create the default Component - if (component == null) { - component = new Component(); - - // The status service is disabled by default. - component.getStatusService().setEnabled(false); - - // Define the list of supported client protocols. - final String clientProtocolsString = getInitParameter(CLIENTS_KEY, - null); - if (clientProtocolsString != null) { - final String[] clientProtocols = clientProtocolsString - .split(" "); - Client client; - - for (final String clientProtocol : clientProtocols) { - client = new Client(clientProtocol); - - if (client.isAvailable()) { - component.getClients().add(client); - } else { - log("[Restlet] Couldn't find a client connector for protocol " - + clientProtocol); - } - } - } - } - - return component; - } - - /** - * Creates the associated HTTP server handling calls. - * - * @param request - * The HTTP Servlet request. - * @return The new HTTP server handling calls. - */ - protected HttpServerHelper createServer(HttpServletRequest request) { - HttpServerHelper result = null; - Component component = getComponent(); - - if (component != null) { - // First, let's create a pseudo server - Server server = new Server(component.getContext() - .createChildContext(), (List) null, - this.getLocalAddr(request), this.getLocalPort(request), - component); - result = new HttpServerHelper(server); - - // Change the default adapter - Context serverContext = server.getContext(); - serverContext.getParameters().add("adapter", - "org.restlet.ext.servlet.internal.ServletServerAdapter"); - - // Attach the hosted application(s) to the right path - String uriPattern = this.getContextPath(request) - + request.getServletPath(); - - if (isDefaultComponent()) { - if (getApplication() != null) { - log("[Restlet] Attaching application: " + getApplication() - + " to URI: " + uriPattern); - component.getDefaultHost().attach(uriPattern, - getApplication()); - } - } else { - // According to the mode, configure correctly the component. - String autoWire = getInitParameter(AUTO_WIRE_KEY, - AUTO_WIRE_KEY_DEFAULT); - if (AUTO_WIRE_KEY_DEFAULT.equalsIgnoreCase(autoWire)) { - // Translate all defined routes as much as possible - // with the context path only or the full servlet path. - - // 1- get the offset - boolean addContextPath = false; - boolean addFullServletPath = false; - - if (component.getDefaultHost().getRoutes().isEmpty()) { - // Case where the default host has a default route (with - // an empty pattern). - addFullServletPath = component.getDefaultHost() - .getDefaultRoute() != null; - } else { - for (Route route : component.getDefaultHost() - .getRoutes()) { - if (route instanceof TemplateRoute) { - TemplateRoute templateRoute = (TemplateRoute) route; - - if (templateRoute.getTemplate().getPattern() == null) { - addFullServletPath = true; - continue; - } - - if (!templateRoute.getTemplate().getPattern() - .startsWith(uriPattern)) { - if (!templateRoute - .getTemplate() - .getPattern() - .startsWith( - request.getServletPath())) { - addFullServletPath = true; - } else { - addContextPath = true; - break; - } - } - } - } - } - if (!addContextPath) { - for (VirtualHost virtualHost : component.getHosts()) { - if (virtualHost.getRoutes().isEmpty()) { - // Case where the default host has a default - // route (with an empty pattern). - addFullServletPath = virtualHost - .getDefaultRoute() != null; - } else { - for (Route route : virtualHost.getRoutes()) { - if (route instanceof TemplateRoute) { - TemplateRoute templateRoute = (TemplateRoute) route; - - if (templateRoute.getTemplate() - .getPattern() == null) { - addFullServletPath = true; - continue; - } - - if (!templateRoute.getTemplate() - .getPattern() - .startsWith(uriPattern)) { - if (!templateRoute - .getTemplate() - .getPattern() - .startsWith( - request.getServletPath())) { - addFullServletPath = true; - } else { - addContextPath = true; - break; - } - } - } - } - } - if (addContextPath) { - break; - } - } - } - - // 2- Translate all routes. - if (addContextPath || addFullServletPath) { - String offsetPath = null; - - if (addContextPath) { - offsetPath = this.getContextPath(request); - } else { - offsetPath = uriPattern; - } - - if (offsetPath != null) { - getComponent() - .getContext() - .getAttributes() - .put(NAME_OFFSET_PATH_ATTRIBUTE, offsetPath); - } - - // Shift the default route (if any) of the default host - Route defaultRoute = component.getDefaultHost() - .getDefaultRoute(); - - if (defaultRoute != null) { - if (defaultRoute instanceof TemplateRoute) { - TemplateRoute defaultTemplateRoute = (TemplateRoute) defaultRoute; - defaultTemplateRoute.getTemplate().setPattern( - offsetPath - + defaultTemplateRoute - .getTemplate() - .getPattern()); - log("[Restlet] Attaching restlet: " - + defaultRoute.getNext() - + " to URI: " - + offsetPath - + defaultTemplateRoute.getTemplate() - .getPattern()); - } else { - log("[Restlet] Attaching restlet: " - + defaultRoute.getNext()); - } - } - - // Shift the routes of the default host - for (Route route : component.getDefaultHost() - .getRoutes()) { - if (route instanceof TemplateRoute) { - TemplateRoute templateRoute = (TemplateRoute) route; - - log("[Restlet] Attaching restlet: " - + route.getNext() - + " to URI: " - + offsetPath - + templateRoute.getTemplate() - .getPattern()); - templateRoute.getTemplate().setPattern( - offsetPath - + templateRoute.getTemplate() - .getPattern()); - } else { - log("[Restlet] Attaching restlet: " - + defaultRoute.getNext()); - } - } - - for (VirtualHost virtualHost : component.getHosts()) { - // Shift the default route (if any) of the virtual - // host - defaultRoute = virtualHost.getDefaultRoute(); - if (defaultRoute != null) { - if (defaultRoute instanceof TemplateRoute) { - TemplateRoute defaultTemplateRoute = (TemplateRoute) defaultRoute; - defaultTemplateRoute - .getTemplate() - .setPattern( - offsetPath - + defaultTemplateRoute - .getTemplate() - .getPattern()); - log("[Restlet] Attaching restlet: " - + defaultRoute.getNext() - + " to URI: " - + offsetPath - + defaultTemplateRoute - .getTemplate().getPattern()); - } else { - log("[Restlet] Attaching restlet: " - + defaultRoute.getNext()); - } - } - - // Shift the routes of the virtual host - for (Route route : virtualHost.getRoutes()) { - if (route instanceof TemplateRoute) { - TemplateRoute templateRoute = (TemplateRoute) route; - - log("[Restlet] Attaching restlet: " - + route.getNext() - + " to URI: " - + offsetPath - + templateRoute.getTemplate() - .getPattern()); - templateRoute.getTemplate().setPattern( - offsetPath - + templateRoute - .getTemplate() - .getPattern()); - } else { - log("[Restlet] Attaching restlet: " - + route.getNext()); - } - } - } - } - } - } - } - - return result; - } - - /** - * Creates a new client for the WAR protocol. - * - * @param context - * The parent context. - * @param config - * The Servlet config. - * @return The new WAR client instance. - */ - protected Client createWarClient(Context context, ServletConfig config) { - return new ServletWarClient(context, config.getServletContext()); - } - - @Override - public void destroy() { - if ((getComponent() != null) && (getComponent().isStarted())) { - try { - getComponent().stop(); - } catch (Exception e) { - log("Error during the stopping of the Restlet component", e); - } - } - - super.destroy(); - } - - /** - * Returns the application. It creates a new one if none exists. - * - * @return The application. - */ - public Application getApplication() { - // Lazy initialization with double-check. - Application result = this.application; - - if (result == null) { - synchronized (this) { - result = this.application; - if (result == null) { - // In case a component is explicitly defined, it cannot be - // completed. - if (isDefaultComponent()) { - // Find the attribute name to use to store the - // application - String applicationAttributeName = getInitParameter( - NAME_APPLICATION_ATTRIBUTE, - NAME_APPLICATION_ATTRIBUTE_DEFAULT + "." - + getServletName()); - - // Look up the attribute for a target - result = (Application) getServletContext() - .getAttribute(applicationAttributeName); - - if (result == null) { - result = createApplication(getComponent() - .getContext()); - init(result); - getServletContext().setAttribute( - applicationAttributeName, result); - } - - this.application = result; - } - } - } - } - - return result; - } - - /** - * Returns the component. It creates a new one if none exists. - * - * @return The component. - */ - public Component getComponent() { - // Lazy initialization with double-check. - Component result = this.component; - - if (result == null) { - synchronized (this) { - result = this.component; - if (result == null) { - // Find the attribute name to use to store the component - final String componentAttributeName = getInitParameter( - NAME_COMPONENT_ATTRIBUTE, - NAME_COMPONENT_ATTRIBUTE_DEFAULT + "." - + getServletName()); - - // Look up the attribute for a target - result = (Component) getServletContext().getAttribute( - componentAttributeName); - - if (result == null) { - result = createComponent(); - init(result); - getServletContext().setAttribute( - componentAttributeName, result); - } - } - - this.component = result; - } - } - - return result; - } - - /** - * Intercepter method need for subclasses such as XdbServerServlet. - * - * @param request - * The Servlet request. - * @return The portion of the request URI that indicates the context of the - * request. - */ - protected String getContextPath(HttpServletRequest request) { - return request.getContextPath(); - } - - /** - * Returns the value of a given initialization parameter, first from the - * Servlet configuration, then from the Web Application context. - * - * @param name - * The parameter name. - * @param defaultValue - * The default to use in case the parameter is not found. - * @return The value of the parameter or null. - */ - public String getInitParameter(String name, String defaultValue) { - String result = getServletConfig().getInitParameter(name); - - if (result == null) { - result = getServletConfig().getServletContext().getInitParameter( - name); - } - - if (result == null) { - result = defaultValue; - } - - return result; - } - - /** - * Intercepter method need for subclasses such as XdbServerServlet. - * - * @param request - * The Servlet request. - * @return The Internet Protocol (IP) address of the interface on which the - * request was received. - */ - protected String getLocalAddr(HttpServletRequest request) { - return request.getLocalAddr(); - } - - /** - * Intercepter method need for subclasses such as XdbServerServlet. - * - * @param request - * The Servlet request. - * @return The Internet Protocol (IP) port number of the interface on which - * the request was received - */ - protected int getLocalPort(HttpServletRequest request) { - return request.getLocalPort(); - } - - /** - * Returns the associated HTTP server handling calls. It creates a new one - * if none exists. - * - * @param request - * The HTTP Servlet request. - * @return The HTTP server handling calls. - */ - public HttpServerHelper getServer(HttpServletRequest request) { - // Lazy initialization with double-check. - HttpServerHelper result = this.helper; - - if (result == null) { - synchronized (this) { - result = this.helper; - if (result == null) { - // Find the attribute name to use to store the server - // reference - final String serverAttributeName = getInitParameter( - NAME_SERVER_ATTRIBUTE, - NAME_SERVER_ATTRIBUTE_DEFAULT + "." - + getServletName()); - - // Look up the attribute for a target - result = (HttpServerHelper) getServletContext() - .getAttribute(serverAttributeName); - - if (result == null) { - result = createServer(request); - getServletContext().setAttribute(serverAttributeName, - result); - } - - this.helper = result; - } - } - } - - return result; - } - - @Override - public void init() throws ServletException { - if ((getComponent() != null) && (getComponent().isStopped())) { - try { - getComponent().start(); - } catch (Exception e) { - log("Error during the starting of the Restlet Application", e); - } - } - } - - /** - * Initialize a application. Copies Servlet parameters into the component's - * context. Copies the ServletContext into an - * "org.restlet.ext.servlet.ServletContext" attribute. - * - * @param application - * The application to configure. - */ - protected void init(Application application) { - if (application != null) { - Context applicationContext = application.getContext(); - - if (applicationContext != null) { - // Copies the ServletContext into an attribute - applicationContext.getAttributes().put( - "org.restlet.ext.servlet.ServletContext", - getServletContext()); - - // Copy all the servlet parameters into the context - String initParam; - - // Copy all the Servlet component initialization parameters - javax.servlet.ServletConfig servletConfig = getServletConfig(); - for (Enumeration enum1 = servletConfig - .getInitParameterNames(); enum1.hasMoreElements();) { - initParam = enum1.nextElement(); - applicationContext.getParameters().add(initParam, - servletConfig.getInitParameter(initParam)); - } - - // Copy all the Servlet application initialization parameters - for (Enumeration enum1 = getServletContext() - .getInitParameterNames(); enum1.hasMoreElements();) { - initParam = enum1.nextElement(); - applicationContext.getParameters().add(initParam, - getServletContext().getInitParameter(initParam)); - } - } - } - } - - /** - * Initialize a component. Adds a default WAR client and copies Servlet - * parameters into the component's context. Copies the ServletContext into - * an "org.restlet.ext.servlet.ServletContext" attribute. - * - * @param component - * The component to configure. - */ - protected void init(Component component) { - if (component != null) { - // Complete the configuration of the Component - // Add the WAR client - component.getClients() - .add(createWarClient(component.getContext(), - getServletConfig())); - - // Copy all the servlet parameters into the context - ComponentContext componentContext = (ComponentContext) component - .getContext(); - - // Copies the ServletContext into an attribute - componentContext.getAttributes().put( - "org.restlet.ext.servlet.ServletContext", - getServletContext()); - - // Copy all the Servlet container initialization parameters - String initParam; - javax.servlet.ServletConfig servletConfig = getServletConfig(); - - for (Enumeration enum1 = servletConfig - .getInitParameterNames(); enum1.hasMoreElements();) { - initParam = enum1.nextElement(); - componentContext.getParameters().add(initParam, - servletConfig.getInitParameter(initParam)); - } - - // Copy all the Servlet application initialization parameters - for (Enumeration enum1 = getServletContext() - .getInitParameterNames(); enum1.hasMoreElements();) { - initParam = enum1.nextElement(); - componentContext.getParameters().add(initParam, - getServletContext().getInitParameter(initParam)); - } - - // Copy all Servlet's context attributes - String attributeName; - for (Enumeration namesEnum = getServletContext() - .getAttributeNames(); namesEnum.hasMoreElements();) { - attributeName = namesEnum.nextElement(); - componentContext.getAttributes().put(attributeName, - getServletContext().getAttribute(attributeName)); - } - } - } - - /** - * Indicates if the Component hosted by this Servlet is the default one or - * one provided by the user. - * - * @return True if the Component is the default one, false otherwise. - */ - private boolean isDefaultComponent() { - // The Component is provided via an XML configuration file. - Client client = createWarClient(new Context(), getServletConfig()); - Response response = client.handle(new Request(Method.GET, - "war:///WEB-INF/restlet.xml")); - if (response.getStatus().isSuccess() && response.isEntityAvailable()) { - return false; - } - - // The Component is provided via a context parameter in the "web.xml" - // file. - String componentAttributeName = getInitParameter(COMPONENT_KEY, null); - if (componentAttributeName != null) { - return false; - } - - return true; - } - - /** - * Returns a class for a given qualified class name. - * - * @param className - * The class name to lookup. - * @return The class object. - * @throws ClassNotFoundException - */ - protected Class loadClass(String className) - throws ClassNotFoundException { - return Engine.loadClass(className); - } - - /** - * Services a HTTP Servlet request as an uniform call. - * - * @param request - * The HTTP Servlet request. - * @param response - * The HTTP Servlet response. - */ - @Override - public void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - HttpServerHelper helper = getServer(request); - - if (helper != null) { - helper.handle(createCall(helper.getHelped(), request, response)); - } else { - log("[Restlet] Unable to get the Restlet HTTP server connector. Status code 500 returned."); - response.sendError(500); - } - } + /** + * Name of the attribute key containing a reference to the current application. + */ + private static final String APPLICATION_KEY = "org.restlet.application"; + + /** + * The Servlet context initialization parameter's name containing a boolean + * value. "true" indicates that all applications will be attached to the + * Component's virtual hosts with the Servlet Context path value. + */ + private static final String AUTO_WIRE_KEY = "org.restlet.autoWire"; + + /** The default value for the AUTO_WIRE_KEY parameter. */ + private static final String AUTO_WIRE_KEY_DEFAULT = "true"; + + /** + * Name of the attribute key containing a list of supported client protocols. + */ + private static final String CLIENTS_KEY = "org.restlet.clients"; + + /** + * Name of the attribute key containing a reference to the current component. + */ + private static final String COMPONENT_KEY = "org.restlet.component"; + + /** + * The Servlet context initialization parameter's name containing the name of + * the Servlet context attribute that should be used to store the Restlet + * Application instance. + */ + private static final String NAME_APPLICATION_ATTRIBUTE = "org.restlet.attribute.application"; + + /** The default value for the NAME_APPLICATION_ATTRIBUTE parameter. */ + private static final String NAME_APPLICATION_ATTRIBUTE_DEFAULT = "org.restlet.ext.servlet.ServerServlet.application"; + + /** + * The Servlet context initialization parameter's name containing the name of + * the Servlet context attribute that should be used to store the Restlet + * Component instance. + */ + private static final String NAME_COMPONENT_ATTRIBUTE = "org.restlet.attribute.component"; + + /** The default value for the NAME_COMPONENT_ATTRIBUTE parameter. */ + private static final String NAME_COMPONENT_ATTRIBUTE_DEFAULT = "org.restlet.ext.servlet.ServerServlet.component"; + + /** + * Name of the attribute containing the computed offset path used to attach + * applications when (and only when) the auto-wiring feature is set, is added to + * the component's context. + */ + private static final String NAME_OFFSET_PATH_ATTRIBUTE = "org.restlet.ext.servlet.offsetPath"; + + /** + * The Servlet context initialization parameter's name containing the name of + * the Servlet context attribute that should be used to store the HTTP server + * connector instance. + */ + private static final String NAME_SERVER_ATTRIBUTE = "org.restlet.attribute.server"; + + /** The default value for the NAME_SERVER_ATTRIBUTE parameter. */ + private static final String NAME_SERVER_ATTRIBUTE_DEFAULT = "org.restlet.ext.servlet.ServerServlet.server"; + + /** Serial version identifier. */ + private static final long serialVersionUID = 1L; + + /** The associated Restlet application. */ + private volatile transient Application application; + + /** The associated Restlet component. */ + private volatile transient Component component; + + /** The associated HTTP server helper. */ + private volatile transient HttpServerHelper helper; + + /** + * Constructor. + */ + public ServerServlet() { + this.application = null; + this.component = null; + this.helper = null; + } + + /** + * Creates the single Application used by this Servlet. + * + * @param parentContext The parent component context. + * + * @return The newly created Application or null if unable to create + */ + protected Application createApplication(Context parentContext) { + Application application = null; + + // Try to instantiate a new target application + // First, find the application class name + String applicationClassName = getInitParameter(APPLICATION_KEY, null); + + // Load the application class using the given class name + if (applicationClassName != null) { + try { + Class targetClass = loadClass(applicationClassName); + + try { + // Instantiate an application with the default constructor + // then invoke the setContext method. + application = (Application) targetClass.getConstructor().newInstance(); + + // Set the context based on the Servlet's context + application.setContext(parentContext.createChildContext()); + } catch (NoSuchMethodException e) { + log("[Restlet] ServerServlet couldn't invoke the constructor of the target class. Please check this class has a constructor without parameter. The constructor with a parameter of type Context will be used instead."); + // The constructor with the Context parameter does not + // exist. Create a new instance of the application class by + // invoking the constructor with the Context parameter. + application = (Application) targetClass.getConstructor(Context.class) + .newInstance(parentContext.createChildContext()); + } + } catch (ClassNotFoundException e) { + log("[Restlet] ServerServlet couldn't find the target class. Please check that your classpath includes " + + applicationClassName, e); + + } catch (InstantiationException e) { + log("[Restlet] ServerServlet couldn't instantiate the target class. Please check this class has an empty constructor " + + applicationClassName, e); + } catch (IllegalAccessException e) { + log("[Restlet] ServerServlet couldn't instantiate the target class. Please check that you have to proper access rights to " + + applicationClassName, e); + } catch (NoSuchMethodException e) { + log("[Restlet] ServerServlet couldn't invoke the constructor of the target class. Please check this class has a constructor with a single parameter of Context " + + applicationClassName, e); + } catch (InvocationTargetException e) { + log("[Restlet] ServerServlet couldn't instantiate the target class. An exception was thrown while creating " + + applicationClassName, e); + } + } + + return application; + } + + /** + * Creates a new Servlet call wrapping a Servlet request/response couple and a + * Server connector. + * + * @param server The Server connector. + * @param request The Servlet request. + * @param response The Servlet response. + * @return The new ServletCall instance. + */ + protected ServerCall createCall(Server server, HttpServletRequest request, HttpServletResponse response) { + return new ServletCall(server, request, response); + } + + /** + * Creates the single Component used by this Servlet. + * + * @return The newly created Component or null if unable to create. + */ + protected Component createComponent() { + // Detect customized Component + String componentClassName = getInitParameter(COMPONENT_KEY, null); + Class targetClass = null; + Component component = null; + + if (componentClassName != null) { + try { + targetClass = loadClass(componentClassName); + } catch (ClassNotFoundException e) { + log("[Restlet] ServerServlet couldn't find the target component class. Please check that your classpath includes " + + componentClassName, e); + } + } + log("[Restlet] ServerServlet: component class is " + componentClassName); + + // Detect the configuration of Component using restlet.xml file. + if (targetClass != null) { + try { + @SuppressWarnings("unchecked") + Constructor ctor = ((Class) targetClass).getConstructor(); + + log("[Restlet] ServerServlet: instantiating custom component"); + component = (Component) ctor.newInstance(); + } catch (IllegalAccessException e) { + log("[Restlet] ServerServlet couldn't instantiate the target class. Please check that you have proper access rights to " + + componentClassName, e); + } catch (InvocationTargetException e) { + log("[Restlet] ServerServlet encountered an exception instantiating the target class " + + componentClassName, e.getTargetException()); + } catch (InstantiationException e) { + log(String.format( + "[Restlet] ServerServlet couldn't instantiate the target class. Please check that %s has %s.", + componentClassName, "an empty constructor"), + e); + } catch (NoSuchMethodException e) { + log(String.format( + "[Restlet] ServerServlet couldn't instantiate the target class. Please check that %s has %s.", + componentClassName, "an empty constructor"), + e); + } + } + + // Create the default Component + if (component == null) { + component = new Component(); + + // The status service is disabled by default. + component.getStatusService().setEnabled(false); + + // Define the list of supported client protocols. + final String clientProtocolsString = getInitParameter(CLIENTS_KEY, null); + if (clientProtocolsString != null) { + final String[] clientProtocols = clientProtocolsString.split(" "); + Client client; + + for (final String clientProtocol : clientProtocols) { + client = new Client(clientProtocol); + + if (client.isAvailable()) { + component.getClients().add(client); + } else { + log("[Restlet] Couldn't find a client connector for protocol " + clientProtocol); + } + } + } + } + + return component; + } + + /** + * Creates the associated HTTP server handling calls. + * + * @param request The HTTP Servlet request. + * @return The new HTTP server handling calls. + */ + protected HttpServerHelper createServer(HttpServletRequest request) { + HttpServerHelper result = null; + Component component = getComponent(); + + if (component != null) { + // First, let's create a pseudo server + Server server = new Server(component.getContext().createChildContext(), (List) null, + this.getLocalAddr(request), this.getLocalPort(request), component); + result = new HttpServerHelper(server); + + // Change the default adapter + Context serverContext = server.getContext(); + serverContext.getParameters().add("adapter", "org.restlet.ext.servlet.internal.ServletServerAdapter"); + + // Attach the hosted application(s) to the right path + String uriPattern = this.getContextPath(request) + request.getServletPath(); + + if (isDefaultComponent()) { + if (getApplication() != null) { + log("[Restlet] Attaching application: " + getApplication() + " to URI: " + uriPattern); + component.getDefaultHost().attach(uriPattern, getApplication()); + } + } else { + // According to the mode, configure correctly the component. + String autoWire = getInitParameter(AUTO_WIRE_KEY, AUTO_WIRE_KEY_DEFAULT); + if (AUTO_WIRE_KEY_DEFAULT.equalsIgnoreCase(autoWire)) { + // Translate all defined routes as much as possible + // with the context path only or the full servlet path. + + // 1- get the offset + boolean addContextPath = false; + boolean addFullServletPath = false; + + if (component.getDefaultHost().getRoutes().isEmpty()) { + // Case where the default host has a default route (with + // an empty pattern). + addFullServletPath = component.getDefaultHost().getDefaultRoute() != null; + } else { + for (Route route : component.getDefaultHost().getRoutes()) { + if (route instanceof TemplateRoute) { + TemplateRoute templateRoute = (TemplateRoute) route; + + if (templateRoute.getTemplate().getPattern() == null) { + addFullServletPath = true; + continue; + } + + if (!templateRoute.getTemplate().getPattern().startsWith(uriPattern)) { + if (!templateRoute.getTemplate().getPattern() + .startsWith(request.getServletPath())) { + addFullServletPath = true; + } else { + addContextPath = true; + break; + } + } + } + } + } + if (!addContextPath) { + for (VirtualHost virtualHost : component.getHosts()) { + if (virtualHost.getRoutes().isEmpty()) { + // Case where the default host has a default + // route (with an empty pattern). + addFullServletPath = virtualHost.getDefaultRoute() != null; + } else { + for (Route route : virtualHost.getRoutes()) { + if (route instanceof TemplateRoute) { + TemplateRoute templateRoute = (TemplateRoute) route; + + if (templateRoute.getTemplate().getPattern() == null) { + addFullServletPath = true; + continue; + } + + if (!templateRoute.getTemplate().getPattern().startsWith(uriPattern)) { + if (!templateRoute.getTemplate().getPattern() + .startsWith(request.getServletPath())) { + addFullServletPath = true; + } else { + addContextPath = true; + break; + } + } + } + } + } + if (addContextPath) { + break; + } + } + } + + // 2- Translate all routes. + if (addContextPath || addFullServletPath) { + String offsetPath = null; + + if (addContextPath) { + offsetPath = this.getContextPath(request); + } else { + offsetPath = uriPattern; + } + + if (offsetPath != null) { + getComponent().getContext().getAttributes().put(NAME_OFFSET_PATH_ATTRIBUTE, offsetPath); + } + + // Shift the default route (if any) of the default host + Route defaultRoute = component.getDefaultHost().getDefaultRoute(); + + if (defaultRoute != null) { + if (defaultRoute instanceof TemplateRoute) { + TemplateRoute defaultTemplateRoute = (TemplateRoute) defaultRoute; + defaultTemplateRoute.getTemplate() + .setPattern(offsetPath + defaultTemplateRoute.getTemplate().getPattern()); + log("[Restlet] Attaching restlet: " + defaultRoute.getNext() + " to URI: " + offsetPath + + defaultTemplateRoute.getTemplate().getPattern()); + } else { + log("[Restlet] Attaching restlet: " + defaultRoute.getNext()); + } + } + + // Shift the routes of the default host + for (Route route : component.getDefaultHost().getRoutes()) { + if (route instanceof TemplateRoute) { + TemplateRoute templateRoute = (TemplateRoute) route; + + log("[Restlet] Attaching restlet: " + route.getNext() + " to URI: " + offsetPath + + templateRoute.getTemplate().getPattern()); + templateRoute.getTemplate() + .setPattern(offsetPath + templateRoute.getTemplate().getPattern()); + } else { + log("[Restlet] Attaching restlet: " + defaultRoute.getNext()); + } + } + + for (VirtualHost virtualHost : component.getHosts()) { + // Shift the default route (if any) of the virtual + // host + defaultRoute = virtualHost.getDefaultRoute(); + if (defaultRoute != null) { + if (defaultRoute instanceof TemplateRoute) { + TemplateRoute defaultTemplateRoute = (TemplateRoute) defaultRoute; + defaultTemplateRoute.getTemplate() + .setPattern(offsetPath + defaultTemplateRoute.getTemplate().getPattern()); + log("[Restlet] Attaching restlet: " + defaultRoute.getNext() + " to URI: " + + offsetPath + defaultTemplateRoute.getTemplate().getPattern()); + } else { + log("[Restlet] Attaching restlet: " + defaultRoute.getNext()); + } + } + + // Shift the routes of the virtual host + for (Route route : virtualHost.getRoutes()) { + if (route instanceof TemplateRoute) { + TemplateRoute templateRoute = (TemplateRoute) route; + + log("[Restlet] Attaching restlet: " + route.getNext() + " to URI: " + offsetPath + + templateRoute.getTemplate().getPattern()); + templateRoute.getTemplate() + .setPattern(offsetPath + templateRoute.getTemplate().getPattern()); + } else { + log("[Restlet] Attaching restlet: " + route.getNext()); + } + } + } + } + } + } + } + + return result; + } + + /** + * Creates a new client for the WAR protocol. + * + * @param context The parent context. + * @param config The Servlet config. + * @return The new WAR client instance. + */ + protected Client createWarClient(Context context, ServletConfig config) { + return new ServletWarClient(context, config.getServletContext()); + } + + @Override + public void destroy() { + if ((getComponent() != null) && (getComponent().isStarted())) { + try { + getComponent().stop(); + } catch (Exception e) { + log("Error during the stopping of the Restlet component", e); + } + } + + super.destroy(); + } + + /** + * Returns the application. It creates a new one if none exists. + * + * @return The application. + */ + public Application getApplication() { + // Lazy initialization with double-check. + Application result = this.application; + + if (result == null) { + synchronized (this) { + result = this.application; + if (result == null) { + // In case a component is explicitly defined, it cannot be + // completed. + if (isDefaultComponent()) { + // Find the attribute name to use to store the + // application + String applicationAttributeName = getInitParameter(NAME_APPLICATION_ATTRIBUTE, + NAME_APPLICATION_ATTRIBUTE_DEFAULT + "." + getServletName()); + + // Look up the attribute for a target + result = (Application) getServletContext().getAttribute(applicationAttributeName); + + if (result == null) { + result = createApplication(getComponent().getContext()); + init(result); + getServletContext().setAttribute(applicationAttributeName, result); + } + + this.application = result; + } + } + } + } + + return result; + } + + /** + * Returns the component. It creates a new one if none exists. + * + * @return The component. + */ + public Component getComponent() { + // Lazy initialization with double-check. + Component result = this.component; + + if (result == null) { + synchronized (this) { + result = this.component; + if (result == null) { + // Find the attribute name to use to store the component + final String componentAttributeName = getInitParameter(NAME_COMPONENT_ATTRIBUTE, + NAME_COMPONENT_ATTRIBUTE_DEFAULT + "." + getServletName()); + + // Look up the attribute for a target + result = (Component) getServletContext().getAttribute(componentAttributeName); + + if (result == null) { + result = createComponent(); + init(result); + getServletContext().setAttribute(componentAttributeName, result); + } + } + + this.component = result; + } + } + + return result; + } + + /** + * Intercepter method need for subclasses such as XdbServerServlet. + * + * @param request The Servlet request. + * @return The portion of the request URI that indicates the context of the + * request. + */ + protected String getContextPath(HttpServletRequest request) { + return request.getContextPath(); + } + + /** + * Returns the value of a given initialization parameter, first from the Servlet + * configuration, then from the Web Application context. + * + * @param name The parameter name. + * @param defaultValue The default to use in case the parameter is not found. + * @return The value of the parameter or null. + */ + public String getInitParameter(String name, String defaultValue) { + String result = getServletConfig().getInitParameter(name); + + if (result == null) { + result = getServletConfig().getServletContext().getInitParameter(name); + } + + if (result == null) { + result = defaultValue; + } + + return result; + } + + /** + * Intercepter method need for subclasses such as XdbServerServlet. + * + * @param request The Servlet request. + * @return The Internet Protocol (IP) address of the interface on which the + * request was received. + */ + protected String getLocalAddr(HttpServletRequest request) { + return request.getLocalAddr(); + } + + /** + * Intercepter method need for subclasses such as XdbServerServlet. + * + * @param request The Servlet request. + * @return The Internet Protocol (IP) port number of the interface on which the + * request was received + */ + protected int getLocalPort(HttpServletRequest request) { + return request.getLocalPort(); + } + + /** + * Returns the associated HTTP server handling calls. It creates a new one if + * none exists. + * + * @param request The HTTP Servlet request. + * @return The HTTP server handling calls. + */ + public HttpServerHelper getServer(HttpServletRequest request) { + // Lazy initialization with double-check. + HttpServerHelper result = this.helper; + + if (result == null) { + synchronized (this) { + result = this.helper; + if (result == null) { + // Find the attribute name to use to store the server + // reference + final String serverAttributeName = getInitParameter(NAME_SERVER_ATTRIBUTE, + NAME_SERVER_ATTRIBUTE_DEFAULT + "." + getServletName()); + + // Look up the attribute for a target + result = (HttpServerHelper) getServletContext().getAttribute(serverAttributeName); + + if (result == null) { + result = createServer(request); + getServletContext().setAttribute(serverAttributeName, result); + } + + this.helper = result; + } + } + } + + return result; + } + + @Override + public void init() throws ServletException { + if ((getComponent() != null) && (getComponent().isStopped())) { + try { + getComponent().start(); + } catch (Exception e) { + log("Error during the starting of the Restlet Application", e); + } + } + } + + /** + * Initialize a application. Copies Servlet parameters into the component's + * context. Copies the ServletContext into an + * "org.restlet.ext.servlet.ServletContext" attribute. + * + * @param application The application to configure. + */ + protected void init(Application application) { + if (application != null) { + Context applicationContext = application.getContext(); + + if (applicationContext != null) { + // Copies the ServletContext into an attribute + applicationContext.getAttributes().put("org.restlet.ext.servlet.ServletContext", getServletContext()); + + // Copy all the servlet parameters into the context + String initParam; + + // Copy all the Servlet component initialization parameters + javax.servlet.ServletConfig servletConfig = getServletConfig(); + for (Enumeration enum1 = servletConfig.getInitParameterNames(); enum1.hasMoreElements();) { + initParam = enum1.nextElement(); + applicationContext.getParameters().add(initParam, servletConfig.getInitParameter(initParam)); + } + + // Copy all the Servlet application initialization parameters + for (Enumeration enum1 = getServletContext().getInitParameterNames(); enum1 + .hasMoreElements();) { + initParam = enum1.nextElement(); + applicationContext.getParameters().add(initParam, getServletContext().getInitParameter(initParam)); + } + } + } + } + + /** + * Initialize a component. Adds a default WAR client and copies Servlet + * parameters into the component's context. Copies the ServletContext into an + * "org.restlet.ext.servlet.ServletContext" attribute. + * + * @param component The component to configure. + */ + protected void init(Component component) { + if (component != null) { + // Complete the configuration of the Component + // Add the WAR client + component.getClients().add(createWarClient(component.getContext(), getServletConfig())); + + // Copy all the servlet parameters into the context + ComponentContext componentContext = (ComponentContext) component.getContext(); + + // Copies the ServletContext into an attribute + componentContext.getAttributes().put("org.restlet.ext.servlet.ServletContext", getServletContext()); + + // Copy all the Servlet container initialization parameters + String initParam; + javax.servlet.ServletConfig servletConfig = getServletConfig(); + + for (Enumeration enum1 = servletConfig.getInitParameterNames(); enum1.hasMoreElements();) { + initParam = enum1.nextElement(); + componentContext.getParameters().add(initParam, servletConfig.getInitParameter(initParam)); + } + + // Copy all the Servlet application initialization parameters + for (Enumeration enum1 = getServletContext().getInitParameterNames(); enum1.hasMoreElements();) { + initParam = enum1.nextElement(); + componentContext.getParameters().add(initParam, getServletContext().getInitParameter(initParam)); + } + + // Copy all Servlet's context attributes + String attributeName; + for (Enumeration namesEnum = getServletContext().getAttributeNames(); namesEnum + .hasMoreElements();) { + attributeName = namesEnum.nextElement(); + componentContext.getAttributes().put(attributeName, getServletContext().getAttribute(attributeName)); + } + } + } + + /** + * Indicates if the Component hosted by this Servlet is the default one or one + * provided by the user. + * + * @return True if the Component is the default one, false otherwise. + */ + private boolean isDefaultComponent() { + // The Component is provided via an XML configuration file. + Client client = createWarClient(new Context(), getServletConfig()); + Response response = client.handle(new Request(Method.GET, "war:///WEB-INF/restlet.xml")); + if (response.getStatus().isSuccess() && response.isEntityAvailable()) { + return false; + } + + // The Component is provided via a context parameter in the "web.xml" + // file. + String componentAttributeName = getInitParameter(COMPONENT_KEY, null); + if (componentAttributeName != null) { + return false; + } + + return true; + } + + /** + * Returns a class for a given qualified class name. + * + * @param className The class name to lookup. + * @return The class object. + * @throws ClassNotFoundException + */ + protected Class loadClass(String className) throws ClassNotFoundException { + return Engine.loadClass(className); + } + + /** + * Services a HTTP Servlet request as an uniform call. + * + * @param request The HTTP Servlet request. + * @param response The HTTP Servlet response. + */ + @Override + public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpServerHelper helper = getServer(request); + + if (helper != null) { + helper.handle(createCall(helper.getHelped(), request, response)); + } else { + log("[Restlet] Unable to get the Restlet HTTP server connector. Status code 500 returned."); + response.sendError(500); + } + } } diff --git a/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/package.html b/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/package.html index 4f27dff098..7632899e02 100644 --- a/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/package.html +++ b/org.restlet.java/org.restlet.ext.servlet/src/main/java/org/restlet/ext/servlet/package.html @@ -1,6 +1,7 @@ -Integration with Servlet API @minor-version@. Java Servlet technology provides Web developers with a simple, consistent mechanism for extending the functionality of a Web server and for accessing existing business systems. +Integration with Servlet API. Java Servlet technology provides Web developers with a simple, +consistent mechanism for extending the functionality of a Web server and for accessing existing business systems. @since Restlet 1.0 @see Servlet HTTP server diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/Application.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/Application.java index 9f1fd2ef2a..72fdbf9f6e 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/Application.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/Application.java @@ -337,18 +337,6 @@ public StatusService getStatusService() { return getServices().get(StatusService.class); } - /** - * Returns a task service to run concurrent tasks. The service is enabled by - * default. - * - * @return A task service. - * @deprecated - */ - @Deprecated - public org.restlet.service.TaskService getTaskService() { - return getServices().get(org.restlet.service.TaskService.class); - } - /** * Returns the tunnel service. The service is enabled by default. * diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/Component.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/Component.java index a42fbaf2ff..b03166bc02 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/Component.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/Component.java @@ -9,18 +9,12 @@ package org.restlet; -import java.io.File; -import java.net.URI; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.logging.Level; -import org.restlet.data.Reference; import org.restlet.engine.Engine; import org.restlet.engine.component.ComponentHelper; import org.restlet.engine.component.InternalRouter; -import org.restlet.representation.Representation; -import org.restlet.resource.ClientResource; import org.restlet.routing.Router; import org.restlet.routing.VirtualHost; import org.restlet.security.Realm; @@ -43,38 +37,6 @@ * that provides a transformation of data via its interface." Roy T. * Fielding
*
- * The configuration of a Component can be done programmatically or by using a - * XML document. There are dedicated constructors that accept either an URI - * reference to such XML document or a representation of such XML document, - * allowing easy configuration of the list of supported client and server - * connectors as well as services. In addition, you can add and configure - * virtual hosts (including the default one). Finally, you can attach - * applications either using their fully qualified class name or by pointing to - * a descriptor document (at this time only WADL description are supported, see - * the WADL Restlet extension for details).
- *
- * The XML Schema of the configuration files is available inside the API JAR - * under the "org.restlet.Component.xsd" name. Here is a sample of XML - * configuration: - * - *
- * <?xml version="1.0"?>
- * <component xmlns="http://restlet.org/schemas/2.0/Component">
- *    <client protocol="CLAP" />
- *    <client protocol="FILE" />
- *    <client protocols="HTTP HTTPS" />
- *    <server protocols="HTTP HTTPS" />
- * 
- *    <defaultHost>
- *       <attach uriPattern="/abcd/{xyz}" 
- *                  targetClass="org.restlet.test.MyApplication" />
- *       <attach uriPattern="/efgh/{xyz}"
- *                  targetDescriptor="clap://class/org/restlet/test/MyApplication.wadl" />
- *    </defaultHost>
- * </component>
- * 
- * - *
* Components also have useful services associated. They are all enabled by * default and are available as properties that can be eventually overridden: *
    @@ -96,32 +58,6 @@ */ public class Component extends Restlet { - /** - * Used as bootstrap for configuring and running a component in command line. - * Just provide as first and unique parameter the URI to the XML file. Note that - * relative paths are accepted. - * - * @param args The list of in-line parameters. - * @deprecated Use XML support in the Spring extension instead. - */ - @Deprecated - public static void main(String[] args) throws Exception { - try { - if ((args == null) || (args.length != 1)) { - // Display program arguments - System.err.println("Can't launch the component. Requires the path to an XML configuration file.\n"); - } else { - // Create and start the component - URI currentDirURI = (new File(".")).toURI(); - URI confURI = currentDirURI.resolve(args[0]); - new Component(confURI.toString()).start(); - } - } catch (Exception e) { - System.err.println("Can't launch the component.\nAn unexpected exception occurred:"); - e.printStackTrace(System.err); - } - } - /** The modifiable list of client connectors. */ private final ClientList clients; @@ -177,61 +113,6 @@ public Component() { } } - /** - * Constructor with the reference to the XML configuration file. - * - * @param xmlConfigRef The URI reference to the XML configuration file. - * @deprecated Use XML support in the Spring extension instead. - */ - @Deprecated - public Component(Reference xmlConfigRef) { - this(); - - // Get the representation of the configuration file. - Representation xmlConfigRepresentation = null; - - if (xmlConfigRef != null) { - ClientResource cr = new ClientResource(xmlConfigRef); - xmlConfigRepresentation = cr.get(); - - if (xmlConfigRepresentation != null) { - new org.restlet.engine.component.ComponentXmlParser(this, xmlConfigRepresentation).parse(); - } else { - getLogger().log(Level.WARNING, - "Unable to get the Component XML configuration located at this URI: " + xmlConfigRef); - } - } - } - - /** - * Constructor with the representation of the XML configuration file. - * - * @param xmlConfigRepresentation The representation of the XML configuration - * file. - * @deprecated Use XML support in the Spring extension instead. - */ - @Deprecated - public Component(Representation xmlConfigRepresentation) { - this(); - - if (xmlConfigRepresentation != null) { - new org.restlet.engine.component.ComponentXmlParser(this, xmlConfigRepresentation).parse(); - } else { - getLogger().log(Level.WARNING, "Unable to parse the Component XML configuration."); - } - } - - /** - * Constructor with the URI reference to the XML configuration file. - * - * @param xmlConfigurationRef The URI reference to the XML configuration file. - * @deprecated Use XML support in the Spring extension instead. - */ - @Deprecated - public Component(String xmlConfigurationRef) { - this((xmlConfigurationRef == null) ? null : new Reference(xmlConfigurationRef)); - } - /** * Returns a modifiable list of client connectors. * diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/data/MediaType.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/data/MediaType.java index f93ad54571..77604ce2b4 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/data/MediaType.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/data/MediaType.java @@ -256,13 +256,6 @@ public final class MediaType extends Metadata { public static final MediaType APPLICATION_RDF_TRIX = register("application/trix", "Simple XML serialized Resource Description Framework document"); - /** - * @deprecated Replaced by the official {@link #TEXT_TURTLE} media type. - */ - @Deprecated - public static final MediaType APPLICATION_RDF_TURTLE = register("application/x-turtle", - "Plain text serialized Resource Description Framework document"); - public static final MediaType APPLICATION_RDF_XML = register("application/rdf+xml", "Normalized XML serialized Resource Description Framework document"); diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/adapter/HttpRequest.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/adapter/HttpRequest.java index 3f149e97cb..271868bf5b 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/adapter/HttpRequest.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/adapter/HttpRequest.java @@ -22,7 +22,6 @@ import java.util.logging.Level; import org.restlet.Context; -import org.restlet.Message; import org.restlet.Request; import org.restlet.data.CacheDirective; import org.restlet.data.ChallengeResponse; @@ -60,19 +59,6 @@ * @author Jerome Louvel */ public class HttpRequest extends Request { - /** - * Adds a new header to the given request. - * - * @param request The request to update. - * @param headerName The header name to add. - * @param headerValue The header value to add. - * @deprecated Use {@link Message#getHeaders()} directly instead. - */ - @Deprecated - public static void addHeader(Request request, String headerName, String headerValue) { - request.getHeaders().add(new Header(headerName, headerValue)); - } - /** * Indicates if the access control data for request headers was parsed and added */ diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/component/ComponentXmlParser.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/component/ComponentXmlParser.java deleted file mode 100644 index 10752933f9..0000000000 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/component/ComponentXmlParser.java +++ /dev/null @@ -1,776 +0,0 @@ -/** - * Copyright 2005-2024 Qlik - * - * The contents of this file is subject to the terms of the Apache 2.0 open - * source license available at http://www.opensource.org/licenses/apache-2.0 - * - * Restlet is a registered trademark of QlikTech International AB. - */ - -package org.restlet.engine.component; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.restlet.Application; -import org.restlet.Client; -import org.restlet.Component; -import org.restlet.Context; -import org.restlet.Request; -import org.restlet.Response; -import org.restlet.Restlet; -import org.restlet.Server; -import org.restlet.data.Method; -import org.restlet.data.Parameter; -import org.restlet.data.Protocol; -import org.restlet.data.Reference; -import org.restlet.engine.Engine; -import org.restlet.engine.util.DefaultSaxHandler; -import org.restlet.representation.Representation; -import org.restlet.resource.ServerResource; -import org.restlet.routing.Router; -import org.restlet.routing.Template; -import org.restlet.routing.TemplateRoute; -import org.restlet.routing.Variable; -import org.restlet.routing.VirtualHost; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -/** - * Parser for component XML configuration. - * - * @author Jerome Louvel - * @see Component - * @deprecated Use XML support in the Spring extension instead. - */ -@Deprecated -public class ComponentXmlParser { - - /** - * Indicates if the DOM node is a "parameter" element. - * - * @param domNode The DOM node to test. - * @return True if the DOM node is a "parameter" element. - */ - private static boolean isParameter(Node domNode) { - return domNode != null && "parameter".equals(domNode.getNodeName()); - } - - /** - * Parses the DOM node into a {@link Parameter} instance. - * - * @param domNode The DOM node to parse. - * @return The {@link Parameter} instance. - */ - private static Parameter parseParameter(Node domNode) { - Parameter result = null; - - if (!isParameter(domNode)) { - return null; - } - - Node nameNode = domNode.getAttributes().getNamedItem("name"); - Node valueNode = domNode.getAttributes().getNamedItem("value"); - - if ((nameNode != null) && (valueNode != null)) { - result = new Parameter(nameNode.getNodeValue(), valueNode.getNodeValue()); - } - - return result; - } - - /** The component to update. */ - private volatile Component component; - - /** The XML configuration to parse. */ - private volatile Representation xmlConfiguration; - - /** - * Constructor. - * - * @param component The component to update. - * @param xmlConfiguration The XML configuration to parse. - */ - public ComponentXmlParser(Component component, Representation xmlConfiguration) { - this.component = component; - this.xmlConfiguration = xmlConfiguration; - } - - /** - * Creates a new route on a router according to a target class name and a URI - * pattern. - * - * @param router the router. - * @param targetClassName the target class name. - * @param uriPattern the URI pattern. - * @param defaultRoute Is this route the default one? - * @return the created route, or null. - */ - @SuppressWarnings("unchecked") - private TemplateRoute attach(Router router, String targetClassName, String uriPattern, boolean defaultRoute) { - TemplateRoute route = null; - - // Load the application class using the given class name - if (targetClassName != null) { - try { - final Class targetClass = Engine.loadClass(targetClassName); - - // First, check if we have a Resource class that should be - // attached directly to the router. - if (ServerResource.class.isAssignableFrom(targetClass)) { - final Class resourceClass = (Class) targetClass; - - if ((uriPattern != null) && !defaultRoute) { - route = router.attach(uriPattern, resourceClass); - } else { - route = router.attachDefault(resourceClass); - } - } else { - Restlet target = null; - - try { - // Create a new instance of the application class by - // invoking the constructor with the Context parameter. - target = (Restlet) targetClass.getConstructor(Context.class) - .newInstance(getComponent().getContext().createChildContext()); - } catch (NoSuchMethodException e) { - getLogger().log(Level.FINE, - "Couldn't invoke the constructor of the target class. Please check this class has a constructor with a single parameter of type Context. The empty constructor and the context setter will be used instead: " - + targetClassName, - e); - - // The constructor with the Context parameter does not - // exist. Instantiate an application with the default - // constructor then invoke the setContext method. - target = (Restlet) targetClass.getConstructor().newInstance(); - target.setContext(getComponent().getContext().createChildContext()); - } - - if (target != null) { - if ((uriPattern != null) && !defaultRoute) { - route = router.attach(uriPattern, target); - } else { - route = router.attachDefault(target); - } - } - } - } catch (ClassNotFoundException e) { - getLogger().log(Level.WARNING, - "Couldn't find the target class. Please check that your classpath includes " + targetClassName, - e); - } catch (InstantiationException e) { - getLogger().log(Level.WARNING, - "Couldn't instantiate the target class. Please check this class has an empty constructor " - + targetClassName, - e); - } catch (IllegalAccessException e) { - getLogger().log(Level.WARNING, - "Couldn't instantiate the target class. Please check that you have to proper access rights to " - + targetClassName, - e); - } catch (NoSuchMethodException e) { - getLogger().log(Level.WARNING, - "Couldn't invoke the constructor of the target class. Please check this class has a constructor with a single parameter of Context " - + targetClassName, - e); - } catch (InvocationTargetException e) { - getLogger().log(Level.WARNING, - "Couldn't instantiate the target class. An exception was thrown while creating " - + targetClassName, - e); - } - } - return route; - } - - /** - * Creates a new route on a router according to a target descriptor and a URI - * pattern. - * - * @param router the router. - * @param targetDescriptor the target descriptor. - * @param uriPattern the URI pattern. - * @param defaultRoute Is this route the default one? - * @return the created route, or null. - */ - private TemplateRoute attachWithDescriptor(Router router, String targetDescriptor, String uriPattern, - boolean defaultRoute) { - TemplateRoute route = null; - String targetClassName = null; - - try { - // Only WADL descriptors are supported at this moment. - targetClassName = "org.restlet.ext.wadl.WadlApplication"; - final Class targetClass = Engine.loadClass(targetClassName); - - // Get the WADL document - final Response response = getComponent().getContext().getClientDispatcher() - .handle(new Request(Method.GET, targetDescriptor)); - if (response.getStatus().isSuccess() && response.isEntityAvailable()) { - final Representation representation = response.getEntity(); - // Create a new instance of the application class by - // invoking the constructor with the Context parameter. - final Application target = (Application) targetClass.getConstructor(Context.class, Representation.class) - .newInstance(getComponent().getContext().createChildContext(), representation); - if (target != null) { - if ((uriPattern != null) && !defaultRoute) { - route = router.attach(uriPattern, target); - } else { - route = router.attachDefault(target); - } - } - } else { - getLogger().log(Level.WARNING, - "The target descriptor has not been found or is not available, or no client supporting the URI's protocol has been defined on this component. " - + targetDescriptor); - } - } catch (ClassNotFoundException e) { - getLogger().log(Level.WARNING, - "Couldn't find the target class. Please check that your classpath includes " + targetClassName, e); - } catch (InstantiationException e) { - getLogger().log(Level.WARNING, - "Couldn't instantiate the target class. Please check this class has an empty constructor " - + targetClassName, - e); - } catch (IllegalAccessException e) { - getLogger().log(Level.WARNING, - "Couldn't instantiate the target class. Please check that you have to proper access rights to " - + targetClassName, - e); - } catch (NoSuchMethodException e) { - getLogger().log(Level.WARNING, - "Couldn't invoke the constructor of the target class. Please check this class has a constructor with a single parameter of Context " - + targetClassName, - e); - } catch (InvocationTargetException e) { - getLogger().log(Level.WARNING, - "Couldn't instantiate the target class. An exception was thrown while creating " + targetClassName, - e); - } - - return route; - } - - /** - * Parses a node and returns its boolean value. - * - * @param Node the node to parse. - * @param defaultValue the default value; - * @return The boolean value of the node. - */ - private boolean getBoolean(Node node, boolean defaultValue) { - boolean value = defaultValue; - if (node != null) { - try { - value = Boolean.parseBoolean(node.getNodeValue()); - } catch (Exception e) { - value = defaultValue; - } - } - return value; - } - - /** - * Returns the component to update. - * - * @return The component to update. - */ - private Component getComponent() { - return component; - } - - /** - * Parses a node and returns the float value. - * - * @param node the node to parse. - * @param defaultValue the default value; - * @return the float value of the node. - */ - private float getFloat(Node node, float defaultValue) { - float value = defaultValue; - if (node != null) { - try { - value = Float.parseFloat(node.getNodeValue()); - } catch (Exception e) { - value = defaultValue; - } - } - return value; - } - - /** - * Parses a node and returns the int value. - * - * @param node the node to parse. - * @param defaultValue the default value; - * @return the int value of the node. - */ - private int getInt(Node node, int defaultValue) { - int value = defaultValue; - if (node != null) { - try { - value = Integer.parseInt(node.getNodeValue()); - } catch (Exception e) { - value = defaultValue; - } - } - return value; - } - - /** - * Returns the component's logger. - * - * @return The component's logger. - */ - private Logger getLogger() { - return getComponent().getLogger(); - } - - /** - * Parses a node and returns the long value. - * - * @param node the node to parse. - * @param defaultValue the default value; - * @return the long value of the node. - */ - private long getLong(Node node, long defaultValue) { - long value = defaultValue; - if (node != null) { - try { - value = Long.parseLong(node.getNodeValue()); - } catch (Exception e) { - value = defaultValue; - } - } - return value; - } - - /** - * Returns a protocol by its scheme. If the latter is unknown, instantiate a new - * protocol object. - * - * @param scheme the scheme of the desired protocol. - * @return a known protocol or a new instance. - */ - private Protocol getProtocol(String scheme) { - Protocol protocol = Protocol.valueOf(scheme); - if (protocol == null) { - protocol = new Protocol(scheme); - } - return protocol; - } - - /** - * Returns the XML configuration to parse. - * - * @return The XML configuration to parse. - */ - private Representation getXmlConfiguration() { - return xmlConfiguration; - } - - /** - * Parse a configuration file and update the component's configuration. - */ - public void parse() { - try { - // Parse and validate the XML configuration - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - dbf.setXIncludeAware(true); - - DefaultSaxHandler handler = new DefaultSaxHandler(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(handler); - db.setEntityResolver(handler); - - // try { - // Client client = new Client(Protocol.CLAP); - // Representation xsd = client.get( - // "clap://class/org/restlet/Component.xsd").getEntity(); - // db.dom.setSchema(xsd); - // } catch (Exception x) { - // Context - // .getCurrentLogger() - // .log( - // Level.CONFIG, - // "Unable to acquire a compiled instance of Component.xsd " - // + "to check the given restlet.xml. Ignore and continue"); - // } - - final Document document = db.parse(new InputSource(getXmlConfiguration().getReader())); - - // Check root node - if ("component".equals(document.getFirstChild().getNodeName())) { - // Look for clients - final NodeList childNodes = document.getFirstChild().getChildNodes(); - Node childNode; - - for (int i = 0; i < childNodes.getLength(); i++) { - childNode = childNodes.item(i); - if ("client".equals(childNode.getNodeName())) { - Node item = childNode.getAttributes().getNamedItem("protocol"); - Client client = null; - - if (item == null) { - item = childNode.getAttributes().getNamedItem("protocols"); - - if (item != null) { - final String[] protocols = item.getNodeValue().split(" "); - final List protocolsList = new ArrayList(); - - for (final String protocol : protocols) { - protocolsList.add(getProtocol(protocol)); - } - - client = new Client(new Context(), protocolsList); - } - } else { - client = new Client(new Context(), getProtocol(item.getNodeValue())); - } - - if (client != null) { - getComponent().getClients().add(client); - - // Look for Restlet's attributes - parseRestlet(client, childNode); - - // Look for parameters - for (int j = 0; j < childNode.getChildNodes().getLength(); j++) { - final Node childNode2 = childNode.getChildNodes().item(j); - - if (isParameter(childNode2)) { - Parameter p = parseParameter(childNode2); - - if (p != null) { - client.getContext().getParameters().add(p); - } - } - } - } - } else if ("server".equals(childNode.getNodeName())) { - Node item = childNode.getAttributes().getNamedItem("protocol"); - final Node portNode = childNode.getAttributes().getNamedItem("port"); - final Node addressNode = childNode.getAttributes().getNamedItem("address"); - Server server = null; - - if (item == null) { - item = childNode.getAttributes().getNamedItem("protocols"); - - if (item != null) { - final String[] protocols = item.getNodeValue().split(" "); - final List protocolsList = new ArrayList(); - - for (final String protocol : protocols) { - protocolsList.add(getProtocol(protocol)); - } - - final int port = getInt(portNode, Protocol.UNKNOWN_PORT); - - if (port == Protocol.UNKNOWN_PORT) { - getLogger().warning("Please specify a port when defining a list of protocols."); - } else { - server = new Server(new Context(), protocolsList, - getInt(portNode, Protocol.UNKNOWN_PORT), - getComponent().getServers().getNext()); - } - } - } else { - final Protocol protocol = getProtocol(item.getNodeValue()); - server = new Server(new Context(), protocol, getInt(portNode, protocol.getDefaultPort()), - getComponent().getServers().getNext()); - } - - if (server != null) { - // Look for Restlet's attributes - parseRestlet(server, childNode); - - if (addressNode != null) { - final String address = addressNode.getNodeValue(); - if (address != null) { - server.setAddress(address); - } - } - - // Look for parameters - for (int j = 0; j < childNode.getChildNodes().getLength(); j++) { - final Node childNode2 = childNode.getChildNodes().item(j); - - if (isParameter(childNode2)) { - Parameter p = parseParameter(childNode2); - - if (p != null) { - server.getContext().getParameters().add(p); - } - } - } - - getComponent().getServers().add(server); - } - } else if (isParameter(childNode)) { - Parameter p = parseParameter(childNode); - - if (p != null) { - getComponent().getContext().getParameters().add(p); - } - } else if ("defaultHost".equals(childNode.getNodeName())) { - parseHost(getComponent().getDefaultHost(), childNode); - } else if ("host".equals(childNode.getNodeName())) { - final VirtualHost host = new VirtualHost(getComponent().getContext()); - parseHost(host, childNode); - getComponent().getHosts().add(host); - } else if ("internalRouter".equals(childNode.getNodeName())) { - parseRouter(getComponent().getInternalRouter(), childNode); - } else if ("logService".equals(childNode.getNodeName())) { - Node item = childNode.getAttributes().getNamedItem("logFormat"); - - if (item != null) { - getComponent().getLogService().setResponseLogFormat(item.getNodeValue()); - } - - item = childNode.getAttributes().getNamedItem("loggerName"); - - if (item != null) { - getComponent().getLogService().setLoggerName(item.getNodeValue()); - } - - item = childNode.getAttributes().getNamedItem("enabled"); - - if (item != null) { - getComponent().getLogService().setEnabled(getBoolean(item, true)); - } - - item = childNode.getAttributes().getNamedItem("identityCheck"); - - if (item != null) { - getComponent().getLogService().setIdentityCheck(getBoolean(item, true)); - } - } else if ("statusService".equals(childNode.getNodeName())) { - Node item = childNode.getAttributes().getNamedItem("contactEmail"); - - if (item != null) { - getComponent().getStatusService().setContactEmail(item.getNodeValue()); - } - - item = childNode.getAttributes().getNamedItem("enabled"); - - if (item != null) { - getComponent().getStatusService().setEnabled(getBoolean(item, true)); - } - - item = childNode.getAttributes().getNamedItem("homeRef"); - - if (item != null) { - getComponent().getStatusService().setHomeRef(new Reference(item.getNodeValue())); - } - - item = childNode.getAttributes().getNamedItem("overwrite"); - - if (item != null) { - getComponent().getStatusService().setOverwriting(getBoolean(item, true)); - } - } - } - } else { - getLogger().log(Level.WARNING, "Unable to find the root \"component\" node in the XML configuration."); - } - } catch (Exception e) { - getLogger().log(Level.WARNING, "Unable to parse the Component XML configuration.", e); - } - } - - /** - * Parse the attributes of a DOM node and update the given host. - * - * @param host the host to update. - * @param hostNode the DOM node. - */ - private void parseHost(VirtualHost host, Node hostNode) { - // Parse the "RouterType" attributes and elements. - parseRouter(host, hostNode); - - Node item = hostNode.getAttributes().getNamedItem("hostDomain"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setHostDomain(item.getNodeValue()); - } - item = hostNode.getAttributes().getNamedItem("hostPort"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setHostPort(item.getNodeValue()); - } - item = hostNode.getAttributes().getNamedItem("hostScheme"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setHostScheme(item.getNodeValue()); - } - item = hostNode.getAttributes().getNamedItem("resourceDomain"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setResourceDomain(item.getNodeValue()); - } - item = hostNode.getAttributes().getNamedItem("resourcePort"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setResourcePort(item.getNodeValue()); - } - item = hostNode.getAttributes().getNamedItem("resourceScheme"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setResourceScheme(item.getNodeValue()); - } - item = hostNode.getAttributes().getNamedItem("serverAddress"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setServerAddress(item.getNodeValue()); - } - item = hostNode.getAttributes().getNamedItem("serverPort"); - if ((item != null) && (item.getNodeValue() != null)) { - host.setServerPort(item.getNodeValue()); - } - } - - /** - * Parse the attributes of a DOM node and update the given restlet. - * - * @param restlet the restlet to update. - * @param restletNode the DOM node. - */ - private void parseRestlet(Restlet restlet, Node restletNode) { - // Parse the "RestletType" attributes and elements. - Node item = restletNode.getAttributes().getNamedItem("name"); - if ((item != null) && (item.getNodeValue() != null)) { - restlet.setName(item.getNodeValue()); - } - item = restletNode.getAttributes().getNamedItem("description"); - if ((item != null) && (item.getNodeValue() != null)) { - restlet.setDescription(item.getNodeValue()); - } - item = restletNode.getAttributes().getNamedItem("owner"); - if ((item != null) && (item.getNodeValue() != null)) { - restlet.setOwner(item.getNodeValue()); - } - item = restletNode.getAttributes().getNamedItem("author"); - if ((item != null) && (item.getNodeValue() != null)) { - restlet.setOwner(item.getNodeValue()); - } - } - - /** - * Parse the attributes of a DOM node and update the given router. - * - * @param router the router to update. - * @param routerNode the DOM node. - */ - private void parseRouter(Router router, Node routerNode) { - parseRestlet(router, routerNode); - - Node item = routerNode.getAttributes().getNamedItem("defaultMatchingMode"); - if (item != null) { - router.setDefaultMatchingMode(getInt(item, getComponent().getInternalRouter().getDefaultMatchingMode())); - } - - item = routerNode.getAttributes().getNamedItem("defaultMatchingQuery"); - if (item != null) { - router.setDefaultMatchingQuery( - getBoolean(item, getComponent().getInternalRouter().getDefaultMatchingQuery())); - } - - item = routerNode.getAttributes().getNamedItem("maxAttempts"); - if (item != null) { - router.setMaxAttempts(getInt(item, getComponent().getInternalRouter().getMaxAttempts())); - } - - item = routerNode.getAttributes().getNamedItem("routingMode"); - if (item != null) { - router.setRoutingMode(getInt(item, getComponent().getInternalRouter().getRoutingMode())); - } - - item = routerNode.getAttributes().getNamedItem("requiredScore"); - if (item != null) { - router.setRequiredScore(getFloat(item, getComponent().getInternalRouter().getRequiredScore())); - } - - item = routerNode.getAttributes().getNamedItem("retryDelay"); - if (item != null) { - router.setRetryDelay(getLong(item, getComponent().getInternalRouter().getRetryDelay())); - } - - // Loops the list of "parameter" and "attach" elements - setAttach(router, routerNode); - } - - /** - * Attaches Restlet to a router. - * - * @param router The router to attach to. - * @param node The node describing the Restlets to attach. - */ - private void setAttach(Router router, Node node) { - NodeList childNodes = node.getChildNodes(); - - for (int i = 0; i < childNodes.getLength(); i++) { - Node childNode = childNodes.item(i); - - if (isParameter(childNode)) { - Parameter p = parseParameter(childNode); - - if (p != null) { - router.getContext().getParameters().add(p); - } - } else if ("attach".equals(childNode.getNodeName()) || "attachDefault".equals(childNode.getNodeName())) { - String uriPattern = null; - Node item = childNode.getAttributes().getNamedItem("uriPattern"); - - if (item != null) { - uriPattern = item.getNodeValue(); - } else { - uriPattern = ""; - } - - item = childNode.getAttributes().getNamedItem("default"); - boolean bDefault = getBoolean(item, false) || "attachDefault".equals(childNode.getNodeName()); - - // Attaches a new route. - TemplateRoute route = null; - item = childNode.getAttributes().getNamedItem("targetClass"); - - if (item != null) { - route = attach(router, item.getNodeValue(), uriPattern, bDefault); - } else { - item = childNode.getAttributes().getNamedItem("targetDescriptor"); - if (item != null) { - route = attachWithDescriptor(router, item.getNodeValue(), uriPattern, bDefault); - } else { - getLogger().log(Level.WARNING, - "Both targetClass name and targetDescriptor are missing. Couldn't attach a new route."); - } - } - - if (route != null) { - Template template = route.getTemplate(); - item = childNode.getAttributes().getNamedItem("matchingMode"); - template.setMatchingMode(getInt(item, router.getDefaultMatchingMode())); - item = childNode.getAttributes().getNamedItem("defaultVariableType"); - template.getDefaultVariable().setType(getInt(item, Variable.TYPE_URI_SEGMENT)); - - // Parse possible parameters specific to this AttachType - final NodeList childNodes2 = childNode.getChildNodes(); - for (int j = 0; j < childNodes2.getLength(); j++) { - Node aNode = childNodes2.item(j); - if (isParameter(aNode)) { - Parameter p = parseParameter(aNode); - - if (p != null) { - route.getNext().getContext().getParameters().add(p); - } - } - } - } - } - } - } - -} diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/local/ZipEntryRepresentation.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/local/ZipEntryRepresentation.java index 7d12c9cf7d..7445a4ebdc 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/local/ZipEntryRepresentation.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/engine/local/ZipEntryRepresentation.java @@ -37,21 +37,6 @@ public class ZipEntryRepresentation extends StreamRepresentation { /** The Zip file. */ protected final ZipFile zipFile; - /** - * Constructor. - * - * @param mediaType The entry media type. - * @param zipFile The parent Zip archive file. - * @param entry The Zip entry. - * @deprecated Use - * {@link #ZipEntryRepresentation(MediaType, ZipFile, ZipEntry, int)} - * instead. - */ - @Deprecated - public ZipEntryRepresentation(MediaType mediaType, ZipFile zipFile, ZipEntry entry) { - this(mediaType, zipFile, entry, -1); - } - /** * Constructor. * diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ResourceException.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ResourceException.java index 1a4820e45f..f8f5fc54cd 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ResourceException.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ResourceException.java @@ -147,17 +147,6 @@ public ResourceException(Status status) { this(status, (status == null) ? null : status.getThrowable()); } - /** - * Constructor. - * - * @param status The status to associate. - * @deprecated use constructor with status, request and response instead. - */ - @Deprecated - public ResourceException(Status status, Resource resource) { - this(status, (status == null) ? null : status.getThrowable(), resource.getRequest(), resource.getResponse()); - } - /** * Constructor. * diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/security/Role.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/security/Role.java index 3cd0df0576..c153209253 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/security/Role.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/security/Role.java @@ -36,32 +36,6 @@ */ public class Role implements Principal { - /** - * Unmodifiable role that covers all existing roles. Its name is "*" by - * convention. - * - * @deprecated To be removed as it is ambiguous, roles being specific to a given - * application. - */ - @Deprecated - public static final Role ALL = new Role("*", "Role that covers all existing roles.") { - @Override - public void setApplication(Application application) { - throw new IllegalStateException("Unmodifiable role"); - } - - @Override - public void setDescription(String description) { - throw new IllegalStateException("Unmodifiable role"); - } - - @Override - public void setName(String name) { - throw new IllegalStateException("Unmodifiable role"); - } - - }; - /** * Finds an existing role or creates a new one if needed. Note that a null * description will be set if the role has to be created. @@ -131,31 +105,6 @@ public Role(Application application, String name, String description) { this.childRoles = new CopyOnWriteArrayList(); } - /** - * Constructor. Note that the parent application is retrieved using the - * {@link Application#getCurrent()} method. - * - * @param name The name. - * @deprecated Use {@link Role#Role(Application, String)} instead. - */ - @Deprecated - public Role(String name) { - this(Application.getCurrent(), name, null); - } - - /** - * Constructor. Note that the parent application is retrieved using the - * {@link Application#getCurrent()} method. - * - * @param name The name. - * @param description The description. - * @deprecated Use {@link Role#Role(Application, String, String)} instead. - */ - @Deprecated - public Role(String name, String description) { - this(Application.getCurrent(), name, description); - } - @Override public boolean equals(Object o) { if (!(o instanceof Role)) diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/service/LogService.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/service/LogService.java index bf179fbf09..99ef0943e1 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/service/LogService.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/service/LogService.java @@ -289,17 +289,6 @@ public String getResponseLogMessage(Response response, int duration) { return result; } - /** - * Indicates if the debugging mode is enabled. False by default. - * - * @return True if the debugging mode is enabled. - * @deprecated Rely on {@link Application#isDebugging()} instead. - */ - @Deprecated - protected boolean isDebugging() { - return debugging; - } - /** * Indicates if the identity check (as specified by RFC1413) is enabled. Default * value is false. @@ -323,17 +312,6 @@ public boolean isLoggable(Request request) { : getLoggableTemplate().match(request.getResourceRef().getTargetRef().toString()) > 0; } - /** - * Indicates if the debugging mode is enabled. - * - * @param debugging True if the debugging mode is enabled. - * @deprecated Rely on {@link Application#setDebugging(boolean)} instead. - */ - @Deprecated - protected void setDebugging(boolean debugging) { - this.debugging = debugging; - } - /** * Indicates if the identity check (as specified by RFC1413) is enabled. * diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/service/StatusService.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/service/StatusService.java index 6227cfdc82..a3e2a95679 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/service/StatusService.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/service/StatusService.java @@ -162,129 +162,6 @@ public MetadataService getMetadataService() { return metadataService; } - /** - * Returns a representation for the given status. In order to customize the - * default representation, this method can be overridden. It returns null by - * default. - * - * @param status The status to represent. - * @param request The request handled. - * @param response The response updated. - * @return The representation of the given status. - * @deprecated Use {@link #toRepresentation(Status, Request, Response)} instead. - */ - @Deprecated - public Representation getRepresentation(Status status, Request request, Response response) { - Representation result = null; - - // Do content negotiation for status - if (converterService != null && connegService != null && metadataService != null) { - Object representationObject = null; - - // Serialize exception if any and if {@link org.restlet.resource.Status} annotation asks for it - Throwable cause = status.getThrowable(); - - if (cause != null) { - org.restlet.engine.resource.ThrowableAnnotationInfo tai = org.restlet.engine.resource.AnnotationUtils - .getInstance().getThrowableAnnotationInfo(cause.getClass()); - - if (tai != null && tai.isSerializable()) { - if (Application.getCurrent() != null && !Application.getCurrent().isDebugging()) { - // We clear the stack trace to prevent technical - // information leak - cause.setStackTrace(new StackTraceElement[] {}); - - if (cause.getCause() != null) { - Context.getCurrentLogger().log(Level.WARNING, - "The cause of the exception should be null except in debug mode"); - } - } - - representationObject = cause; - } - } - - try { - // Default representation match with the status properties - if (representationObject == null) { - representationObject = new StatusInfo(status, getContactEmail(), getHomeRef().toString()); - } - - List variants = org.restlet.engine.converter.ConverterUtils - .getVariants(representationObject.getClass(), null); - if (variants == null) { - variants = new ArrayList<>(); - } - - Variant variant = connegService.getPreferredVariant(variants, request, metadataService); - result = converterService.toRepresentation(representationObject, variant); - } catch (Exception e) { - Context.getCurrentLogger().log(Level.WARNING, - "Could not serialize throwable class " + ((cause == null) ? null : cause.getClass()), e); - } - } - - return result; - } - - /** - * Returns a status for a given exception or error. By default, it unwraps the - * status of {@link ResourceException}. For other exceptions or errors, it - * returns an {@link Status#SERVER_ERROR_INTERNAL} status.
    - *
    - * In order to customize the default behavior, this method can be overridden. - * - * @param throwable The exception or error caught. - * @param request The request handled. - * @param response The response updated. - * @return The representation of the given status. - * @deprecated Use {@link #toStatus(Throwable, Request, Response)} instead. - */ - @Deprecated - public Status getStatus(Throwable throwable, Request request, Response response) { - Status result; - - Status defaultStatus = Status.SERVER_ERROR_INTERNAL; - Throwable t = throwable; - - // If throwable is a ResourceException, use its status and the cause. - if (throwable instanceof ResourceException) { - defaultStatus = ((ResourceException) throwable).getStatus(); - - if (throwable.getCause() != null && throwable.getCause() != throwable) { - t = throwable.getCause(); - } - } - - // look for Status annotation - org.restlet.engine.resource.ThrowableAnnotationInfo tai = org.restlet.engine.resource.AnnotationUtils - .getInstance().getThrowableAnnotationInfo(t.getClass()); - - if (tai != null) { - result = new Status(tai.getStatus(), t); - } else { - result = new Status(defaultStatus, t); - } - - return result; - } - - /** - * Returns a status for a given exception or error. By default it returns an - * {@link Status#SERVER_ERROR_INTERNAL} status and logs a severe message.
    - * In order to customize the default behavior, this method can be overridden. - * - * @param throwable The exception or error caught. - * @param resource The parent resource. - * @return The representation of the given status. - * @deprecated Use {@link #toStatus(Throwable, Resource)} instead. - */ - @Deprecated - public Status getStatus(Throwable throwable, Resource resource) { - return toStatus(throwable, (resource == null) ? null : resource.getRequest(), - (resource == null) ? null : resource.getResponse()); - } - /** * Indicates if an existing entity should be overwritten. False by default. * @@ -363,7 +240,56 @@ public void setOverwriting(boolean overwriting) { * @return The representation of the given status. */ public Representation toRepresentation(Status status, Request request, Response response) { - return getRepresentation(status, request, response); + Representation result = null; + + // Do content negotiation for status + if (converterService != null && connegService != null && metadataService != null) { + Object representationObject = null; + + // Serialize exception if any and if {@link org.restlet.resource.Status} annotation asks for it + Throwable cause = status.getThrowable(); + + if (cause != null) { + org.restlet.engine.resource.ThrowableAnnotationInfo tai = org.restlet.engine.resource.AnnotationUtils + .getInstance().getThrowableAnnotationInfo(cause.getClass()); + + if (tai != null && tai.isSerializable()) { + if (Application.getCurrent() != null && !Application.getCurrent().isDebugging()) { + // We clear the stack trace to prevent technical + // information leak + cause.setStackTrace(new StackTraceElement[] {}); + + if (cause.getCause() != null) { + Context.getCurrentLogger().log(Level.WARNING, + "The cause of the exception should be null except in debug mode"); + } + } + + representationObject = cause; + } + } + + try { + // Default representation match with the status properties + if (representationObject == null) { + representationObject = new StatusInfo(status, getContactEmail(), getHomeRef().toString()); + } + + List variants = org.restlet.engine.converter.ConverterUtils + .getVariants(representationObject.getClass(), null); + if (variants == null) { + variants = new ArrayList<>(); + } + + Variant variant = connegService.getPreferredVariant(variants, request, metadataService); + result = converterService.toRepresentation(representationObject, variant); + } catch (Exception e) { + Context.getCurrentLogger().log(Level.WARNING, + "Could not serialize throwable class " + ((cause == null) ? null : cause.getClass()), e); + } + } + + return result; } /** @@ -393,7 +319,31 @@ public Representation toRepresentation(Status status, Resource resource) { * @return The representation of the given status. */ public Status toStatus(Throwable throwable, Request request, Response response) { - return getStatus(throwable, request, response); + Status result; + + Status defaultStatus = Status.SERVER_ERROR_INTERNAL; + Throwable t = throwable; + + // If throwable is a ResourceException, use its status and the cause. + if (throwable instanceof ResourceException) { + defaultStatus = ((ResourceException) throwable).getStatus(); + + if (throwable.getCause() != null && throwable.getCause() != throwable) { + t = throwable.getCause(); + } + } + + // look for Status annotation + org.restlet.engine.resource.ThrowableAnnotationInfo tai = org.restlet.engine.resource.AnnotationUtils + .getInstance().getThrowableAnnotationInfo(t.getClass()); + + if (tai != null) { + result = new Status(tai.getStatus(), t); + } else { + result = new Status(defaultStatus, t); + } + + return result; } /** @@ -406,6 +356,7 @@ public Status toStatus(Throwable throwable, Request request, Response response) * @return The representation of the given status. */ public Status toStatus(Throwable throwable, Resource resource) { - return getStatus(throwable, resource); + return toStatus(throwable, (resource == null) ? null : resource.getRequest(), + (resource == null) ? null : resource.getResponse()); } }